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-2017 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 "5.0.0"
50 #if defined _WIN32 || defined __CYGWIN__
51 #if defined(RTAUDIO_EXPORT)
52 #define RTAUDIO_DLL_PUBLIC __declspec(dllexport)
54 #define RTAUDIO_DLL_PUBLIC
58 #define RTAUDIO_DLL_PUBLIC __attribute__( (visibility( "default" )) )
60 #define RTAUDIO_DLL_PUBLIC
69 /*! \typedef typedef unsigned long RtAudioFormat;
70 \brief RtAudio data format type.
72 Support for signed integers and floats. Audio data fed to/from an
73 RtAudio stream is assumed to ALWAYS be in host byte order. The
74 internal routines will automatically take care of any necessary
75 byte-swapping between the host format and the soundcard. Thus,
76 endian-ness is not a concern in the following format definitions.
78 - \e RTAUDIO_SINT8: 8-bit signed integer.
79 - \e RTAUDIO_SINT16: 16-bit signed integer.
80 - \e RTAUDIO_SINT24: 24-bit signed integer.
81 - \e RTAUDIO_SINT32: 32-bit signed integer.
82 - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
83 - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
85 typedef unsigned long RtAudioFormat;
86 static const RtAudioFormat RTAUDIO_SINT8 = 0x1; // 8-bit signed integer.
87 static const RtAudioFormat RTAUDIO_SINT16 = 0x2; // 16-bit signed integer.
88 static const RtAudioFormat RTAUDIO_SINT24 = 0x4; // 24-bit signed integer.
89 static const RtAudioFormat RTAUDIO_SINT32 = 0x8; // 32-bit signed integer.
90 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
91 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
93 /*! \typedef typedef unsigned long RtAudioStreamFlags;
94 \brief RtAudio stream option flags.
96 The following flags can be OR'ed together to allow a client to
97 make changes to the default stream behavior:
99 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
100 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
101 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
102 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
103 - \e RTAUDIO_JACK_DONT_CONNECT: Do not automatically connect ports (JACK only).
105 By default, RtAudio streams pass and receive audio data from the
106 client in an interleaved format. By passing the
107 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
108 data will instead be presented in non-interleaved buffers. In
109 this case, each buffer argument in the RtAudioCallback function
110 will point to a single array of data, with \c nFrames samples for
111 each channel concatenated back-to-back. For example, the first
112 sample of data for the second channel would be located at index \c
113 nFrames (assuming the \c buffer pointer was recast to the correct
114 data type for the stream).
116 Certain audio APIs offer a number of parameters that influence the
117 I/O latency of a stream. By default, RtAudio will attempt to set
118 these parameters internally for robust (glitch-free) performance
119 (though some APIs, like Windows Direct Sound, make this difficult).
120 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
121 function, internal stream settings will be influenced in an attempt
122 to minimize stream latency, though possibly at the expense of stream
125 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
126 open the input and/or output stream device(s) for exclusive use.
127 Note that this is not possible with all supported audio APIs.
129 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
130 to select realtime scheduling (round-robin) for the callback thread.
132 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
133 open the "default" PCM device when using the ALSA API. Note that this
134 will override any specified input or output device id.
136 If the RTAUDIO_JACK_DONT_CONNECT flag is set, RtAudio will not attempt
137 to automatically connect the ports of the client to the audio device.
139 typedef unsigned int RtAudioStreamFlags;
140 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1; // Use non-interleaved buffers (default = interleaved).
141 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2; // Attempt to set stream parameters for lowest possible latency.
142 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4; // Attempt grab device and prevent use by others.
143 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
144 static const RtAudioStreamFlags RTAUDIO_ALSA_USE_DEFAULT = 0x10; // Use the "default" PCM device (ALSA only).
145 static const RtAudioStreamFlags RTAUDIO_JACK_DONT_CONNECT = 0x20; // Do not automatically connect ports (JACK only).
147 /*! \typedef typedef unsigned long RtAudioStreamStatus;
148 \brief RtAudio stream status (over- or underflow) flags.
150 Notification of a stream over- or underflow is indicated by a
151 non-zero stream \c status argument in the RtAudioCallback function.
152 The stream status can be one of the following two options,
153 depending on whether the stream is open for output and/or input:
155 - \e RTAUDIO_INPUT_OVERFLOW: Input data was discarded because of an overflow condition at the driver.
156 - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
158 typedef unsigned int RtAudioStreamStatus;
159 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver.
160 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound.
162 //! RtAudio callback function prototype.
164 All RtAudio clients must create a function of type RtAudioCallback
165 to read and/or write data from/to the audio stream. When the
166 underlying audio system is ready for new input or output data, this
167 function will be invoked.
169 \param outputBuffer For output (or duplex) streams, the client
170 should write \c nFrames of audio sample frames into this
171 buffer. This argument should be recast to the datatype
172 specified when the stream was opened. For input-only
173 streams, this argument will be NULL.
175 \param inputBuffer For input (or duplex) streams, this buffer will
176 hold \c nFrames of input audio sample frames. This
177 argument should be recast to the datatype specified when the
178 stream was opened. For output-only streams, this argument
181 \param nFrames The number of sample frames of input or output
182 data in the buffers. The actual buffer size in bytes is
183 dependent on the data type and number of channels in use.
185 \param streamTime The number of seconds that have elapsed since the
188 \param status If non-zero, this argument indicates a data overflow
189 or underflow condition for the stream. The particular
190 condition can be determined by comparison with the
191 RtAudioStreamStatus flags.
193 \param userData A pointer to optional data provided by the client
194 when opening the stream (default = NULL).
196 To continue normal stream operation, the RtAudioCallback function
197 should return a value of zero. To stop the stream and drain the
198 output buffer, the function should return a value of one. To abort
199 the stream immediately, the client should return a value of two.
201 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
202 unsigned int nFrames,
204 RtAudioStreamStatus status,
207 /************************************************************************/
208 /*! \class RtAudioError
209 \brief Exception handling class for RtAudio.
211 The RtAudioError class is quite simple but it does allow errors to be
212 "caught" by RtAudioError::Type. See the RtAudio documentation to know
213 which methods can throw an RtAudioError.
215 /************************************************************************/
217 class RTAUDIO_DLL_PUBLIC RtAudioError : public std::runtime_error
220 //! Defined RtAudioError types.
222 WARNING, /*!< A non-critical error. */
223 DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */
224 UNSPECIFIED, /*!< The default, unspecified error type. */
225 NO_DEVICES_FOUND, /*!< No devices found on system. */
226 INVALID_DEVICE, /*!< An invalid device ID was specified. */
227 MEMORY_ERROR, /*!< An error occured during memory allocation. */
228 INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */
229 INVALID_USE, /*!< The function was called incorrectly. */
230 DRIVER_ERROR, /*!< A system driver error occured. */
231 SYSTEM_ERROR, /*!< A system error occured. */
232 THREAD_ERROR /*!< A thread error occured. */
236 RtAudioError( const std::string& message,
237 Type type = RtAudioError::UNSPECIFIED )
238 : std::runtime_error(message), type_(type) {}
240 //! Prints thrown error message to stderr.
241 virtual void printMessage( void ) const
242 { std::cerr << '\n' << what() << "\n\n"; }
244 //! Returns the thrown error message type.
245 virtual const Type& getType(void) const { return type_; }
247 //! Returns the thrown error message string.
248 virtual const std::string getMessage(void) const
249 { return std::string(what()); }
255 //! RtAudio error callback function prototype.
257 \param type Type of error.
258 \param errorText Error description.
260 typedef void (*RtAudioErrorCallback)( RtAudioError::Type type, const std::string &errorText );
262 // **************************************************************** //
264 // RtAudio class declaration.
266 // RtAudio is a "controller" used to select an available audio i/o
267 // interface. It presents a common API for the user to call but all
268 // functionality is implemented by the class RtApi and its
269 // subclasses. RtAudio creates an instance of an RtApi subclass
270 // based on the user's API choice. If no choice is made, RtAudio
271 // attempts to make a "logical" API selection.
273 // **************************************************************** //
277 class RTAUDIO_DLL_PUBLIC RtAudio
281 //! Audio API specifier arguments.
283 UNSPECIFIED, /*!< Search for a working compiled API. */
284 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
285 LINUX_PULSE, /*!< The Linux PulseAudio API. */
286 LINUX_OSS, /*!< The Linux Open Sound System API. */
287 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
288 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
289 WINDOWS_WASAPI, /*!< The Microsoft WASAPI API. */
290 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
291 WINDOWS_DS, /*!< The Microsoft Direct Sound API. */
292 RTAUDIO_DUMMY, /*!< A compilable but non-functional API. */
293 NUM_APIS /*!< Number of values in this enum. */
296 //! The public device information structure for returning queried values.
298 bool probed; /*!< true if the device capabilities were successfully probed. */
299 std::string name; /*!< Character string device identifier. */
300 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
301 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
302 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
303 bool isDefaultOutput; /*!< true if this is the default output device. */
304 bool isDefaultInput; /*!< true if this is the default input device. */
305 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
306 unsigned int preferredSampleRate; /*!< Preferred sample rate, eg. for WASAPI the system sample rate. */
307 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
309 // Default constructor.
311 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
312 isDefaultOutput(false), isDefaultInput(false), preferredSampleRate(0), nativeFormats(0) {}
315 //! The structure for specifying input or ouput stream parameters.
316 struct StreamParameters {
317 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
318 unsigned int nChannels; /*!< Number of channels. */
319 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
321 // Default constructor.
323 : deviceId(0), nChannels(0), firstChannel(0) {}
326 //! The structure for specifying stream options.
328 The following flags can be OR'ed together to allow a client to
329 make changes to the default stream behavior:
331 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
332 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
333 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
334 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
335 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
337 By default, RtAudio streams pass and receive audio data from the
338 client in an interleaved format. By passing the
339 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
340 data will instead be presented in non-interleaved buffers. In
341 this case, each buffer argument in the RtAudioCallback function
342 will point to a single array of data, with \c nFrames samples for
343 each channel concatenated back-to-back. For example, the first
344 sample of data for the second channel would be located at index \c
345 nFrames (assuming the \c buffer pointer was recast to the correct
346 data type for the stream).
348 Certain audio APIs offer a number of parameters that influence the
349 I/O latency of a stream. By default, RtAudio will attempt to set
350 these parameters internally for robust (glitch-free) performance
351 (though some APIs, like Windows Direct Sound, make this difficult).
352 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
353 function, internal stream settings will be influenced in an attempt
354 to minimize stream latency, though possibly at the expense of stream
357 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
358 open the input and/or output stream device(s) for exclusive use.
359 Note that this is not possible with all supported audio APIs.
361 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
362 to select realtime scheduling (round-robin) for the callback thread.
363 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
364 flag is set. It defines the thread's realtime priority.
366 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
367 open the "default" PCM device when using the ALSA API. Note that this
368 will override any specified input or output device id.
370 The \c numberOfBuffers parameter can be used to control stream
371 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
372 only. A value of two is usually the smallest allowed. Larger
373 numbers can potentially result in more robust stream performance,
374 though likely at the cost of stream latency. The value set by the
375 user is replaced during execution of the RtAudio::openStream()
376 function by the value actually used by the system.
378 The \c streamName parameter can be used to set the client name
379 when using the Jack API. By default, the client name is set to
380 RtApiJack. However, if you wish to create multiple instances of
381 RtAudio with Jack, each instance must have a unique client name.
383 struct StreamOptions {
384 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
385 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
386 std::string streamName; /*!< A stream name (currently used only in Jack). */
387 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
389 // Default constructor.
391 : flags(0), numberOfBuffers(0), priority(0) {}
394 //! A static function to determine the current RtAudio version.
395 static std::string getVersion( void );
397 //! A static function to determine the available compiled audio APIs.
399 The values returned in the std::vector can be compared against
400 the enumerated list values. Note that there can be more than one
401 API compiled for certain operating systems.
403 static void getCompiledApi( std::vector<RtAudio::Api> &apis );
405 //! A static function to determine the available compiled audio APIs.
407 The values returned in the std::vector can be compared against
408 the enumerated list values. Note that there can be more than one
409 API compiled for certain operating systems.
411 static const std::vector<RtAudio::Api>& getCompiledApis();
413 //! Return the name of a specified compiled audio API.
415 This obtains a short lower-case name used for identification purposes.
416 This value is guaranteed to remain identical across library versions.
417 If the API is unknown or not compiled, this function will return
420 static const std::string getCompiledApiName( RtAudio::Api api );
422 //! Return the display name of a specified compiled audio API.
424 This obtains a long name used for display purposes.
425 If the API is unknown or not compiled, this function will return
428 static const std::string getCompiledApiDisplayName( RtAudio::Api api );
430 //! Return the compiled audio API having the given name.
432 A case insensitive comparison will check the specified name
433 against the list of compiled APIs, and return the one which
434 matches. On failure, the function returns UNSPECIFIED.
436 static RtAudio::Api getCompiledApiByName( const std::string &name );
438 //! The class constructor.
440 The constructor performs minor initialization tasks. An exception
441 can be thrown if no API support is compiled.
443 If no API argument is specified and multiple API support has been
444 compiled, the default order of use is JACK, ALSA, OSS (Linux
445 systems) and ASIO, DS (Windows systems).
447 RtAudio( RtAudio::Api api=UNSPECIFIED );
451 If a stream is running or open, it will be stopped and closed
456 //! Returns the audio API specifier for the current instance of RtAudio.
457 RtAudio::Api getCurrentApi( void );
459 //! A public function that queries for the number of audio devices available.
461 This function performs a system query of available devices each time it
462 is called, thus supporting devices connected \e after instantiation. If
463 a system error occurs during processing, a warning will be issued.
465 unsigned int getDeviceCount( void );
467 //! Return an RtAudio::DeviceInfo structure for a specified device number.
470 Any device integer between 0 and getDeviceCount() - 1 is valid.
471 If an invalid argument is provided, an RtAudioError (type = INVALID_USE)
472 will be thrown. If a device is busy or otherwise unavailable, the
473 structure member "probed" will have a value of "false" and all
474 other members are undefined. If the specified device is the
475 current default input or output device, the corresponding
476 "isDefault" member will have a value of "true".
478 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
480 //! A function that returns the index of the default output device.
482 If the underlying audio API does not provide a "default
483 device", or if no devices are available, the return value will be
484 0. Note that this is a valid device identifier and it is the
485 client's responsibility to verify that a device is available
486 before attempting to open a stream.
488 unsigned int getDefaultOutputDevice( void );
490 //! A function that returns the index of the default input device.
492 If the underlying audio API does not provide a "default
493 device", or if no devices are available, the return value will be
494 0. Note that this is a valid device identifier and it is the
495 client's responsibility to verify that a device is available
496 before attempting to open a stream.
498 unsigned int getDefaultInputDevice( void );
500 //! A public function for opening a stream with the specified parameters.
502 An RtAudioError (type = SYSTEM_ERROR) is thrown if a stream cannot be
503 opened with the specified parameters or an error occurs during
504 processing. An RtAudioError (type = INVALID_USE) is thrown if any
505 invalid device ID or channel number parameters are specified.
507 \param outputParameters Specifies output stream parameters to use
508 when opening a stream, including a device ID, number of channels,
509 and starting channel number. For input-only streams, this
510 argument should be NULL. The device ID is an index value between
511 0 and getDeviceCount() - 1.
512 \param inputParameters Specifies input stream parameters to use
513 when opening a stream, including a device ID, number of channels,
514 and starting channel number. For output-only streams, this
515 argument should be NULL. The device ID is an index value between
516 0 and getDeviceCount() - 1.
517 \param format An RtAudioFormat specifying the desired sample data format.
518 \param sampleRate The desired sample rate (sample frames per second).
519 \param *bufferFrames A pointer to a value indicating the desired
520 internal buffer size in sample frames. The actual value
521 used by the device is returned via the same pointer. A
522 value of zero can be specified, in which case the lowest
523 allowable value is determined.
524 \param callback A client-defined function that will be invoked
525 when input data is available and/or output data is needed.
526 \param userData An optional pointer to data that can be accessed
527 from within the callback function.
528 \param options An optional pointer to a structure containing various
529 global stream options, including a list of OR'ed RtAudioStreamFlags
530 and a suggested number of stream buffers that can be used to
531 control stream latency. More buffers typically result in more
532 robust performance, though at a cost of greater latency. If a
533 value of zero is specified, a system-specific median value is
534 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
535 lowest allowable value is used. The actual value used is
536 returned via the structure argument. The parameter is API dependent.
537 \param errorCallback A client-defined function that will be invoked
538 when an error has occured.
540 void openStream( RtAudio::StreamParameters *outputParameters,
541 RtAudio::StreamParameters *inputParameters,
542 RtAudioFormat format, unsigned int sampleRate,
543 unsigned int *bufferFrames, RtAudioCallback callback,
544 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
546 //! A function that closes a stream and frees any associated stream memory.
548 If a stream is not open, this function issues a warning and
549 returns (no exception is thrown).
551 void closeStream( void );
553 //! A function that starts a stream.
555 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
556 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
557 stream is not open. A warning is issued if the stream is already
560 void startStream( void );
562 //! Stop a stream, allowing any samples remaining in the output queue to be played.
564 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
565 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
566 stream is not open. A warning is issued if the stream is already
569 void stopStream( void );
571 //! Stop a stream, discarding any samples remaining in the input/output queue.
573 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
574 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
575 stream is not open. A warning is issued if the stream is already
578 void abortStream( void );
580 //! Returns true if a stream is open and false if not.
581 bool isStreamOpen( void ) const;
583 //! Returns true if the stream is running and false if it is stopped or not open.
584 bool isStreamRunning( void ) const;
586 //! Returns the number of elapsed seconds since the stream was started.
588 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
590 double getStreamTime( void );
592 //! Set the stream time to a time in seconds greater than or equal to 0.0.
594 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
596 void setStreamTime( double time );
598 //! Returns the internal stream latency in sample frames.
600 The stream latency refers to delay in audio input and/or output
601 caused by internal buffering by the audio system and/or hardware.
602 For duplex streams, the returned value will represent the sum of
603 the input and output latencies. If a stream is not open, an
604 RtAudioError (type = INVALID_USE) will be thrown. If the API does not
605 report latency, the return value will be zero.
607 long getStreamLatency( void );
609 //! Returns actual sample rate in use by the stream.
611 On some systems, the sample rate used may be slightly different
612 than that specified in the stream parameters. If a stream is not
613 open, an RtAudioError (type = INVALID_USE) will be thrown.
615 unsigned int getStreamSampleRate( void );
617 //! Specify whether warning messages should be printed to stderr.
618 void showWarnings( bool value = true );
622 //! Storage for compiled API list
623 static const std::vector<RtAudio::Api> compiledApis;
625 void openRtApi( RtAudio::Api api );
629 // Operating system dependent thread functionality.
630 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
638 typedef uintptr_t ThreadHandle;
639 typedef CRITICAL_SECTION StreamMutex;
641 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
642 // Using pthread library for various flavors of unix.
645 typedef pthread_t ThreadHandle;
646 typedef pthread_mutex_t StreamMutex;
648 #else // Setup for "dummy" behavior
650 #define __RTAUDIO_DUMMY__
651 typedef int ThreadHandle;
652 typedef int StreamMutex;
656 // This global structure type is used to pass callback information
657 // between the private RtAudio stream structure and global callback
658 // handling functions.
659 struct CallbackInfo {
660 void *object; // Used as a "this" pointer.
665 void *apiInfo; // void pointer for API specific callback information
670 // Default constructor.
672 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false), priority(0) {}
675 // **************************************************************** //
677 // RtApi class declaration.
679 // Subclasses of RtApi contain all API- and OS-specific code necessary
680 // to fully implement the RtAudio API.
682 // Note that RtApi is an abstract base class and cannot be
683 // explicitly instantiated. The class RtAudio will create an
684 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
685 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
687 // **************************************************************** //
689 #pragma pack(push, 1)
698 S24& operator = ( const int& i ) {
699 c3[0] = (i & 0x000000ff);
700 c3[1] = (i & 0x0000ff00) >> 8;
701 c3[2] = (i & 0x00ff0000) >> 16;
705 S24( const S24& v ) { *this = v; }
706 S24( const double& d ) { *this = (int) d; }
707 S24( const float& f ) { *this = (int) f; }
708 S24( const signed short& s ) { *this = (int) s; }
709 S24( const char& c ) { *this = (int) c; }
712 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
713 if (i & 0x800000) i |= ~0xffffff;
719 #if defined( HAVE_GETTIMEOFDAY )
720 #include <sys/time.h>
725 class RTAUDIO_DLL_PUBLIC RtApi
731 virtual RtAudio::Api getCurrentApi( void ) = 0;
732 virtual unsigned int getDeviceCount( void ) = 0;
733 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
734 virtual unsigned int getDefaultInputDevice( void );
735 virtual unsigned int getDefaultOutputDevice( void );
736 void openStream( RtAudio::StreamParameters *outputParameters,
737 RtAudio::StreamParameters *inputParameters,
738 RtAudioFormat format, unsigned int sampleRate,
739 unsigned int *bufferFrames, RtAudioCallback callback,
740 void *userData, RtAudio::StreamOptions *options,
741 RtAudioErrorCallback errorCallback );
742 virtual void closeStream( void );
743 virtual void startStream( void ) = 0;
744 virtual void stopStream( void ) = 0;
745 virtual void abortStream( void ) = 0;
746 long getStreamLatency( void );
747 unsigned int getStreamSampleRate( void );
748 virtual double getStreamTime( void );
749 virtual void setStreamTime( double time );
750 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
751 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
752 void showWarnings( bool value ) { showWarnings_ = value; }
757 static const unsigned int MAX_SAMPLE_RATES;
758 static const unsigned int SAMPLE_RATES[];
760 enum { FAILURE, SUCCESS };
776 // A protected structure used for buffer conversion.
780 RtAudioFormat inFormat, outFormat;
781 std::vector<int> inOffset;
782 std::vector<int> outOffset;
785 // A protected structure for audio streams.
787 unsigned int device[2]; // Playback and record, respectively.
788 void *apiHandle; // void pointer for API specific stream handle information
789 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
790 StreamState state; // STOPPED, RUNNING, or CLOSED
791 char *userBuffer[2]; // Playback and record, respectively.
793 bool doConvertBuffer[2]; // Playback and record, respectively.
794 bool userInterleaved;
795 bool deviceInterleaved[2]; // Playback and record, respectively.
796 bool doByteSwap[2]; // Playback and record, respectively.
797 unsigned int sampleRate;
798 unsigned int bufferSize;
799 unsigned int nBuffers;
800 unsigned int nUserChannels[2]; // Playback and record, respectively.
801 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
802 unsigned int channelOffset[2]; // Playback and record, respectively.
803 unsigned long latency[2]; // Playback and record, respectively.
804 RtAudioFormat userFormat;
805 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
807 CallbackInfo callbackInfo;
808 ConvertInfo convertInfo[2];
809 double streamTime; // Number of elapsed seconds since the stream started.
811 #if defined(HAVE_GETTIMEOFDAY)
812 struct timeval lastTickTimestamp;
816 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
820 typedef signed short Int16;
821 typedef signed int Int32;
822 typedef float Float32;
823 typedef double Float64;
825 std::ostringstream errorStream_;
826 std::string errorText_;
829 bool firstErrorOccurred_;
832 Protected, api-specific method that attempts to open a device
833 with the given parameters. This function MUST be implemented by
834 all subclasses. If an error is encountered during the probe, a
835 "warning" message is reported and FAILURE is returned. A
836 successful probe is indicated by a return value of SUCCESS.
838 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
839 unsigned int firstChannel, unsigned int sampleRate,
840 RtAudioFormat format, unsigned int *bufferSize,
841 RtAudio::StreamOptions *options );
843 //! A protected function used to increment the stream time.
844 void tickStreamTime( void );
846 //! Protected common method to clear an RtApiStream structure.
847 void clearStreamInfo();
850 Protected common method that throws an RtAudioError (type =
851 INVALID_USE) if a stream is not open.
853 void verifyStream( void );
855 //! Protected common error method to allow global control over error handling.
856 void error( RtAudioError::Type type );
859 Protected method used to perform format, channel number, and/or interleaving
860 conversions between the user and device buffers.
862 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
864 //! Protected common method used to perform byte-swapping on buffers.
865 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
867 //! Protected common method that returns the number of bytes for a given format.
868 unsigned int formatBytes( RtAudioFormat format );
870 //! Protected common method that sets up the parameters for buffer conversion.
871 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
874 // **************************************************************** //
876 // Inline RtAudio definitions.
878 // **************************************************************** //
880 inline RtAudio::Api RtAudio :: getCurrentApi( void ) { return rtapi_->getCurrentApi(); }
881 inline unsigned int RtAudio :: getDeviceCount( void ) { return rtapi_->getDeviceCount(); }
882 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
883 inline unsigned int RtAudio :: getDefaultInputDevice( void ) { return rtapi_->getDefaultInputDevice(); }
884 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) { return rtapi_->getDefaultOutputDevice(); }
885 inline void RtAudio :: closeStream( void ) { return rtapi_->closeStream(); }
886 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
887 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
888 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
889 inline bool RtAudio :: isStreamOpen( void ) const { return rtapi_->isStreamOpen(); }
890 inline bool RtAudio :: isStreamRunning( void ) const { return rtapi_->isStreamRunning(); }
891 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
892 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
893 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
894 inline void RtAudio :: setStreamTime( double time ) { return rtapi_->setStreamTime( time ); }
895 inline void RtAudio :: showWarnings( bool value ) { rtapi_->showWarnings( value ); }
897 // RtApi Subclass prototypes.
899 #if defined(__MACOSX_CORE__)
901 #include <CoreAudio/AudioHardware.h>
903 class RtApiCore: public RtApi
909 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
910 unsigned int getDeviceCount( void );
911 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
912 unsigned int getDefaultOutputDevice( void );
913 unsigned int getDefaultInputDevice( void );
914 void closeStream( void );
915 void startStream( void );
916 void stopStream( void );
917 void abortStream( void );
918 long getStreamLatency( void );
920 // This function is intended for internal use only. It must be
921 // public because it is called by the internal callback handler,
922 // which is not a member of RtAudio. External use of this function
923 // will most likely produce highly undesireable results!
924 bool callbackEvent( AudioDeviceID deviceId,
925 const AudioBufferList *inBufferList,
926 const AudioBufferList *outBufferList );
930 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
931 unsigned int firstChannel, unsigned int sampleRate,
932 RtAudioFormat format, unsigned int *bufferSize,
933 RtAudio::StreamOptions *options );
934 static const char* getErrorCode( OSStatus code );
939 #if defined(__UNIX_JACK__)
941 class RtApiJack: public RtApi
947 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
948 unsigned int getDeviceCount( void );
949 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
950 void closeStream( void );
951 void startStream( void );
952 void stopStream( void );
953 void abortStream( void );
954 long getStreamLatency( void );
956 // This function is intended for internal use only. It must be
957 // public because it is called by the internal callback handler,
958 // which is not a member of RtAudio. External use of this function
959 // will most likely produce highly undesireable results!
960 bool callbackEvent( unsigned long nframes );
964 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
965 unsigned int firstChannel, unsigned int sampleRate,
966 RtAudioFormat format, unsigned int *bufferSize,
967 RtAudio::StreamOptions *options );
969 bool shouldAutoconnect_;
974 #if defined(__WINDOWS_ASIO__)
976 class RtApiAsio: public RtApi
982 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
983 unsigned int getDeviceCount( void );
984 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
985 void closeStream( void );
986 void startStream( void );
987 void stopStream( void );
988 void abortStream( void );
989 long getStreamLatency( void );
991 // This function is intended for internal use only. It must be
992 // public because it is called by the internal callback handler,
993 // which is not a member of RtAudio. External use of this function
994 // will most likely produce highly undesireable results!
995 bool callbackEvent( long bufferIndex );
999 std::vector<RtAudio::DeviceInfo> devices_;
1000 void saveDeviceInfo( void );
1001 bool coInitialized_;
1002 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1003 unsigned int firstChannel, unsigned int sampleRate,
1004 RtAudioFormat format, unsigned int *bufferSize,
1005 RtAudio::StreamOptions *options );
1010 #if defined(__WINDOWS_DS__)
1012 class RtApiDs: public RtApi
1018 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
1019 unsigned int getDeviceCount( void );
1020 unsigned int getDefaultOutputDevice( void );
1021 unsigned int getDefaultInputDevice( void );
1022 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1023 void closeStream( void );
1024 void startStream( void );
1025 void stopStream( void );
1026 void abortStream( void );
1027 long getStreamLatency( void );
1029 // This function is intended for internal use only. It must be
1030 // public because it is called by the internal callback handler,
1031 // which is not a member of RtAudio. External use of this function
1032 // will most likely produce highly undesireable results!
1033 void callbackEvent( void );
1037 bool coInitialized_;
1038 bool buffersRolling;
1039 long duplexPrerollBytes;
1040 std::vector<struct DsDevice> dsDevices;
1041 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1042 unsigned int firstChannel, unsigned int sampleRate,
1043 RtAudioFormat format, unsigned int *bufferSize,
1044 RtAudio::StreamOptions *options );
1049 #if defined(__WINDOWS_WASAPI__)
1051 struct IMMDeviceEnumerator;
1053 class RtApiWasapi : public RtApi
1059 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_WASAPI; }
1060 unsigned int getDeviceCount( void );
1061 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1062 unsigned int getDefaultOutputDevice( void );
1063 unsigned int getDefaultInputDevice( void );
1064 void closeStream( void );
1065 void startStream( void );
1066 void stopStream( void );
1067 void abortStream( void );
1070 bool coInitialized_;
1071 IMMDeviceEnumerator* deviceEnumerator_;
1073 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1074 unsigned int firstChannel, unsigned int sampleRate,
1075 RtAudioFormat format, unsigned int* bufferSize,
1076 RtAudio::StreamOptions* options );
1078 static DWORD WINAPI runWasapiThread( void* wasapiPtr );
1079 static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
1080 static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
1081 void wasapiThread();
1086 #if defined(__LINUX_ALSA__)
1088 class RtApiAlsa: public RtApi
1094 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
1095 unsigned int getDeviceCount( void );
1096 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1097 void closeStream( void );
1098 void startStream( void );
1099 void stopStream( void );
1100 void abortStream( void );
1102 // This function is intended for internal use only. It must be
1103 // public because it is called by the internal callback handler,
1104 // which is not a member of RtAudio. External use of this function
1105 // will most likely produce highly undesireable results!
1106 void callbackEvent( void );
1110 std::vector<RtAudio::DeviceInfo> devices_;
1111 void saveDeviceInfo( void );
1112 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1113 unsigned int firstChannel, unsigned int sampleRate,
1114 RtAudioFormat format, unsigned int *bufferSize,
1115 RtAudio::StreamOptions *options );
1120 #if defined(__LINUX_PULSE__)
1122 class RtApiPulse: public RtApi
1126 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
1127 unsigned int getDeviceCount( void );
1128 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1129 void closeStream( void );
1130 void startStream( void );
1131 void stopStream( void );
1132 void abortStream( void );
1134 // This function is intended for internal use only. It must be
1135 // public because it is called by the internal callback handler,
1136 // which is not a member of RtAudio. External use of this function
1137 // will most likely produce highly undesireable results!
1138 void callbackEvent( void );
1142 std::vector<RtAudio::DeviceInfo> devices_;
1143 void saveDeviceInfo( void );
1144 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1145 unsigned int firstChannel, unsigned int sampleRate,
1146 RtAudioFormat format, unsigned int *bufferSize,
1147 RtAudio::StreamOptions *options );
1152 #if defined(__LINUX_OSS__)
1154 class RtApiOss: public RtApi
1160 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1161 unsigned int getDeviceCount( void );
1162 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1163 void closeStream( void );
1164 void startStream( void );
1165 void stopStream( void );
1166 void abortStream( void );
1168 // This function is intended for internal use only. It must be
1169 // public because it is called by the internal callback handler,
1170 // which is not a member of RtAudio. External use of this function
1171 // will most likely produce highly undesireable results!
1172 void callbackEvent( void );
1176 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1177 unsigned int firstChannel, unsigned int sampleRate,
1178 RtAudioFormat format, unsigned int *bufferSize,
1179 RtAudio::StreamOptions *options );
1184 #if defined(__RTAUDIO_DUMMY__)
1186 class RtApiDummy: public RtApi
1190 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtAudioError::WARNING ); }
1191 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1192 unsigned int getDeviceCount( void ) { return 0; }
1193 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1194 void closeStream( void ) {}
1195 void startStream( void ) {}
1196 void stopStream( void ) {}
1197 void abortStream( void ) {}
1201 bool probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
1202 unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
1203 RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
1204 RtAudio::StreamOptions * /*options*/ ) { return false; }
1211 // Indentation settings for Vim and Emacs
1214 // c-basic-offset: 2
1215 // indent-tabs-mode: nil
1218 // vim: et sts=2 sw=2