#!/usr/bin/env python
import sys
import os.path
import time
import gst
import gobject

from glob import glob

UPDATE_PERIOD = 500

VOICE_TRACK_PATH = "/music/Genaside II/New Life IV The Hunted/"

voice_tracks = glob ('%s*.ogg' % VOICE_TRACK_PATH)

current_track = 0
timer = 0.0

gobject.threads_init()

main_loop = gobject.MainLoop ()

def on_decoder_new_pad (decoder, pad, _, sink):    
    gst.debug ("Pad added")
    pad.link (sink.get_pad ('sink'))

def on_decoder_pad_removed (decoder, pad):
    gst.debug ("Pad removed!")

def check_file_end (pad, event):
    if event.type == gst.EVENT_EOS:
        global timer
        timer = time.time ()
        gst.debug ("Event probe received EOS")

    return True

def set_input_file (input, filename):
    gst.info ('Changing track to %s' % voice_tracks[current_track])

    filesrc = input.get_by_name ('file source')
    filesrc.set_property ('location', filename)

def make_input_bin (name = None):
    bin = gst.Bin (name)

    filesrc   = gst.element_factory_make ('filesrc', 'file source')
    decoder   = gst.element_factory_make ('decodebin', 'decoder')
    converter = gst.element_factory_make ('audioconvert', 'converter')

    bin.add (filesrc, decoder, converter)
    
    filesrc.link (decoder)

    decoder.connect ('new-decoded-pad', on_decoder_new_pad, converter)
    decoder.connect ('removed-decoded-pad', on_decoder_pad_removed)

    bin.add_pad (gst.GhostPad ('src', converter.get_pad ('src')))

    filesrc.get_pad ('src').add_event_probe (check_file_end)
    bin.get_pad ('src').add_event_probe (check_file_end)

    return bin

def select_next_track (pipeline):
    global voice_tracks
    global current_track
    global timer
    
    pipeline.set_state (gst.STATE_READY)
    set_input_file (pipeline.get_by_name ('input'), voice_tracks[current_track])
    current_track += 1
    pipeline.set_state (gst.STATE_PLAYING)

    gst.info ("Time taken: %f" % (time.time () - timer))
   
def bus_watch (bus, msg, pipeline):
    if msg.type == gst.MESSAGE_EOS:
        gst.debug ("EOS received on bus watch")
        select_next_track (pipeline)

    return True

def make_pipeline (name = None):
    input = make_input_bin ('input')
    sink = gst.element_factory_make ('autoaudiosink', 'output')

    pipeline = gst.Pipeline (name)
    pipeline.add (input, sink)
    input.link (sink)
    
    return pipeline

def main (args):
    pipeline = make_pipeline ('pipeline')
    pipeline.get_bus ().add_watch (bus_watch, pipeline)
    
    select_next_track (pipeline)

    main_loop.run ()

if __name__ == '__main__':
    main (sys.argv)
    sys.exit (0)
