#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery 

import sys
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst

FILE = "/tmp/test.mp4"

def on_message(bus, message, pipeline):
    t = message.type
    if t == Gst.MessageType.ERROR:
        print(message.parse_error())
        print('Critical error, exiting')
        sys.exit()
    elif t == Gst.MessageType.EOS:
        action = actions.pop(0)
        pipeline.set_state(Gst.State.NULL)
        print('EOS, running next action (%s)' %action)
        action(pipeline)

def run_pipe(pipe_desc):
    p = Gst.parse_launch(pipe_desc)
    p.set_name('test')
    bus = p.get_bus()
    bus.add_signal_watch()
    bus.connect('message', on_message, p)
    p.set_state(Gst.State.PLAYING)

def build_file():
    print('Building reference video')
    pipe_desc = "videotestsrc num-buffers=300 ! x264enc ! mp4mux ! filesink location=%s" %FILE
    run_pipe(pipe_desc)

def play_file(pipeline):
    pipe_desc = "filesrc location=%s ! qtdemux ! fakesink" %FILE
    print('Parsing playback pipeline')
    run_pipe(pipe_desc)

def replay_file(pipeline):
    print('Re-initializing pipeline') 
    pipeline.set_state(Gst.State.PLAYING)

actions = [
    play_file,
    replay_file,
]

if __name__ == '__main__':
    Gst.init(None)
    ml = GObject.MainLoop()
    GObject.idle_add(build_file)
    ml.run()
