import gtk
import gst
import sys
import os.path
import threading

class DurationHelper(object):
	def __init__(self, uri):
		self.event = threading.Event()
		fakesink = gst.element_factory_make(
				'fakesink', 'fakesink')
		self.bin = bin = gst.element_factory_make(
				'playbin', 'playbin')
		bin.set_property('video-sink', fakesink)
		bin.set_property('audio-sink', fakesink)
		self.bus = bus = bin.get_bus()
		bus.add_signal_watch()
		bus.connect('message', self.on_message)
		bin.set_property('uri', uri)
		assert bin.set_state(gst.STATE_PLAYING)
	def join(self):
		self.event.wait()
	def __del__(self):
		self.bin.set_state(gst.STATE_NULL)
		self.bus.remove_signal_watch()
		del(self.bus)
		del(self.bin)
	def on_message(self, bus, message):
		if message.type == gst.MESSAGE_EOS:
			self.duration = self.bin.query_duration(
						gst.FORMAT_TIME)[0]
			self.event.set()

def get_duration(path):
	p = os.path.abspath(path)
	if not os.path.exists(p):
		print "file not found"
		sys.exit(-2)
	helper = DurationHelper("file://"+p)
	helper.join()
	return helper.duration

if __name__ == '__main__':
	gtk.gdk.threads_init()
	threading.Thread(target=gtk.main).start()
	try:
		if len(sys.argv) <= 1:
			print "usage: python gst-duration.py <file name>"
			sys.exit(-1)
		print get_duration(sys.argv[1])
	finally:
		gtk.main_quit()
	
