#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
#    Copyright (c) 2007 Intel Corporation
#    Copyright (C) 2006,2007 Fluendo Embedded S.L. (www.fluendo.com).
#
#    NOTE:  Some of the code used in this file was pulled from the 
#           thumbnailer component in the Elisa home multimedia server 
#           via the GPL version 2 license
#
#    This program is free software; you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by the Free
#    Software Foundation; version 2 of the License
#
#    This program 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 General Public License
#    for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc., 59
#    Temple Place - Suite 330, Boston, MA 02111-1307, USA.


import dbus
import dbus.glib
import dbus.service
import gobject
import gc
import gtk
import Image
import ImageStat
import os
import pygst
import pygtk
import re
import string
import sys
import threading
import timeit
import types

pygst.require("0.10")
import gst

DBUS_INTERFACE_NAME = 'org.moblin.MobileMediaService'
ENG_NO_RENDERER, ENG_INVALID_PROTOCOL, \
                 ENG_INVALID_URL, \
                 ENG_CORRUPT_FILE, \
                 ENG_OUTOFMEMORY, \
                 ENG_OTHER_ERROR = range(0, 6) 

class VideoFrameError(Exception):
    def __init__(self, message):
        self.message = message

class VideoSinkBin(gst.Bin):
    def __init__(self, caps):
        self.reset()
        gst.Bin.__init__(self)
        capsfilter = gst.element_factory_make('capsfilter', 'capsfilter')
        capsfilter.set_property("caps", gst.caps_from_string(caps))
        self.add(capsfilter)
        fakesink = gst.element_factory_make('fakesink', 'fakesink')
        fakesink.set_property("sync", False)
        self.add(fakesink)
        capsfilter.link(fakesink)
        pad = capsfilter.get_pad("sink")
        ghostpad = gst.GhostPad("sink", pad)
        pad2probe = fakesink.get_pad("sink")
        pad2probe.add_buffer_probe(self.__buffer_probe)
        self.add_pad(ghostpad)

    def __buffer_probe(self, pad, buffer):
        if buffer.caps:
            self.width = buffer.caps[0]['width']
            self.height = buffer.caps[0]['height']
            if self.width and self.height and buffer:
                self.__current_frame = buffer.data
        return True

    def get_current_frame(self):
        frame = self.__current_frame
        self.__current_frame = None
        return frame
    
    def reset(self):
        self.width = 0
        self.height = 0
        self.__current_frame = None

gobject.type_register(VideoSinkBin)

class VideoFramePlayer:
    def __init__(self):
        self._pipeline = gst.element_factory_make('playbin', 'playbin')
        caps = "video/x-raw-rgb,bpp=24,depth=24"
        self._sink = VideoSinkBin(caps)
        self._blocker = threading.Event()
        self._pipeline.set_property("video-sink", self._sink)
        self._pipeline.set_property('volume', 0)

    def __seek_for_frame(self, duration , sink_size):
        frame_locations = [ 1.0 / 3.0, 2.0 / 3.0, 0.1, 0.9, 0.5 ]
        img=None
        for location in frame_locations:
            abs_location = int(location * duration)
            event = self._pipeline.seek(1.0, gst.FORMAT_TIME,
                                        gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_KEY_UNIT,
                                        gst.SEEK_TYPE_SET, abs_location,
                                        gst.SEEK_TYPE_NONE, 0)
            if not event:
              raise VideoFrameError("Not Seekable")

            if not self.set_state_blocking(self._pipeline, gst.STATE_PAUSED):
                raise VideoFrameError("Not Pausable")
            frame = self._sink.get_current_frame()
            img = Image.frombuffer("RGB", sink_size, frame, "raw", "RGB", 0, 1)
	
        self._sink.reset()
	self.set_state_blocking(self._pipeline, gst.STATE_NULL)
        if img.mode != 'RGBA':
            img = img.convert(mode='RGBA')
        img.save(self.output_file , 'png')
        return self.output_file

    def set_state_blocking(self, pipeline, state):
        res = False
        status = pipeline.set_state(state)
        if status == gst.STATE_CHANGE_ASYNC:
            attempts = 0
            while attempts < 100 and not res == gst.STATE_CHANGE_SUCCESS:
                attempts += 1
                res = pipeline.get_state(50*gst.MSECOND)[0]
        elif status == gst.STATE_CHANGE_SUCCESS:
            res = True
        return res

    def GetVideoFrame( self, uri , output_file ):
        try:
            self.set_state_blocking(self._pipeline, gst.STATE_NULL)
            self._pipeline.set_property('uri', uri)
            self.output_file = output_file
            self.set_state_blocking(self._pipeline, gst.STATE_PAUSED)
            duration = self._pipeline.query_duration(gst.FORMAT_TIME)[0] / gst.NSECOND
            res = self.__seek_for_frame(duration,
                                       (self._sink.width ,
                                        self._sink.height))
        except Exception, e:
            print "GetVideoFrame(%s) Error: %s" % (uri, e)
            res = ''
        self.set_state_blocking(self._pipeline, gst.STATE_NULL)
        return res

class Timer:
    def __init__(self, time, callback):
        self.__time = time
        self.__callback = callback
        self.__timeout_id = None

    def start(self):
        if self.__timeout_id == None:
            self.__timeout_id = gobject.timeout_add(self.__time, self.__callback)
            return True
        return False

    def stop(self):
        if self.__timeout_id != None:
            gobject.source_remove(self.__timeout_id)
            self.__timeout_id = None
            return True
        return False

    def restart(self):
        self.stop()
        self.start()
		
class MediaService(dbus.service.Object):
    def __init__(self):
        self.__xid = 0
        self.__width = 800
        self.__height = 600
        self.__name = 'org.moblin.MobileMediaService'
        self.__path = '/org/moblin/MobileMediaService'
	self.__player = gst.element_factory_make("playbin", "player")
        self.__recreate_window()
        gstbus = self.__player.get_bus()
        gstbus.enable_sync_message_emission()
        gstbus.add_signal_watch()
        gstbus.connect('message', self.__on_message)
        gstbus.connect('sync-message::element', self.__on_sync_message)
        bus_name = dbus.service.BusName(self.__name, bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, self.__path) 
        self.__vsink = None;
        self.__position_timer = Timer(500 , self.__pos_timer_cb )
	self.__frame_player = VideoFramePlayer()
	
    def __recreate_window(self):
        try:
            self.window.destory()
        except:
            pass
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title("Media-Player")
        window.set_position(gtk.WIN_POS_CENTER)
        window.set_default_size(self.__width, self.__height)
        window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN)
        window.connect("destroy", self.__on_destroy, "WM destroy")
        self.surface = gtk.DrawingArea()
        window.add(self.surface)
        self.window = window
	
    def __get_error_code(self, domain,  code):
        res = ENG_OTHER_ERROR
	if gst.STREAM_ERROR == domain:
            if code in [gst.STREAM_ERROR_CODEC_NOT_FOUND,
                        gst.STREAM_ERROR_DECODE,
                        gst.STREAM_ERROR_DEMUX]:
                res = ENG_NO_RENDERER
	    if gst.STREAM_ERROR_TYPE_NOT_FOUND == code:
    	        res = ENG_CORRUPT_FILE
        elif gst.RESOURCE_ERROR == domain:
    	    if gst.RESOURCE_ERROR_NOT_FOUND == code:
    	        res = ENG_INVALID_URL 
    	    if gst.RESOURCE_ERROR_FAILED == code:
    	        res = ENG_CORRUPT_FILE
            if code in [gst.RESOURCE_ERROR_OPEN_READ,
                        gst.RESOUCE_ERROR_OPEN_READ_WRITE,
                        gst.RESOURCE_ERROR_OPEN_WRITE]:
                res = ENG_INVALID_URL
	elif gst.CORE_ERROR == domain:
    	    if gst.CORE_MISSING_PLUGIN == code:
    	        res = ENG_NO_RENDERER
    	return res

    def __on_err_message( self, message ) :
            self.__player.set_state(gst.STATE_NULL)
            try:
                if self.__xid == self.surface.window.xid:
                    self.__xid = 0
                    self.window.destroy()
            except:
                pass
            err = message.parse_error()
            msg = err[0].message
            if err[0].code == gst.RESOURCE_ERROR_NOT_FOUND:
                   msg = "Invalid media."
            self.ErrorOccur(self.__get_error_code(err[0].domain ,err[0].code),
                            msg)

    def __on_message(self, bus, message):
        if message.type == gst.MESSAGE_EOS : 
            self.Stop()
	    self.EOSOccur()
        elif message.type == gst.MESSAGE_ERROR:
            self.__on_err_message(message)
        elif message.type == gst.MESSAGE_STATE_CHANGED:
            prev, new, pending = message.parse_state_changed()
            self.StatusChange(prev, new, pending)
            if new == gst.STATE_PLAYING and new != prev :
                dur = gst.query_new_duration(gst.FORMAT_TIME)
                self.__player.query( dur )
                duration = dur.parse_duration()[1]
                self.UpdateMediaInfo( "duration" , duration*1000/gst.SECOND)
            if new < gst.STATE_PAUSED :	
                self.__position_timer.stop() 
            else :
                self.__position_timer.start()
        elif message.type == gst.MESSAGE_TAG:
            tags = {}
            for key in message.parse_tag().keys():
                if type(message.structure[key]) is types.StringType or type(message.structure[key]) is types.IntType :
                    self.UpdateMediaInfo( key ,  message.structure[key] )
                else :
                    if key == "date":
                        self.UpdateMediaInfo( "album_year" ,  message.structure[key].year )
                    if key == "image":
                        cover = file( '/tmp/cover.jpg' , 'w')
                        cover.write(message.structure[key])
                        cover.close();
                        self.UpdateMediaInfo( "image", 0)
        elif message.type == gst.MESSAGE_ELEMENT:
            if message.structure.has_name("missing-plugin") :	
                self.__player.set_state(gst.STATE_NULL)
                try:
                    if self.__xid == self.surface.window.xid:
                        self.__xid = 0
                        self.window.destroy()
                except:
                    pass
                msg = "Missing plugin %s. Please install this plugin." % \
                      (message.structure['name'])
		err_code = ENG_NO_RENDERER
		if 'urisource'== message.structure["type"] :
		    err_code = ENG_INVALID_PROTOCOL
                self.ErrorOccur(err_code , msg)

    def __on_sync_message(self, bus, message):
        if message.structure.get_name() == 'prepare-xwindow-id':
            imagesink = message.src
            imagesink.set_property('force-aspect-ratio', True)
            imagesink.set_xwindow_id(self.__xid)
            self.__vsink = imagesink
            
    def __on_destroy(self, object, data):
        self.__player.set_state(gst.STATE_NULL)

    def __pos_timer_cb(self): 
        format = gst.FORMAT_TIME
        cur = 0
        pos = gst.query_new_position(gst.FORMAT_TIME) 
        self.__player.query( pos ) 
        res = pos.parse_position()
        self.UpdatePos( res[1]*1000/gst.SECOND )
        self.__position_timer.restart()
    
    @dbus.service.signal(dbus_interface=DBUS_INTERFACE_NAME)
    def StatusChange(self, prev, new, pending):
        return [prev, new, pending]

    @dbus.service.signal(dbus_interface=DBUS_INTERFACE_NAME)
    def EOSOccur(self ):
        return 

    @dbus.service.signal(dbus_interface=DBUS_INTERFACE_NAME)
    def ErrorOccur(self, code , msg):
        return [code, msg]
    
    @dbus.service.signal(dbus_interface=DBUS_INTERFACE_NAME)
    def UpdateMediaInfo(self, key, value):
        return [key, value]
    
    @dbus.service.signal(dbus_interface=DBUS_INTERFACE_NAME)
    def UpdatePos(self, cur ):
        return [cur]
    
    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='i', out_signature='b')
    def SetWindow(self, xid):
        self.__xid = xid
        return True

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='i')
    def GetWindow(self):
        return self.__xid

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='ii', out_signature='')
    def SetGeometry(self, width, height):
        self.__width = width
        self.__height = height
        self.window.set_default_size(self.__width, self.__height)

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='ii')
    def GetGeometry(self):
        return [self.__width, self.__height]

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='s', out_signature='b')
    def OpenUri(self, uri):
	gc.collect()
        self.__player.set_state(gst.STATE_NULL)
        try:
            if self.__xid == self.surface.window.xid:
                self.__xid = 0
            self.window.destroy()
        except:
            pass
        self.__player.set_property('uri', uri)
        return True

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def Play(self):
        if self.__player.get_state()[1] == gst.STATE_PLAYING:
            return
        if self.__xid == 0:
            self.__recreate_window()
            self.window.show_all()
            self.__xid = self.surface.window.xid
        self.__player.set_state(gst.STATE_PLAYING)
        
    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def Pause(self):
        if self.__player.get_state()[1] == gst.STATE_PLAYING:
            self.__player.set_state(gst.STATE_PAUSED)
    
    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def Stop(self):
        self.__player.set_state(gst.STATE_READY)
        try:
            if self.__xid == self.surface.window.xid:
                self.__xid = 0
                self.window.destroy()
        except:
            pass
	gc.collect()

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='v')    
    def Status(self):
        return self.__player.get_state()[1]

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='u', out_signature='')
    def SetVolume(self, volume):
        self.__player.set_property('volume', volume)

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='i')
    def GetVolume(self):
        return self.__player.get_property('volume')

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='u', out_signature='b')
    def SetPosition(self, position):
        gst_time = position * gst.SECOND / 1000
        event = gst.event_new_seek(1.0, gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE, gst.SEEK_TYPE_SET, gst_time, gst.SEEK_TYPE_NONE, 0)
        res = self.__player.send_event(event)
        if res:
            self.__player.set_new_stream_time(0L)
            return True
        else:
            return False;

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='i')
    def GetPosition(self):
        pos = gst.query_new_position( gst.FORMAT_TIME )
        self.__player.query(pos)
        res = pos.parse_position()
        return ( res[1]*1000/gst.SECOND )

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def Close(self):
        self.__player.set_state(gst.STATE_NULL)
        try:		
            if self.__xid == self.surface.window.xid:
                self.__xid = 0
                self.window.destroy()	
        except:
                pass
	if None != self.__vsink :
            self.__vsink.set_xwindow_id(0L)
	    self.__vsink = None
	self.__xid = 0
        gc.collect()

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def Quit(self):
        gtk.main_quit()
    
    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def Expose(self):
        self.__vsink.expose()
	
    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def FastForward(self, rate ):
	print "FastForward Not implemented"

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='', out_signature='')
    def FastRewind(self,rate ):
	print "FastRewind not implemented"

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='ss', out_signature='s')
    def GetVideoFrame(self, uri, output_file):
	gc.collect()
	return self.__frame_player.GetVideoFrame( uri , output_file )

    @dbus.service.method(dbus_interface=DBUS_INTERFACE_NAME, in_signature='i', out_signature='i')
    def ResizeWindow(self,size):
        return True

if __name__ == '__main__':
    gtk.gdk.threads_init()
    MediaService()
    gtk.main()

