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