
// ml - A media library representation.

// Copyright (C) 2005 Editopia Inc.
// Released under the LGPL.
// For more information, see http://www.openlibraries.org.

// simple example to exercise the load and store features of ml

#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>

#include <openpluginlib/pl/openpluginlib.hpp>
#include <openpluginlib/pl/utf8_utils.hpp>

#include <openimagelib/il/openimagelib_plugin.hpp>
#include <openmedialib/ml/openmedialib_plugin.hpp>

namespace ml  = olib::openmedialib::ml;
namespace il  = olib::openimagelib::il;
namespace opl = olib::openpluginlib;

class handler : public ml::store_keyboard_handler
{
	public:
		handler( ml::input_type_ptr input, ml::store_type_ptr store )
			: input_( input )
			, store_( store )
			, speed_( 1 )
			, done_( false )
		{
			ml::store_keyboard_feedback *feedback = dynamic_cast< ml::store_keyboard_feedback * >( store.get( ) );
			if ( feedback )
				feedback->register_keyboard_handler( this );
		}

		virtual ~handler( ) 
		{ 
		}

		virtual void keyboard_handler( unsigned char key )
		{ 
			boost::mutex::scoped_lock scoped_lock( mutex_ );

			switch( key )
			{
				case 27:
					done_ = true;
					break;
		
				default:
					break;
			}
		}

		void run( )
		{
			while( !done_ && input_->get_position( ) != input_->get_frames( ) )
			{
				ml::frame_type_ptr frame = input_->fetch( );
				if ( speed_ != 1 )
					frame->set_audio( ml::audio_type_ptr( ) );
				if ( !store_->push( frame ) )
					break;
				boost::mutex::scoped_lock scoped_lock( mutex_ );
				input_->seek( speed_, true );
			}
			store_->complete( );
		}

	private:
		ml::input_type_ptr input_;
		ml::store_type_ptr store_;
		int speed_;
		boost::mutex mutex_;
		bool done_;
};

int main( int argc, char* argv[ ] )
{
	opl::init( "" );

	if ( argc > 2 )
	{
		ml::input_type_ptr input = ml::create_input( argv[ 1 ] );
		if ( input == 0 ) return 1;
		ml::store_type_ptr store = ml::create_store( argv[ 2 ], input->fetch( ) );
		if ( store == 0 ) return 1;

		handler handler( input, store );
		handler.run( );
	}
	else
	{
		std::cerr << "Usage: store input store" << std::endl;
		std::cerr << "   ie: file.avi glew:" << std::endl;
	}

	return 0;
}
