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