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