#!/usr/bin/env python

"""
gst-launch with goodies

It allows to seek in the pipeline.
"""

# JBC. April 2011.

import sys
from optparse import OptionParser

parser = OptionParser(version='%prog 1.0', usage='%prog [options]',
                      description=__doc__)

parser.add_option('--start', type='int', help='start time')
parser.add_option('--end',   type='int', help='end time')

opts, rest = parser.parse_args()


#
# Initialization
#

import pygtk
pygtk.require('2.0')
import pygst
pygst.require('0.10')
import gobject, gst
from gstlal import simplehandler


#
# Create the pipeline (yes, it's *that* easy)
#

mainloop = gobject.MainLoop()
pipeline = gst.parse_launch(' '.join(rest))


#
# Make it start playing at the appropriate time
#

if opts.start is not None:
    start_seektype = gst.SEEK_TYPE_SET
    start_ns = opts.start * 1e9
else:
    start_seektype = gst.SEEK_TYPE_NONE
    start_ns = 0  # not used anyway

if opts.end is not None:
    end_seektype = gst.SEEK_TYPE_SET
    end_ns = opts.end * 1e9
else:
    end_seektype = gst.SEEK_TYPE_NONE
    end_ns = 0  # not used anyway

for src in pipeline.iterate_sources():
    src.seek(1.0, gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH,
             start_seektype, start_ns,
             end_seektype, end_ns)


#
# Boilerplate
#

handler = simplehandler.Handler(mainloop, pipeline)
if pipeline.set_state(gst.STATE_PLAYING) == gst.STATE_CHANGE_FAILURE:
	raise RuntimeError("pipeline failed to enter PLAYING state")
mainloop.run()
