gmyth-stream/server/0.3/plugins/transcoders/mencoder.py
author morphbr
Fri Jun 01 15:01:43 2007 +0100 (2007-06-01)
branchtrunk
changeset 737 fe8df7fd5229
parent 736 1bc4c47e4ad8
child 738 293e6c9546e5
permissions -rw-r--r--
[svn r743] Tests with tv
morphbr@718
     1
#!/usr/bin/env python
morphbr@718
     2
morphbr@718
     3
__author__ = "Artur Duque de Souza"
morphbr@718
     4
__author_email__ = "artur.souza@indt.org.br"
morphbr@718
     5
__license__ = "GPL"
morphbr@718
     6
__version__ = "0.1"
morphbr@718
     7
morphbr@718
     8
import os
morphbr@718
     9
import shlex
morphbr@718
    10
import signal
morphbr@718
    11
import subprocess
morphbr@718
    12
import time
morphbr@718
    13
import fcntl
morphbr@718
    14
morphbr@718
    15
import lib.utils as utils
morphbr@718
    16
import lib.server as server
morphbr@718
    17
import plugins.transcoders.mencoder_lib.mythtv as mythtv
morphbr@718
    18
morphbr@718
    19
from select import select
morphbr@718
    20
import lib.transcoder as transcoder
morphbr@718
    21
morphbr@718
    22
__all__ = ("TranscoderMencoder",)
morphbr@718
    23
morphbr@718
    24
class TranscoderMencoder(transcoder.Transcoder):
morphbr@718
    25
    """Transcoder class that implements a transcoder using Mencoder"""
morphbr@718
    26
    mencoder_path = utils.which("mencoder")
morphbr@718
    27
    name = "mencoder"
morphbr@718
    28
    priority = -1
morphbr@718
    29
    args = {}
morphbr@718
    30
    proc = None
morphbr@718
    31
    gmyth = None
morphbr@718
    32
morphbr@718
    33
    # only works with avi container
morphbr@718
    34
    status = 0
morphbr@718
    35
morphbr@718
    36
    def _setup_params(self):
morphbr@718
    37
        params_first = self.params_first
morphbr@718
    38
morphbr@718
    39
        # general_opts
morphbr@718
    40
        self.args["local"]    = params_first("local", False)
morphbr@718
    41
        self.args["language"] = params_first("language", False)
morphbr@718
    42
        self.args["subtitle"] = params_first("subtitle", False)
morphbr@718
    43
        self.args["format"]   = params_first("format", "mpeg1")
morphbr@718
    44
        self.args["outfile"]  = params_first("outfile", "-")
morphbr@718
    45
morphbr@718
    46
        # input_opt
morphbr@718
    47
        self.args["type"]     = params_first("type", "file")
morphbr@718
    48
        self.args["input"]    = params_first("uri", "-")
morphbr@718
    49
morphbr@718
    50
        # audio_opts
morphbr@718
    51
        self.args["acodec"]   = params_first("acodec", "mp2")
morphbr@718
    52
        self.args["abitrate"] = params_first("abitrate", 192)
morphbr@718
    53
        self.args["volume"]   = params_first("volume", 5)
morphbr@718
    54
morphbr@718
    55
        # video_opts
morphbr@718
    56
        self.args["mux"]      = params_first("mux", "mpeg")
morphbr@718
    57
        self.args["fps"]      = params_first("fps", 25)
morphbr@718
    58
        self.args["vcodec"]   = params_first("vcodec", "mpeg1video")
morphbr@718
    59
        self.args["vbitrate"] = params_first("vbitrate", 400)
morphbr@718
    60
        self.args["width"]    = params_first("width", 320)
morphbr@718
    61
        self.args["height"]   = params_first("height", 240)
morphbr@718
    62
    # _setup_params()
morphbr@718
    63
morphbr@718
    64
morphbr@718
    65
    def _setup_audio(self):
morphbr@718
    66
        if self.args["acodec"] == "mp3lame":
morphbr@718
    67
            audio = "-oac mp3lame -lameopts cbr:br=%s vol=%s" % (
morphbr@718
    68
                self.args["abitrate"], self.args["volume"])
morphbr@718
    69
        else:
morphbr@718
    70
            audio = "-oac lavc -lavcopts acodec=%s:abitrate=%s" % (
morphbr@718
    71
                self.args["acodec"], self.args["abitrate"])
morphbr@718
    72
morphbr@718
    73
        return audio
morphbr@718
    74
    # _setup_audio()
morphbr@718
    75
morphbr@718
    76
morphbr@718
    77
    def _setup_video(self):
morphbr@718
    78
        video = " -of %s" % self.args["mux"]
morphbr@718
    79
        video += " -ofps %s" % self.args["fps"]
morphbr@718
    80
morphbr@718
    81
        vcodec = self.args["vcodec"]
morphbr@718
    82
        if vcodec == "nuv" or vcodec == "xvid"\
morphbr@718
    83
               or vcodec == "qtvideo" or vcodec == "copy":
morphbr@718
    84
            video += " -ovc %s" % vcodec
morphbr@718
    85
        else:
morphbr@718
    86
            video += " -ovc lavc -lavcopts vcodec=%s:vbitrate=%s" % (
morphbr@718
    87
                vcodec, self.args["vbitrate"])
morphbr@718
    88
morphbr@718
    89
        if self.args["mux"] == "mpeg":
morphbr@718
    90
            video += " -mpegopts format=%s" % self.args["format"]
morphbr@736
    91
morphbr@718
    92
        video += " -vf scale=%s:%s" % (self.args["width"], self.args["height"])
morphbr@718
    93
        return video
morphbr@718
    94
    # _setup_video()
morphbr@718
    95
morphbr@718
    96
morphbr@718
    97
    def _arg_append(self, args, options):
morphbr@718
    98
        for arg in shlex.split(options):
morphbr@718
    99
            args.append(arg)
morphbr@718
   100
    # arg_append()
morphbr@718
   101
morphbr@718
   102
    def _setup_mencoder_opts(self, args):
morphbr@718
   103
        args.append(self.mencoder_path)
morphbr@718
   104
morphbr@718
   105
        if self.args["outfile"] == "-" and self.args["type"]:
morphbr@718
   106
            args.append(self.args["input"])
morphbr@718
   107
        else:
morphbr@718
   108
            args.append("-")
morphbr@718
   109
morphbr@718
   110
        if self.args["language"]:
morphbr@718
   111
            self._arg_append(args, "-alang %s" % self.args["language"])
morphbr@718
   112
morphbr@718
   113
        if self.args["subtitle"]:
morphbr@718
   114
            self._arg_append(args, "-slang %s" % self.args["subtitle"])
morphbr@718
   115
            self._arg_append(args, "-subfps %s" % self.args["fps"])
morphbr@718
   116
morphbr@718
   117
        self._arg_append(args, "-idx")
morphbr@718
   118
        self._arg_append(args, "-cache 1024")
morphbr@718
   119
        self._arg_append(args, self._setup_audio())
morphbr@718
   120
        self._arg_append(args, self._setup_video())
morphbr@718
   121
morphbr@718
   122
        self._arg_append(args, "-really-quiet")
morphbr@723
   123
morphbr@723
   124
        if self.args["outfile"] != "-":
morphbr@723
   125
            self.args["outfile"] = ".transcoded/%s" % (
morphbr@723
   126
                                   os.path.basename(self.args["outfile"]))
morphbr@723
   127
morphbr@718
   128
        self._arg_append(args, "-o %s" % self.args["outfile"])
morphbr@718
   129
        self._arg_append(args, "2>%s" % os.devnull)
morphbr@718
   130
    # _setup_args()
morphbr@718
   131
morphbr@718
   132
    def _setup_filename(self):
morphbr@718
   133
        """This function setups the file to encode parsing the uri.
morphbr@718
   134
        So, type can be:
morphbr@718
   135
        * file
morphbr@718
   136
        * dvd
morphbr@718
   137
        * myth
morphbr@718
   138
morphbr@718
   139
        If the last one is detected we have to parse the uri to find args.
morphbr@718
   140
        Then we store all the args inside a dictionary: self.args['gmyth-cat']
morphbr@718
   141
        """
morphbr@718
   142
        _type = self.args["type"]
morphbr@718
   143
morphbr@718
   144
        if _type == "file":
morphbr@718
   145
            if not os.path.exists(self.args["input"]):
morphbr@718
   146
                raise IOError,\
morphbr@718
   147
                      "File requested does not exist: %s." % self.args["input"]
morphbr@718
   148
            else:
morphbr@718
   149
                self.args["input"] = "file://%s" % self.args["input"]
morphbr@718
   150
morphbr@718
   151
        elif _type == "dvd":
morphbr@736
   152
            self.args["input"] = "dvd://%s" % self.args["input"]
morphbr@718
   153
morphbr@718
   154
        elif _type == "myth":
morphbr@718
   155
            self.args["gmyth-cat"] = mythtv._setup_mythfilename(self)
morphbr@736
   156
morphbr@736
   157
        elif _type == "tv":
morphbr@736
   158
            driver = self.params_first("driver", "v4l2")
morphbr@736
   159
            norm = self.params_first("norm", "pal-m")
morphbr@736
   160
            channel = self.params_first("channel", "13")
morphbr@736
   161
            chanlist = self.params_first("chanlist", "us-bcast")
morphbr@736
   162
            outfmt = self.params_first("outfmt", "yuy2")
morphbr@736
   163
            vdev = self.params_first("vdev", "/dev/video0")
morphbr@736
   164
            adev = self.params_first("adev", "/dev/dsp")
morphbr@736
   165
            print "teste1"
morphbr@736
   166
            self.args["input"] = "tv:// -v -tv driver=%s:norm=%s:channel=%s:" \
morphbr@736
   167
                                 "chanlist=%s:width=%s:height=%s:outfmt=%s:" \
morphbr@736
   168
                                 "device=%s:adevice=%s" % (driver, norm,
morphbr@736
   169
                                                           channel, chanlist,
morphbr@736
   170
                                                           self.args["width"],
morphbr@736
   171
                                                           self.args["height"],
morphbr@736
   172
                                                           outfmt, vdev, adev)
morphbr@718
   173
    # _setup_filename()
morphbr@718
   174
morphbr@718
   175
morphbr@718
   176
    def __init__(self, params):
morphbr@718
   177
        transcoder.Transcoder.__init__(self, params)
morphbr@718
   178
        self.mencoder_opts = []
morphbr@718
   179
morphbr@718
   180
        try:
morphbr@718
   181
            self._setup_params()
morphbr@718
   182
            self._setup_filename()
morphbr@718
   183
            self._setup_mencoder_opts(self.mencoder_opts)
morphbr@718
   184
        except Exception, e:
morphbr@723
   185
            self.log.error(self.tid, "Error: %s" % e)
morphbr@718
   186
    # __init__()
morphbr@718
   187
morphbr@718
   188
morphbr@718
   189
    def _check_opened_file(self, stdw, _stdin):
morphbr@718
   190
        loop = True
morphbr@718
   191
        while loop:
morphbr@718
   192
            try:
morphbr@718
   193
                return open(self.args["outfile"])
morphbr@718
   194
            except:
morphbr@718
   195
                os.write(stdw, _stdin.read(1024))
morphbr@718
   196
    # _check_opened_file
morphbr@718
   197
morphbr@718
   198
morphbr@718
   199
    def _start_outfile(self, outfd):
morphbr@718
   200
        finished = False
morphbr@718
   201
morphbr@718
   202
        # Configuring stdin
morphbr@718
   203
        try:
morphbr@723
   204
            filename = self.args["input"].split("://")[1]
morphbr@723
   205
            _stdin = open(filename)
morphbr@723
   206
            size = int(os.path.getsize(filename))
morphbr@718
   207
        except Exception, e:
morphbr@723
   208
            self.log.error(self.tid, "Error: Mencoder stdin"\
morphbr@723
   209
                           " setup error: %s" % e)
morphbr@723
   210
            outfd.write("Error: Mencoder stdin setup error: %s" %e)
morphbr@718
   211
            return False
morphbr@718
   212
morphbr@718
   213
        self.status = 0
morphbr@718
   214
        total_read = 0
morphbr@718
   215
morphbr@718
   216
        # Configuring pipes
morphbr@718
   217
        stdr, stdw = os.pipe()
morphbr@718
   218
morphbr@718
   219
        if not self._run_mencoder(input=stdr):
morphbr@718
   220
            return False
morphbr@718
   221
morphbr@718
   222
        stdout = self._check_opened_file(stdw, _stdin)
morphbr@726
   223
        outfd.write("OK   ")
morphbr@726
   224
morphbr@718
   225
        try:
morphbr@718
   226
            while self.proc and self.proc.poll() == None:
morphbr@718
   227
                if not finished:
morphbr@718
   228
                    data_in = _stdin.read(4096)
morphbr@718
   229
                    if data_in != "":
morphbr@718
   230
                        os.write(stdw, data_in)
morphbr@718
   231
                        total_read += 4096
morphbr@718
   232
                        d = stdout.read(4096)
morphbr@723
   233
                        self.status = utils.progress_bar(int(total_read),
morphbr@718
   234
                                                         int(size), 50)
morphbr@718
   235
                    else:
morphbr@718
   236
                        finished = True
morphbr@718
   237
                        os.close(stdw)
morphbr@718
   238
morphbr@718
   239
                else:
morphbr@718
   240
                    d = stdout.read(4096)
morphbr@718
   241
morphbr@718
   242
        except Exception, e:
morphbr@723
   243
            self.log.error(self.tid, "Error: %s" % e)
morphbr@718
   244
            self.stop()
morphbr@718
   245
            return False
morphbr@718
   246
morphbr@723
   247
        self.log.info(self.tid, "OK: Done")
morphbr@718
   248
        return True
morphbr@718
   249
    # _start_outfile()
morphbr@718
   250
morphbr@736
   251
morphbr@718
   252
    def _start(self, outfd):
morphbr@718
   253
        # Play a file on disk or DVD
morphbr@718
   254
        if not self._run_mencoder(output=subprocess.PIPE):
morphbr@718
   255
            return False
morphbr@718
   256
morphbr@718
   257
        try:
morphbr@718
   258
            while self.proc and self.proc.poll() == None:
morphbr@718
   259
                d = self.proc.stdout.read(1024)
morphbr@718
   260
                outfd.write(d)
morphbr@718
   261
        except Exception, e:
morphbr@723
   262
            self.log.error(self.tid, "Error: %s" % e)
morphbr@718
   263
            return False
morphbr@718
   264
morphbr@723
   265
        self.log.info(self.tid, "OK: Done")
morphbr@718
   266
        return True
morphbr@718
   267
    # _start()
morphbr@718
   268
morphbr@737
   269
    def _run_mencoder(self, input=None, output=None, error=os.devnull):
morphbr@718
   270
        try:
morphbr@718
   271
            self.proc = subprocess.Popen(self.mencoder_opts, stdin=input,
morphbr@737
   272
                                         stdout=output, stderr=error,
morphbr@737
   273
                                         close_fds=True)
morphbr@718
   274
        except Exception, e:
morphbr@723
   275
            self.log.error(self.tid, "Error: Mencoder: %s" % e)
morphbr@718
   276
            return False
morphbr@718
   277
morphbr@718
   278
        return True
morphbr@718
   279
    # _run_mencoder()
morphbr@718
   280
morphbr@718
   281
    def start(self, outfd):
morphbr@718
   282
        cmd = " ".join(self.mencoder_opts)
morphbr@718
   283
        self.log.debug(self.tid, "Plugin's tid: %s" % self.tid)
morphbr@718
   284
        self.log.debug(self.tid, "Mencoder: %s" % cmd)
morphbr@718
   285
morphbr@718
   286
        ret = False
morphbr@718
   287
morphbr@718
   288
        if self.args["outfile"] == "-" and \
morphbr@736
   289
               self.args["type"] in ["file", "dvd", "tv"]:
morphbr@718
   290
            ret = self._start(outfd)
morphbr@718
   291
morphbr@718
   292
        elif self.args["type"] == "myth":
morphbr@718
   293
            ret = mythtv.start_myth(self, outfd)
morphbr@718
   294
morphbr@718
   295
        else:
morphbr@718
   296
            ret = self._start_outfile(outfd)
morphbr@718
   297
morphbr@718
   298
        self.stop()
morphbr@718
   299
morphbr@718
   300
        if not ret:
morphbr@723
   301
            self.log.error(self.tid, "Error: Problems while "\
morphbr@723
   302
                           "starting streaming.")
morphbr@718
   303
morphbr@718
   304
        return ret
morphbr@718
   305
    # start()
morphbr@718
   306
morphbr@718
   307
    def _aux_stop(self, obj, next=False):
morphbr@718
   308
        if obj:
morphbr@718
   309
            try:
morphbr@718
   310
                os.kill(obj.pid, signal.SIGKILL)
morphbr@718
   311
                if next:
morphbr@718
   312
                    os.kill(obj.pid+1, signal.SIGKILL)
morphbr@718
   313
            except OSError, e:
morphbr@718
   314
                pass
morphbr@718
   315
morphbr@718
   316
            try:
morphbr@718
   317
                obj.wait()
morphbr@718
   318
            except Exception, e:
morphbr@718
   319
                pass
morphbr@718
   320
morphbr@718
   321
            obj = None
morphbr@718
   322
    # _aux_stop
morphbr@718
   323
morphbr@718
   324
    def stop(self):
morphbr@718
   325
        self._aux_stop(self.proc, True)
morphbr@718
   326
        self._aux_stop(self.gmyth)
morphbr@718
   327
    # stop()
morphbr@718
   328
morphbr@718
   329
# TranscoderMencoder