#! /usr/bin/env python2

import os
import sys
from pprint import pprint

import gi
import signal

gi.require_version ('Gst', '1.0')
from gi.repository import GObject, Gst, GstPbutils, GLib, GES

GObject.threads_init()
Gst.init (None)
GES.init()

signal.signal(signal.SIGINT, signal.SIG_DFL)

g_main_loop = GLib.MainLoop ()

def default_bus_cb (unused_bus, message): # {{{
    if message.type == Gst.MessageType.EOS:
        print ('Finished')
        g_main_loop.quit ()
# }}}

class MyTimeline (GES.Timeline): # {{{
    CONTAINER_CAPS = 'video/quicktime,variant=iso'
    ENCODER_CAPS = 'video/x-h264, profile=baseline'
    RAW_CAPS = 'video/x-raw,format={I420,RGBA,RGB,ARGB64}'

    def __init__(self):
        GES.Timeline.__init__ (self)

    def my_render (self, out_fn, _bus_cb=default_bus_cb):
        self.commit ()

        # {{{ create container_profile
        container_profile = GstPbutils.EncodingContainerProfile.new(
                "pitivi-profile",
                "Pitivi encoding profile",
                Gst.Caps (MyTimeline.CONTAINER_CAPS), #("video/quicktime,variant=iso")
                None)

        video_profile = GstPbutils.EncodingVideoProfile.new (
                Gst.Caps (MyTimeline.ENCODER_CAPS),
                None,
                Gst.Caps (MyTimeline.RAW_CAPS),
                0)

        container_profile.add_profile (video_profile)
        # }}}

        # {{{ Create pipeline, set timeline, set render, enter PLAYING state
        pipeline = GES.Pipeline ()
        pipeline.set_timeline (self)

        pipeline.set_render_settings (out_fn, container_profile)
        pipeline.set_mode (GES.PipelineFlags.RENDER)

        pipeline.set_state (Gst.State.PLAYING)

        bus = pipeline.get_bus ()
        bus.add_signal_watch ()
        bus.connect ("message", _bus_cb)

        self.pipeline = pipeline
        # }}}
# }}}

def get_video_source (clip): # {{{
    for source in clip.get_children(False):
        if source.props.track_type == GES.TrackType.VIDEO:
            break
    return source
# }}}
