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