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