Various changes for true 24-bit support, changes regarding Jack get_latency, and...
[rtaudio-cdist.git] / RtAudio.h
1 /************************************************************************/
2 /*! \class RtAudio
3     \brief Realtime audio i/o C++ classes.
4
5     RtAudio provides a common API (Application Programming Interface)
6     for realtime audio input/output across Linux (native ALSA, Jack,
7     and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
8     (DirectSound and ASIO) operating systems.
9
10     RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
11
12     RtAudio: realtime audio i/o C++ classes
13     Copyright (c) 2001-2012 Gary P. Scavone
14
15     Permission is hereby granted, free of charge, to any person
16     obtaining a copy of this software and associated documentation files
17     (the "Software"), to deal in the Software without restriction,
18     including without limitation the rights to use, copy, modify, merge,
19     publish, distribute, sublicense, and/or sell copies of the Software,
20     and to permit persons to whom the Software is furnished to do so,
21     subject to the following conditions:
22
23     The above copyright notice and this permission notice shall be
24     included in all copies or substantial portions of the Software.
25
26     Any person wishing to distribute modifications to the Software is
27     asked to send the modifications to the original developer so that
28     they can be incorporated into the canonical version.  This is,
29     however, not a binding provision of this license.
30
31     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
34     IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
35     ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
36     CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37     WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 */
39 /************************************************************************/
40
41 /*!
42   \file RtAudio.h
43  */
44
45 // RtAudio: Version 4.0.11
46
47 #ifndef __RTAUDIO_H
48 #define __RTAUDIO_H
49
50 #include <string>
51 #include <vector>
52 #include "RtError.h"
53
54 /*! \typedef typedef unsigned long RtAudioFormat;
55     \brief RtAudio data format type.
56
57     Support for signed integers and floats.  Audio data fed to/from an
58     RtAudio stream is assumed to ALWAYS be in host byte order.  The
59     internal routines will automatically take care of any necessary
60     byte-swapping between the host format and the soundcard.  Thus,
61     endian-ness is not a concern in the following format definitions.
62     Note that 24-bit data is expected to be encapsulated in a 32-bit
63     format.
64
65     - \e RTAUDIO_SINT8:   8-bit signed integer.
66     - \e RTAUDIO_SINT16:  16-bit signed integer.
67     - \e RTAUDIO_SINT24:  Lower 3 bytes of 32-bit signed integer.
68     - \e RTAUDIO_SINT32:  32-bit signed integer.
69     - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
70     - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
71 */
72 typedef unsigned long RtAudioFormat;
73 static const RtAudioFormat RTAUDIO_SINT8 = 0x1;    // 8-bit signed integer.
74 static const RtAudioFormat RTAUDIO_SINT16 = 0x2;   // 16-bit signed integer.
75 static const RtAudioFormat RTAUDIO_SINT24 = 0x4;   // Lower 3 bytes of 32-bit signed integer.
76 static const RtAudioFormat RTAUDIO_SINT32 = 0x8;   // 32-bit signed integer.
77 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
78 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
79
80 /*! \typedef typedef unsigned long RtAudioStreamFlags;
81     \brief RtAudio stream option flags.
82
83     The following flags can be OR'ed together to allow a client to
84     make changes to the default stream behavior:
85
86     - \e RTAUDIO_NONINTERLEAVED:   Use non-interleaved buffers (default = interleaved).
87     - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
88     - \e RTAUDIO_HOG_DEVICE:       Attempt grab device for exclusive use.
89     - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
90
91     By default, RtAudio streams pass and receive audio data from the
92     client in an interleaved format.  By passing the
93     RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
94     data will instead be presented in non-interleaved buffers.  In
95     this case, each buffer argument in the RtAudioCallback function
96     will point to a single array of data, with \c nFrames samples for
97     each channel concatenated back-to-back.  For example, the first
98     sample of data for the second channel would be located at index \c
99     nFrames (assuming the \c buffer pointer was recast to the correct
100     data type for the stream).
101
102     Certain audio APIs offer a number of parameters that influence the
103     I/O latency of a stream.  By default, RtAudio will attempt to set
104     these parameters internally for robust (glitch-free) performance
105     (though some APIs, like Windows Direct Sound, make this difficult).
106     By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
107     function, internal stream settings will be influenced in an attempt
108     to minimize stream latency, though possibly at the expense of stream
109     performance.
110
111     If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
112     open the input and/or output stream device(s) for exclusive use.
113     Note that this is not possible with all supported audio APIs.
114
115     If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt 
116     to select realtime scheduling (round-robin) for the callback thread.
117
118     If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
119     open the "default" PCM device when using the ALSA API. Note that this
120     will override any specified input or output device id.
121 */
122 typedef unsigned int RtAudioStreamFlags;
123 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1;    // Use non-interleaved buffers (default = interleaved).
124 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2;  // Attempt to set stream parameters for lowest possible latency.
125 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4;        // Attempt grab device and prevent use by others.
126 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
127 static const RtAudioStreamFlags RTAUDIO_ALSA_USE_DEFAULT = 0x10; // Use the "default" PCM device (ALSA only).
128
129 /*! \typedef typedef unsigned long RtAudioStreamStatus;
130     \brief RtAudio stream status (over- or underflow) flags.
131
132     Notification of a stream over- or underflow is indicated by a
133     non-zero stream \c status argument in the RtAudioCallback function.
134     The stream status can be one of the following two options,
135     depending on whether the stream is open for output and/or input:
136
137     - \e RTAUDIO_INPUT_OVERFLOW:   Input data was discarded because of an overflow condition at the driver.
138     - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
139 */
140 typedef unsigned int RtAudioStreamStatus;
141 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1;    // Input data was discarded because of an overflow condition at the driver.
142 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2;  // The output buffer ran low, likely causing a gap in the output sound.
143
144 //! RtAudio callback function prototype.
145 /*!
146    All RtAudio clients must create a function of type RtAudioCallback
147    to read and/or write data from/to the audio stream.  When the
148    underlying audio system is ready for new input or output data, this
149    function will be invoked.
150
151    \param outputBuffer For output (or duplex) streams, the client
152           should write \c nFrames of audio sample frames into this
153           buffer.  This argument should be recast to the datatype
154           specified when the stream was opened.  For input-only
155           streams, this argument will be NULL.
156
157    \param inputBuffer For input (or duplex) streams, this buffer will
158           hold \c nFrames of input audio sample frames.  This
159           argument should be recast to the datatype specified when the
160           stream was opened.  For output-only streams, this argument
161           will be NULL.
162
163    \param nFrames The number of sample frames of input or output
164           data in the buffers.  The actual buffer size in bytes is
165           dependent on the data type and number of channels in use.
166
167    \param streamTime The number of seconds that have elapsed since the
168           stream was started.
169
170    \param status If non-zero, this argument indicates a data overflow
171           or underflow condition for the stream.  The particular
172           condition can be determined by comparison with the
173           RtAudioStreamStatus flags.
174
175    \param userData A pointer to optional data provided by the client
176           when opening the stream (default = NULL).
177
178    To continue normal stream operation, the RtAudioCallback function
179    should return a value of zero.  To stop the stream and drain the
180    output buffer, the function should return a value of one.  To abort
181    the stream immediately, the client should return a value of two.
182  */
183 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
184                                 unsigned int nFrames,
185                                 double streamTime,
186                                 RtAudioStreamStatus status,
187                                 void *userData );
188
189
190 // **************************************************************** //
191 //
192 // RtAudio class declaration.
193 //
194 // RtAudio is a "controller" used to select an available audio i/o
195 // interface.  It presents a common API for the user to call but all
196 // functionality is implemented by the class RtApi and its
197 // subclasses.  RtAudio creates an instance of an RtApi subclass
198 // based on the user's API choice.  If no choice is made, RtAudio
199 // attempts to make a "logical" API selection.
200 //
201 // **************************************************************** //
202
203 class RtApi;
204
205 class RtAudio
206 {
207  public:
208
209   //! Audio API specifier arguments.
210   enum Api {
211     UNSPECIFIED,    /*!< Search for a working compiled API. */
212     LINUX_ALSA,     /*!< The Advanced Linux Sound Architecture API. */
213     LINUX_PULSE,    /*!< The Linux PulseAudio API. */
214     LINUX_OSS,      /*!< The Linux Open Sound System API. */
215     UNIX_JACK,      /*!< The Jack Low-Latency Audio Server API. */
216     MACOSX_CORE,    /*!< Macintosh OS-X Core Audio API. */
217     WINDOWS_ASIO,   /*!< The Steinberg Audio Stream I/O API. */
218     WINDOWS_DS,     /*!< The Microsoft Direct Sound API. */
219     RTAUDIO_DUMMY   /*!< A compilable but non-functional API. */
220   };
221
222   //! The public device information structure for returning queried values.
223   struct DeviceInfo {
224     bool probed;                  /*!< true if the device capabilities were successfully probed. */
225     std::string name;             /*!< Character string device identifier. */
226     unsigned int outputChannels;  /*!< Maximum output channels supported by device. */
227     unsigned int inputChannels;   /*!< Maximum input channels supported by device. */
228     unsigned int duplexChannels;  /*!< Maximum simultaneous input/output channels supported by device. */
229     bool isDefaultOutput;         /*!< true if this is the default output device. */
230     bool isDefaultInput;          /*!< true if this is the default input device. */
231     std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
232     RtAudioFormat nativeFormats;  /*!< Bit mask of supported data formats. */
233
234     // Default constructor.
235     DeviceInfo()
236       :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
237        isDefaultOutput(false), isDefaultInput(false), nativeFormats(0) {}
238   };
239
240   //! The structure for specifying input or ouput stream parameters.
241   struct StreamParameters {
242     unsigned int deviceId;     /*!< Device index (0 to getDeviceCount() - 1). */
243     unsigned int nChannels;    /*!< Number of channels. */
244     unsigned int firstChannel; /*!< First channel index on device (default = 0). */
245
246     // Default constructor.
247     StreamParameters()
248       : deviceId(0), nChannels(0), firstChannel(0) {}
249   };
250
251   //! The structure for specifying stream options.
252   /*!
253     The following flags can be OR'ed together to allow a client to
254     make changes to the default stream behavior:
255
256     - \e RTAUDIO_NONINTERLEAVED:    Use non-interleaved buffers (default = interleaved).
257     - \e RTAUDIO_MINIMIZE_LATENCY:  Attempt to set stream parameters for lowest possible latency.
258     - \e RTAUDIO_HOG_DEVICE:        Attempt grab device for exclusive use.
259     - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
260     - \e RTAUDIO_ALSA_USE_DEFAULT:  Use the "default" PCM device (ALSA only).
261
262     By default, RtAudio streams pass and receive audio data from the
263     client in an interleaved format.  By passing the
264     RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
265     data will instead be presented in non-interleaved buffers.  In
266     this case, each buffer argument in the RtAudioCallback function
267     will point to a single array of data, with \c nFrames samples for
268     each channel concatenated back-to-back.  For example, the first
269     sample of data for the second channel would be located at index \c
270     nFrames (assuming the \c buffer pointer was recast to the correct
271     data type for the stream).
272
273     Certain audio APIs offer a number of parameters that influence the
274     I/O latency of a stream.  By default, RtAudio will attempt to set
275     these parameters internally for robust (glitch-free) performance
276     (though some APIs, like Windows Direct Sound, make this difficult).
277     By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
278     function, internal stream settings will be influenced in an attempt
279     to minimize stream latency, though possibly at the expense of stream
280     performance.
281
282     If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
283     open the input and/or output stream device(s) for exclusive use.
284     Note that this is not possible with all supported audio APIs.
285
286     If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt 
287     to select realtime scheduling (round-robin) for the callback thread.
288     The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
289     flag is set. It defines the thread's realtime priority.
290
291     If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
292     open the "default" PCM device when using the ALSA API. Note that this
293     will override any specified input or output device id.
294
295     The \c numberOfBuffers parameter can be used to control stream
296     latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
297     only.  A value of two is usually the smallest allowed.  Larger
298     numbers can potentially result in more robust stream performance,
299     though likely at the cost of stream latency.  The value set by the
300     user is replaced during execution of the RtAudio::openStream()
301     function by the value actually used by the system.
302
303     The \c streamName parameter can be used to set the client name
304     when using the Jack API.  By default, the client name is set to
305     RtApiJack.  However, if you wish to create multiple instances of
306     RtAudio with Jack, each instance must have a unique client name.
307   */
308   struct StreamOptions {
309     RtAudioStreamFlags flags;      /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
310     unsigned int numberOfBuffers;  /*!< Number of stream buffers. */
311     std::string streamName;        /*!< A stream name (currently used only in Jack). */
312     int priority;                  /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
313
314     // Default constructor.
315     StreamOptions()
316     : flags(0), numberOfBuffers(0), priority(0) {}
317   };
318
319   //! A static function to determine the available compiled audio APIs.
320   /*!
321     The values returned in the std::vector can be compared against
322     the enumerated list values.  Note that there can be more than one
323     API compiled for certain operating systems.
324   */
325   static void getCompiledApi( std::vector<RtAudio::Api> &apis ) throw();
326
327   //! The class constructor.
328   /*!
329     The constructor performs minor initialization tasks.  No exceptions
330     can be thrown.
331
332     If no API argument is specified and multiple API support has been
333     compiled, the default order of use is JACK, ALSA, OSS (Linux
334     systems) and ASIO, DS (Windows systems).
335   */
336   RtAudio( RtAudio::Api api=UNSPECIFIED ) throw();
337
338   //! The destructor.
339   /*!
340     If a stream is running or open, it will be stopped and closed
341     automatically.
342   */
343   ~RtAudio() throw();
344
345   //! Returns the audio API specifier for the current instance of RtAudio.
346   RtAudio::Api getCurrentApi( void ) throw();
347
348   //! A public function that queries for the number of audio devices available.
349   /*!
350     This function performs a system query of available devices each time it
351     is called, thus supporting devices connected \e after instantiation. If
352     a system error occurs during processing, a warning will be issued. 
353   */
354   unsigned int getDeviceCount( void ) throw();
355
356   //! Return an RtAudio::DeviceInfo structure for a specified device number.
357   /*!
358
359     Any device integer between 0 and getDeviceCount() - 1 is valid.
360     If an invalid argument is provided, an RtError (type = INVALID_USE)
361     will be thrown.  If a device is busy or otherwise unavailable, the
362     structure member "probed" will have a value of "false" and all
363     other members are undefined.  If the specified device is the
364     current default input or output device, the corresponding
365     "isDefault" member will have a value of "true".
366   */
367   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
368
369   //! A function that returns the index of the default output device.
370   /*!
371     If the underlying audio API does not provide a "default
372     device", or if no devices are available, the return value will be
373     0.  Note that this is a valid device identifier and it is the
374     client's responsibility to verify that a device is available
375     before attempting to open a stream.
376   */
377   unsigned int getDefaultOutputDevice( void ) throw();
378
379   //! A function that returns the index of the default input device.
380   /*!
381     If the underlying audio API does not provide a "default
382     device", or if no devices are available, the return value will be
383     0.  Note that this is a valid device identifier and it is the
384     client's responsibility to verify that a device is available
385     before attempting to open a stream.
386   */
387   unsigned int getDefaultInputDevice( void ) throw();
388
389   //! A public function for opening a stream with the specified parameters.
390   /*!
391     An RtError (type = SYSTEM_ERROR) is thrown if a stream cannot be
392     opened with the specified parameters or an error occurs during
393     processing.  An RtError (type = INVALID_USE) is thrown if any
394     invalid device ID or channel number parameters are specified.
395
396     \param outputParameters Specifies output stream parameters to use
397            when opening a stream, including a device ID, number of channels,
398            and starting channel number.  For input-only streams, this
399            argument should be NULL.  The device ID is an index value between
400            0 and getDeviceCount() - 1.
401     \param inputParameters Specifies input stream parameters to use
402            when opening a stream, including a device ID, number of channels,
403            and starting channel number.  For output-only streams, this
404            argument should be NULL.  The device ID is an index value between
405            0 and getDeviceCount() - 1.
406     \param format An RtAudioFormat specifying the desired sample data format.
407     \param sampleRate The desired sample rate (sample frames per second).
408     \param *bufferFrames A pointer to a value indicating the desired
409            internal buffer size in sample frames.  The actual value
410            used by the device is returned via the same pointer.  A
411            value of zero can be specified, in which case the lowest
412            allowable value is determined.
413     \param callback A client-defined function that will be invoked
414            when input data is available and/or output data is needed.
415     \param userData An optional pointer to data that can be accessed
416            from within the callback function.
417     \param options An optional pointer to a structure containing various
418            global stream options, including a list of OR'ed RtAudioStreamFlags
419            and a suggested number of stream buffers that can be used to 
420            control stream latency.  More buffers typically result in more
421            robust performance, though at a cost of greater latency.  If a
422            value of zero is specified, a system-specific median value is
423            chosen.  If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
424            lowest allowable value is used.  The actual value used is
425            returned via the structure argument.  The parameter is API dependent.
426   */
427   void openStream( RtAudio::StreamParameters *outputParameters,
428                    RtAudio::StreamParameters *inputParameters,
429                    RtAudioFormat format, unsigned int sampleRate,
430                    unsigned int *bufferFrames, RtAudioCallback callback,
431                    void *userData = NULL, RtAudio::StreamOptions *options = NULL );
432
433   //! A function that closes a stream and frees any associated stream memory.
434   /*!
435     If a stream is not open, this function issues a warning and
436     returns (no exception is thrown).
437   */
438   void closeStream( void ) throw();
439
440   //! A function that starts a stream.
441   /*!
442     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
443     during processing.  An RtError (type = INVALID_USE) is thrown if a
444     stream is not open.  A warning is issued if the stream is already
445     running.
446   */
447   void startStream( void );
448
449   //! Stop a stream, allowing any samples remaining in the output queue to be played.
450   /*!
451     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
452     during processing.  An RtError (type = INVALID_USE) is thrown if a
453     stream is not open.  A warning is issued if the stream is already
454     stopped.
455   */
456   void stopStream( void );
457
458   //! Stop a stream, discarding any samples remaining in the input/output queue.
459   /*!
460     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
461     during processing.  An RtError (type = INVALID_USE) is thrown if a
462     stream is not open.  A warning is issued if the stream is already
463     stopped.
464   */
465   void abortStream( void );
466
467   //! Returns true if a stream is open and false if not.
468   bool isStreamOpen( void ) const throw();
469
470   //! Returns true if the stream is running and false if it is stopped or not open.
471   bool isStreamRunning( void ) const throw();
472
473   //! Returns the number of elapsed seconds since the stream was started.
474   /*!
475     If a stream is not open, an RtError (type = INVALID_USE) will be thrown.
476   */
477   double getStreamTime( void );
478
479   //! Returns the internal stream latency in sample frames.
480   /*!
481     The stream latency refers to delay in audio input and/or output
482     caused by internal buffering by the audio system and/or hardware.
483     For duplex streams, the returned value will represent the sum of
484     the input and output latencies.  If a stream is not open, an
485     RtError (type = INVALID_USE) will be thrown.  If the API does not
486     report latency, the return value will be zero.
487   */
488   long getStreamLatency( void );
489
490  //! Returns actual sample rate in use by the stream.
491  /*!
492    On some systems, the sample rate used may be slightly different
493    than that specified in the stream parameters.  If a stream is not
494    open, an RtError (type = INVALID_USE) will be thrown.
495  */
496   unsigned int getStreamSampleRate( void );
497
498   //! Specify whether warning messages should be printed to stderr.
499   void showWarnings( bool value = true ) throw();
500
501  protected:
502
503   void openRtApi( RtAudio::Api api );
504   RtApi *rtapi_;
505 };
506
507 // Operating system dependent thread functionality.
508 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
509   #include <windows.h>
510   #include <process.h>
511
512   typedef unsigned long ThreadHandle;
513   typedef CRITICAL_SECTION StreamMutex;
514
515 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
516   // Using pthread library for various flavors of unix.
517   #include <pthread.h>
518
519   typedef pthread_t ThreadHandle;
520   typedef pthread_mutex_t StreamMutex;
521
522 #else // Setup for "dummy" behavior
523
524   #define __RTAUDIO_DUMMY__
525   typedef int ThreadHandle;
526   typedef int StreamMutex;
527
528 #endif
529
530 // This global structure type is used to pass callback information
531 // between the private RtAudio stream structure and global callback
532 // handling functions.
533 struct CallbackInfo {
534   void *object;    // Used as a "this" pointer.
535   ThreadHandle thread;
536   void *callback;
537   void *userData;
538   void *apiInfo;   // void pointer for API specific callback information
539   bool isRunning;
540
541   // Default constructor.
542   CallbackInfo()
543     :object(0), callback(0), userData(0), apiInfo(0), isRunning(false) {}
544 };
545
546 // **************************************************************** //
547 //
548 // RtApi class declaration.
549 //
550 // Subclasses of RtApi contain all API- and OS-specific code necessary
551 // to fully implement the RtAudio API.
552 //
553 // Note that RtApi is an abstract base class and cannot be
554 // explicitly instantiated.  The class RtAudio will create an
555 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
556 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
557 //
558 // **************************************************************** //
559
560 #pragma pack(push, 1)
561 class S24 {
562
563  protected:
564   unsigned char c3[3];
565
566  public:
567   S24() {}
568
569   S24& operator = ( const int& i ) {
570     c3[0] = (i & 0x000000ff);
571     c3[1] = (i & 0x0000ff00) >> 8;
572     c3[2] = (i & 0x00ff0000) >> 16;
573     return *this;
574   }
575
576   S24( const S24& v ) { *this = v; }
577   S24( const double& d ) { *this = (int) d; }
578   S24( const float& f ) { *this = (int) f; }
579   S24( const signed short& s ) { *this = (int) s; }
580   S24( const char& c ) { *this = (int) c; }
581
582   int asInt() {
583     int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
584     if (i & 0x800000) i |= ~0xffffff;
585     return i;
586   }
587 };
588 #pragma pack(pop)
589
590 #if defined( HAVE_GETTIMEOFDAY )
591   #include <sys/time.h>
592 #endif
593
594 #include <sstream>
595
596 class RtApi
597 {
598 public:
599
600   RtApi();
601   virtual ~RtApi();
602   virtual RtAudio::Api getCurrentApi( void ) = 0;
603   virtual unsigned int getDeviceCount( void ) = 0;
604   virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
605   virtual unsigned int getDefaultInputDevice( void );
606   virtual unsigned int getDefaultOutputDevice( void );
607   void openStream( RtAudio::StreamParameters *outputParameters,
608                    RtAudio::StreamParameters *inputParameters,
609                    RtAudioFormat format, unsigned int sampleRate,
610                    unsigned int *bufferFrames, RtAudioCallback callback,
611                    void *userData, RtAudio::StreamOptions *options );
612   virtual void closeStream( void );
613   virtual void startStream( void ) = 0;
614   virtual void stopStream( void ) = 0;
615   virtual void abortStream( void ) = 0;
616   long getStreamLatency( void );
617   unsigned int getStreamSampleRate( void );
618   virtual double getStreamTime( void );
619   bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; };
620   bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; };
621   void showWarnings( bool value ) { showWarnings_ = value; };
622
623
624 protected:
625
626   static const unsigned int MAX_SAMPLE_RATES;
627   static const unsigned int SAMPLE_RATES[];
628
629   enum { FAILURE, SUCCESS };
630
631   enum StreamState {
632     STREAM_STOPPED,
633     STREAM_STOPPING,
634     STREAM_RUNNING,
635     STREAM_CLOSED = -50
636   };
637
638   enum StreamMode {
639     OUTPUT,
640     INPUT,
641     DUPLEX,
642     UNINITIALIZED = -75
643   };
644
645   // A protected structure used for buffer conversion.
646   struct ConvertInfo {
647     int channels;
648     int inJump, outJump;
649     RtAudioFormat inFormat, outFormat;
650     std::vector<int> inOffset;
651     std::vector<int> outOffset;
652   };
653
654   // A protected structure for audio streams.
655   struct RtApiStream {
656     unsigned int device[2];    // Playback and record, respectively.
657     void *apiHandle;           // void pointer for API specific stream handle information
658     StreamMode mode;           // OUTPUT, INPUT, or DUPLEX.
659     StreamState state;         // STOPPED, RUNNING, or CLOSED
660     char *userBuffer[2];       // Playback and record, respectively.
661     char *deviceBuffer;
662     bool doConvertBuffer[2];   // Playback and record, respectively.
663     bool userInterleaved;
664     bool deviceInterleaved[2]; // Playback and record, respectively.
665     bool doByteSwap[2];        // Playback and record, respectively.
666     unsigned int sampleRate;
667     unsigned int bufferSize;
668     unsigned int nBuffers;
669     unsigned int nUserChannels[2];    // Playback and record, respectively.
670     unsigned int nDeviceChannels[2];  // Playback and record channels, respectively.
671     unsigned int channelOffset[2];    // Playback and record, respectively.
672     unsigned long latency[2];         // Playback and record, respectively.
673     RtAudioFormat userFormat;
674     RtAudioFormat deviceFormat[2];    // Playback and record, respectively.
675     StreamMutex mutex;
676     CallbackInfo callbackInfo;
677     ConvertInfo convertInfo[2];
678     double streamTime;         // Number of elapsed seconds since the stream started.
679
680 #if defined(HAVE_GETTIMEOFDAY)
681     struct timeval lastTickTimestamp;
682 #endif
683
684     RtApiStream()
685       :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
686   };
687
688   typedef S24 Int24;
689   typedef signed short Int16;
690   typedef signed int Int32;
691   typedef float Float32;
692   typedef double Float64;
693
694   std::ostringstream errorStream_;
695   std::string errorText_;
696   bool showWarnings_;
697   RtApiStream stream_;
698
699   /*!
700     Protected, api-specific method that attempts to open a device
701     with the given parameters.  This function MUST be implemented by
702     all subclasses.  If an error is encountered during the probe, a
703     "warning" message is reported and FAILURE is returned. A
704     successful probe is indicated by a return value of SUCCESS.
705   */
706   virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
707                                 unsigned int firstChannel, unsigned int sampleRate,
708                                 RtAudioFormat format, unsigned int *bufferSize,
709                                 RtAudio::StreamOptions *options );
710
711   //! A protected function used to increment the stream time.
712   void tickStreamTime( void );
713
714   //! Protected common method to clear an RtApiStream structure.
715   void clearStreamInfo();
716
717   /*!
718     Protected common method that throws an RtError (type =
719     INVALID_USE) if a stream is not open.
720   */
721   void verifyStream( void );
722
723   //! Protected common error method to allow global control over error handling.
724   void error( RtError::Type type );
725
726   /*!
727     Protected method used to perform format, channel number, and/or interleaving
728     conversions between the user and device buffers.
729   */
730   void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
731
732   //! Protected common method used to perform byte-swapping on buffers.
733   void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
734
735   //! Protected common method that returns the number of bytes for a given format.
736   unsigned int formatBytes( RtAudioFormat format );
737
738   //! Protected common method that sets up the parameters for buffer conversion.
739   void setConvertInfo( StreamMode mode, unsigned int firstChannel );
740 };
741
742 // **************************************************************** //
743 //
744 // Inline RtAudio definitions.
745 //
746 // **************************************************************** //
747
748 inline RtAudio::Api RtAudio :: getCurrentApi( void ) throw() { return rtapi_->getCurrentApi(); }
749 inline unsigned int RtAudio :: getDeviceCount( void ) throw() { return rtapi_->getDeviceCount(); }
750 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
751 inline unsigned int RtAudio :: getDefaultInputDevice( void ) throw() { return rtapi_->getDefaultInputDevice(); }
752 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) throw() { return rtapi_->getDefaultOutputDevice(); }
753 inline void RtAudio :: closeStream( void ) throw() { return rtapi_->closeStream(); }
754 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
755 inline void RtAudio :: stopStream( void )  { return rtapi_->stopStream(); }
756 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
757 inline bool RtAudio :: isStreamOpen( void ) const throw() { return rtapi_->isStreamOpen(); }
758 inline bool RtAudio :: isStreamRunning( void ) const throw() { return rtapi_->isStreamRunning(); }
759 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
760 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); };
761 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
762 inline void RtAudio :: showWarnings( bool value ) throw() { rtapi_->showWarnings( value ); }
763
764 // RtApi Subclass prototypes.
765
766 #if defined(__MACOSX_CORE__)
767
768 #include <CoreAudio/AudioHardware.h>
769
770 class RtApiCore: public RtApi
771 {
772 public:
773
774   RtApiCore();
775   ~RtApiCore();
776   RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; };
777   unsigned int getDeviceCount( void );
778   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
779   unsigned int getDefaultOutputDevice( void );
780   unsigned int getDefaultInputDevice( void );
781   void closeStream( void );
782   void startStream( void );
783   void stopStream( void );
784   void abortStream( void );
785   long getStreamLatency( void );
786
787   // This function is intended for internal use only.  It must be
788   // public because it is called by the internal callback handler,
789   // which is not a member of RtAudio.  External use of this function
790   // will most likely produce highly undesireable results!
791   bool callbackEvent( AudioDeviceID deviceId,
792                       const AudioBufferList *inBufferList,
793                       const AudioBufferList *outBufferList );
794
795   private:
796
797   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
798                         unsigned int firstChannel, unsigned int sampleRate,
799                         RtAudioFormat format, unsigned int *bufferSize,
800                         RtAudio::StreamOptions *options );
801   static const char* getErrorCode( OSStatus code );
802 };
803
804 #endif
805
806 #if defined(__UNIX_JACK__)
807
808 class RtApiJack: public RtApi
809 {
810 public:
811
812   RtApiJack();
813   ~RtApiJack();
814   RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; };
815   unsigned int getDeviceCount( void );
816   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
817   void closeStream( void );
818   void startStream( void );
819   void stopStream( void );
820   void abortStream( void );
821   long getStreamLatency( void );
822
823   // This function is intended for internal use only.  It must be
824   // public because it is called by the internal callback handler,
825   // which is not a member of RtAudio.  External use of this function
826   // will most likely produce highly undesireable results!
827   bool callbackEvent( unsigned long nframes );
828
829   private:
830
831   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
832                         unsigned int firstChannel, unsigned int sampleRate,
833                         RtAudioFormat format, unsigned int *bufferSize,
834                         RtAudio::StreamOptions *options );
835 };
836
837 #endif
838
839 #if defined(__WINDOWS_ASIO__)
840
841 class RtApiAsio: public RtApi
842 {
843 public:
844
845   RtApiAsio();
846   ~RtApiAsio();
847   RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; };
848   unsigned int getDeviceCount( void );
849   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
850   void closeStream( void );
851   void startStream( void );
852   void stopStream( void );
853   void abortStream( void );
854   long getStreamLatency( void );
855
856   // This function is intended for internal use only.  It must be
857   // public because it is called by the internal callback handler,
858   // which is not a member of RtAudio.  External use of this function
859   // will most likely produce highly undesireable results!
860   bool callbackEvent( long bufferIndex );
861
862   private:
863
864   std::vector<RtAudio::DeviceInfo> devices_;
865   void saveDeviceInfo( void );
866   bool coInitialized_;
867   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
868                         unsigned int firstChannel, unsigned int sampleRate,
869                         RtAudioFormat format, unsigned int *bufferSize,
870                         RtAudio::StreamOptions *options );
871 };
872
873 #endif
874
875 #if defined(__WINDOWS_DS__)
876
877 class RtApiDs: public RtApi
878 {
879 public:
880
881   RtApiDs();
882   ~RtApiDs();
883   RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; };
884   unsigned int getDeviceCount( void );
885   unsigned int getDefaultOutputDevice( void );
886   unsigned int getDefaultInputDevice( void );
887   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
888   void closeStream( void );
889   void startStream( void );
890   void stopStream( void );
891   void abortStream( void );
892   long getStreamLatency( void );
893
894   // This function is intended for internal use only.  It must be
895   // public because it is called by the internal callback handler,
896   // which is not a member of RtAudio.  External use of this function
897   // will most likely produce highly undesireable results!
898   void callbackEvent( void );
899
900   private:
901
902   bool coInitialized_;
903   bool buffersRolling;
904   long duplexPrerollBytes;
905   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
906                         unsigned int firstChannel, unsigned int sampleRate,
907                         RtAudioFormat format, unsigned int *bufferSize,
908                         RtAudio::StreamOptions *options );
909 };
910
911 #endif
912
913 #if defined(__LINUX_ALSA__)
914
915 class RtApiAlsa: public RtApi
916 {
917 public:
918
919   RtApiAlsa();
920   ~RtApiAlsa();
921   RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; };
922   unsigned int getDeviceCount( void );
923   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
924   void closeStream( void );
925   void startStream( void );
926   void stopStream( void );
927   void abortStream( void );
928
929   // This function is intended for internal use only.  It must be
930   // public because it is called by the internal callback handler,
931   // which is not a member of RtAudio.  External use of this function
932   // will most likely produce highly undesireable results!
933   void callbackEvent( void );
934
935   private:
936
937   std::vector<RtAudio::DeviceInfo> devices_;
938   void saveDeviceInfo( void );
939   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
940                         unsigned int firstChannel, unsigned int sampleRate,
941                         RtAudioFormat format, unsigned int *bufferSize,
942                         RtAudio::StreamOptions *options );
943 };
944
945 #endif
946
947 #if defined(__LINUX_PULSE__)
948
949 class RtApiPulse: public RtApi
950 {
951 public:
952   ~RtApiPulse();
953   RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; };
954   unsigned int getDeviceCount( void );
955   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
956   void closeStream( void );
957   void startStream( void );
958   void stopStream( void );
959   void abortStream( void );
960
961   // This function is intended for internal use only.  It must be
962   // public because it is called by the internal callback handler,
963   // which is not a member of RtAudio.  External use of this function
964   // will most likely produce highly undesireable results!
965   void callbackEvent( void );
966
967   private:
968
969   std::vector<RtAudio::DeviceInfo> devices_;
970   void saveDeviceInfo( void );
971   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
972                         unsigned int firstChannel, unsigned int sampleRate,
973                         RtAudioFormat format, unsigned int *bufferSize,
974                         RtAudio::StreamOptions *options );
975 };
976
977 #endif
978
979 #if defined(__LINUX_OSS__)
980
981 class RtApiOss: public RtApi
982 {
983 public:
984
985   RtApiOss();
986   ~RtApiOss();
987   RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; };
988   unsigned int getDeviceCount( void );
989   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
990   void closeStream( void );
991   void startStream( void );
992   void stopStream( void );
993   void abortStream( void );
994
995   // This function is intended for internal use only.  It must be
996   // public because it is called by the internal callback handler,
997   // which is not a member of RtAudio.  External use of this function
998   // will most likely produce highly undesireable results!
999   void callbackEvent( void );
1000
1001   private:
1002
1003   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
1004                         unsigned int firstChannel, unsigned int sampleRate,
1005                         RtAudioFormat format, unsigned int *bufferSize,
1006                         RtAudio::StreamOptions *options );
1007 };
1008
1009 #endif
1010
1011 #if defined(__RTAUDIO_DUMMY__)
1012
1013 class RtApiDummy: public RtApi
1014 {
1015 public:
1016
1017   RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtError::WARNING ); };
1018   RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; };
1019   unsigned int getDeviceCount( void ) { return 0; };
1020   RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) { RtAudio::DeviceInfo info; return info; };
1021   void closeStream( void ) {};
1022   void startStream( void ) {};
1023   void stopStream( void ) {};
1024   void abortStream( void ) {};
1025
1026   private:
1027
1028   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
1029                         unsigned int firstChannel, unsigned int sampleRate,
1030                         RtAudioFormat format, unsigned int *bufferSize,
1031                         RtAudio::StreamOptions *options ) { return false; };
1032 };
1033
1034 #endif
1035
1036 #endif
1037
1038 // Indentation settings for Vim and Emacs
1039 //
1040 // Local Variables:
1041 // c-basic-offset: 2
1042 // indent-tabs-mode: nil
1043 // End:
1044 //
1045 // vim: et sts=2 sw=2