This file is indexed.

/usr/include/vt/tonegen.h is in libvpb-dev 4.2.58-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
//! @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