1 /************************************************************************/
3 \brief Realtime audio i/o C++ classes.
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.
10 RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
12 RtAudio: realtime audio i/o C++ classes
13 Copyright (c) 2001-2016 Gary P. Scavone
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:
23 The above copyright notice and this permission notice shall be
24 included in all copies or substantial portions of the Software.
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.
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.
39 /************************************************************************/
48 #define RTAUDIO_VERSION "4.1.2"
55 #ifndef _GLIBCXX_USE_NOEXCEPT
56 #define _GLIBCXX_USE_NOEXCEPT
59 /*! \typedef typedef unsigned long RtAudioFormat;
60 \brief RtAudio data format type.
62 Support for signed integers and floats. Audio data fed to/from an
63 RtAudio stream is assumed to ALWAYS be in host byte order. The
64 internal routines will automatically take care of any necessary
65 byte-swapping between the host format and the soundcard. Thus,
66 endian-ness is not a concern in the following format definitions.
68 - \e RTAUDIO_SINT8: 8-bit signed integer.
69 - \e RTAUDIO_SINT16: 16-bit signed integer.
70 - \e RTAUDIO_SINT24: 24-bit signed integer.
71 - \e RTAUDIO_SINT32: 32-bit signed integer.
72 - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
73 - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
75 typedef unsigned long RtAudioFormat;
76 static const RtAudioFormat RTAUDIO_SINT8 = 0x1; // 8-bit signed integer.
77 static const RtAudioFormat RTAUDIO_SINT16 = 0x2; // 16-bit signed integer.
78 static const RtAudioFormat RTAUDIO_SINT24 = 0x4; // 24-bit signed integer.
79 static const RtAudioFormat RTAUDIO_SINT32 = 0x8; // 32-bit signed integer.
80 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
81 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
83 /*! \typedef typedef unsigned long RtAudioStreamFlags;
84 \brief RtAudio stream option flags.
86 The following flags can be OR'ed together to allow a client to
87 make changes to the default stream behavior:
89 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
90 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
91 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
92 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
94 By default, RtAudio streams pass and receive audio data from the
95 client in an interleaved format. By passing the
96 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
97 data will instead be presented in non-interleaved buffers. In
98 this case, each buffer argument in the RtAudioCallback function
99 will point to a single array of data, with \c nFrames samples for
100 each channel concatenated back-to-back. For example, the first
101 sample of data for the second channel would be located at index \c
102 nFrames (assuming the \c buffer pointer was recast to the correct
103 data type for the stream).
105 Certain audio APIs offer a number of parameters that influence the
106 I/O latency of a stream. By default, RtAudio will attempt to set
107 these parameters internally for robust (glitch-free) performance
108 (though some APIs, like Windows Direct Sound, make this difficult).
109 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
110 function, internal stream settings will be influenced in an attempt
111 to minimize stream latency, though possibly at the expense of stream
114 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
115 open the input and/or output stream device(s) for exclusive use.
116 Note that this is not possible with all supported audio APIs.
118 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
119 to select realtime scheduling (round-robin) for the callback thread.
121 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
122 open the "default" PCM device when using the ALSA API. Note that this
123 will override any specified input or output device id.
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).
132 /*! \typedef typedef unsigned long RtAudioStreamStatus;
133 \brief RtAudio stream status (over- or underflow) flags.
135 Notification of a stream over- or underflow is indicated by a
136 non-zero stream \c status argument in the RtAudioCallback function.
137 The stream status can be one of the following two options,
138 depending on whether the stream is open for output and/or input:
140 - \e RTAUDIO_INPUT_OVERFLOW: Input data was discarded because of an overflow condition at the driver.
141 - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
143 typedef unsigned int RtAudioStreamStatus;
144 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver.
145 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound.
147 //! RtAudio callback function prototype.
149 All RtAudio clients must create a function of type RtAudioCallback
150 to read and/or write data from/to the audio stream. When the
151 underlying audio system is ready for new input or output data, this
152 function will be invoked.
154 \param outputBuffer For output (or duplex) streams, the client
155 should write \c nFrames of audio sample frames into this
156 buffer. This argument should be recast to the datatype
157 specified when the stream was opened. For input-only
158 streams, this argument will be NULL.
160 \param inputBuffer For input (or duplex) streams, this buffer will
161 hold \c nFrames of input audio sample frames. This
162 argument should be recast to the datatype specified when the
163 stream was opened. For output-only streams, this argument
166 \param nFrames The number of sample frames of input or output
167 data in the buffers. The actual buffer size in bytes is
168 dependent on the data type and number of channels in use.
170 \param streamTime The number of seconds that have elapsed since the
173 \param status If non-zero, this argument indicates a data overflow
174 or underflow condition for the stream. The particular
175 condition can be determined by comparison with the
176 RtAudioStreamStatus flags.
178 \param userData A pointer to optional data provided by the client
179 when opening the stream (default = NULL).
181 To continue normal stream operation, the RtAudioCallback function
182 should return a value of zero. To stop the stream and drain the
183 output buffer, the function should return a value of one. To abort
184 the stream immediately, the client should return a value of two.
186 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
187 unsigned int nFrames,
189 RtAudioStreamStatus status,
192 /************************************************************************/
193 /*! \class RtAudioError
194 \brief Exception handling class for RtAudio.
196 The RtAudioError class is quite simple but it does allow errors to be
197 "caught" by RtAudioError::Type. See the RtAudio documentation to know
198 which methods can throw an RtAudioError.
200 /************************************************************************/
202 class RtAudioError : public std::exception
205 //! Defined RtAudioError types.
207 WARNING, /*!< A non-critical error. */
208 DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */
209 UNSPECIFIED, /*!< The default, unspecified error type. */
210 NO_DEVICES_FOUND, /*!< No devices found on system. */
211 INVALID_DEVICE, /*!< An invalid device ID was specified. */
212 MEMORY_ERROR, /*!< An error occured during memory allocation. */
213 INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */
214 INVALID_USE, /*!< The function was called incorrectly. */
215 DRIVER_ERROR, /*!< A system driver error occured. */
216 SYSTEM_ERROR, /*!< A system error occured. */
217 THREAD_ERROR /*!< A thread error occured. */
221 RtAudioError( const std::string& message, Type type = RtAudioError::UNSPECIFIED ) : message_(message), type_(type) {}
224 virtual ~RtAudioError( void ) _GLIBCXX_USE_NOEXCEPT {}
226 //! Prints thrown error message to stderr.
227 virtual void printMessage( void ) const { std::cerr << '\n' << message_ << "\n\n"; }
229 //! Returns the thrown error message type.
230 virtual const Type& getType(void) const { return type_; }
232 //! Returns the thrown error message string.
233 virtual const std::string& getMessage(void) const { return message_; }
235 //! Returns the thrown error message as a c-style string.
236 virtual const char* what( void ) const _GLIBCXX_USE_NOEXCEPT { return message_.c_str(); }
239 std::string message_;
243 //! RtAudio error callback function prototype.
245 \param type Type of error.
246 \param errorText Error description.
248 typedef void (*RtAudioErrorCallback)( RtAudioError::Type type, const std::string &errorText );
250 // **************************************************************** //
252 // RtAudio class declaration.
254 // RtAudio is a "controller" used to select an available audio i/o
255 // interface. It presents a common API for the user to call but all
256 // functionality is implemented by the class RtApi and its
257 // subclasses. RtAudio creates an instance of an RtApi subclass
258 // based on the user's API choice. If no choice is made, RtAudio
259 // attempts to make a "logical" API selection.
261 // **************************************************************** //
269 //! Audio API specifier arguments.
271 UNSPECIFIED, /*!< Search for a working compiled API. */
272 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
273 LINUX_PULSE, /*!< The Linux PulseAudio API. */
274 LINUX_OSS, /*!< The Linux Open Sound System API. */
275 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
276 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
277 WINDOWS_WASAPI, /*!< The Microsoft WASAPI API. */
278 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
279 WINDOWS_DS, /*!< The Microsoft Direct Sound API. */
280 RTAUDIO_DUMMY /*!< A compilable but non-functional API. */
283 //! The public device information structure for returning queried values.
285 bool probed; /*!< true if the device capabilities were successfully probed. */
286 std::string name; /*!< Character string device identifier. */
287 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
288 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
289 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
290 bool isDefaultOutput; /*!< true if this is the default output device. */
291 bool isDefaultInput; /*!< true if this is the default input device. */
292 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
293 unsigned int preferredSampleRate; /*!< Preferred sample rate, eg. for WASAPI the system sample rate. */
294 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
296 // Default constructor.
298 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
299 isDefaultOutput(false), isDefaultInput(false), preferredSampleRate(0), nativeFormats(0) {}
302 //! The structure for specifying input or ouput stream parameters.
303 struct StreamParameters {
304 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
305 unsigned int nChannels; /*!< Number of channels. */
306 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
308 // Default constructor.
310 : deviceId(0), nChannels(0), firstChannel(0) {}
313 //! The structure for specifying stream options.
315 The following flags can be OR'ed together to allow a client to
316 make changes to the default stream behavior:
318 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
319 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
320 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
321 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
322 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
324 By default, RtAudio streams pass and receive audio data from the
325 client in an interleaved format. By passing the
326 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
327 data will instead be presented in non-interleaved buffers. In
328 this case, each buffer argument in the RtAudioCallback function
329 will point to a single array of data, with \c nFrames samples for
330 each channel concatenated back-to-back. For example, the first
331 sample of data for the second channel would be located at index \c
332 nFrames (assuming the \c buffer pointer was recast to the correct
333 data type for the stream).
335 Certain audio APIs offer a number of parameters that influence the
336 I/O latency of a stream. By default, RtAudio will attempt to set
337 these parameters internally for robust (glitch-free) performance
338 (though some APIs, like Windows Direct Sound, make this difficult).
339 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
340 function, internal stream settings will be influenced in an attempt
341 to minimize stream latency, though possibly at the expense of stream
344 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
345 open the input and/or output stream device(s) for exclusive use.
346 Note that this is not possible with all supported audio APIs.
348 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
349 to select realtime scheduling (round-robin) for the callback thread.
350 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
351 flag is set. It defines the thread's realtime priority.
353 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
354 open the "default" PCM device when using the ALSA API. Note that this
355 will override any specified input or output device id.
357 The \c numberOfBuffers parameter can be used to control stream
358 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
359 only. A value of two is usually the smallest allowed. Larger
360 numbers can potentially result in more robust stream performance,
361 though likely at the cost of stream latency. The value set by the
362 user is replaced during execution of the RtAudio::openStream()
363 function by the value actually used by the system.
365 The \c streamName parameter can be used to set the client name
366 when using the Jack API. By default, the client name is set to
367 RtApiJack. However, if you wish to create multiple instances of
368 RtAudio with Jack, each instance must have a unique client name.
370 struct StreamOptions {
371 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
372 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
373 std::string streamName; /*!< A stream name (currently used only in Jack). */
374 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
376 // Default constructor.
378 : flags(0), numberOfBuffers(0), priority(0) {}
381 //! A static function to determine the current RtAudio version.
382 static std::string getVersion( void );
384 //! A static function to determine the available compiled audio APIs.
386 The values returned in the std::vector can be compared against
387 the enumerated list values. Note that there can be more than one
388 API compiled for certain operating systems.
390 static void getCompiledApi( std::vector<RtAudio::Api> &apis );
392 //! The class constructor.
394 The constructor performs minor initialization tasks. An exception
395 can be thrown if no API support is compiled.
397 If no API argument is specified and multiple API support has been
398 compiled, the default order of use is JACK, ALSA, OSS (Linux
399 systems) and ASIO, DS (Windows systems).
401 RtAudio( RtAudio::Api api=UNSPECIFIED );
405 If a stream is running or open, it will be stopped and closed
410 //! Returns the audio API specifier for the current instance of RtAudio.
411 RtAudio::Api getCurrentApi( void );
413 //! A public function that queries for the number of audio devices available.
415 This function performs a system query of available devices each time it
416 is called, thus supporting devices connected \e after instantiation. If
417 a system error occurs during processing, a warning will be issued.
419 unsigned int getDeviceCount( void );
421 //! Return an RtAudio::DeviceInfo structure for a specified device number.
424 Any device integer between 0 and getDeviceCount() - 1 is valid.
425 If an invalid argument is provided, an RtAudioError (type = INVALID_USE)
426 will be thrown. If a device is busy or otherwise unavailable, the
427 structure member "probed" will have a value of "false" and all
428 other members are undefined. If the specified device is the
429 current default input or output device, the corresponding
430 "isDefault" member will have a value of "true".
432 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
434 //! A function that returns the index of the default output device.
436 If the underlying audio API does not provide a "default
437 device", or if no devices are available, the return value will be
438 0. Note that this is a valid device identifier and it is the
439 client's responsibility to verify that a device is available
440 before attempting to open a stream.
442 unsigned int getDefaultOutputDevice( void );
444 //! A function that returns the index of the default input device.
446 If the underlying audio API does not provide a "default
447 device", or if no devices are available, the return value will be
448 0. Note that this is a valid device identifier and it is the
449 client's responsibility to verify that a device is available
450 before attempting to open a stream.
452 unsigned int getDefaultInputDevice( void );
454 //! A public function for opening a stream with the specified parameters.
456 An RtAudioError (type = SYSTEM_ERROR) is thrown if a stream cannot be
457 opened with the specified parameters or an error occurs during
458 processing. An RtAudioError (type = INVALID_USE) is thrown if any
459 invalid device ID or channel number parameters are specified.
461 \param outputParameters Specifies output stream parameters to use
462 when opening a stream, including a device ID, number of channels,
463 and starting channel number. For input-only streams, this
464 argument should be NULL. The device ID is an index value between
465 0 and getDeviceCount() - 1.
466 \param inputParameters Specifies input stream parameters to use
467 when opening a stream, including a device ID, number of channels,
468 and starting channel number. For output-only streams, this
469 argument should be NULL. The device ID is an index value between
470 0 and getDeviceCount() - 1.
471 \param format An RtAudioFormat specifying the desired sample data format.
472 \param sampleRate The desired sample rate (sample frames per second).
473 \param *bufferFrames A pointer to a value indicating the desired
474 internal buffer size in sample frames. The actual value
475 used by the device is returned via the same pointer. A
476 value of zero can be specified, in which case the lowest
477 allowable value is determined.
478 \param callback A client-defined function that will be invoked
479 when input data is available and/or output data is needed.
480 \param userData An optional pointer to data that can be accessed
481 from within the callback function.
482 \param options An optional pointer to a structure containing various
483 global stream options, including a list of OR'ed RtAudioStreamFlags
484 and a suggested number of stream buffers that can be used to
485 control stream latency. More buffers typically result in more
486 robust performance, though at a cost of greater latency. If a
487 value of zero is specified, a system-specific median value is
488 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
489 lowest allowable value is used. The actual value used is
490 returned via the structure argument. The parameter is API dependent.
491 \param errorCallback A client-defined function that will be invoked
492 when an error has occured.
494 void openStream( RtAudio::StreamParameters *outputParameters,
495 RtAudio::StreamParameters *inputParameters,
496 RtAudioFormat format, unsigned int sampleRate,
497 unsigned int *bufferFrames, RtAudioCallback callback,
498 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
500 //! A function that closes a stream and frees any associated stream memory.
502 If a stream is not open, this function issues a warning and
503 returns (no exception is thrown).
505 void closeStream( void );
507 //! A function that starts a stream.
509 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
510 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
511 stream is not open. A warning is issued if the stream is already
514 void startStream( void );
516 //! Stop a stream, allowing any samples remaining in the output queue to be played.
518 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
519 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
520 stream is not open. A warning is issued if the stream is already
523 void stopStream( void );
525 //! Stop a stream, discarding any samples remaining in the input/output queue.
527 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
528 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
529 stream is not open. A warning is issued if the stream is already
532 void abortStream( void );
534 //! Returns true if a stream is open and false if not.
535 bool isStreamOpen( void ) const;
537 //! Returns true if the stream is running and false if it is stopped or not open.
538 bool isStreamRunning( void ) const;
540 //! Returns the number of elapsed seconds since the stream was started.
542 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
544 double getStreamTime( void );
546 //! Set the stream time to a time in seconds greater than or equal to 0.0.
548 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
550 void setStreamTime( double time );
552 //! Returns the internal stream latency in sample frames.
554 The stream latency refers to delay in audio input and/or output
555 caused by internal buffering by the audio system and/or hardware.
556 For duplex streams, the returned value will represent the sum of
557 the input and output latencies. If a stream is not open, an
558 RtAudioError (type = INVALID_USE) will be thrown. If the API does not
559 report latency, the return value will be zero.
561 long getStreamLatency( void );
563 //! Returns actual sample rate in use by the stream.
565 On some systems, the sample rate used may be slightly different
566 than that specified in the stream parameters. If a stream is not
567 open, an RtAudioError (type = INVALID_USE) will be thrown.
569 unsigned int getStreamSampleRate( void );
571 //! Specify whether warning messages should be printed to stderr.
572 void showWarnings( bool value = true );
576 void openRtApi( RtAudio::Api api );
580 // Operating system dependent thread functionality.
581 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
589 typedef uintptr_t ThreadHandle;
590 typedef CRITICAL_SECTION StreamMutex;
592 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
593 // Using pthread library for various flavors of unix.
596 typedef pthread_t ThreadHandle;
597 typedef pthread_mutex_t StreamMutex;
599 #else // Setup for "dummy" behavior
601 #define __RTAUDIO_DUMMY__
602 typedef int ThreadHandle;
603 typedef int StreamMutex;
607 // This global structure type is used to pass callback information
608 // between the private RtAudio stream structure and global callback
609 // handling functions.
610 struct CallbackInfo {
611 void *object; // Used as a "this" pointer.
616 void *apiInfo; // void pointer for API specific callback information
621 // Default constructor.
623 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false), priority(0) {}
626 // **************************************************************** //
628 // RtApi class declaration.
630 // Subclasses of RtApi contain all API- and OS-specific code necessary
631 // to fully implement the RtAudio API.
633 // Note that RtApi is an abstract base class and cannot be
634 // explicitly instantiated. The class RtAudio will create an
635 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
636 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
638 // **************************************************************** //
640 #pragma pack(push, 1)
649 S24& operator = ( const int& i ) {
650 c3[0] = (i & 0x000000ff);
651 c3[1] = (i & 0x0000ff00) >> 8;
652 c3[2] = (i & 0x00ff0000) >> 16;
656 S24( const S24& v ) { *this = v; }
657 S24( const double& d ) { *this = (int) d; }
658 S24( const float& f ) { *this = (int) f; }
659 S24( const signed short& s ) { *this = (int) s; }
660 S24( const char& c ) { *this = (int) c; }
663 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
664 if (i & 0x800000) i |= ~0xffffff;
670 #if defined( HAVE_GETTIMEOFDAY )
671 #include <sys/time.h>
682 virtual RtAudio::Api getCurrentApi( void ) = 0;
683 virtual unsigned int getDeviceCount( void ) = 0;
684 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
685 virtual unsigned int getDefaultInputDevice( void );
686 virtual unsigned int getDefaultOutputDevice( void );
687 void openStream( RtAudio::StreamParameters *outputParameters,
688 RtAudio::StreamParameters *inputParameters,
689 RtAudioFormat format, unsigned int sampleRate,
690 unsigned int *bufferFrames, RtAudioCallback callback,
691 void *userData, RtAudio::StreamOptions *options,
692 RtAudioErrorCallback errorCallback );
693 virtual void closeStream( void );
694 virtual void startStream( void ) = 0;
695 virtual void stopStream( void ) = 0;
696 virtual void abortStream( void ) = 0;
697 long getStreamLatency( void );
698 unsigned int getStreamSampleRate( void );
699 virtual double getStreamTime( void );
700 virtual void setStreamTime( double time );
701 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
702 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
703 void showWarnings( bool value ) { showWarnings_ = value; }
708 static const unsigned int MAX_SAMPLE_RATES;
709 static const unsigned int SAMPLE_RATES[];
711 enum { FAILURE, SUCCESS };
727 // A protected structure used for buffer conversion.
731 RtAudioFormat inFormat, outFormat;
732 std::vector<int> inOffset;
733 std::vector<int> outOffset;
736 // A protected structure for audio streams.
738 unsigned int device[2]; // Playback and record, respectively.
739 void *apiHandle; // void pointer for API specific stream handle information
740 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
741 StreamState state; // STOPPED, RUNNING, or CLOSED
742 char *userBuffer[2]; // Playback and record, respectively.
744 bool doConvertBuffer[2]; // Playback and record, respectively.
745 bool userInterleaved;
746 bool deviceInterleaved[2]; // Playback and record, respectively.
747 bool doByteSwap[2]; // Playback and record, respectively.
748 unsigned int sampleRate;
749 unsigned int bufferSize;
750 unsigned int nBuffers;
751 unsigned int nUserChannels[2]; // Playback and record, respectively.
752 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
753 unsigned int channelOffset[2]; // Playback and record, respectively.
754 unsigned long latency[2]; // Playback and record, respectively.
755 RtAudioFormat userFormat;
756 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
758 CallbackInfo callbackInfo;
759 ConvertInfo convertInfo[2];
760 double streamTime; // Number of elapsed seconds since the stream started.
762 #if defined(HAVE_GETTIMEOFDAY)
763 struct timeval lastTickTimestamp;
767 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
771 typedef signed short Int16;
772 typedef signed int Int32;
773 typedef float Float32;
774 typedef double Float64;
776 std::ostringstream errorStream_;
777 std::string errorText_;
780 bool firstErrorOccurred_;
783 Protected, api-specific method that attempts to open a device
784 with the given parameters. This function MUST be implemented by
785 all subclasses. If an error is encountered during the probe, a
786 "warning" message is reported and FAILURE is returned. A
787 successful probe is indicated by a return value of SUCCESS.
789 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
790 unsigned int firstChannel, unsigned int sampleRate,
791 RtAudioFormat format, unsigned int *bufferSize,
792 RtAudio::StreamOptions *options );
794 //! A protected function used to increment the stream time.
795 void tickStreamTime( void );
797 //! Protected common method to clear an RtApiStream structure.
798 void clearStreamInfo();
801 Protected common method that throws an RtAudioError (type =
802 INVALID_USE) if a stream is not open.
804 void verifyStream( void );
806 //! Protected common error method to allow global control over error handling.
807 void error( RtAudioError::Type type );
810 Protected method used to perform format, channel number, and/or interleaving
811 conversions between the user and device buffers.
813 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
815 //! Protected common method used to perform byte-swapping on buffers.
816 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
818 //! Protected common method that returns the number of bytes for a given format.
819 unsigned int formatBytes( RtAudioFormat format );
821 //! Protected common method that sets up the parameters for buffer conversion.
822 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
825 // **************************************************************** //
827 // Inline RtAudio definitions.
829 // **************************************************************** //
831 inline RtAudio::Api RtAudio :: getCurrentApi( void ) { return rtapi_->getCurrentApi(); }
832 inline unsigned int RtAudio :: getDeviceCount( void ) { return rtapi_->getDeviceCount(); }
833 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
834 inline unsigned int RtAudio :: getDefaultInputDevice( void ) { return rtapi_->getDefaultInputDevice(); }
835 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) { return rtapi_->getDefaultOutputDevice(); }
836 inline void RtAudio :: closeStream( void ) { return rtapi_->closeStream(); }
837 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
838 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
839 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
840 inline bool RtAudio :: isStreamOpen( void ) const { return rtapi_->isStreamOpen(); }
841 inline bool RtAudio :: isStreamRunning( void ) const { return rtapi_->isStreamRunning(); }
842 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
843 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
844 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
845 inline void RtAudio :: setStreamTime( double time ) { return rtapi_->setStreamTime( time ); }
846 inline void RtAudio :: showWarnings( bool value ) { rtapi_->showWarnings( value ); }
848 // RtApi Subclass prototypes.
850 #if defined(__MACOSX_CORE__)
852 #include <CoreAudio/AudioHardware.h>
854 class RtApiCore: public RtApi
860 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
861 unsigned int getDeviceCount( void );
862 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
863 unsigned int getDefaultOutputDevice( void );
864 unsigned int getDefaultInputDevice( void );
865 void closeStream( void );
866 void startStream( void );
867 void stopStream( void );
868 void abortStream( void );
869 long getStreamLatency( void );
871 // This function is intended for internal use only. It must be
872 // public because it is called by the internal callback handler,
873 // which is not a member of RtAudio. External use of this function
874 // will most likely produce highly undesireable results!
875 bool callbackEvent( AudioDeviceID deviceId,
876 const AudioBufferList *inBufferList,
877 const AudioBufferList *outBufferList );
881 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
882 unsigned int firstChannel, unsigned int sampleRate,
883 RtAudioFormat format, unsigned int *bufferSize,
884 RtAudio::StreamOptions *options );
885 static const char* getErrorCode( OSStatus code );
890 #if defined(__UNIX_JACK__)
892 class RtApiJack: public RtApi
898 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
899 unsigned int getDeviceCount( void );
900 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
901 void closeStream( void );
902 void startStream( void );
903 void stopStream( void );
904 void abortStream( void );
905 long getStreamLatency( void );
907 // This function is intended for internal use only. It must be
908 // public because it is called by the internal callback handler,
909 // which is not a member of RtAudio. External use of this function
910 // will most likely produce highly undesireable results!
911 bool callbackEvent( unsigned long nframes );
915 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
916 unsigned int firstChannel, unsigned int sampleRate,
917 RtAudioFormat format, unsigned int *bufferSize,
918 RtAudio::StreamOptions *options );
923 #if defined(__WINDOWS_ASIO__)
925 class RtApiAsio: public RtApi
931 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
932 unsigned int getDeviceCount( void );
933 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
934 void closeStream( void );
935 void startStream( void );
936 void stopStream( void );
937 void abortStream( void );
938 long getStreamLatency( void );
940 // This function is intended for internal use only. It must be
941 // public because it is called by the internal callback handler,
942 // which is not a member of RtAudio. External use of this function
943 // will most likely produce highly undesireable results!
944 bool callbackEvent( long bufferIndex );
948 std::vector<RtAudio::DeviceInfo> devices_;
949 void saveDeviceInfo( void );
951 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
952 unsigned int firstChannel, unsigned int sampleRate,
953 RtAudioFormat format, unsigned int *bufferSize,
954 RtAudio::StreamOptions *options );
959 #if defined(__WINDOWS_DS__)
961 class RtApiDs: public RtApi
967 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
968 unsigned int getDeviceCount( void );
969 unsigned int getDefaultOutputDevice( void );
970 unsigned int getDefaultInputDevice( void );
971 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
972 void closeStream( void );
973 void startStream( void );
974 void stopStream( void );
975 void abortStream( void );
976 long getStreamLatency( void );
978 // This function is intended for internal use only. It must be
979 // public because it is called by the internal callback handler,
980 // which is not a member of RtAudio. External use of this function
981 // will most likely produce highly undesireable results!
982 void callbackEvent( void );
988 long duplexPrerollBytes;
989 std::vector<struct DsDevice> dsDevices;
990 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
991 unsigned int firstChannel, unsigned int sampleRate,
992 RtAudioFormat format, unsigned int *bufferSize,
993 RtAudio::StreamOptions *options );
998 #if defined(__WINDOWS_WASAPI__)
1000 struct IMMDeviceEnumerator;
1002 class RtApiWasapi : public RtApi
1008 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_WASAPI; }
1009 unsigned int getDeviceCount( void );
1010 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1011 unsigned int getDefaultOutputDevice( void );
1012 unsigned int getDefaultInputDevice( void );
1013 void closeStream( void );
1014 void startStream( void );
1015 void stopStream( void );
1016 void abortStream( void );
1019 bool coInitialized_;
1020 IMMDeviceEnumerator* deviceEnumerator_;
1022 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1023 unsigned int firstChannel, unsigned int sampleRate,
1024 RtAudioFormat format, unsigned int* bufferSize,
1025 RtAudio::StreamOptions* options );
1027 static DWORD WINAPI runWasapiThread( void* wasapiPtr );
1028 static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
1029 static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
1030 void wasapiThread();
1035 #if defined(__LINUX_ALSA__)
1037 class RtApiAlsa: public RtApi
1043 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
1044 unsigned int getDeviceCount( void );
1045 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1046 void closeStream( void );
1047 void startStream( void );
1048 void stopStream( void );
1049 void abortStream( void );
1051 // This function is intended for internal use only. It must be
1052 // public because it is called by the internal callback handler,
1053 // which is not a member of RtAudio. External use of this function
1054 // will most likely produce highly undesireable results!
1055 void callbackEvent( void );
1059 std::vector<RtAudio::DeviceInfo> devices_;
1060 void saveDeviceInfo( void );
1061 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1062 unsigned int firstChannel, unsigned int sampleRate,
1063 RtAudioFormat format, unsigned int *bufferSize,
1064 RtAudio::StreamOptions *options );
1069 #if defined(__LINUX_PULSE__)
1071 class RtApiPulse: public RtApi
1075 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
1076 unsigned int getDeviceCount( void );
1077 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1078 void closeStream( void );
1079 void startStream( void );
1080 void stopStream( void );
1081 void abortStream( void );
1083 // This function is intended for internal use only. It must be
1084 // public because it is called by the internal callback handler,
1085 // which is not a member of RtAudio. External use of this function
1086 // will most likely produce highly undesireable results!
1087 void callbackEvent( void );
1091 std::vector<RtAudio::DeviceInfo> devices_;
1092 void saveDeviceInfo( void );
1093 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1094 unsigned int firstChannel, unsigned int sampleRate,
1095 RtAudioFormat format, unsigned int *bufferSize,
1096 RtAudio::StreamOptions *options );
1101 #if defined(__LINUX_OSS__)
1103 class RtApiOss: public RtApi
1109 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1110 unsigned int getDeviceCount( void );
1111 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1112 void closeStream( void );
1113 void startStream( void );
1114 void stopStream( void );
1115 void abortStream( void );
1117 // This function is intended for internal use only. It must be
1118 // public because it is called by the internal callback handler,
1119 // which is not a member of RtAudio. External use of this function
1120 // will most likely produce highly undesireable results!
1121 void callbackEvent( void );
1125 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1126 unsigned int firstChannel, unsigned int sampleRate,
1127 RtAudioFormat format, unsigned int *bufferSize,
1128 RtAudio::StreamOptions *options );
1133 #if defined(__RTAUDIO_DUMMY__)
1135 class RtApiDummy: public RtApi
1139 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtAudioError::WARNING ); }
1140 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1141 unsigned int getDeviceCount( void ) { return 0; }
1142 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1143 void closeStream( void ) {}
1144 void startStream( void ) {}
1145 void stopStream( void ) {}
1146 void abortStream( void ) {}
1150 bool probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
1151 unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
1152 RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
1153 RtAudio::StreamOptions * /*options*/ ) { return false; }
1160 // Indentation settings for Vim and Emacs
1163 // c-basic-offset: 2
1164 // indent-tabs-mode: nil
1167 // vim: et sts=2 sw=2