#!/usr/bin/env python

import bootstrap
import sys
import openpluginlib
import openimagelib
import openmedialib

openpluginlib.init( "" )

if len( sys.argv ) > 1:
	sys.argv.pop( 0 )

	fps_num = 1
	fps_den = 1

	openal = None

	for clip in range( len( sys.argv ) ):
		try:
			reseat = openmedialib.create_audio_reseat( )
			input = openmedialib.create_input( sys.argv[ clip ] )
			if input is not None:
				frame = input.fetch( )
				if frame is not None and frame.get_audio( ) is not None:
					input_index = 0
					store_index = 0
					audio = frame.get_audio( )
					frequency = audio.frequency( )
					needed = openmedialib.audio_samples_for_frame( store_index, frequency, fps_num, fps_den )
					while input_index < input.get_frames( ):
						reseat.append( frame.get_audio( ) )
						while reseat.has( needed ):
							frame.set_audio( reseat.retrieve( needed, False ) )
							if openal is None:
								openal = openmedialib.create_store( "openal:", frame )
								if not openal.init( ):
									print "Failed to open audio"
									break
							openal.push( frame )
							store_index += 1
							needed = openmedialib.audio_samples_for_frame( store_index, frequency, fps_num, fps_den )
						input_index += 1
						input.seek( input_index, False )
						frame = input.fetch( )
		except KeyboardInterrupt:
			pass
else:
	print "Usage: reseat.py <input> ..."
	
openpluginlib.uninit( )
