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