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 GitHub site: https://github.com/thestk/rtaudio
11 RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
13 RtAudio: realtime audio i/o C++ classes
14 Copyright (c) 2001-2019 Gary P. Scavone
16 Permission is hereby granted, free of charge, to any person
17 obtaining a copy of this software and associated documentation files
18 (the "Software"), to deal in the Software without restriction,
19 including without limitation the rights to use, copy, modify, merge,
20 publish, distribute, sublicense, and/or sell copies of the Software,
21 and to permit persons to whom the Software is furnished to do so,
22 subject to the following conditions:
24 The above copyright notice and this permission notice shall be
25 included in all copies or substantial portions of the Software.
27 Any person wishing to distribute modifications to the Software is
28 asked to send the modifications to the original developer so that
29 they can be incorporated into the canonical version. This is,
30 however, not a binding provision of this license.
32 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
33 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
34 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
35 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
36 ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
37 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
38 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40 /************************************************************************/
49 #define RTAUDIO_VERSION "5.1.0"
51 #if defined _WIN32 || defined __CYGWIN__
52 #if defined(RTAUDIO_EXPORT)
53 #define RTAUDIO_DLL_PUBLIC __declspec(dllexport)
55 #define RTAUDIO_DLL_PUBLIC
59 #define RTAUDIO_DLL_PUBLIC __attribute__( (visibility( "default" )) )
61 #define RTAUDIO_DLL_PUBLIC
70 /*! \typedef typedef unsigned long RtAudioFormat;
71 \brief RtAudio data format type.
73 Support for signed integers and floats. Audio data fed to/from an
74 RtAudio stream is assumed to ALWAYS be in host byte order. The
75 internal routines will automatically take care of any necessary
76 byte-swapping between the host format and the soundcard. Thus,
77 endian-ness is not a concern in the following format definitions.
79 - \e RTAUDIO_SINT8: 8-bit signed integer.
80 - \e RTAUDIO_SINT16: 16-bit signed integer.
81 - \e RTAUDIO_SINT24: 24-bit signed integer.
82 - \e RTAUDIO_SINT32: 32-bit signed integer.
83 - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
84 - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
86 typedef unsigned long RtAudioFormat;
87 static const RtAudioFormat RTAUDIO_SINT8 = 0x1; // 8-bit signed integer.
88 static const RtAudioFormat RTAUDIO_SINT16 = 0x2; // 16-bit signed integer.
89 static const RtAudioFormat RTAUDIO_SINT24 = 0x4; // 24-bit signed integer.
90 static const RtAudioFormat RTAUDIO_SINT32 = 0x8; // 32-bit signed integer.
91 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
92 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
94 /*! \typedef typedef unsigned long RtAudioStreamFlags;
95 \brief RtAudio stream option flags.
97 The following flags can be OR'ed together to allow a client to
98 make changes to the default stream behavior:
100 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
101 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
102 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
103 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
104 - \e RTAUDIO_JACK_DONT_CONNECT: Do not automatically connect ports (JACK only).
106 By default, RtAudio streams pass and receive audio data from the
107 client in an interleaved format. By passing the
108 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
109 data will instead be presented in non-interleaved buffers. In
110 this case, each buffer argument in the RtAudioCallback function
111 will point to a single array of data, with \c nFrames samples for
112 each channel concatenated back-to-back. For example, the first
113 sample of data for the second channel would be located at index \c
114 nFrames (assuming the \c buffer pointer was recast to the correct
115 data type for the stream).
117 Certain audio APIs offer a number of parameters that influence the
118 I/O latency of a stream. By default, RtAudio will attempt to set
119 these parameters internally for robust (glitch-free) performance
120 (though some APIs, like Windows DirectSound, make this difficult).
121 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
122 function, internal stream settings will be influenced in an attempt
123 to minimize stream latency, though possibly at the expense of stream
126 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
127 open the input and/or output stream device(s) for exclusive use.
128 Note that this is not possible with all supported audio APIs.
130 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
131 to select realtime scheduling (round-robin) for the callback thread.
133 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
134 open the "default" PCM device when using the ALSA API. Note that this
135 will override any specified input or output device id.
137 If the RTAUDIO_JACK_DONT_CONNECT flag is set, RtAudio will not attempt
138 to automatically connect the ports of the client to the audio device.
140 typedef unsigned int RtAudioStreamFlags;
141 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1; // Use non-interleaved buffers (default = interleaved).
142 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2; // Attempt to set stream parameters for lowest possible latency.
143 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4; // Attempt grab device and prevent use by others.
144 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
145 static const RtAudioStreamFlags RTAUDIO_ALSA_USE_DEFAULT = 0x10; // Use the "default" PCM device (ALSA only).
146 static const RtAudioStreamFlags RTAUDIO_JACK_DONT_CONNECT = 0x20; // Do not automatically connect ports (JACK only).
148 /*! \typedef typedef unsigned long RtAudioStreamStatus;
149 \brief RtAudio stream status (over- or underflow) flags.
151 Notification of a stream over- or underflow is indicated by a
152 non-zero stream \c status argument in the RtAudioCallback function.
153 The stream status can be one of the following two options,
154 depending on whether the stream is open for output and/or input:
156 - \e RTAUDIO_INPUT_OVERFLOW: Input data was discarded because of an overflow condition at the driver.
157 - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
159 typedef unsigned int RtAudioStreamStatus;
160 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver.
161 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound.
163 //! RtAudio callback function prototype.
165 All RtAudio clients must create a function of type RtAudioCallback
166 to read and/or write data from/to the audio stream. When the
167 underlying audio system is ready for new input or output data, this
168 function will be invoked.
170 \param outputBuffer For output (or duplex) streams, the client
171 should write \c nFrames of audio sample frames into this
172 buffer. This argument should be recast to the datatype
173 specified when the stream was opened. For input-only
174 streams, this argument will be NULL.
176 \param inputBuffer For input (or duplex) streams, this buffer will
177 hold \c nFrames of input audio sample frames. This
178 argument should be recast to the datatype specified when the
179 stream was opened. For output-only streams, this argument
182 \param nFrames The number of sample frames of input or output
183 data in the buffers. The actual buffer size in bytes is
184 dependent on the data type and number of channels in use.
186 \param streamTime The number of seconds that have elapsed since the
189 \param status If non-zero, this argument indicates a data overflow
190 or underflow condition for the stream. The particular
191 condition can be determined by comparison with the
192 RtAudioStreamStatus flags.
194 \param userData A pointer to optional data provided by the client
195 when opening the stream (default = NULL).
198 To continue normal stream operation, the RtAudioCallback function
199 should return a value of zero. To stop the stream and drain the
200 output buffer, the function should return a value of one. To abort
201 the stream immediately, the client should return a value of two.
203 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
204 unsigned int nFrames,
206 RtAudioStreamStatus status,
209 /************************************************************************/
210 /*! \class RtAudioError
211 \brief Exception handling class for RtAudio.
213 The RtAudioError class is quite simple but it does allow errors to be
214 "caught" by RtAudioError::Type. See the RtAudio documentation to know
215 which methods can throw an RtAudioError.
217 /************************************************************************/
219 class RTAUDIO_DLL_PUBLIC RtAudioError : public std::runtime_error
222 //! Defined RtAudioError types.
224 WARNING, /*!< A non-critical error. */
225 DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */
226 UNSPECIFIED, /*!< The default, unspecified error type. */
227 NO_DEVICES_FOUND, /*!< No devices found on system. */
228 INVALID_DEVICE, /*!< An invalid device ID was specified. */
229 DEVICE_DISCONNECT, /*!< A device in use was disconnected. */
230 MEMORY_ERROR, /*!< An error occured during memory allocation. */
231 INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */
232 INVALID_USE, /*!< The function was called incorrectly. */
233 DRIVER_ERROR, /*!< A system driver error occured. */
234 SYSTEM_ERROR, /*!< A system error occured. */
235 THREAD_ERROR /*!< A thread error occured. */
239 RtAudioError( const std::string& message,
240 Type type = RtAudioError::UNSPECIFIED )
241 : std::runtime_error(message), type_(type) {}
243 //! Prints thrown error message to stderr.
244 virtual void printMessage( void ) const
245 { std::cerr << '\n' << what() << "\n\n"; }
247 //! Returns the thrown error message type.
248 virtual const Type& getType(void) const { return type_; }
250 //! Returns the thrown error message string.
251 virtual const std::string getMessage(void) const
252 { return std::string(what()); }
258 //! RtAudio error callback function prototype.
260 \param type Type of error.
261 \param errorText Error description.
263 typedef void (*RtAudioErrorCallback)( RtAudioError::Type type, const std::string &errorText );
265 // **************************************************************** //
267 // RtAudio class declaration.
269 // RtAudio is a "controller" used to select an available audio i/o
270 // interface. It presents a common API for the user to call but all
271 // functionality is implemented by the class RtApi and its
272 // subclasses. RtAudio creates an instance of an RtApi subclass
273 // based on the user's API choice. If no choice is made, RtAudio
274 // attempts to make a "logical" API selection.
276 // **************************************************************** //
280 class RTAUDIO_DLL_PUBLIC RtAudio
284 //! Audio API specifier arguments.
286 UNSPECIFIED, /*!< Search for a working compiled API. */
287 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
288 LINUX_PULSE, /*!< The Linux PulseAudio API. */
289 LINUX_OSS, /*!< The Linux Open Sound System API. */
290 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
291 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
292 WINDOWS_WASAPI, /*!< The Microsoft WASAPI API. */
293 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
294 WINDOWS_DS, /*!< The Microsoft DirectSound API. */
295 RTAUDIO_DUMMY, /*!< A compilable but non-functional API. */
296 NUM_APIS /*!< Number of values in this enum. */
299 //! The public device information structure for returning queried values.
301 bool probed; /*!< true if the device capabilities were successfully probed. */
302 std::string name; /*!< Character string device identifier. */
303 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
304 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
305 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
306 bool isDefaultOutput; /*!< true if this is the default output device. */
307 bool isDefaultInput; /*!< true if this is the default input device. */
308 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
309 unsigned int currentSampleRate; /*!< Current sample rate, system sample rate as currently configured. */
310 unsigned int preferredSampleRate; /*!< Preferred sample rate, e.g. for WASAPI the system sample rate. */
311 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
313 // Default constructor.
315 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
316 isDefaultOutput(false), isDefaultInput(false), currentSampleRate(0), preferredSampleRate(0), nativeFormats(0) {}
319 //! The structure for specifying input or ouput stream parameters.
320 struct StreamParameters {
321 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
322 unsigned int nChannels; /*!< Number of channels. */
323 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
325 // Default constructor.
327 : deviceId(0), nChannels(0), firstChannel(0) {}
330 //! The structure for specifying stream options.
332 The following flags can be OR'ed together to allow a client to
333 make changes to the default stream behavior:
335 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
336 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
337 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
338 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
339 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
341 By default, RtAudio streams pass and receive audio data from the
342 client in an interleaved format. By passing the
343 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
344 data will instead be presented in non-interleaved buffers. In
345 this case, each buffer argument in the RtAudioCallback function
346 will point to a single array of data, with \c nFrames samples for
347 each channel concatenated back-to-back. For example, the first
348 sample of data for the second channel would be located at index \c
349 nFrames (assuming the \c buffer pointer was recast to the correct
350 data type for the stream).
352 Certain audio APIs offer a number of parameters that influence the
353 I/O latency of a stream. By default, RtAudio will attempt to set
354 these parameters internally for robust (glitch-free) performance
355 (though some APIs, like Windows DirectSound, make this difficult).
356 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
357 function, internal stream settings will be influenced in an attempt
358 to minimize stream latency, though possibly at the expense of stream
361 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
362 open the input and/or output stream device(s) for exclusive use.
363 Note that this is not possible with all supported audio APIs.
365 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
366 to select realtime scheduling (round-robin) for the callback thread.
367 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
368 flag is set. It defines the thread's realtime priority.
370 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
371 open the "default" PCM device when using the ALSA API. Note that this
372 will override any specified input or output device id.
374 The \c numberOfBuffers parameter can be used to control stream
375 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
376 only. A value of two is usually the smallest allowed. Larger
377 numbers can potentially result in more robust stream performance,
378 though likely at the cost of stream latency. The value set by the
379 user is replaced during execution of the RtAudio::openStream()
380 function by the value actually used by the system.
382 The \c streamName parameter can be used to set the client name
383 when using the Jack API. By default, the client name is set to
384 RtApiJack. However, if you wish to create multiple instances of
385 RtAudio with Jack, each instance must have a unique client name.
387 struct StreamOptions {
388 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
389 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
390 std::string streamName; /*!< A stream name (currently used only in Jack). */
391 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
393 // Default constructor.
395 : flags(0), numberOfBuffers(0), priority(0) {}
398 //! A static function to determine the current RtAudio version.
399 static std::string getVersion( void );
401 //! A static function to determine the available compiled audio APIs.
403 The values returned in the std::vector can be compared against
404 the enumerated list values. Note that there can be more than one
405 API compiled for certain operating systems.
407 static void getCompiledApi( std::vector<RtAudio::Api> &apis );
409 //! Return the name of a specified compiled audio API.
411 This obtains a short lower-case name used for identification purposes.
412 This value is guaranteed to remain identical across library versions.
413 If the API is unknown, this function will return the empty string.
415 static std::string getApiName( RtAudio::Api api );
417 //! Return the display name of a specified compiled audio API.
419 This obtains a long name used for display purposes.
420 If the API is unknown, this function will return the empty string.
422 static std::string getApiDisplayName( RtAudio::Api api );
424 //! Return the compiled audio API having the given name.
426 A case insensitive comparison will check the specified name
427 against the list of compiled APIs, and return the one which
428 matches. On failure, the function returns UNSPECIFIED.
430 static RtAudio::Api getCompiledApiByName( const std::string &name );
432 //! The class constructor.
434 The constructor performs minor initialization tasks. An exception
435 can be thrown if no API support is compiled.
437 If no API argument is specified and multiple API support has been
438 compiled, the default order of use is JACK, ALSA, OSS (Linux
439 systems) and ASIO, DS (Windows systems).
441 RtAudio( RtAudio::Api api=UNSPECIFIED );
445 If a stream is running or open, it will be stopped and closed
450 //! Returns the audio API specifier for the current instance of RtAudio.
451 RtAudio::Api getCurrentApi( void );
453 //! A public function that queries for the number of audio devices available.
455 This function performs a system query of available devices each time it
456 is called, thus supporting devices connected \e after instantiation. If
457 a system error occurs during processing, a warning will be issued.
459 unsigned int getDeviceCount( void );
461 //! Return an RtAudio::DeviceInfo structure for a specified device number.
464 Any device integer between 0 and getDeviceCount() - 1 is valid.
465 If an invalid argument is provided, an RtAudioError (type = INVALID_USE)
466 will be thrown. If a device is busy or otherwise unavailable, the
467 structure member "probed" will have a value of "false" and all
468 other members are undefined. If the specified device is the
469 current default input or output device, the corresponding
470 "isDefault" member will have a value of "true".
472 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
474 //! A function that returns the index of the default output device.
476 If the underlying audio API does not provide a "default
477 device", or if no devices are available, the return value will be
478 0. Note that this is a valid device identifier and it is the
479 client's responsibility to verify that a device is available
480 before attempting to open a stream.
482 unsigned int getDefaultOutputDevice( void );
484 //! A function that returns the index of the default input device.
486 If the underlying audio API does not provide a "default
487 device", or if no devices are available, the return value will be
488 0. Note that this is a valid device identifier and it is the
489 client's responsibility to verify that a device is available
490 before attempting to open a stream.
492 unsigned int getDefaultInputDevice( void );
494 //! A public function for opening a stream with the specified parameters.
496 An RtAudioError (type = SYSTEM_ERROR) is thrown if a stream cannot be
497 opened with the specified parameters or an error occurs during
498 processing. An RtAudioError (type = INVALID_USE) is thrown if any
499 invalid device ID or channel number parameters are specified.
501 \param outputParameters Specifies output stream parameters to use
502 when opening a stream, including a device ID, number of channels,
503 and starting channel number. For input-only streams, this
504 argument should be NULL. The device ID is an index value between
505 0 and getDeviceCount() - 1.
506 \param inputParameters Specifies input stream parameters to use
507 when opening a stream, including a device ID, number of channels,
508 and starting channel number. For output-only streams, this
509 argument should be NULL. The device ID is an index value between
510 0 and getDeviceCount() - 1.
511 \param format An RtAudioFormat specifying the desired sample data format.
512 \param sampleRate The desired sample rate (sample frames per second).
513 \param *bufferFrames A pointer to a value indicating the desired
514 internal buffer size in sample frames. The actual value
515 used by the device is returned via the same pointer. A
516 value of zero can be specified, in which case the lowest
517 allowable value is determined.
518 \param callback A client-defined function that will be invoked
519 when input data is available and/or output data is needed.
520 \param userData An optional pointer to data that can be accessed
521 from within the callback function.
522 \param options An optional pointer to a structure containing various
523 global stream options, including a list of OR'ed RtAudioStreamFlags
524 and a suggested number of stream buffers that can be used to
525 control stream latency. More buffers typically result in more
526 robust performance, though at a cost of greater latency. If a
527 value of zero is specified, a system-specific median value is
528 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
529 lowest allowable value is used. The actual value used is
530 returned via the structure argument. The parameter is API dependent.
531 \param errorCallback A client-defined function that will be invoked
532 when an error has occured.
534 void openStream( RtAudio::StreamParameters *outputParameters,
535 RtAudio::StreamParameters *inputParameters,
536 RtAudioFormat format, unsigned int sampleRate,
537 unsigned int *bufferFrames, RtAudioCallback callback,
538 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
540 //! A function that closes a stream and frees any associated stream memory.
542 If a stream is not open, this function issues a warning and
543 returns (no exception is thrown).
545 void closeStream( void );
547 //! A function that starts a stream.
549 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
550 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
551 stream is not open. A warning is issued if the stream is already
554 void startStream( void );
556 //! Stop a stream, allowing any samples remaining in the output queue to be played.
558 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
559 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
560 stream is not open. A warning is issued if the stream is already
563 void stopStream( void );
565 //! Stop a stream, discarding any samples remaining in the input/output queue.
567 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
568 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
569 stream is not open. A warning is issued if the stream is already
572 void abortStream( void );
574 //! Returns true if a stream is open and false if not.
575 bool isStreamOpen( void ) const;
577 //! Returns true if the stream is running and false if it is stopped or not open.
578 bool isStreamRunning( void ) const;
580 //! Returns the number of elapsed seconds since the stream was started.
582 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
584 double getStreamTime( void );
586 //! Set the stream time to a time in seconds greater than or equal to 0.0.
588 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
590 void setStreamTime( double time );
592 //! Returns the internal stream latency in sample frames.
594 The stream latency refers to delay in audio input and/or output
595 caused by internal buffering by the audio system and/or hardware.
596 For duplex streams, the returned value will represent the sum of
597 the input and output latencies. If a stream is not open, an
598 RtAudioError (type = INVALID_USE) will be thrown. If the API does not
599 report latency, the return value will be zero.
601 long getStreamLatency( void );
603 //! Returns actual sample rate in use by the stream.
605 On some systems, the sample rate used may be slightly different
606 than that specified in the stream parameters. If a stream is not
607 open, an RtAudioError (type = INVALID_USE) will be thrown.
609 unsigned int getStreamSampleRate( void );
611 //! Specify whether warning messages should be printed to stderr.
612 void showWarnings( bool value = true );
616 void openRtApi( RtAudio::Api api );
620 // Operating system dependent thread functionality.
621 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
630 typedef uintptr_t ThreadHandle;
631 typedef CRITICAL_SECTION StreamMutex;
633 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
634 // Using pthread library for various flavors of unix.
637 typedef pthread_t ThreadHandle;
638 typedef pthread_mutex_t StreamMutex;
640 #else // Setup for "dummy" behavior
642 #define __RTAUDIO_DUMMY__
643 typedef int ThreadHandle;
644 typedef int StreamMutex;
648 // This global structure type is used to pass callback information
649 // between the private RtAudio stream structure and global callback
650 // handling functions.
651 struct CallbackInfo {
652 void *object; // Used as a "this" pointer.
657 void *apiInfo; // void pointer for API specific callback information
661 bool deviceDisconnected;
663 // Default constructor.
665 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false), priority(0), deviceDisconnected(false) {}
668 // **************************************************************** //
670 // RtApi class declaration.
672 // Subclasses of RtApi contain all API- and OS-specific code necessary
673 // to fully implement the RtAudio API.
675 // Note that RtApi is an abstract base class and cannot be
676 // explicitly instantiated. The class RtAudio will create an
677 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
678 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
680 // **************************************************************** //
682 #pragma pack(push, 1)
691 S24& operator = ( const int& i ) {
692 c3[0] = (i & 0x000000ff);
693 c3[1] = (i & 0x0000ff00) >> 8;
694 c3[2] = (i & 0x00ff0000) >> 16;
698 S24( const double& d ) { *this = (int) d; }
699 S24( const float& f ) { *this = (int) f; }
700 S24( const signed short& s ) { *this = (int) s; }
701 S24( const char& c ) { *this = (int) c; }
704 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
705 if (i & 0x800000) i |= ~0xffffff;
711 #if defined( HAVE_GETTIMEOFDAY )
712 #include <sys/time.h>
717 class RTAUDIO_DLL_PUBLIC RtApi
723 virtual RtAudio::Api getCurrentApi( void ) = 0;
724 virtual unsigned int getDeviceCount( void ) = 0;
725 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
726 virtual unsigned int getDefaultInputDevice( void );
727 virtual unsigned int getDefaultOutputDevice( void );
728 void openStream( RtAudio::StreamParameters *outputParameters,
729 RtAudio::StreamParameters *inputParameters,
730 RtAudioFormat format, unsigned int sampleRate,
731 unsigned int *bufferFrames, RtAudioCallback callback,
732 void *userData, RtAudio::StreamOptions *options,
733 RtAudioErrorCallback errorCallback );
734 virtual void closeStream( void );
735 virtual void startStream( void ) = 0;
736 virtual void stopStream( void ) = 0;
737 virtual void abortStream( void ) = 0;
738 long getStreamLatency( void );
739 unsigned int getStreamSampleRate( void ) const { return stream_.sampleRate; }
740 virtual double getStreamTime( void ) const { return stream_.streamTime; }
741 virtual void setStreamTime( double time );
742 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
743 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
744 void showWarnings( bool value ) { showWarnings_ = value; }
749 static const unsigned int MAX_SAMPLE_RATES;
750 static const unsigned int SAMPLE_RATES[];
752 enum { FAILURE, SUCCESS };
768 // A protected structure used for buffer conversion.
772 RtAudioFormat inFormat, outFormat;
773 std::vector<int> inOffset;
774 std::vector<int> outOffset;
777 // A protected structure for audio streams.
779 unsigned int device[2]; // Playback and record, respectively.
780 void *apiHandle; // void pointer for API specific stream handle information
781 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
782 StreamState state; // STOPPED, RUNNING, or CLOSED
783 char *userBuffer[2]; // Playback and record, respectively.
785 bool doConvertBuffer[2]; // Playback and record, respectively.
786 bool userInterleaved;
787 bool deviceInterleaved[2]; // Playback and record, respectively.
788 bool doByteSwap[2]; // Playback and record, respectively.
789 unsigned int sampleRate;
790 unsigned int bufferSize;
791 unsigned int nBuffers;
792 unsigned int nUserChannels[2]; // Playback and record, respectively.
793 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
794 unsigned int channelOffset[2]; // Playback and record, respectively.
795 unsigned long latency[2]; // Playback and record, respectively.
796 RtAudioFormat userFormat;
797 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
799 CallbackInfo callbackInfo;
800 ConvertInfo convertInfo[2];
801 double streamTime; // Number of elapsed seconds since the stream started.
803 #if defined(HAVE_GETTIMEOFDAY)
804 struct timeval lastTickTimestamp;
808 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
812 typedef signed short Int16;
813 typedef signed int Int32;
814 typedef float Float32;
815 typedef double Float64;
817 std::ostringstream errorStream_;
818 std::string errorText_;
821 bool firstErrorOccurred_;
824 Protected, api-specific method that attempts to open a device
825 with the given parameters. This function MUST be implemented by
826 all subclasses. If an error is encountered during the probe, a
827 "warning" message is reported and FAILURE is returned. A
828 successful probe is indicated by a return value of SUCCESS.
830 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
831 unsigned int firstChannel, unsigned int sampleRate,
832 RtAudioFormat format, unsigned int *bufferSize,
833 RtAudio::StreamOptions *options );
835 //! A protected function used to increment the stream time.
836 void tickStreamTime( void );
838 //! Protected common method to clear an RtApiStream structure.
839 void clearStreamInfo();
842 Protected common method that throws an RtAudioError (type =
843 INVALID_USE) if a stream is not open.
845 void verifyStream( void );
847 //! Protected common error method to allow global control over error handling.
848 void error( RtAudioError::Type type );
851 Protected method used to perform format, channel number, and/or interleaving
852 conversions between the user and device buffers.
854 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
856 //! Protected common method used to perform byte-swapping on buffers.
857 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
859 //! Protected common method that returns the number of bytes for a given format.
860 unsigned int formatBytes( RtAudioFormat format );
862 //! Protected common method that sets up the parameters for buffer conversion.
863 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
866 // **************************************************************** //
868 // Inline RtAudio definitions.
870 // **************************************************************** //
872 inline RtAudio::Api RtAudio :: getCurrentApi( void ) { return rtapi_->getCurrentApi(); }
873 inline unsigned int RtAudio :: getDeviceCount( void ) { return rtapi_->getDeviceCount(); }
874 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
875 inline unsigned int RtAudio :: getDefaultInputDevice( void ) { return rtapi_->getDefaultInputDevice(); }
876 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) { return rtapi_->getDefaultOutputDevice(); }
877 inline void RtAudio :: closeStream( void ) { return rtapi_->closeStream(); }
878 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
879 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
880 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
881 inline bool RtAudio :: isStreamOpen( void ) const { return rtapi_->isStreamOpen(); }
882 inline bool RtAudio :: isStreamRunning( void ) const { return rtapi_->isStreamRunning(); }
883 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
884 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
885 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
886 inline void RtAudio :: setStreamTime( double time ) { return rtapi_->setStreamTime( time ); }
887 inline void RtAudio :: showWarnings( bool value ) { rtapi_->showWarnings( value ); }
889 // RtApi Subclass prototypes.
891 #if defined(__MACOSX_CORE__)
893 #include <CoreAudio/AudioHardware.h>
895 class RtApiCore: public RtApi
901 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
902 unsigned int getDeviceCount( void );
903 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
904 unsigned int getDefaultOutputDevice( void );
905 unsigned int getDefaultInputDevice( void );
906 void closeStream( void );
907 void startStream( void );
908 void stopStream( void );
909 void abortStream( void );
911 // This function is intended for internal use only. It must be
912 // public because it is called by the internal callback handler,
913 // which is not a member of RtAudio. External use of this function
914 // will most likely produce highly undesireable results!
915 bool callbackEvent( AudioDeviceID deviceId,
916 const AudioBufferList *inBufferList,
917 const AudioBufferList *outBufferList );
921 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
922 unsigned int firstChannel, unsigned int sampleRate,
923 RtAudioFormat format, unsigned int *bufferSize,
924 RtAudio::StreamOptions *options );
925 static const char* getErrorCode( OSStatus code );
930 #if defined(__UNIX_JACK__)
932 class RtApiJack: public RtApi
938 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
939 unsigned int getDeviceCount( void );
940 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
941 void closeStream( void );
942 void startStream( void );
943 void stopStream( void );
944 void abortStream( void );
946 // This function is intended for internal use only. It must be
947 // public because it is called by the internal callback handler,
948 // which is not a member of RtAudio. External use of this function
949 // will most likely produce highly undesireable results!
950 bool callbackEvent( unsigned long nframes );
954 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
955 unsigned int firstChannel, unsigned int sampleRate,
956 RtAudioFormat format, unsigned int *bufferSize,
957 RtAudio::StreamOptions *options );
959 bool shouldAutoconnect_;
964 #if defined(__WINDOWS_ASIO__)
966 class RtApiAsio: public RtApi
972 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
973 unsigned int getDeviceCount( void );
974 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
975 void closeStream( void );
976 void startStream( void );
977 void stopStream( void );
978 void abortStream( void );
980 // This function is intended for internal use only. It must be
981 // public because it is called by the internal callback handler,
982 // which is not a member of RtAudio. External use of this function
983 // will most likely produce highly undesireable results!
984 bool callbackEvent( long bufferIndex );
988 std::vector<RtAudio::DeviceInfo> devices_;
989 void saveDeviceInfo( void );
991 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
992 unsigned int firstChannel, unsigned int sampleRate,
993 RtAudioFormat format, unsigned int *bufferSize,
994 RtAudio::StreamOptions *options );
999 #if defined(__WINDOWS_DS__)
1001 class RtApiDs: public RtApi
1007 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
1008 unsigned int getDeviceCount( void );
1009 unsigned int getDefaultOutputDevice( void );
1010 unsigned int getDefaultInputDevice( void );
1011 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1012 void closeStream( void );
1013 void startStream( void );
1014 void stopStream( void );
1015 void abortStream( void );
1017 // This function is intended for internal use only. It must be
1018 // public because it is called by the internal callback handler,
1019 // which is not a member of RtAudio. External use of this function
1020 // will most likely produce highly undesireable results!
1021 void callbackEvent( void );
1025 bool coInitialized_;
1026 bool buffersRolling;
1027 long duplexPrerollBytes;
1028 std::vector<struct DsDevice> dsDevices;
1029 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1030 unsigned int firstChannel, unsigned int sampleRate,
1031 RtAudioFormat format, unsigned int *bufferSize,
1032 RtAudio::StreamOptions *options );
1037 #if defined(__WINDOWS_WASAPI__)
1039 struct IMMDeviceEnumerator;
1041 class RtApiWasapi : public RtApi
1045 virtual ~RtApiWasapi();
1047 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_WASAPI; }
1048 unsigned int getDeviceCount( void );
1049 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1050 unsigned int getDefaultOutputDevice( void );
1051 unsigned int getDefaultInputDevice( void );
1052 void closeStream( void );
1053 void startStream( void );
1054 void stopStream( void );
1055 void abortStream( void );
1058 bool coInitialized_;
1059 IMMDeviceEnumerator* deviceEnumerator_;
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 );
1066 static DWORD WINAPI runWasapiThread( void* wasapiPtr );
1067 static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
1068 static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
1069 void wasapiThread();
1074 #if defined(__LINUX_ALSA__)
1076 class RtApiAlsa: public RtApi
1082 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
1083 unsigned int getDeviceCount( void );
1084 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1085 void closeStream( void );
1086 void startStream( void );
1087 void stopStream( void );
1088 void abortStream( void );
1090 // This function is intended for internal use only. It must be
1091 // public because it is called by the internal callback handler,
1092 // which is not a member of RtAudio. External use of this function
1093 // will most likely produce highly undesireable results!
1094 void callbackEvent( void );
1098 std::vector<RtAudio::DeviceInfo> devices_;
1099 void saveDeviceInfo( void );
1100 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1101 unsigned int firstChannel, unsigned int sampleRate,
1102 RtAudioFormat format, unsigned int *bufferSize,
1103 RtAudio::StreamOptions *options );
1108 #if defined(__LINUX_PULSE__)
1110 class RtApiPulse: public RtApi
1114 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
1115 unsigned int getDeviceCount( void );
1116 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1117 void closeStream( void );
1118 void startStream( void );
1119 void stopStream( void );
1120 void abortStream( void );
1122 // This function is intended for internal use only. It must be
1123 // public because it is called by the internal callback handler,
1124 // which is not a member of RtAudio. External use of this function
1125 // will most likely produce highly undesireable results!
1126 void callbackEvent( void );
1130 std::vector<RtAudio::DeviceInfo> devices_;
1131 void saveDeviceInfo( void );
1132 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1133 unsigned int firstChannel, unsigned int sampleRate,
1134 RtAudioFormat format, unsigned int *bufferSize,
1135 RtAudio::StreamOptions *options );
1140 #if defined(__LINUX_OSS__)
1142 class RtApiOss: public RtApi
1148 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1149 unsigned int getDeviceCount( void );
1150 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1151 void closeStream( void );
1152 void startStream( void );
1153 void stopStream( void );
1154 void abortStream( void );
1156 // This function is intended for internal use only. It must be
1157 // public because it is called by the internal callback handler,
1158 // which is not a member of RtAudio. External use of this function
1159 // will most likely produce highly undesireable results!
1160 void callbackEvent( void );
1164 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1165 unsigned int firstChannel, unsigned int sampleRate,
1166 RtAudioFormat format, unsigned int *bufferSize,
1167 RtAudio::StreamOptions *options );
1172 #if defined(__RTAUDIO_DUMMY__)
1174 class RtApiDummy: public RtApi
1178 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtAudioError::WARNING ); }
1179 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1180 unsigned int getDeviceCount( void ) { return 0; }
1181 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1182 void closeStream( void ) {}
1183 void startStream( void ) {}
1184 void stopStream( void ) {}
1185 void abortStream( void ) {}
1189 bool probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
1190 unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
1191 RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
1192 RtAudio::StreamOptions * /*options*/ ) { return false; }
1199 // Indentation settings for Vim and Emacs
1202 // c-basic-offset: 2
1203 // indent-tabs-mode: nil
1206 // vim: et sts=2 sw=2