Updates for release 4.0.8, including new python binding, new teststops.cpp program...
[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-2011 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.8
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_OSS,      /*!< The Linux Open Sound System API. */
214     UNIX_JACK,      /*!< The Jack Low-Latency Audio Server API. */
215     MACOSX_CORE,    /*!< Macintosh OS-X Core Audio API. */
216     WINDOWS_ASIO,   /*!< The Steinberg Audio Stream I/O API. */
217     WINDOWS_DS,     /*!< The Microsoft Direct Sound API. */
218     RTAUDIO_DUMMY   /*!< A compilable but non-functional API. */
219   };
220
221   //! The public device information structure for returning queried values.
222   struct DeviceInfo {
223     bool probed;                  /*!< true if the device capabilities were successfully probed. */
224     std::string name;             /*!< Character string device identifier. */
225     unsigned int outputChannels;  /*!< Maximum output channels supported by device. */
226     unsigned int inputChannels;   /*!< Maximum input channels supported by device. */
227     unsigned int duplexChannels;  /*!< Maximum simultaneous input/output channels supported by device. */
228     bool isDefaultOutput;         /*!< true if this is the default output device. */
229     bool isDefaultInput;          /*!< true if this is the default input device. */
230     std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
231     RtAudioFormat nativeFormats;  /*!< Bit mask of supported data formats. */
232
233     // Default constructor.
234     DeviceInfo()
235       :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
236        isDefaultOutput(false), isDefaultInput(false), nativeFormats(0) {}
237   };
238
239   //! The structure for specifying input or ouput stream parameters.
240   struct StreamParameters {
241     unsigned int deviceId;     /*!< Device index (0 to getDeviceCount() - 1). */
242     unsigned int nChannels;    /*!< Number of channels. */
243     unsigned int firstChannel; /*!< First channel index on device (default = 0). */
244
245     // Default constructor.
246     StreamParameters()
247       : deviceId(0), nChannels(0), firstChannel(0) {}
248   };
249
250   //! The structure for specifying stream options.
251   /*!
252     The following flags can be OR'ed together to allow a client to
253     make changes to the default stream behavior:
254
255     - \e RTAUDIO_NONINTERLEAVED:    Use non-interleaved buffers (default = interleaved).
256     - \e RTAUDIO_MINIMIZE_LATENCY:  Attempt to set stream parameters for lowest possible latency.
257     - \e RTAUDIO_HOG_DEVICE:        Attempt grab device for exclusive use.
258     - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
259     - \e RTAUDIO_ALSA_USE_DEFAULT:  Use the "default" PCM device (ALSA only).
260
261     By default, RtAudio streams pass and receive audio data from the
262     client in an interleaved format.  By passing the
263     RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
264     data will instead be presented in non-interleaved buffers.  In
265     this case, each buffer argument in the RtAudioCallback function
266     will point to a single array of data, with \c nFrames samples for
267     each channel concatenated back-to-back.  For example, the first
268     sample of data for the second channel would be located at index \c
269     nFrames (assuming the \c buffer pointer was recast to the correct
270     data type for the stream).
271
272     Certain audio APIs offer a number of parameters that influence the
273     I/O latency of a stream.  By default, RtAudio will attempt to set
274     these parameters internally for robust (glitch-free) performance
275     (though some APIs, like Windows Direct Sound, make this difficult).
276     By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
277     function, internal stream settings will be influenced in an attempt
278     to minimize stream latency, though possibly at the expense of stream
279     performance.
280
281     If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
282     open the input and/or output stream device(s) for exclusive use.
283     Note that this is not possible with all supported audio APIs.
284
285     If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt 
286     to select realtime scheduling (round-robin) for the callback thread.
287     The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
288     flag is set. It defines the thread's realtime priority.
289
290     If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
291     open the "default" PCM device when using the ALSA API. Note that this
292     will override any specified input or output device id.
293
294     The \c numberOfBuffers parameter can be used to control stream
295     latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
296     only.  A value of two is usually the smallest allowed.  Larger
297     numbers can potentially result in more robust stream performance,
298     though likely at the cost of stream latency.  The value set by the
299     user is replaced during execution of the RtAudio::openStream()
300     function by the value actually used by the system.
301
302     The \c streamName parameter can be used to set the client name
303     when using the Jack API.  By default, the client name is set to
304     RtApiJack.  However, if you wish to create multiple instances of
305     RtAudio with Jack, each instance must have a unique client name.
306   */
307   struct StreamOptions {
308     RtAudioStreamFlags flags;      /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
309     unsigned int numberOfBuffers;  /*!< Number of stream buffers. */
310     std::string streamName;        /*!< A stream name (currently used only in Jack). */
311     int priority;                  /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
312
313     // Default constructor.
314     StreamOptions()
315     : flags(0), numberOfBuffers(0), priority(0) {}
316   };
317
318   //! A static function to determine the available compiled audio APIs.
319   /*!
320     The values returned in the std::vector can be compared against
321     the enumerated list values.  Note that there can be more than one
322     API compiled for certain operating systems.
323   */
324   static void getCompiledApi( std::vector<RtAudio::Api> &apis ) throw();
325
326   //! The class constructor.
327   /*!
328     The constructor performs minor initialization tasks.  No exceptions
329     can be thrown.
330
331     If no API argument is specified and multiple API support has been
332     compiled, the default order of use is JACK, ALSA, OSS (Linux
333     systems) and ASIO, DS (Windows systems).
334   */
335   RtAudio( RtAudio::Api api=UNSPECIFIED ) throw();
336
337   //! The destructor.
338   /*!
339     If a stream is running or open, it will be stopped and closed
340     automatically.
341   */
342   ~RtAudio() throw();
343
344   //! Returns the audio API specifier for the current instance of RtAudio.
345   RtAudio::Api getCurrentApi( void ) throw();
346
347   //! A public function that queries for the number of audio devices available.
348   /*!
349     This function performs a system query of available devices each time it
350     is called, thus supporting devices connected \e after instantiation. If
351     a system error occurs during processing, a warning will be issued. 
352   */
353   unsigned int getDeviceCount( void ) throw();
354
355   //! Return an RtAudio::DeviceInfo structure for a specified device number.
356   /*!
357
358     Any device integer between 0 and getDeviceCount() - 1 is valid.
359     If an invalid argument is provided, an RtError (type = INVALID_USE)
360     will be thrown.  If a device is busy or otherwise unavailable, the
361     structure member "probed" will have a value of "false" and all
362     other members are undefined.  If the specified device is the
363     current default input or output device, the corresponding
364     "isDefault" member will have a value of "true".
365   */
366   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
367
368   //! A function that returns the index of the default output device.
369   /*!
370     If the underlying audio API does not provide a "default
371     device", or if no devices are available, the return value will be
372     0.  Note that this is a valid device identifier and it is the
373     client's responsibility to verify that a device is available
374     before attempting to open a stream.
375   */
376   unsigned int getDefaultOutputDevice( void ) throw();
377
378   //! A function that returns the index of the default input device.
379   /*!
380     If the underlying audio API does not provide a "default
381     device", or if no devices are available, the return value will be
382     0.  Note that this is a valid device identifier and it is the
383     client's responsibility to verify that a device is available
384     before attempting to open a stream.
385   */
386   unsigned int getDefaultInputDevice( void ) throw();
387
388   //! A public function for opening a stream with the specified parameters.
389   /*!
390     An RtError (type = SYSTEM_ERROR) is thrown if a stream cannot be
391     opened with the specified parameters or an error occurs during
392     processing.  An RtError (type = INVALID_USE) is thrown if any
393     invalid device ID or channel number parameters are specified.
394
395     \param outputParameters Specifies output stream parameters to use
396            when opening a stream, including a device ID, number of channels,
397            and starting channel number.  For input-only streams, this
398            argument should be NULL.  The device ID is an index value between
399            0 and getDeviceCount() - 1.
400     \param inputParameters Specifies input stream parameters to use
401            when opening a stream, including a device ID, number of channels,
402            and starting channel number.  For output-only streams, this
403            argument should be NULL.  The device ID is an index value between
404            0 and getDeviceCount() - 1.
405     \param format An RtAudioFormat specifying the desired sample data format.
406     \param sampleRate The desired sample rate (sample frames per second).
407     \param *bufferFrames A pointer to a value indicating the desired
408            internal buffer size in sample frames.  The actual value
409            used by the device is returned via the same pointer.  A
410            value of zero can be specified, in which case the lowest
411            allowable value is determined.
412     \param callback A client-defined function that will be invoked
413            when input data is available and/or output data is needed.
414     \param userData An optional pointer to data that can be accessed
415            from within the callback function.
416     \param options An optional pointer to a structure containing various
417            global stream options, including a list of OR'ed RtAudioStreamFlags
418            and a suggested number of stream buffers that can be used to 
419            control stream latency.  More buffers typically result in more
420            robust performance, though at a cost of greater latency.  If a
421            value of zero is specified, a system-specific median value is
422            chosen.  If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
423            lowest allowable value is used.  The actual value used is
424            returned via the structure argument.  The parameter is API dependent.
425   */
426   void openStream( RtAudio::StreamParameters *outputParameters,
427                    RtAudio::StreamParameters *inputParameters,
428                    RtAudioFormat format, unsigned int sampleRate,
429                    unsigned int *bufferFrames, RtAudioCallback callback,
430                    void *userData = NULL, RtAudio::StreamOptions *options = NULL );
431
432   //! A function that closes a stream and frees any associated stream memory.
433   /*!
434     If a stream is not open, this function issues a warning and
435     returns (no exception is thrown).
436   */
437   void closeStream( void ) throw();
438
439   //! A function that starts a stream.
440   /*!
441     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
442     during processing.  An RtError (type = INVALID_USE) is thrown if a
443     stream is not open.  A warning is issued if the stream is already
444     running.
445   */
446   void startStream( void );
447
448   //! Stop a stream, allowing any samples remaining in the output queue to be played.
449   /*!
450     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
451     during processing.  An RtError (type = INVALID_USE) is thrown if a
452     stream is not open.  A warning is issued if the stream is already
453     stopped.
454   */
455   void stopStream( void );
456
457   //! Stop a stream, discarding any samples remaining in the input/output queue.
458   /*!
459     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
460     during processing.  An RtError (type = INVALID_USE) is thrown if a
461     stream is not open.  A warning is issued if the stream is already
462     stopped.
463   */
464   void abortStream( void );
465
466   //! Returns true if a stream is open and false if not.
467   bool isStreamOpen( void ) const throw();
468
469   //! Returns true if the stream is running and false if it is stopped or not open.
470   bool isStreamRunning( void ) const throw();
471
472   //! Returns the number of elapsed seconds since the stream was started.
473   /*!
474     If a stream is not open, an RtError (type = INVALID_USE) will be thrown.
475   */
476   double getStreamTime( void );
477
478   //! Returns the internal stream latency in sample frames.
479   /*!
480     The stream latency refers to delay in audio input and/or output
481     caused by internal buffering by the audio system and/or hardware.
482     For duplex streams, the returned value will represent the sum of
483     the input and output latencies.  If a stream is not open, an
484     RtError (type = INVALID_USE) will be thrown.  If the API does not
485     report latency, the return value will be zero.
486   */
487   long getStreamLatency( void );
488
489  //! Returns actual sample rate in use by the stream.
490  /*!
491    On some systems, the sample rate used may be slightly different
492    than that specified in the stream parameters.  If a stream is not
493    open, an RtError (type = INVALID_USE) will be thrown.
494  */
495   unsigned int getStreamSampleRate( void );
496
497   //! Specify whether warning messages should be printed to stderr.
498   void showWarnings( bool value = true ) throw();
499
500  protected:
501
502   void openRtApi( RtAudio::Api api );
503   RtApi *rtapi_;
504 };
505
506 // Operating system dependent thread functionality.
507 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
508   #include <windows.h>
509   #include <process.h>
510
511   typedef unsigned long ThreadHandle;
512   typedef CRITICAL_SECTION StreamMutex;
513
514 #elif defined(__LINUX_ALSA__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
515   // Using pthread library for various flavors of unix.
516   #include <pthread.h>
517
518   typedef pthread_t ThreadHandle;
519   typedef pthread_mutex_t StreamMutex;
520
521 #else // Setup for "dummy" behavior
522
523   #define __RTAUDIO_DUMMY__
524   typedef int ThreadHandle;
525   typedef int StreamMutex;
526
527 #endif
528
529 // This global structure type is used to pass callback information
530 // between the private RtAudio stream structure and global callback
531 // handling functions.
532 struct CallbackInfo {
533   void *object;    // Used as a "this" pointer.
534   ThreadHandle thread;
535   void *callback;
536   void *userData;
537   void *apiInfo;   // void pointer for API specific callback information
538   bool isRunning;
539
540   // Default constructor.
541   CallbackInfo()
542     :object(0), callback(0), userData(0), apiInfo(0), isRunning(false) {}
543 };
544
545 // **************************************************************** //
546 //
547 // RtApi class declaration.
548 //
549 // Subclasses of RtApi contain all API- and OS-specific code necessary
550 // to fully implement the RtAudio API.
551 //
552 // Note that RtApi is an abstract base class and cannot be
553 // explicitly instantiated.  The class RtAudio will create an
554 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
555 // RtApiJack, RtApiCore, RtApiAl, RtApiDs, or RtApiAsio).
556 //
557 // **************************************************************** //
558
559 #if defined( HAVE_GETTIMEOFDAY )
560   #include <sys/time.h>
561 #endif
562
563 #include <sstream>
564
565 class RtApi
566 {
567 public:
568
569   RtApi();
570   virtual ~RtApi();
571   virtual RtAudio::Api getCurrentApi( void ) = 0;
572   virtual unsigned int getDeviceCount( void ) = 0;
573   virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
574   virtual unsigned int getDefaultInputDevice( void );
575   virtual unsigned int getDefaultOutputDevice( void );
576   void openStream( RtAudio::StreamParameters *outputParameters,
577                    RtAudio::StreamParameters *inputParameters,
578                    RtAudioFormat format, unsigned int sampleRate,
579                    unsigned int *bufferFrames, RtAudioCallback callback,
580                    void *userData, RtAudio::StreamOptions *options );
581   virtual void closeStream( void );
582   virtual void startStream( void ) = 0;
583   virtual void stopStream( void ) = 0;
584   virtual void abortStream( void ) = 0;
585   long getStreamLatency( void );
586   unsigned int getStreamSampleRate( void );
587   virtual double getStreamTime( void );
588   bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; };
589   bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; };
590   void showWarnings( bool value ) { showWarnings_ = value; };
591
592
593 protected:
594
595   static const unsigned int MAX_SAMPLE_RATES;
596   static const unsigned int SAMPLE_RATES[];
597
598   enum { FAILURE, SUCCESS };
599
600   enum StreamState {
601     STREAM_STOPPED,
602     STREAM_RUNNING,
603     STREAM_CLOSED = -50
604   };
605
606   enum StreamMode {
607     OUTPUT,
608     INPUT,
609     DUPLEX,
610     UNINITIALIZED = -75
611   };
612
613   // A protected structure used for buffer conversion.
614   struct ConvertInfo {
615     int channels;
616     int inJump, outJump;
617     RtAudioFormat inFormat, outFormat;
618     std::vector<int> inOffset;
619     std::vector<int> outOffset;
620   };
621
622   // A protected structure for audio streams.
623   struct RtApiStream {
624     unsigned int device[2];    // Playback and record, respectively.
625     void *apiHandle;           // void pointer for API specific stream handle information
626     StreamMode mode;           // OUTPUT, INPUT, or DUPLEX.
627     StreamState state;         // STOPPED, RUNNING, or CLOSED
628     char *userBuffer[2];       // Playback and record, respectively.
629     char *deviceBuffer;
630     bool doConvertBuffer[2];   // Playback and record, respectively.
631     bool userInterleaved;
632     bool deviceInterleaved[2]; // Playback and record, respectively.
633     bool doByteSwap[2];        // Playback and record, respectively.
634     unsigned int sampleRate;
635     unsigned int bufferSize;
636     unsigned int nBuffers;
637     unsigned int nUserChannels[2];    // Playback and record, respectively.
638     unsigned int nDeviceChannels[2];  // Playback and record channels, respectively.
639     unsigned int channelOffset[2];    // Playback and record, respectively.
640     unsigned long latency[2];         // Playback and record, respectively.
641     RtAudioFormat userFormat;
642     RtAudioFormat deviceFormat[2];    // Playback and record, respectively.
643     StreamMutex mutex;
644     CallbackInfo callbackInfo;
645     ConvertInfo convertInfo[2];
646     double streamTime;         // Number of elapsed seconds since the stream started.
647
648 #if defined(HAVE_GETTIMEOFDAY)
649     struct timeval lastTickTimestamp;
650 #endif
651
652     RtApiStream()
653       :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
654   };
655
656   typedef signed short Int16;
657   typedef signed int Int32;
658   typedef float Float32;
659   typedef double Float64;
660
661   std::ostringstream errorStream_;
662   std::string errorText_;
663   bool showWarnings_;
664   RtApiStream stream_;
665
666   /*!
667     Protected, api-specific method that attempts to open a device
668     with the given parameters.  This function MUST be implemented by
669     all subclasses.  If an error is encountered during the probe, a
670     "warning" message is reported and FAILURE is returned. A
671     successful probe is indicated by a return value of SUCCESS.
672   */
673   virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
674                                 unsigned int firstChannel, unsigned int sampleRate,
675                                 RtAudioFormat format, unsigned int *bufferSize,
676                                 RtAudio::StreamOptions *options );
677
678   //! A protected function used to increment the stream time.
679   void tickStreamTime( void );
680
681   //! Protected common method to clear an RtApiStream structure.
682   void clearStreamInfo();
683
684   /*!
685     Protected common method that throws an RtError (type =
686     INVALID_USE) if a stream is not open.
687   */
688   void verifyStream( void );
689
690   //! Protected common error method to allow global control over error handling.
691   void error( RtError::Type type );
692
693   /*!
694     Protected method used to perform format, channel number, and/or interleaving
695     conversions between the user and device buffers.
696   */
697   void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
698
699   //! Protected common method used to perform byte-swapping on buffers.
700   void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
701
702   //! Protected common method that returns the number of bytes for a given format.
703   unsigned int formatBytes( RtAudioFormat format );
704
705   //! Protected common method that sets up the parameters for buffer conversion.
706   void setConvertInfo( StreamMode mode, unsigned int firstChannel );
707 };
708
709 // **************************************************************** //
710 //
711 // Inline RtAudio definitions.
712 //
713 // **************************************************************** //
714
715 inline RtAudio::Api RtAudio :: getCurrentApi( void ) throw() { return rtapi_->getCurrentApi(); }
716 inline unsigned int RtAudio :: getDeviceCount( void ) throw() { return rtapi_->getDeviceCount(); }
717 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
718 inline unsigned int RtAudio :: getDefaultInputDevice( void ) throw() { return rtapi_->getDefaultInputDevice(); }
719 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) throw() { return rtapi_->getDefaultOutputDevice(); }
720 inline void RtAudio :: closeStream( void ) throw() { return rtapi_->closeStream(); }
721 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
722 inline void RtAudio :: stopStream( void )  { return rtapi_->stopStream(); }
723 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
724 inline bool RtAudio :: isStreamOpen( void ) const throw() { return rtapi_->isStreamOpen(); }
725 inline bool RtAudio :: isStreamRunning( void ) const throw() { return rtapi_->isStreamRunning(); }
726 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
727 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); };
728 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
729 inline void RtAudio :: showWarnings( bool value ) throw() { rtapi_->showWarnings( value ); }
730
731 // RtApi Subclass prototypes.
732
733 #if defined(__MACOSX_CORE__)
734
735 #include <CoreAudio/AudioHardware.h>
736
737 class RtApiCore: public RtApi
738 {
739 public:
740
741   RtApiCore();
742   ~RtApiCore();
743   RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; };
744   unsigned int getDeviceCount( void );
745   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
746   unsigned int getDefaultOutputDevice( void );
747   unsigned int getDefaultInputDevice( void );
748   void closeStream( void );
749   void startStream( void );
750   void stopStream( void );
751   void abortStream( void );
752   long getStreamLatency( void );
753
754   // This function is intended for internal use only.  It must be
755   // public because it is called by the internal callback handler,
756   // which is not a member of RtAudio.  External use of this function
757   // will most likely produce highly undesireable results!
758   bool callbackEvent( AudioDeviceID deviceId,
759                       const AudioBufferList *inBufferList,
760                       const AudioBufferList *outBufferList );
761
762   private:
763
764   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
765                         unsigned int firstChannel, unsigned int sampleRate,
766                         RtAudioFormat format, unsigned int *bufferSize,
767                         RtAudio::StreamOptions *options );
768   static const char* getErrorCode( OSStatus code );
769 };
770
771 #endif
772
773 #if defined(__UNIX_JACK__)
774
775 class RtApiJack: public RtApi
776 {
777 public:
778
779   RtApiJack();
780   ~RtApiJack();
781   RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; };
782   unsigned int getDeviceCount( void );
783   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
784   void closeStream( void );
785   void startStream( void );
786   void stopStream( void );
787   void abortStream( void );
788   long getStreamLatency( void );
789
790   // This function is intended for internal use only.  It must be
791   // public because it is called by the internal callback handler,
792   // which is not a member of RtAudio.  External use of this function
793   // will most likely produce highly undesireable results!
794   bool callbackEvent( unsigned long nframes );
795
796   private:
797
798   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
799                         unsigned int firstChannel, unsigned int sampleRate,
800                         RtAudioFormat format, unsigned int *bufferSize,
801                         RtAudio::StreamOptions *options );
802 };
803
804 #endif
805
806 #if defined(__WINDOWS_ASIO__)
807
808 class RtApiAsio: public RtApi
809 {
810 public:
811
812   RtApiAsio();
813   ~RtApiAsio();
814   RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; };
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( long bufferIndex );
828
829   private:
830
831   std::vector<RtAudio::DeviceInfo> devices_;
832   void saveDeviceInfo( void );
833   bool coInitialized_;
834   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
835                         unsigned int firstChannel, unsigned int sampleRate,
836                         RtAudioFormat format, unsigned int *bufferSize,
837                         RtAudio::StreamOptions *options );
838 };
839
840 #endif
841
842 #if defined(__WINDOWS_DS__)
843
844 class RtApiDs: public RtApi
845 {
846 public:
847
848   RtApiDs();
849   ~RtApiDs();
850   RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; };
851   unsigned int getDeviceCount( void );
852   unsigned int getDefaultOutputDevice( void );
853   unsigned int getDefaultInputDevice( void );
854   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
855   void closeStream( void );
856   void startStream( void );
857   void stopStream( void );
858   void abortStream( void );
859   long getStreamLatency( void );
860
861   // This function is intended for internal use only.  It must be
862   // public because it is called by the internal callback handler,
863   // which is not a member of RtAudio.  External use of this function
864   // will most likely produce highly undesireable results!
865   void callbackEvent( void );
866
867   private:
868
869   bool coInitialized_;
870   bool buffersRolling;
871   long duplexPrerollBytes;
872   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
873                         unsigned int firstChannel, unsigned int sampleRate,
874                         RtAudioFormat format, unsigned int *bufferSize,
875                         RtAudio::StreamOptions *options );
876 };
877
878 #endif
879
880 #if defined(__LINUX_ALSA__)
881
882 class RtApiAlsa: public RtApi
883 {
884 public:
885
886   RtApiAlsa();
887   ~RtApiAlsa();
888   RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; };
889   unsigned int getDeviceCount( void );
890   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
891   void closeStream( void );
892   void startStream( void );
893   void stopStream( void );
894   void abortStream( void );
895
896   // This function is intended for internal use only.  It must be
897   // public because it is called by the internal callback handler,
898   // which is not a member of RtAudio.  External use of this function
899   // will most likely produce highly undesireable results!
900   void callbackEvent( void );
901
902   private:
903
904   std::vector<RtAudio::DeviceInfo> devices_;
905   void saveDeviceInfo( void );
906   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
907                         unsigned int firstChannel, unsigned int sampleRate,
908                         RtAudioFormat format, unsigned int *bufferSize,
909                         RtAudio::StreamOptions *options );
910 };
911
912 #endif
913
914 #if defined(__LINUX_OSS__)
915
916 class RtApiOss: public RtApi
917 {
918 public:
919
920   RtApiOss();
921   ~RtApiOss();
922   RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; };
923   unsigned int getDeviceCount( void );
924   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
925   void closeStream( void );
926   void startStream( void );
927   void stopStream( void );
928   void abortStream( void );
929
930   // This function is intended for internal use only.  It must be
931   // public because it is called by the internal callback handler,
932   // which is not a member of RtAudio.  External use of this function
933   // will most likely produce highly undesireable results!
934   void callbackEvent( void );
935
936   private:
937
938   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
939                         unsigned int firstChannel, unsigned int sampleRate,
940                         RtAudioFormat format, unsigned int *bufferSize,
941                         RtAudio::StreamOptions *options );
942 };
943
944 #endif
945
946 #if defined(__RTAUDIO_DUMMY__)
947
948 class RtApiDummy: public RtApi
949 {
950 public:
951
952   RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtError::WARNING ); };
953   RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; };
954   unsigned int getDeviceCount( void ) { return 0; };
955   RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) { RtAudio::DeviceInfo info; return info; };
956   void closeStream( void ) {};
957   void startStream( void ) {};
958   void stopStream( void ) {};
959   void abortStream( void ) {};
960
961   private:
962
963   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
964                         unsigned int firstChannel, unsigned int sampleRate,
965                         RtAudioFormat format, unsigned int *bufferSize,
966                         RtAudio::StreamOptions *options ) { return false; };
967 };
968
969 #endif
970
971 #endif
972
973 // Indentation settings for Vim and Emacs
974 //
975 // Local Variables:
976 // c-basic-offset: 2
977 // indent-tabs-mode: nil
978 // End:
979 //
980 // vim: et sts=2 sw=2