gmyth-stream/server/0.2/plugins/transcoders/gstreamer.py
author rosfran
Tue May 15 22:14:04 2007 +0100 (2007-05-15)
branchtrunk
changeset 657 0469baf4217c
parent 573 f4927ca53da7
permissions -rw-r--r--
[svn r663] Added verification to GMYTH_FILE_READ_NEXT_PROG_CHAIN return values.
     1 #vim:ts=4:sw=4:et
     2 import pygst
     3 pygst.require("0.10")
     4 import gst
     5 import gobject
     6 import time
     7 import lib.utils as utils
     8 import lib.server as server
     9 
    10 from threading import Thread
    11 
    12 __all__ = ("TranscoderGstreamer",)
    13 
    14 class TranscoderGstreamer(server.Transcoder):
    15     gstreamer_path = utils.which("gst-launch-0.10")
    16     name = "gstreamer"
    17     priority = -2
    18 
    19     # StreamListener()
    20 
    21     class StreamData:
    22         stream_count = 0
    23 
    24         def __init__(self, log, pipe, abin, vbin, sink):
    25             self.log = log
    26             self.stream_count += 1
    27             self.Id = self.stream_count
    28             self.Pipe = pipe
    29             self.Abin = abin
    30             self.Vbin = vbin
    31             self.Sink = sink
    32             self.Loop = gobject.MainLoop()
    33             self.Ready = False
    34         # __init__()
    35 
    36     # StreamData()
    37 
    38 
    39     def __init__(self, params):
    40         server.Transcoder.__init__(self, params)
    41         gobject.threads_init ()
    42         # set gstreamer basic options
    43         self.connection = None
    44         self.addr = None
    45         self.ready = False
    46         self.log.debug("Params for Gstreamer: %s" % self.params)
    47     # __init__()
    48 
    49 
    50     def _create_start_elements(self, uri):
    51         self.log.debug("Opening Uri:" + uri)
    52         src = gst.element_make_from_uri(gst.URI_SRC, uri, "src")
    53         decode = gst.element_factory_make("decodebin", "decode")
    54         mux = gst.element_factory_make("ffmux_mpeg", "mux")
    55         sink = gst.element_factory_make("fdsink", "sink")
    56 
    57         return [src, decode, mux, sink]
    58     # _create_start_elements()
    59 
    60 
    61     def _setup_video_encode(self, vbin, width, height):
    62         vqueue = gst.element_factory_make("queue", "vqueue")
    63         colorspace = gst.element_factory_make("ffmpegcolorspace", "")
    64         vrate = gst.element_factory_make("videorate", "vrate")
    65         #vencode = gst.element_factory_make("ffenc_mpeg4", "vencode")
    66         vencode = gst.element_factory_make("ffenc_mpeg1video", "vencode")
    67         vqueue_src = gst.element_factory_make("queue", "vqueue_src")
    68 
    69         vencode.set_property("bitrate", 200)
    70         vencode.set_property ("pass", 2)
    71         vencode.set_property ("quantizer", 5)
    72 
    73         if None in [vbin, vqueue, vrate, vencode, vqueue_src]:
    74             self.log.error("Fail to create video encode elements.")
    75             return False
    76 
    77         vbin.add(vqueue)
    78         if int(width) > 0 and int(height) > 0:
    79             self.log.debug("Formating output to %d / %d" % ( int(width), int(height)))
    80 
    81             vscale = gst.element_factory_make("ffvideoscale", "vscale")
    82 
    83             vbin.add(vscale);
    84             if not vqueue.link(vscale):
    85                 self.log.error("Fail to link video elements")
    86                 return False
    87 
    88             vbin.add(colorspace)
    89 
    90             if not vscale.link(colorspace, \
    91                 gst.caps_from_string("video/x-raw-yuv,width=(int)%d,height=(int)%d" %(\
    92                 int(width), int(height)))):
    93                 self.log.error("Fail to link video elements")
    94                 return False
    95         else:
    96             vbin.add(colorspace)
    97             vqueue.link(colorspace)
    98 
    99         vbin.add(vrate, vencode, vqueue_src)
   100         if not colorspace.link(vrate):
   101             self.log.error("Fail to colorspace with vrate")
   102             return False
   103 
   104         if not vrate.link(vencode, \
   105             gst.caps_from_string("video/x-raw-yuv,framerate=(fraction)10/1")):
   106             self.log.error("Fail to link vrate element")
   107             return False
   108 
   109         if not vencode.link(vqueue_src):
   110             self.log.error("Fail to link video encode with queue")
   111             return False
   112 
   113         vbin.add_pad(gst.GhostPad("sink", vqueue.get_pad("sink")))
   114         vbin.add_pad(gst.GhostPad("src", vqueue_src.get_pad("src")))
   115 
   116         return True
   117     # _setup_video_encode()
   118 
   119 
   120     def _setup_audio_encode(self, abin):
   121         aqueue = gst.element_factory_make("queue", "aqueue")
   122         aconvert = gst.element_factory_make("audioconvert", "aconvert")
   123         #aencode = gst.element_factory_make("queue", "aencode")
   124         #aencode = gst.element_factory_make("ffenc_mp2", "aencode")
   125         aencode = gst.element_factory_make("lame", "aencode")
   126         aqueue_src = gst.element_factory_make("queue", "aqueue_src")
   127 
   128         if None in [abin, aqueue, aencode, aqueue_src]:
   129             self.log.error("Fail to create video encode elements.")
   130             return False
   131 
   132         #aencode.set_property ("bitrate", 32)
   133         #aencode.set_property ("vbr-quality", 2)
   134 
   135         abin.add(aqueue, aconvert, aencode, aqueue_src)
   136 
   137         self.log.debug("Link queue -> aconvert")
   138         if not aqueue.link (aconvert):
   139             self.log.error("Fail to link queue video")
   140             return False
   141 
   142         self.log.debug("Link aconvert -> aencode")
   143         if not aconvert.link (aencode):
   144             self.log.error("Fail to link video elements")
   145             return False
   146 
   147         self.log.debug("Link aencode -> aqueue_src")
   148         if not aencode.link (aqueue_src):
   149             self.log.error("Fail to link aencode -> aqueue_src")
   150             return False
   151 
   152         self.log.debug("Link:OK")
   153 
   154         ghost_sink = gst.GhostPad("sink", aqueue.get_pad("sink"))
   155         ghost_src = gst.GhostPad("src", aqueue_src.get_pad("src"))
   156         #ghost_src.set_caps (gst.caps_from_string ("audio/mpeg,mpegversion=(int)1,layer=(int)3,rate=(int)32000"))
   157         abin.add_pad(ghost_sink)
   158         abin.add_pad(ghost_src)
   159 
   160         return True
   161     # _setup_audio_encode()
   162 
   163 
   164     def setup(self, uri, mux, vcodec, vbitrate,
   165               fps, acodec, abitrate, width, height, options):
   166 
   167         ## Pipelines
   168         pipe = gst.Pipeline()
   169         src, decode, mux, sink = self._create_start_elements(uri)
   170 
   171         if None in [src, decode, mux, sink]:
   172             self.log.info("Problems with while starting basic elements");
   173             return False
   174 
   175         #video encode
   176         #queue ! videoscale ! video/x-raw-yuv,width=240,height=144 ! videorate !
   177         #ffenc_h263p bitrate=256000 me-method=2 ! rtph263ppay ! udpsink  host=224.0.0.1
   178         #port=5000
   179 
   180         vbin = gst.Bin()
   181         if not self._setup_video_encode(vbin, width, height):
   182             return False
   183 
   184         #audio encode
   185         #audio/x-raw-int ! queue ! audioconvert ! faac ! rtpmp4gpay !
   186         #udpsink name=upd_audio host=224.0.0.1 port=5002
   187 
   188         abin = gst.Bin()
   189         if not self._setup_audio_encode(abin):
   190             return False
   191 
   192         #Finish Pipeline
   193         pipe.add(src, decode, abin, vbin, mux, sink)
   194         gst.element_link_many(src, decode)
   195         gst.element_link_many(mux, sink)
   196 
   197         #Linking decode with mux
   198         mux_audio = mux.get_pad("audio_0")
   199         mux_video = mux.get_pad("video_0")
   200 
   201         audio_pad = abin.get_pad("src")
   202         video_pad = vbin.get_pad("src")
   203 
   204         if audio_pad.link(mux_audio) != gst.PAD_LINK_OK:
   205             self.log.error("Fail to link audio with mux")
   206             return False
   207 
   208         if video_pad.link(mux_video) != gst.PAD_LINK_OK:
   209             self.log.error("Fail to link audio with mux")
   210             return False
   211 
   212         self.stream_data = self.StreamData(self.log, pipe, abin, vbin, sink)
   213         bus = pipe.get_bus()
   214         bus.add_signal_watch()
   215         bus.connect("message", self.__on_bus_message, self.stream_data)
   216 
   217         decode.connect("new-decoded-pad", self.__on_decode_new_pad, self.stream_data)
   218         decode.connect("unknown-type", self.__on_decode_unknown_type, self.stream_data)
   219 
   220         self.log.info("Setting PIPELINE state to PAUSED")
   221         pipe.set_state(gst.STATE_PAUSED)
   222         self.log.info("Running Loop")
   223         self.stream_data.Loop.run()
   224     # setup()
   225 
   226     def __on_bus_message(self, bus, message, stream_data):
   227 
   228         t = message.type
   229         self.log.debug("__on_bus_message")
   230 
   231         if t == gst.MESSAGE_STATE_CHANGED:
   232             oldstate = -1
   233             newstate = -1
   234             pending = -1
   235 
   236             oldstate, newstate, pending = message.parse_state_changed()
   237 
   238             if oldstate == gst.STATE_READY and \
   239                newstate == gst.STATE_PAUSED and \
   240                pending == gst.STATE_VOID_PENDING and \
   241                stream_data.Ready == False:
   242 
   243                 state_changed_status, current_state, pending_state = stream_data.Pipe.get_state()
   244                 if current_state == gst.STATE_PAUSED and \
   245                     pending_state == gst.STATE_VOID_PENDING:
   246                     self.log.info("Pipe paused")
   247                     stream_data.Loop.quit()
   248                     stream_data.Ready = True
   249 
   250         elif t == gst.MESSAGE_EOS:
   251             self.log.info("Pipe finished")
   252             if stream_data.Ready:
   253                 self.stop()
   254             else:
   255                 stream_data.Loop.quit()
   256 
   257         elif t == gst.MESSAGE_ERROR:
   258             err, debug = message.parse_error()
   259             self.log.error("Error: %s %s" %(err, debug))
   260             if stream_data.Ready:
   261                 self.stop()
   262             else:
   263                 stream_data.Loop.quit()
   264 
   265         return True
   266     # __on_bus_message()
   267 
   268     def __on_decode_unknown_type(self, decode, pad, caps, stream_data):
   269         self.log.info("Unknown Type")
   270         return None
   271     # __on_decode_unknown_type
   272 
   273     def __on_decode_new_pad(self, decode, pad, arg1, stream_data):
   274 
   275         caps = pad.get_caps().to_string()
   276         self.log.debug("New pad " + caps)
   277         if caps.rfind("audio") != -1:
   278             apad = stream_data.Abin.get_pad("sink")
   279             if pad.link(apad) != gst.PAD_LINK_OK:
   280                 self.log.error("Error on link audio pad")
   281                 return None
   282         elif caps.rfind("video") != -1:
   283             vpad = stream_data.Vbin.get_pad("sink")
   284             if pad.link(vpad) != gst.PAD_LINK_OK:
   285                 self.log.error("Error on link video pad")
   286                 return None
   287         else:
   288             self.log.error("Invalid caps")
   289         self.log.debug("Linked")
   290     # __on_decode_new_pad
   291 
   292 
   293     def start(self, outfd):
   294         params_first = self.params_first
   295 
   296         uri = '%s://%s' % (params_first("uri_prefix", ""), params_first("uri_path", ""))
   297         self.setup(uri, params_first("mux", "avi"),
   298                    params_first("vcodec", "ffenc_h263p"), params_first("vbitrate", 256000),
   299                    params_first("fps", 25),  params_first("acodec", "faac"),
   300                    params_first("abitrate", 192000),  params_first("width", 320),
   301                    params_first("height", 240), params_first("options", ""))
   302 
   303         self.log.debug("Play %s", outfd.fileno())
   304         self.stream_data.Sink.set_property("fd", outfd.fileno())
   305         self.log.info("Setting Pipeline state to PLAYING")
   306         self.stream_data.Pipe.set_state(gst.STATE_PLAYING)
   307 
   308         # keep playing until EOS
   309         self.stream_data.Loop.run()
   310         return True
   311     # start()
   312 
   313     def stop(self):
   314         self.log.info("Stop stream_data: %s" % self.stream_data)
   315 
   316         if self.stream_data:
   317             self.stream_data.Pipe.set_state(gst.STATE_NULL)
   318 
   319         self.stream_data.Ready = False
   320         self.stream_data.Loop.quit ()
   321         del self.stream_data
   322         self.stream_data = None
   323         time.sleep (2)
   324     # stop