# 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
os.environ["GST_DEBUG_DUMP_DOT_DIR"] = "/tmp"
import time
from gi.repository import GObject
from gi.repository import GLib
from gi.repository import Gst
Gst.init(None)
from gi.repository import GstPbutils


class Transcoder(GObject.GObject):
   def __init__(self):
       mainloop = GObject.MainLoop()
       GObject.GObject.__init__(self)

       self.pipeline = Gst.Pipeline()
       self.pipeline.set_state(Gst.State.PAUSED)
      
       self.videoencoder =  Gst.ElementFactory.make('theoraenc', None)
       self.muxer = Gst.ElementFactory.make('oggmux', None)
       self.audioencoder = Gst.ElementFactory.make('vorbisenc', None)

       factory=self.audioencoder.get_factory()
       if factory != None:
           tagyes = factory.has_interface("GstTagSetter")
           if tagyes ==True:
               taglistbob=Gst.TagList.new_empty()
               taglistbob.add_value(Gst.TagMergeMode.APPEND, Gst.TAG_APPLICATION_NAME, "Transmageddon transcoder")
               taglistbob.add_value(Gst.TagMergeMode.APPEND, Gst.TAG_LANGUAGE_CODE, "af")  
               taglistbob.add_value(Gst.TagMergeMode.APPEND, Gst.TAG_LANGUAGE_NAME, "Afrikaans")
               print(taglistbob.to_string())
               self.audioencoder.merge_tags(taglistbob, Gst.TagMergeMode.REPLACE)



       self.audioconvert = Gst.ElementFactory.make('audioconvert', "audio")
       self.videoconvert = Gst.ElementFactory.make('videoconvert', "video")
       
       self.transcodefileoutput = Gst.ElementFactory.make("filesink", \
               "transcodefileoutput")
       self.transcodefileoutput.set_property("location", "/tmp/video.ogg")
       self.pipeline.add(self.transcodefileoutput)

       self.pipeline.add(self.audioconvert)
       self.pipeline.add(self.videoconvert)
       self.pipeline.add(self.videoencoder)
       self.pipeline.add(self.audioencoder)
       self.pipeline.add(self.muxer)

       self.audioconvert.set_state(Gst.State.PAUSED)
       self.videoconvert.set_state(Gst.State.PAUSED)
       self.audioencoder.set_state(Gst.State.PAUSED)
       self.videoencoder.set_state(Gst.State.PAUSED)
       self.muxer.set_state(Gst.State.PAUSED)

       self.audioconvert.link(self.audioencoder)
       self.videoconvert.link(self.videoencoder)
       self.audioencoder.link(self.muxer)
       self.videoencoder.link(self.muxer)
       self.muxer.link(self.transcodefileoutput)
       
       self.uridecoder = Gst.ElementFactory.make("uridecodebin", "uridecoder")
       self.uridecoder.set_property("uri", "file:///home/cschalle/Videos/gravity.mpg")
       self.uridecoder.connect("pad-added", self.OnDynamicPad)
       self.uridecoder.connect("no-more-pads", self.noMorePads)
       print("set decoder to paused")
       self.uridecoder.set_state(Gst.State.PAUSED)
       self.pipeline.add(self.uridecoder)

       mainloop.run()

   def noMorePads(self, dbin):
       print("no more pads")
       self.transcodefileoutput.set_state(Gst.State.PAUSED)
       GLib.idle_add(self.idlePlay)

   def idlePlay(self):
        print("going to playing")
        Gst.debug_bin_to_dot_file (self.pipeline, \
               Gst.DebugGraphDetails.ALL, 'test-graph')
        self.pipeline.set_state(Gst.State.PLAYING)
        return False

   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/"):
                    print("got audio")
                    src_pad.link(self.audioconvert.get_static_pad("sink"))
               elif (c.startswith("video/") or c.startswith("image/")):
                    src_pad.link(self.videoconvert.get_static_pad("sink"))
 
   def OnEncodebinElementAdd(self, encodebin, element):
       factory=element.get_factory()
       if factory != None:
          # Set Transmageddon as Application name using Tagsetter interface
           tagyes = factory.has_interface("GstTagSetter")
           if tagyes ==True:
               taglistbob=Gst.TagList.new_empty()
               taglistbob.add_value(Gst.TagMergeMode.APPEND, Gst.TAG_APPLICATION_NAME, "Transmageddon transcoder")
               #element.merge_tags(taglist, Gst.TagMergeMode.REPLACE)
               #print("testing for audio encoder")
               #print(factory.get_element_type())
               #if Gst.ElementFactory.list_is_type(factory, 1125899906842626): # Audio Encoders factory code        
               #print("is audio encoder")
                   #taglist=Gst.TagList.new_empty()
               if self.audiodata[0]['languagecode'] != None:
                       taglistbob.add_value(Gst.TagMergeMode.APPEND, Gst.TAG_LANGUAGE_CODE, self.audiodata[0]['languagecode'])  # FIXME: Currently only doing 1 stream
                       taglistbob.add_value(Gst.TagMergeMode.APPEND, Gst.TAG_LANGUAGE_NAME, self.audiodata[0]['language'])
                       print(taglistbob.to_string())
                   #longname=factory.get_metadata('long-name')
                   #taglist.add_value(Gst.TagMergeMode.APPEND, Gst.TAG_ENCODER, longname)
               element.merge_tags(taglistbob, Gst.TagMergeMode.REPLACE)

if __name__ == "__main__":
    app = Transcoder()
    #signal.signal(signal.SIGINT, signal.SIG_DFL)
    # exit_status = app.run(sys.argv)
    #sys.exit(exit_status)

