gmyth-stream/server/0.3/plugins/transcoders/mencoder.py
author morphbr
Tue May 29 21:24:48 2007 +0100 (2007-05-29)
branchtrunk
changeset 718 3fbcd3d9b2d1
child 723 f5f7abc760aa
permissions -rw-r--r--
[svn r724] * GMyth-Streamer version 0.3 released
- Improved Log architecture;
- Creation of a history for the transcoder's actions
- Creation of an id for each transcoder instanciated
- Also wrapps default actions for python's default logger

- Created new functions to make use of this new Log architecture;
- serve_new_id
- serve_get_log
- serve_get_all_log

- _Lot_ of small bug fixes;

- Inserted header for all files;

- Splited files with too many lines (more than 1 class per file)
in more files;
     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         self._arg_append(args, "-o %s" % self.args["outfile"])
   124         self._arg_append(args, "2>%s" % os.devnull)
   125     # _setup_args()
   126 
   127     def _setup_filename(self):
   128         """This function setups the file to encode parsing the uri.
   129         So, type can be:
   130         * file
   131         * dvd
   132         * myth
   133 
   134         If the last one is detected we have to parse the uri to find args.
   135         Then we store all the args inside a dictionary: self.args['gmyth-cat']
   136         """
   137         _type = self.args["type"]
   138 
   139         if _type == "file":
   140             if not os.path.exists(self.args["input"]):
   141                 raise IOError,\
   142                       "File requested does not exist: %s." % self.args["input"]
   143             else:
   144                 self.args["input"] = "file://%s" % self.args["input"]
   145 
   146         elif _type == "dvd":
   147             self.args["input"] = "dvd://".join(self.args["input"])
   148 
   149         elif _type == "myth":
   150             self.args["gmyth-cat"] = mythtv._setup_mythfilename(self)
   151     # _setup_filename()
   152 
   153 
   154     def __init__(self, params):
   155         transcoder.Transcoder.__init__(self, params)
   156         self.mencoder_opts = []
   157 
   158         try:
   159             self._setup_params()
   160             self._setup_filename()
   161             self._setup_mencoder_opts(self.mencoder_opts)
   162         except Exception, e:
   163             self.log.error(self.tid, e)
   164     # __init__()
   165 
   166 
   167     def _check_opened_file(self, stdw, _stdin):
   168         loop = True
   169         while loop:
   170             try:
   171                 return open(self.args["outfile"])
   172             except:
   173                 os.write(stdw, _stdin.read(1024))
   174     # _check_opened_file
   175 
   176 
   177     def _start_outfile(self, outfd):
   178         finished = False
   179 
   180         # fix this (not necessary)
   181         outfd.write("OK")
   182 
   183         # Configuring stdin
   184         try:
   185             _stdin = open(self.args["input"])
   186             size = int(os.path.getsize(self.args["input"]))
   187         except Exception, e:
   188             self.log.error(self.tid, "Mencoder stdin setup error: %s" % e)
   189             return False
   190 
   191         self.status = 0
   192         total_read = 0
   193 
   194         # Configuring pipes
   195         stdr, stdw = os.pipe()
   196 
   197         if not self._run_mencoder(input=stdr):
   198             return False
   199 
   200         stdout = self._check_opened_file(stdw, _stdin)
   201 
   202         try:
   203             while self.proc and self.proc.poll() == None:
   204                 if not finished:
   205                     data_in = _stdin.read(4096)
   206                     if data_in != "":
   207                         os.write(stdw, data_in)
   208                         total_read += 4096
   209                         d = stdout.read(4096)
   210                         self.status = utils.progress_bar(self.log,
   211                                                          int(total_read),
   212                                                          int(size), 50)
   213                     else:
   214                         finished = True
   215                         os.close(stdw)
   216 
   217                 else:
   218                     d = stdout.read(4096)
   219 
   220         except Exception, e:
   221             self.log.error(self.tid, "Problems handling data: %s" % e)
   222             self.stop()
   223             return False
   224 
   225         self.log.info(self.tid, "%s: Finished sending data to client" % repr(self))
   226         return True
   227     # _start_outfile()
   228 
   229     def _start(self, outfd):
   230         # Play a file on disk or DVD
   231         if not self._run_mencoder(output=subprocess.PIPE):
   232             return False
   233 
   234         try:
   235             while self.proc and self.proc.poll() == None:
   236                 d = self.proc.stdout.read(1024)
   237                 outfd.write(d)
   238         except Exception, e:
   239             self.log.error(self.tid, "Problems handling data: %s" % e)
   240             return False
   241 
   242         self.log.info(self.tid, "%s: Finished sending data to client" % repr(self))
   243         return True
   244     # _start()
   245 
   246     def _run_mencoder(self, input=None, output=None):
   247         try:
   248             self.proc = subprocess.Popen(self.mencoder_opts, stdin=input,
   249                                          stdout=output, close_fds=True)
   250         except Exception, e:
   251             self.log.error(self.tid, "Error executing mencoder: %s" % e)
   252             return False
   253 
   254         return True
   255     # _run_mencoder()
   256 
   257     def start(self, outfd):
   258         cmd = " ".join(self.mencoder_opts)
   259         self.log.debug(self.tid, "Plugin's tid: %s" % self.tid)
   260         self.log.debug(self.tid, "Mencoder: %s" % cmd)
   261         #fixme
   262 
   263         ret = False
   264 
   265         if self.args["outfile"] == "-" and \
   266                self.args["type"] in ["file", "dvd"]:
   267             ret = self._start(outfd)
   268 
   269         elif self.args["type"] == "myth":
   270             ret = mythtv.start_myth(self, outfd)
   271 
   272         else:
   273             ret = self._start_outfile(outfd)
   274 
   275         self.stop()
   276 
   277         if not ret:
   278             self.log.error(self.tid, "Problems while starting streaming.")
   279 
   280         return ret
   281     # start()
   282 
   283     def _aux_stop(self, obj, next=False):
   284         if obj:
   285             try:
   286                 os.kill(obj.pid, signal.SIGKILL)
   287                 if next:
   288                     os.kill(obj.pid+1, signal.SIGKILL)
   289             except OSError, e:
   290                 pass
   291 
   292             try:
   293                 obj.wait()
   294             except Exception, e:
   295                 pass
   296 
   297             obj = None
   298     # _aux_stop
   299 
   300     def stop(self):
   301         self._aux_stop(self.proc, True)
   302         self._aux_stop(self.gmyth)
   303     # stop()
   304 
   305 # TranscoderMencoder