gmyth-stream/server/0.2/plugins/transcoders/mencoder.py
author melunko
Tue May 08 14:54:37 2007 +0100 (2007-05-08)
branchtrunk
changeset 633 65eaca328e22
parent 628 c6af9d7a88b5
child 638 e38953623405
permissions -rw-r--r--
[svn r639] Added creation of package gmyth-utils containing gmyth-cat application
morphbr@577
     1
import os
morphbr@577
     2
import shlex
morphbr@577
     3
import signal
morphbr@577
     4
import subprocess
morphbr@595
     5
import time
morphbr@577
     6
morphbr@565
     7
import lib.utils as utils
morphbr@565
     8
import lib.server as server
morphbr@565
     9
morphbr@595
    10
from select import select
morphbr@595
    11
morphbr@565
    12
__all__ = ("TranscoderMencoder",)
morphbr@565
    13
morphbr@565
    14
class TranscoderMencoder(server.Transcoder):
morphbr@585
    15
    """Transcoder class that implements a transcoder using Mencoder"""
morphbr@565
    16
    mencoder_path = utils.which("mencoder")
morphbr@565
    17
    name = "mencoder"
morphbr@565
    18
    priority = -1
morphbr@577
    19
    args = {}
morphbr@577
    20
    proc = None
morphbr@605
    21
    gmyth = None
morphbr@565
    22
morphbr@595
    23
    # only works with avi container
morphbr@595
    24
    status = 0
morphbr@595
    25
morphbr@569
    26
    def _setup_params(self):
morphbr@569
    27
        params_first = self.params_first
morphbr@569
    28
morphbr@569
    29
        # general_opts
morphbr@569
    30
        self.args["local"]    = params_first("local", False)
morphbr@569
    31
        self.args["language"] = params_first("language", False)
morphbr@569
    32
        self.args["subtitle"] = params_first("subtitle", False)
morphbr@628
    33
        self.args["format"]   = params_first("format", "mpeg1")
morphbr@569
    34
        self.args["outfile"]  = params_first("outfile", "-")
morphbr@595
    35
        self.args["sendback"] = params_first("sendback", True)
morphbr@595
    36
morphbr@595
    37
        # handle sendback variable
morphbr@595
    38
        if self.args["sendback"] == "False":
morphbr@595
    39
            self.args["sendback"] = False
morphbr@569
    40
morphbr@569
    41
        # input_opt
morphbr@605
    42
        uri = params_first("uri", "file:-").split(":", 1)
morphbr@577
    43
        self.args["type"]     = uri[0]
morphbr@577
    44
        self.args["input"]    = uri[1]
morphbr@569
    45
morphbr@569
    46
        # audio_opts
morphbr@569
    47
        self.args["acodec"]   = params_first("acodec", "mp2")
morphbr@569
    48
        self.args["abitrate"] = params_first("abitrate", 192)
morphbr@569
    49
        self.args["volume"]   = params_first("volume", 5)
morphbr@569
    50
morphbr@569
    51
        # video_opts
morphbr@569
    52
        self.args["mux"]      = params_first("mux", "mpeg")
morphbr@569
    53
        self.args["fps"]      = params_first("fps", 25)
morphbr@569
    54
        self.args["vcodec"]   = params_first("vcodec", "mpeg1video")
morphbr@569
    55
        self.args["vbitrate"] = params_first("vbitrate", 400)
morphbr@569
    56
        self.args["width"]    = params_first("width", 320)
morphbr@569
    57
        self.args["height"]   = params_first("height", 240)
morphbr@569
    58
    # _setup_params()
morphbr@569
    59
morphbr@569
    60
morphbr@569
    61
    def _setup_audio(self):
morphbr@569
    62
        if self.args["acodec"] == "mp3lame":
morphbr@569
    63
            audio = "-oac mp3lame -lameopts cbr:br=%s vol=%s" % (
morphbr@569
    64
                self.args["abitrate"], self.args["volume"])
morphbr@569
    65
        else:
morphbr@569
    66
            audio = "-oac lavc -lavcopts acodec=%s:abitrate=%s" % (
morphbr@569
    67
                self.args["acodec"], self.args["abitrate"])
morphbr@569
    68
morphbr@569
    69
        return audio
morphbr@569
    70
    # _setup_audio()
morphbr@569
    71
morphbr@569
    72
morphbr@569
    73
    def _setup_video(self):
morphbr@577
    74
        video = " -of %s" % self.args["mux"]
morphbr@577
    75
        video += " -ofps %s" % self.args["fps"]
morphbr@569
    76
morphbr@569
    77
        vcodec = self.args["vcodec"]
morphbr@569
    78
        if vcodec == "nuv" or vcodec == "xvid"\
morphbr@569
    79
               or vcodec == "qtvideo" or vcodec == "copy":
morphbr@569
    80
            video += " -ovc %s" % vcodec
morphbr@569
    81
        else:
morphbr@569
    82
            video += " -ovc lavc -lavcopts vcodec=%s:vbitrate=%s" % (
morphbr@569
    83
                vcodec, self.args["vbitrate"])
morphbr@569
    84
morphbr@628
    85
        if self.args["mux"] == "mpeg":
morphbr@628
    86
            video += " -mpegopts format=%s" % self.args["format"]
morphbr@569
    87
        video += " -vf scale=%s:%s" % (self.args["width"], self.args["height"])
morphbr@569
    88
morphbr@569
    89
        return video
morphbr@569
    90
    # _setup_video()
morphbr@569
    91
morphbr@569
    92
morphbr@569
    93
    def _arg_append(self, args, options):
morphbr@577
    94
        for arg in shlex.split(options):
morphbr@569
    95
            args.append(arg)
morphbr@569
    96
    # arg_append()
morphbr@569
    97
morphbr@569
    98
    def _setup_mencoder_opts(self, args):
morphbr@569
    99
        args.append(self.mencoder_path)
morphbr@595
   100
morphbr@595
   101
        if self.args["outfile"] == "-" and self.args["type"]:
morphbr@595
   102
            args.append(self.args["input"])
morphbr@595
   103
        else:
morphbr@595
   104
            args.append("-")
morphbr@569
   105
morphbr@569
   106
        if self.args["language"]:
morphbr@569
   107
            self._arg_append(args, "-alang %s" % self.args["language"])
morphbr@569
   108
morphbr@569
   109
        if self.args["subtitle"]:
morphbr@569
   110
            self._arg_append(args, "-slang %s" % self.args["subtitle"])
morphbr@569
   111
            self._arg_append(args, "-subfps %s" % self.args["fps"])
morphbr@569
   112
morphbr@569
   113
        self._arg_append(args, "-idx")
morphbr@628
   114
        self._arg_append(args, "-cache 1024")
morphbr@577
   115
        self._arg_append(args, self._setup_audio())
morphbr@577
   116
        self._arg_append(args, self._setup_video())
morphbr@569
   117
morphbr@569
   118
        self._arg_append(args, "-really-quiet")
morphbr@569
   119
        self._arg_append(args, "-o %s" % self.args["outfile"])
morphbr@595
   120
        self._arg_append(args, "2>%s" % os.devnull)
morphbr@569
   121
    # _setup_args()
morphbr@569
   122
morphbr@569
   123
morphbr@569
   124
    def _setup_filename(self):
morphbr@569
   125
        _type = self.args["type"]
morphbr@569
   126
morphbr@569
   127
        if _type == "file":
morphbr@569
   128
            if not os.path.exists(self.args["input"]):
morphbr@577
   129
                raise IOError,\
morphbr@577
   130
                      "File requested does not exist: %s." % self.args["input"]
morphbr@605
   131
            else:
morphbr@605
   132
                self.args["input"] = "file://%s" % self.args["input"]
morphbr@569
   133
morphbr@569
   134
        elif _type == "dvd":
morphbr@569
   135
            self.args["input"] = "dvd://".join(self.args["input"])
morphbr@595
   136
morphbr@595
   137
        elif _type == "myth":
morphbr@595
   138
            # gmyth-cat -h 192.168.1.124 -p 6543 -c 111
morphbr@595
   139
            # gmyth-cat -h 192.168.1.124 -p 6543 -f file.nuv
morphbr@595
   140
            # myth://IP:PORT:type:file
morphbr@595
   141
            self.args["gmyth-cat"] = self.args["input"].split(":")
morphbr@605
   142
            self.args["input"] = "-"
morphbr@569
   143
    # _setup_filename()
morphbr@569
   144
morphbr@569
   145
morphbr@572
   146
    def __init__(self, params):
morphbr@565
   147
        server.Transcoder.__init__(self, params)
morphbr@577
   148
        self.mencoder_opts = []
morphbr@565
   149
morphbr@569
   150
        try:
morphbr@569
   151
            self._setup_params()
morphbr@569
   152
            self._setup_filename()
morphbr@569
   153
            self._setup_mencoder_opts(self.mencoder_opts)
morphbr@569
   154
        except Exception, e:
morphbr@569
   155
            self.log.error(e)
morphbr@565
   156
    # __init__()
morphbr@565
   157
morphbr@565
   158
morphbr@595
   159
    def _check_opened_file(self, stdw, _stdin):
morphbr@595
   160
        loop = True
morphbr@595
   161
        while loop:
morphbr@595
   162
            try:
morphbr@595
   163
                return open(self.args["outfile"])
morphbr@595
   164
            except:
morphbr@595
   165
                os.write(stdw, _stdin.read(1024))
morphbr@595
   166
    # _check_opened_file
morphbr@595
   167
morphbr@595
   168
morphbr@595
   169
    def _start_outfile(self, outfd):
morphbr@595
   170
        finished = False
morphbr@595
   171
morphbr@595
   172
        # fix this (not necessary)
morphbr@595
   173
        outfd.write("OK")
morphbr@595
   174
morphbr@595
   175
        # Configuring stdin
morphbr@595
   176
        _stdin = open(self.args["input"])
morphbr@595
   177
        size = int(os.path.getsize(self.args["input"]))
morphbr@595
   178
        self.status = 0
morphbr@595
   179
        total_read = 0
morphbr@595
   180
morphbr@595
   181
        # Configuring pipes
morphbr@595
   182
        stdr, stdw = os.pipe()
morphbr@569
   183
morphbr@605
   184
        if not self._run_mencoder(input=stdr):
morphbr@565
   185
            return False
morphbr@565
   186
morphbr@595
   187
        stdout = self._check_opened_file(stdw, _stdin)
morphbr@595
   188
morphbr@595
   189
        try:
morphbr@595
   190
            while self.proc and self.proc.poll() == None:
morphbr@595
   191
                if not finished:
morphbr@595
   192
                    data_in = _stdin.read(4096)
morphbr@595
   193
                    if data_in != "":
morphbr@595
   194
                        os.write(stdw, data_in)
morphbr@595
   195
                        total_read += 4096
morphbr@595
   196
                        d = stdout.read(4096)
morphbr@595
   197
                        if self.args["sendback"]:
morphbr@595
   198
                            outfd.write(d)
morphbr@595
   199
                        self.status = total_read * 100 / size
morphbr@595
   200
                    else:
morphbr@595
   201
                        finished = True
morphbr@595
   202
                        os.close(stdw)
morphbr@595
   203
morphbr@595
   204
                else:
morphbr@595
   205
                    d = stdout.read(4096)
morphbr@595
   206
                    if self.args["sendback"] and d != "":
morphbr@595
   207
                        outfd.write(d)
morphbr@595
   208
morphbr@595
   209
        except Exception, e:
morphbr@595
   210
            self.log.error("Problems handling data: %s" % e)
morphbr@628
   211
            self.stop()
morphbr@595
   212
            return False
morphbr@595
   213
morphbr@595
   214
        self.log.info("%s: Finished sending data to client" % repr(self))
morphbr@595
   215
        if not self.args["sendback"]:
morphbr@595
   216
            outfd.write("DONE")
morphbr@595
   217
morphbr@595
   218
        return True
morphbr@595
   219
    # _start_outfile()
morphbr@595
   220
morphbr@595
   221
    def _start(self, outfd):
morphbr@605
   222
        if not self._run_mencoder(output=subprocess.PIPE):
morphbr@595
   223
            return False
morphbr@595
   224
morphbr@565
   225
        try:
morphbr@565
   226
            while self.proc and self.proc.poll() == None:
morphbr@577
   227
                d = self.proc.stdout.read(1024)
morphbr@565
   228
                outfd.write(d)
morphbr@565
   229
        except Exception, e:
morphbr@565
   230
            self.log.error("Problems handling data: %s" % e)
morphbr@565
   231
            return False
morphbr@565
   232
morphbr@595
   233
        self.log.info("%s: Finished sending data to client" % repr(self))
morphbr@565
   234
        return True
morphbr@595
   235
    # _start()
morphbr@595
   236
morphbr@605
   237
    def _start_myth(self, outfd):
morphbr@605
   238
        # gmyth-cat -h 192.168.1.124 -p 6543 -c 111
morphbr@605
   239
        # gmyth-cat -h 192.168.1.124 -p 6543 -f file.nuv
morphbr@605
   240
        # myth://IP:PORT:type:file
morphbr@605
   241
        host = self.args["gmyth-cat"][0]
morphbr@605
   242
        port = self.args["gmyth-cat"][1]
morphbr@605
   243
        kind = self.args["gmyth-cat"][2]
morphbr@605
   244
        fchan = self.args["gmyth-cat"][3]
morphbr@605
   245
morphbr@605
   246
        gmyth_cat = utils.which("gmyth-cat")
morphbr@605
   247
        opts = [gmyth_cat, "-h", host, "-p", port, "-" + kind, fchan]
morphbr@605
   248
morphbr@605
   249
        try:
morphbr@605
   250
            self.gmyth = subprocess.Popen(opts, stdout=subprocess.PIPE, close_fds=True)
morphbr@605
   251
        except Exception, e:
morphbr@605
   252
            self.log.error("Error executing gmyth-cat: %s" % e)
morphbr@605
   253
            return False
morphbr@605
   254
morphbr@605
   255
        if not self._run_mencoder(input=self.gmyth.stdout, output=subprocess.PIPE):
morphbr@605
   256
            return False
morphbr@605
   257
morphbr@628
   258
        show_loading = 0
morphbr@628
   259
        show = True
morphbr@628
   260
morphbr@628
   261
        #n800 150000 and 1000
morphbr@628
   262
morphbr@605
   263
        try:
morphbr@605
   264
            while self.proc and self.proc.poll() == None:
morphbr@630
   265
morphbr@630
   266
                r, w, x = select([self.proc.stdout], [], [], 0)
morphbr@605
   267
                if self.proc.stdout in r:
morphbr@605
   268
                    d = self.proc.stdout.read(4096)
morphbr@605
   269
                    outfd.write(d)
morphbr@630
   270
                #    self.log.debug("Sending tv data: %d" % show_loading)
morphbr@630
   271
                #    if show_loading > 150000 and show:
morphbr@630
   272
                #        self.log.debug("Disabling loading video")
morphbr@630
   273
                #        show = False
morphbr@628
   274
morphbr@630
   275
                #elif show_loading % 10000 == 0 and show:
morphbr@630
   276
                #    show_loading += 1
morphbr@630
   277
                #    d = open("loading.mpg")
morphbr@630
   278
                #    outfd.write(d.read())
morphbr@630
   279
                #    self.log.debug("Sendind loading video: %d" % show_loading)
morphbr@628
   280
morphbr@630
   281
                #else:
morphbr@630
   282
                #    show_loading += 1
morphbr@628
   283
morphbr@628
   284
                #self.log.debug("SHOW_LOADING: %d" % show_loading)
morphbr@628
   285
morphbr@605
   286
        except Exception, e:
morphbr@605
   287
            self.log.error("Problems handling data: %s" % e)
morphbr@605
   288
            return False
morphbr@605
   289
morphbr@605
   290
        return True
morphbr@605
   291
    # _start_myth()
morphbr@605
   292
morphbr@605
   293
    def _run_mencoder(self, input=None, output=None):
morphbr@605
   294
        try:
morphbr@605
   295
            self.proc = subprocess.Popen(self.mencoder_opts, stdin=input,
morphbr@605
   296
                                         stdout=output, close_fds=True)
morphbr@605
   297
        except Exception, e:
morphbr@605
   298
            self.log.error("Error executing mencoder: %s" % e)
morphbr@605
   299
            return False
morphbr@605
   300
morphbr@605
   301
        return True
morphbr@605
   302
    # _run_mencoder()
morphbr@595
   303
morphbr@595
   304
    def start(self, outfd):
morphbr@595
   305
        cmd = " ".join(self.mencoder_opts)
morphbr@595
   306
        self.log.debug("Mencoder: %s" % cmd)
morphbr@595
   307
morphbr@605
   308
        ret = False
morphbr@605
   309
morphbr@605
   310
        if self.args["outfile"] == "-" and self.args["type"] in ["file", "dvd"]:
morphbr@605
   311
            ret = self._start(outfd)
morphbr@605
   312
morphbr@605
   313
        elif self.args["type"] == "myth":
morphbr@605
   314
            ret = self._start_myth(outfd)
morphbr@605
   315
morphbr@595
   316
        else:
morphbr@605
   317
            ret = self._start_outfile(outfd)
morphbr@605
   318
morphbr@605
   319
        self.stop()
morphbr@605
   320
        return ret
morphbr@565
   321
    # start()
morphbr@565
   322
morphbr@565
   323
morphbr@565
   324
    def stop(self):
morphbr@565
   325
        if self.proc:
morphbr@565
   326
            try:
morphbr@605
   327
                os.kill(self.proc.pid, signal.SIGKILL)
morphbr@565
   328
            except OSError, e:
morphbr@565
   329
                pass
morphbr@565
   330
morphbr@565
   331
            try:
morphbr@565
   332
                self.proc.wait()
morphbr@565
   333
            except Exception, e:
morphbr@565
   334
                pass
morphbr@565
   335
morphbr@565
   336
            self.proc = None
morphbr@605
   337
morphbr@605
   338
        if self.gmyth:
morphbr@605
   339
            try:
morphbr@605
   340
                os.kill(self.gmyth.pid, signal.SIGKILL)
morphbr@605
   341
            except OSError, e:
morphbr@605
   342
                pass
morphbr@605
   343
morphbr@605
   344
            try:
morphbr@605
   345
                self.gmyth.wait()
morphbr@605
   346
            except Exception, e:
morphbr@605
   347
                pass
morphbr@605
   348
morphbr@605
   349
            self.gmyth = None
morphbr@605
   350
morphbr@569
   351
    # stop()
morphbr@565
   352
morphbr@565
   353
# TranscoderMencoder