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