import os
import sys
import time

import pygtk
pygtk.require('2.0')

import gst

pipeline_types = {
    'mp3' : ['id3demux'],
    'ogg' : ['oggdemux', 'vorbistag'],
    }

pipelines = {}

def new_pad_cb(current, pad, elements):
    next = elements[elements.index(current)+1]
    #print 'linking', current, 'with', next
    pad.link(next.get_pad('sink'))
    
def create_pipelines():
    global pipelines
    for kind in pipeline_types.keys():
        pipeline = gst.Pipeline('pipeline')
        source = gst.Element('filesrc', 'source')
        elements = []
        elements.append(source)
        
        elements += [gst.Element(element) for element in pipeline_types[kind]]
        if elements[1].get_name().startswith('oggdemux'):
            elements[1].connect('new-pad', new_pad_cb, elements)
            elements[1].set_property('accurate', False)
            
        elements[-1].set_name('tag')
        sink = gst.Element('fakesink')
        sink.set_property('silent', 1)
        elements.append(sink)

        pipeline.add_many(*elements)
        gst.element_link_many(*elements)

        pipelines[kind] = pipeline

def read_tag_from_file(filename):
    global pipelines
    if filename.endswith('.mp3'):
        pipeline = pipelines['mp3']
    elif filename.endswith('ogg'):
        pipeline = pipelines['ogg']
    else:
        return

    source = pipeline.get_by_name('source')
    source.set_property('location', filename)
    tag = pipeline.get_by_name('tag')

    tags = {}

    def found_tags_cb(pipeline, element, taglist):
        if element == tag:
            tags.update(dict(taglist))
            pipeline.set_state(gst.STATE_READY)
    
    signal_id = pipeline.connect('found_tag', found_tags_cb)

    pipeline.set_state(gst.STATE_PLAYING)

    iterations = 0
    t1 = time.time()
    while pipeline.iterate():
        iterations += 1
    t2 = time.time()
    
    if pipeline.get_state() != gst.STATE_READY:
        pipeline.set_state(gst.STATE_READY)
    
    
    print '%s (%d) iterating (%d iters) took %2.1f ms' % (filename[-3:], len(tags), iterations, (t2-t1)*1000)
    return iterations, tags

create_pipelines()

if os.path.isdir(sys.argv[1]):
    dirname = sys.argv[1]
    for filename in os.listdir(dirname):
        if not filename.endswith('mp3') and not filename.endswith('ogg'):
            continue

        read_tag_from_file(os.path.join(dirname, filename))
else:
    read_tag_from_file(sys.argv[1])
    
