# Transmageddon
# Copyright (C) 2009-2011 Christian Schaller <uraeus@gnome.org>
# 
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This librarmy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import sys
import os
from gi.repository import GObject
GObject.threads_init()
from gi.repository import GLib
from gi.repository import Gst
Gst.init(None)
from gi.repository import GstPbutils

os.environ["GST_DEBUG_DUMP_DOT_DIR"] = "/tmp"

class Mixer(GObject.GObject):

   __gsignals__ = {
            'ready-for-querying' : (GObject.SignalFlags.RUN_LAST, None, []),
            'got-eos' : (GObject.SignalFlags.RUN_LAST, None, []),
            'missing-plugin' : (GObject.SignalFlags.RUN_LAST, None, []),
            'got-error' : (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,))
                    }

   def __init__(self):
       mainloop = GObject.MainLoop()
       GObject.GObject.__init__(self)
       
       self.streamcounter=0
       # Create transcoding pipeline
       self.pipeline = Gst.Pipeline()
       self.pipeline.set_state(Gst.State.PAUSED)

       self.videomixer = Gst.ElementFactory.make('videomixer', None)
       self.pipeline.add(self.videomixer)
       self.videomixer.set_state(Gst.State.PAUSED)

       self.audiomixer = Gst.ElementFactory.make('adder', None)
       self.pipeline.add(self.audiomixer)
       self.audiomixer.set_state(Gst.State.PAUSED)

       self.mediamuxer = Gst.ElementFactory.make("oggmux", None)
       self.pipeline.add(self.mediamuxer)
       self.mediamuxer.set_state(Gst.State.PAUSED)

       self.videoencoder = Gst.ElementFactory.make("theoraenc", None)
       self.pipeline.add(self.videoencoder)
       self.videoencoder.set_state(Gst.State.PAUSED)
 
       self.audioencoder = Gst.ElementFactory.make("speexenc", None)
       self.pipeline.add(self.audioencoder)
       self.audioencoder.set_state(Gst.State.PAUSED)

       self.filesink = Gst.ElementFactory.make("filesink", None)
       self.filesink.set_property("location","/tmp/test.ogg")
       self.pipeline.add(self.filesink)

       self.videobox1 = Gst.ElementFactory.make('videobox', None)
       self.videobox1.set_property("border-alpha",0)
       self.videobox1.set_property("top",0)
       self.videobox1.set_property("left",-320)
       self.pipeline.add(self.videobox1)
       self.videobox1.set_state(Gst.State.PAUSED)

       self.videoformatconverter1 = Gst.ElementFactory.make('videoconvert', None)
       self.pipeline.add(self.videoformatconverter1)
       self.videoformatconverter1.set_state(Gst.State.PAUSED)

       self.videoformatconverter2 = Gst.ElementFactory.make('videoconvert', None)
       self.pipeline.add(self.videoformatconverter2)
       self.videoformatconverter2.set_state(Gst.State.PAUSED)


       self.videomixer.link(self.videoencoder)
       self.videoencoder.link(self.mediamuxer)
       self.audiomixer.link(self.audioencoder)
       self.audioencoder.link(self.mediamuxer)
       self.mediamuxer.link(self.filesink)

       self.uridecoder = Gst.ElementFactory.make("uridecodebin", "uridecoder")
       self.uridecoder.set_property("uri", "file:///tmp/test.mkv" )
       self.uridecoder.connect("pad-added", self.OnDynamicPad)
       self.pipeline.add(self.uridecoder)
       self.uridecoder.set_state(Gst.State.PAUSED)

       # we need to wait on this one before going further
       self.uridecoder.connect("no-more-pads", self.noMorePads)

       self.BusMessages = self.BusWatcher()

       mainloop.run()

   def noMorePads(self, dbin):
       print("No more pads")
       Gst.debug_bin_to_dot_file (self.pipeline, Gst.DebugGraphDetails.ALL, 'mixer-debug-graph.dot')
       self.filesink.set_state(Gst.State.PAUSED)
       GLib.idle_add(self.idlePlay)

   def idlePlay(self):
        print("going to playing")
        self.pipeline.set_state(Gst.State.PLAYING)

   def BusWatcher(self):
     bus = self.pipeline.get_bus()
     bus.add_signal_watch()
     bus.connect('message', self.on_message)

   def on_message(self, bus, message):
       mtype = message.type
       if mtype == Gst.MessageType.ERROR:
           print("we got an error, life is shit")
           err, debug = message.parse_error()
           print(err) 
           print(debug)
           Gst.debug_bin_to_dot_file (self.pipeline, \
           Gst.DebugGraphDetails.ALL, 'transmageddon-debug-graph')
       elif mtype == Gst.MessageType.ELEMENT:
           if GstPbutils.is_missing_plugin_message(message):
               if self.missingplugin==False:
                   self.missingplugin=message
                   self.emit('missing-plugin')
           
       elif mtype == Gst.MessageType.ASYNC_DONE:
           self.emit('ready-for-querying')
       elif mtype == Gst.MessageType.EOS:
           self.emit('got-eos')
           self.pipeline.set_state(Gst.State.NULL)
       elif mtype == Gst.MessageType.APPLICATION:
           self.pipeline.set_state(Gst.State.NULL)
           self.pipeline.remove(self.uridecoder)
       return True

   def OnDynamicPad(self, uridecodebin, src_pad):
       origin = src_pad.query_caps(None)
       c = origin.to_string()
       if not c.startswith("text/"):
               if c.startswith("audio/"):
                   x=self.audiomixer.get_compatible_pad(src_pad, None)
                   src_pad.link(x)
               elif (c.startswith("video/") or c.startswith("image/")):
                   if self.streamcounter==0:
                       videoboxpad=self.videoformatconverter1.get_compatible_pad(src_pad, None)
                       src_pad.link(videoboxpad)
                       self.videoformatconverter1.link(self.videobox1)
                       self.videobox1.link(self.videomixer)
                       self.streamcounter=1
                   else:
                       videomixpad=self.videoformatconverter2.get_compatible_pad(src_pad, None)
                       src_pad.link(videomixpad)
                       factory=self.videoformatconverter2.get_factory()
                       pad_template=factory.get_static_pad_templates()
                       for x in pad_template:
                           caps=x.get_caps()
                           print("incoming caps are " +c)
                           print("videomix caps are " + caps.to_string())
                       self.videoformatconverter2.link(self.videomixer)

   def debug_cb(self, action, parameter):
       dotfile = "/tmp/proto4.dot"
       pngfile = "/tmp/proto4.png"
       if os.access(dotfile, os.F_OK):
           os.remove(dotfile)
       if os.access(pngfile, os.F_OK):
           os.remove(pngfile)
       Gst.debug_bin_to_dot_file (Mixer.pipeline, \
               Gst.DebugGraphDetails.ALL, 'mixer-debug-graph')
       # check if graphviz is installed with a simple test
       try:
           dot = which.which("dot")
           os.system(dot + " -Tpng -o " + pngfile + " " + dotfile)
       except which.WhichError:
              print("The debug feature requires graphviz (dot) to be installed.")
              print("Transmageddon can not find the (dot) binary.")


if __name__ == "__main__":
    app = Mixer()
