/*
    Copyright (C) 2004 Paul Davis 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    $Id: port.h,v 1.2 2002/06/01 03:32:49 trutkin Exp $
*/

#ifndef __midipp_threaded_midi_port_h__
#define __midipp_threaded_midi_port_h__

#include <list>
#include <sigc++/signal_system.h>

namespace MIDI {

class Port;

class ThreadedMidiPort {
   public:
       ThreadedMidiPort (Port&);
       ~ThreadedMidiPort ();

       void set_timeout (long usecs);
       int register_client (unsigned long bufsize);

       long write (byte*, long bytecnt);
       
       SigC::Signal0<void,unsigned long> Timer;

   private:
       Port& _port;
       pthread_t _thread;
       int _timeout;

       static void* _thread_work (void*);
       void* _thread_work ();
    
       static void _timer();
       void timer();

       struct Client {
	   RingBuffer<MIDI::byte> buffer;
	   int fifo[2];

	   Client (unsigned long bufsize);
       };
    
       std::list<Client*> Clients;
       pthread_mutex_t client_lock;

       int midi_deliver (Client&);
       int midi_read ();
};

} /* namespace MIDI */

#endif /* __midipp_threaded_midi_port_h__ */
