
//! @file tonegen.h
//! @ingroup PublicAPI
//! @brief Voicetronix programmable tone generator API
//!
//! This file contains the Voicetronix tone generator interface.

/*
    AUTHOR..: Ron Lee
    DATE....: 9/2/07

    Digital oscillator algorithm originally coded by David Rowe, 5/11/97.

	 Voicetronix Voice Processing Board (VPB) Software
	 Copyright (C) 1997-2008 Voicetronix www.voicetronix.com.au

	 This library is free software; you can redistribute it and/or
	 modify it under the terms of the GNU Lesser General Public
	 License version 2.1 as published by the Free Software Foundation.

	 This library 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
	 Lesser General Public License for more details.

	 You should have received a copy of the GNU Lesser General Public
	 License along with this library; if not, write to the Free Software
	 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
	 MA  02110-1301  USA
*/

#ifndef _VT_TONEGEN_H
#define _VT_TONEGEN_H

#include <vector>
#include <string>
#include <stdint.h>


//XXX this might be better as a generic tool in some other file, but for
//    now, this is the only place we need it, and it sits at a low enough
//    level that without the LOCAL_ONLY options it catches most other
//    mutex calls too.

//! Set this to @c 1 for verbose logging of mutex operations.
#define VERBOSE_MUTEX            0

//! Set this to @c 1 to confine the action of @c VERBOSE_MUTEX to this file.
#define VERBOSE_MUTEX_LOCAL_ONLY 1

#if VERBOSE_MUTEX
//{{{
#define pthread_mutex_lock(x) {                             \
    fprintf(stdout, "+++ %lx   lock " #x " %s:%d\n",        \
	    pthread_self(), __PRETTY_FUNCTION__, __LINE__); \
    pthread_mutex_lock(x); }

#define pthread_mutex_unlock(x) {                           \
    fprintf(stdout, "--- %lx unlock " #x " %s:%d\n",        \
	    pthread_self(), __PRETTY_FUNCTION__, __LINE__); \
    pthread_mutex_unlock(x); }

#define	pthread_cond_wait( x, y ) {                         \
    fprintf(stdout, "=== %lx wait   " #x " %s:%d\n",        \
	    pthread_self(), __PRETTY_FUNCTION__, __LINE__); \
    pthread_cond_wait( x, y );                              \
    fprintf(stdout, "~~~ %lx wait   " #x " %s:%d\n",        \
	    pthread_self(), __PRETTY_FUNCTION__, __LINE__); }
//}}}
#endif


//! Base type for the programmable tone generator interface.
//{{{
//! The @c %ToneGen interface facilitates the definition and creation of pure
//! or composite tones, of fixed, cadenced, or continuous duration.
//! The number of frequency components per tone is implementation defined.
//! For the @c HostToneGen it is unlimited, but the hardware based generators
//! typically have a fixed number of oscillators available.
//}}}
class ToneGen
{ //{{{
public:

    //! Container type for a list of pointers to @c %ToneGen structures.
    typedef std::vector<ToneGen*>	List;

    //! Call back type for tone completion notification.
    typedef void (*CompletionCallback)(ToneGen&);

    //! @c %ToneGen state information
    enum State {
	IDLE,           //!< Tone generator is idle
	SEQUENCE,	//!< Tone generator is handling a sequence of tones
	CONTINUOUS,     //!< Continuous tone generation in progress
	ONESHOT         //!< One-shot tone generation in progress
    };


    //! @c ToneGen configuration data structure.
    //{{{
    //! This is kept separate from the @c ToneGen itself so that parameters
    //! can be composed independently and applied to a shared @c ToneGen
    //! object atomically.
    //}}}
    class Config
    { //{{{
    friend class ToneGen;

    public:

	//! Data storage for a @c ToneGen frequency component.
	struct Freq
	{ //{{{

	    //! Container type for a list of @c %Freq structures.
	    typedef std::vector<Freq>	List;

	    //! Container type for a list of @c %Freq::List structures.
	    typedef std::vector<List>	ListList;

	    unsigned int    hz;	    //!< Frequency in @c Hz.
	    float           db;	    //!< Magnitude in @c dB, from @c -inf to @c 0dB.

	    //! Default constructor.
	    Freq() : hz(0), db(0) {}

	}; //}}}

	//! Data storage for a @c ToneGen cadence component.
	struct Cadence
	{ //{{{

	    //! Container type for a list of @c %Cadence structures.
	    typedef std::vector<Cadence>    List;

	    unsigned int    onms;	//!< On time is @c ms.
	    unsigned int    offms;	//!< Off time in @c ms.

	    //! Default constructor.
	    Cadence() : onms(0), offms(0) {}

	}; //}}}


    private:

	//! Base type for heterogeneous user data storage.
	struct UserData
	{ //{{{
	private:

	    //! You cannot copy objects of this class.
	    UserData( const UserData& );
	    UserData &operator=( const UserData& );


	public:

	    //! Container type for lists of @c %UserData.
	    typedef std::vector<UserData*>  List;

	    //! Default constructor.
	    UserData() {}

	    //! Virtual destructor.
	    virtual ~UserData() {}

	}; //}}}

	//! Implementation type for user data storage.
	template <typename T> struct UData : public UserData
	{ //{{{

	    //! Storage for the user data.
	    T data;

	    //! Constructor.
	    UData( T d ) : data(d) {}

	}; //}}}


	Freq::ListList	         m_tones;	//!< Frequency components for each tone.
	Cadence::List            m_cadences;    //!< Cadences for each tone.
	CompletionCallback       m_callback;    //!< Completion callback.
	UserData::List           m_userdata;    //!< User defined data.

	Freq::ListList::iterator m_nexttone;    //!< Next tone to generate.
	Cadence::List::iterator  m_nextcadence; //!< Cadence for the next tone.
	bool                     m_repeat;      //!< Loop the tone sequence if @c true.


      //! @name ToneGen-only methods
      //@{ //{{{

	//! Initialises the tone and cadence iterators to return the first tone.
	void Begin()
	{ //{{{
	    m_nexttone    = m_tones.begin();
	    m_nextcadence = m_cadences.begin();
	} //}}}

	//! Called by the @c ToneGen to check if a completion is final
	//{{{
	//! @return @c true if there are no more tones to in the sequence and
	//!         this tone does not repeat.  @c false if there are more
	//!         tones to play.
	//!
	//! If the end of the sequence has been reached and this tone is to
	//! loop, then this method will reinitialise the tone and cadence
	//! iterators so subsequent calls to the @c GetNextFreqs() and
	//! @c GetNextCadence() methods will begin with the first tone again.
	//}}}
	bool HasCompleted()
	{ //{{{
	    if( m_nexttone == m_tones.end() ) {
		if( ! m_repeat ) return true;
		Begin();
	    }
	    return false;
	} //}}}

	//! Called by the @c ToneGen to invoke the completion callback
	//{{{
	//! @warning There should be no reason to ever call this function from
	//!          a user application, and doing so may lead to corruption or
	//!          a crash since the callback should expect the @c ToneGen to
	//!          be locked when it is called.
	//}}}
	void SignalCompletion( ToneGen &tonegen )
	{ //{{{
	    if(m_callback) m_callback(tonegen);
	} //}}}

      //@} //}}}


    public:

	//! Default constructor.
	Config()
	    : m_callback(    NULL )
	    , m_nexttone(    m_tones.begin() )
	    , m_nextcadence( m_cadences.begin() )
	    , m_repeat(      false )
	{}

	//! Destructor.
	~Config()
	{ //{{{
	    for( UserData::List::iterator i = m_userdata.begin(),
					  e = m_userdata.end(); i != e; ++i )
		    delete *i;
	} //}}}


      //! @name Tone configuration
      //@{ //{{{

	//! Set one of the component frequencies for a tone.
	//{{{
	//! @param hz   The frequency in @c Hz of this tone component.
	//! @param db   The magnitude of this tone component in @c dB, from @c -inf to @c 0dB.
	//! @param fnum The index of the frequency to set, from @c 0 to @c n-1,
	//!             where @c n is the number of discrete frequency
	//!             components employed to generate some single tone.
	//! @param tnum The index of the tone that this frequency is a
	//!             component for, from @c 0 to @c t-1, where @c t is the
	//!             number of discrete sequential tones in a complex tone.
	//}}}
	void SetFreq( unsigned int hz, float db = 0.0,
		      unsigned int fnum = 0, unsigned int tnum = 0 )
	{ //{{{

	    if( tnum >= m_tones.size() )    m_tones.resize(tnum + 1);
	    if( tnum >= m_cadences.size() ) m_cadences.resize(tnum + 1);
	    Freq::List &freqlist = m_tones[tnum];

	    if( fnum >= freqlist.size() ) freqlist.resize(fnum + 1);
	    Freq &freq = freqlist[fnum];

	    freq.hz = hz;
	    freq.db = db;

	} //}}}

	//! Set the on and off time in @c ms for a cadenced tone.
	//{{{
	//! @param onms  The on time for this tone in @c ms.  If the on time
	//!              is 0 (or no cadence is explicitly specified for some
	//!              tone) then the tone generated will be continuous, and
	//!              any off time will be ignored.  Such a tone must be
	//!              explicitly explicitly terminated by the user
	//!              application at the appropriate time.
	//! @param offms The off time for a cadenced tone.  Ignored unless
	//!              @a onms is non zero.
	//! @param tnum  The index of the tone to apply this cadence to, from
	//!              @c 0 to @c t-1, where @c t is the number of discrete
	//!              sequential tones in a complex tone.
	//}}}
	void SetCadence( unsigned int onms, unsigned int offms = 0,
			 unsigned int tnum = 0 )
	{ //{{{

	    if( tnum >= m_cadences.size() ) m_cadences.resize(tnum + 1);
	    Cadence &cadence = m_cadences[tnum];

	    cadence.onms  = onms;
	    cadence.offms = offms;

	} //}}}

	//! Set this (sequence of) tone(s) to play once, or loop continuously.
	//{{{
	//! @param repeat Loop continuously if @c true.
	//!
	//! By default, cadenced tones will not repeat and will signal
	//! completion at the end of one full cycle.  Tones that are set to
	//! loop with this method must be explicitly terminated by the user
	//! application at the appropriate time.
	//!
	//! This option is mostly useful when composing sequences with complex
	//! tones and/or complex cadences that should play continuously.
	//! For continuous single tones, simply set a cadence on-time of @c 0
	//! (which is its default value) instead.
	//}}}
	void SetRepeat( bool repeat = true ) { m_repeat = repeat; }

	//! Clear all frequency and cadence data from this @c %Config.
	//{{{
	//! This method may be used to partially clear an existing @c %Config
	//! for reuse with a new set of tones.  Any previously set
	//! <tt>@ref SetCompletionCallback "CompletionCallback"</tt> or
	//! <tt>@ref SetUserData "UserData"</tt> will be unaffected by it.
	//!
	//! @note It mostly is only useful when composing a
	//!       <tt>@ref BeginSequence "SEQUENCE"</tt> of tones for a
	//!       @c ToneGen, and is @b unsafe to call once the @c %Config
	//!       object has been passed to one unless that @c ToneGen's
	//!       mutex is locked.  The only time that is guaranteed to
	//!       the user application at present is in the scope of a
	//!       @c CompletionCallback call.
	//}}}
	void ClearTones()
	{ //{{{
	    m_tones.clear();
	    m_cadences.clear();
	    //Begin();
	    m_repeat = false;
	} //}}}

      //@} //}}}

      //! @name Completion notification
      //@{ //{{{

	//! Request asynchronous notification of normal tone completion.
	//{{{
	//! @param callback The function to call.
	//!
	//! No notification will be sent to the @a callback if the tone generator
	//! is stopped by an explicit call from the user, such as to @c Stop().
	//! Only normal completion of a (usually cadenced) tone will invoke this
	//! signalling mechanism.
	//!
	//! @note The @a callback will be invoked with the @c ToneGen mutex
	//!       locked.  This means you are guaranteed that the @c ToneGen
	//!       object passed as its argument will have @c this @c %Config
	//!       set for the duration of its scope.  It also means that the
	//!       @a callback function @b must @b not call, or cause to be
	//!       called, any @c ToneGen method that would also try to take
	//!       the lock, such as:
	//!       - @c Start()
	//!       - @c Stop()
	//!       - @c BeginSequence()
	//!       - @c SignalCompletion()
	//! @par
	//!       In general, a callback for a @c ONESHOT tone should @b never
	//!       try to begin any new activity on the same @c ToneGen.  If it
	//!       must play some new tone or continue the existing one, then a
	//!       @c SEQUENCE, started with @c BeginSequence() should be used
	//!       instead.  The following @c ToneGen functions are safe to call
	//!       from the @a callback:
	//!       - @c GetConfig()
	//!       - @c ContinueSequence()
	//!       - @c EndSequence()
	//}}}
	void SetCompletionCallback( CompletionCallback callback )
	{ //{{{
	    m_callback = callback;
	} //}}}

      //@} //}}}

      //! @name User defined data storage
      //@{ //{{{

	//! Store arbitrary, typed @a data into a user-data @a slot.
	//{{{
	//! @param slot A user defined index from <tt>0 - n</tt> to use when
	//!             retrieving this data element.
	//! @param data The data to store in @a slot.
	//}}}
	template <typename T> void SetUserData( size_t slot, T data )
	{ //{{{

	    if( slot < m_userdata.size() )
		    delete m_userdata[slot];
	    else	m_userdata.resize(slot + 1, NULL);

	    m_userdata[slot] = new UData<T>(data);

	} //}}}

	//! Retreive arbitrary, typed data from a user-data @a slot.
	//{{{
	//! @param slot The user defined index from <tt>0 - n</tt> that was used
	//!             to store the data with a call to @c SetUserData().
	//! @return A reference to the data stored.  This means that you may alter
	//!         the data in place if desired, as well as inspecting it.
	//! @exception ToneGen::Exception will be thrown if there is no data stored
	//!                               in @a slot.
	//! @exception std::bad_cast      will be thrown if the data in @a slot is
	//!                               not of type @a T.
	//}}}
	template <typename T> T &GetUserData( size_t slot ) const
	{ //{{{

	    if( slot < m_userdata.size() )
		    return dynamic_cast<UData<T>&>(*m_userdata[slot]).data;
	    throw Exception("No user data set for requested slot");

	} //}}}

      //@} //}}}

      //! @name Tone data iteration
      //! These methods provide access to tone data for @c ToneGen implementations.
      //@{ //{{{

	//XXX make these private too and provide an accessor through ToneGen?
	//    Lets start with a trust/efficiency tradeoff on that one, we can
	//    always bring the big cluebat out later if its really needed...

	//! Return the next frequency component in the sequence.
	//{{{
	//! This function is used by the various @c ToneGen implementations to
	//! retrieve the configuration data for the next set of frequencies to
	//! generate.  You should @b not usually call it from a user application.
	//!
	//! Bounds checking is done by the @c HasCompleted() method which should
	//! be called when each discrete tone generates a completion event at
	//! the end of its cadence cycle.
	//}}}
	const Freq::List &GetNextFreqs() { return *m_nexttone++; }

	//! Return the next cadence timing in the sequence.
	//{{{
	//! This function is used by the various @c ToneGen implementations
	//! to retrieve the configuration data for the next discrete tone to
	//! generate.  You should @b not usually call it from a user application.
	//!
	//! Bounds checking is done by the @c HasCompleted() method which should
	//! be called when each discrete tone generates a completion event at
	//! the end of its cadence cycle.
	//}}}
	const Cadence &GetNextCadence() { return *m_nextcadence++; }

      //@} //}}}

    }; //}}}


protected:

    //! @c ToneGen runtime exception type
    class Exception : public std::exception
    { //{{{
    private:

	std::string  m_msg;

    public:

	//! Construct an exception object with a simple @a message string.
	Exception(const std::string &message) : m_msg( message ) {}

	//! Destructor.
	~Exception() throw() {};


    //! @name Error summary
    //@{

	//! Return the message associated with the exception.
	const char *what() const throw()
	{ //{{{
		return m_msg.empty() ? "Unspecified ToneGen::Exception"
				     : m_msg.c_str();
	} //}}}

    //@}

    }; //}}}


    //! Called by @c Start() for implementation specific operations.
    virtual State ImplStart() = 0;

    //! Called by @c Stop() for implementation specific operations.
    virtual void  ImplStop() {};


private:

    State               m_state;    //!< Current tone generator state
    Config             *m_config;   //!< Tone completion callback

    pthread_mutex_t     m_mutex;    //!< global state protection
    pthread_cond_t      m_cond;     //!< state change signalling


    //! Cleanup handler for cancellable methods that hold a mutex.
    static void mutex_cleanup(void *p)
    { //{{{
	    pthread_mutex_unlock((pthread_mutex_t*)p);
    } //}}}


    //! Internal helper.  You must hold @c m_mutex to call this method.
    void DoStop()
    { //{{{

	if( m_state != IDLE ) {
		ImplStop();
		m_state = IDLE;
		pthread_cond_broadcast( &m_cond );
	}
	delete m_config;
	m_config = NULL;

    } //}}}


    //! You cannot copy objects of this class.
    ToneGen( const ToneGen& );
    ToneGen &operator=( const ToneGen& );


public:

    //! Default constructor
    ToneGen()
	: m_state(IDLE)
	, m_config(NULL)
    { //{{{

	pthread_mutex_init(&m_mutex, NULL);
	pthread_cond_init(&m_cond, NULL);

    } //}}}

    //! Virtual destructor
    virtual ~ToneGen()
    { //{{{

	delete m_config;
	pthread_mutex_destroy(&m_mutex);
	pthread_cond_destroy(&m_cond);

    } //}}}


  //! @name Tone generation
  //@{ //{{{

    //! Begin generation of a single tone.
    //{{{
    //! If a tone is already playing it will be terminated before playing the
    //! new tone as if you had called @c Stop() immediately prior.
    //!
    //! @param tone The @c Config data for the tone to play.  The @c %ToneGen
    //!             will take ownership of this data and destroy it when it is
    //!             no longer required.  The calling function should make no
    //!             assumptions about the lifetime of this data after passing
    //!             it to this method, it may already be destroyed by the time
    //!             this method returns control to the calling thread.
    //! @param sync If @c true, this method will block the calling thread until
    //!             the @a tone has completed playing, else this function will
    //!             return immediately.
    //!
    //! Most well behaved applications should confirm the completion of a tone
    //! started with this function (whether they are terminated by cadence or
    //! an explicit call to the @c Stop() function) before any subsequent calls
    //! to @c %Start() are made.
    //!
    //! @sa @c BeginSequence() for composing atomic sequences of discrete tones.
    //}}}
    void Start( Config *tone, bool sync = false )
    { //{{{

	pthread_mutex_lock( &m_mutex );
	pthread_cleanup_push(mutex_cleanup, &m_mutex);

	DoStop();
	m_config = tone;
	m_config->Begin();
	m_state  = ImplStart();

	// NOTE: we don't keep checking the state here, since whatever has
	//       signalled the completion may have already made it busy
	//       again and we only care about the completion of _this_ tone
	//       not the _state_ of the @c ToneGen when it returns from a
	//       synchronous playback.
	if(sync && m_state != IDLE) pthread_cond_wait( &m_cond, &m_mutex );

	pthread_cleanup_pop(1);

    } //}}}

    //! Stop tone generation.
    //{{{
    //! This function may be used to explicitly terminate a tone.  Any threads
    //! that are blocked waiting for its completion will be woken up.
    //!
    //! @note The @c CompletionCallback function (if any) will @b not be called
    //!       if the tone is explicitly terminated.
    //!       You should call @c SignalCompletion() instead if you wish to
    //!       create the appearance of a normal tone completion event.
    //}}}
    void Stop()
    { //{{{

	pthread_mutex_lock( &m_mutex );
	pthread_cleanup_push(mutex_cleanup, &m_mutex);
	DoStop();
	pthread_cleanup_pop(1);

    } //}}}

    //! Return the current state of this @c %ToneGen.
    //{{{
    //! @note The return value from this function @b must @b not be relied upon
    //!       by the calling function if it does not hold the @c ToneGen mutex,
    //!       since the real state may have already changed even before control
    //!       is returned to the calling thread.  In those cases it must be
    //!       considered as an unreliable hint and any following code should be
    //!       well behaved for any state the @c ToneGen may really be in.
    //}}}
    State GetState() const { return m_state; }

  //@} //}}}

  //! @name Tone sequences
  //@{ //{{{

    //! Prepare the tone generator for playing a sequence of related tones.
    //{{{
    //! At times it may be desirable to generate a complex sequence of tones
    //! which should appear to the calling application as a single coherent
    //! tone generation cycle, for example: dialling a @c DTMF string, or
    //! signal tones which consists of a series of discrete tones.  If you
    //! were to simply call @c Start() repeatedly, then a completion event
    //! would be generated for each discrete tone to be played and other
    //! threads may try to interleave tones between those calls.
    //!
    //! To initiate an atomic sequence of tones, call @c %BeginSequence()
    //! instead of @c Start(), and supply a @c CompletionCallback in the
    //! @c Config data.  The callback will be invoked at the completion of
    //! each discrete tone.  Subsequent tones may be played by modifying the
    //! tone parameters of the config (retrieved with @c GetConfig()), and
    //! then calling the @c ContinueSequence() method to begin that tone.
    //! When all tones in the sequence have been played, the @c EndSequence()
    //! method @b must be called to signal that to the @c %ToneGen and wake
    //! the thread that blocked on the @c BeginSequence() call if its @a sync
    //! flag was set.
    //!
    //! @param tone The @c Config data for the first tone to play.
    //!             The @c %ToneGen will take ownership of this data and will
    //!             destroy it when it is no longer required.  The caller must
    //!             make no assumptions about the lifetime of this data after
    //!             passing it to this method, it may already be destroyed by
    //!             the time this method returns control to the calling thread.
    //! @param sync If @c true, this method will block the calling thread until
    //!             the full sequence has completed playing and @c EndSequence()
    //!             is called, else this function will return immediately.
    //!
    //! @note Any call which performs an explicit termination of a tone, such
    //!       as @c Stop(), @c Start(), or another call to @c %BeginSequence(),
    //!       will terminate an active sequence as if @c EndSequence() had been
    //!       called immediately prior.  You @b must @b not call such functions
    //!       from a @c CompletionCallback, but other threads may invoke them
    //!       and interrupt a sequence before its natural completion.
    //}}}
    void BeginSequence( Config *tone, bool sync = false )
    { //{{{

	pthread_mutex_lock( &m_mutex );
	pthread_cleanup_push(mutex_cleanup, &m_mutex);

	DoStop();
	m_config = tone;
	m_state  = SEQUENCE;
	m_config->Begin();
	ImplStart();

	// NOTE: we don't keep checking the state here, since whatever has
	//       signalled the completion may have already made it busy
	//       again and we only care about the completion of _this_ tone
	//       not the _state_ of the @c ToneGen when it returns from a
	//       synchronous playback.
	if(sync && m_state != IDLE) pthread_cond_wait( &m_cond, &m_mutex );

	pthread_cleanup_pop(1);

    } //}}}

    //! Begin the next discrete tone in an atomic sequence.
    //{{{
    //! This function should @b only be used between calls to @c BeginSequence()
    //! and @c EndSequence().  It @b must be called with the @c %ToneGen mutex
    //! locked and assumes that any tone previously started with a call to
    //! @c BeginSequence() or @c %ContinueSequence() has already terminated.
    //! To ensure these conditions are met, it should only be called from a
    //! @c CompletionCallback that was set with the initial call to the
    //! @c BeginSequence() method.
    //}}}
    void ContinueSequence()
    { //{{{
	m_config->Begin();
	ImplStart();
    } //}}}

    //! Signal the completion of an atomic sequence of tones.
    //{{{
    //! This function should be called after the last tone in a sequence has
    //! completed.  It will wake the thread blocked on a call to @c BeginSequence()
    //! if that method was called with the @a sync flag set.  It @b must be called
    //! with the @c %ToneGen mutex locked.  To ensure this conditions is met, it
    //! should only be called from a @c CompletionCallback that was set with the
    //! initial call to the @c BeginSequence() method.  It will not invoke the
    //! @c CompletionCallback function (again).
    //}}}
    void EndSequence()
    { //{{{

	DoStop();

    } //}}}

  //@} //}}}

  //! @name Tone completion
  //@{ //{{{

    //! Notify the tone generator of an external completion event.
    //{{{
    //! This function should be called by specialised @c %ToneGen instances
    //! upon normal completion of a generated tone.  It will set the
    //! @c ToneGen::State to @c IDLE and notify the user of that transition.
    //! It will do nothing if the current state is already @c IDLE.
    //}}}
    void SignalCompletion()
    { //{{{

	pthread_mutex_lock( &m_mutex );
	pthread_cleanup_push(mutex_cleanup, &m_mutex);

	if( m_config == NULL || m_config->HasCompleted() ) {
		switch( m_state ) {
		    case CONTINUOUS:
		    case ONESHOT:
			m_state = IDLE;
			pthread_cond_broadcast( &m_cond );

		    case SEQUENCE:
			m_config->SignalCompletion(*this);
			//XXX if there was no completion handler, then call DoStop?
			//    that doesn't alway help cleaning up old Config data does it?

		    case IDLE: ;
		}
	}
	else if( __builtin_expect(m_state != IDLE,1) ) ImplStart();

	pthread_cleanup_pop(1);

    } //}}}

    //! Return the @c ToneGen::Config data.
    //{{{
    //! This method may be called from a @c CompletionCallback, either to
    //! retrieve user data that was associated with the current @c %ToneGen
    //! operation, or to modify the @c %ToneGen parameters for a subsequent
    //! tone in a @c SEQUENCE.
    //!
    //! @warning It is not safe to use the object returned by this call at
    //!          any other time when the @c %ToneGen mutex is not locked,
    //!          since the @c Config it returns may be destroyed at any time
    //!          by any asynchronous operation that stops the @c %ToneGen.
    //}}}
    Config &GetConfig() const { return *m_config; }

  //@} //}}}

}; //}}}



//! Host based tone generator implementation.
class HostToneGen : public ToneGen
{ //{{{
private:

    //! The maximum supported tone frequency.
    static const unsigned int FREQ_MAX = 4000;


    //! Digital oscillator for a single tone component.
    class Oscillator
    { //{{{
    private:

	unsigned int m_freq;
	float        m_mag;

	float m_cosw2;  //!< 2cos(w)
	float m_y1;     //!< y(n-1)
	float m_y2;     //!< y(n-2)


    public:

	//! Container type for a list of @c Oscillator's.
	typedef std::vector<Oscillator>     List;

	//! Default constructor.
	Oscillator() : m_freq(0), m_mag(0.0) {}

	//! Set the parameters for this oscillator.
	void Set( unsigned freq, float mag );

	//! Reset this oscillator to the initial state for its current parameters.
	inline void Reset();

	//! Add the next @a n samples to the signal in @a buf.
	inline void GetSamples( int16_t *buf, size_t n );

    }; //}}}


    //! The list of digital oscillators used to generate the samples.
    Oscillator::List    m_osc;

    size_t  m_samplecount; //!< The number of samples returned since last reset.
    size_t  m_onsamp;      //!< The number of samples the tone should be on for.
    size_t  m_cadencesamp; //!< The total number of samples for a cadenced tone.


protected:

    State ImplStart();


public:


    //! Default constructor.
    HostToneGen()
	: m_samplecount(0)
	, m_onsamp(0)
	, m_cadencesamp(0)
    {}

    //! Add the next @a samples of this tone to the signal in @a buf.
    //
    //! @param buf     A buffer of 16bit linear audio data to add this tone to.
    //! @param samples The number of tone samples to place in @a buf.
    //! @return @c true if the tone generator is not @c IDLE, else @c false.
    bool MixTone( int16_t *buf, size_t samples );

}; //}}}


#if VERBOSE_MUTEX_LOCAL_ONLY
  #undef pthread_mutex_lock
  #undef pthread_mutex_unlock
  #undef pthread_cond_wait
#endif

#endif

