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 DirectSound, 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).
197 To continue normal stream operation, the RtAudioCallback function
198 should return a value of zero. To stop the stream and drain the
199 output buffer, the function should return a value of one. To abort
200 the stream immediately, the client should return a value of two.
202 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
203 unsigned int nFrames,
205 RtAudioStreamStatus status,
208 /************************************************************************/
209 /*! \class RtAudioError
210 \brief Exception handling class for RtAudio.
212 The RtAudioError class is quite simple but it does allow errors to be
213 "caught" by RtAudioError::Type. See the RtAudio documentation to know
214 which methods can throw an RtAudioError.
216 /************************************************************************/
218 class RTAUDIO_DLL_PUBLIC RtAudioError : public std::runtime_error
221 //! Defined RtAudioError types.
223 WARNING, /*!< A non-critical error. */
224 DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */
225 UNSPECIFIED, /*!< The default, unspecified error type. */
226 NO_DEVICES_FOUND, /*!< No devices found on system. */
227 INVALID_DEVICE, /*!< An invalid device ID was specified. */
228 MEMORY_ERROR, /*!< An error occured during memory allocation. */
229 INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */
230 INVALID_USE, /*!< The function was called incorrectly. */
231 DRIVER_ERROR, /*!< A system driver error occured. */
232 SYSTEM_ERROR, /*!< A system error occured. */
233 THREAD_ERROR /*!< A thread error occured. */
237 RtAudioError( const std::string& message,
238 Type type = RtAudioError::UNSPECIFIED )
239 : std::runtime_error(message), type_(type) {}
241 //! Prints thrown error message to stderr.
242 virtual void printMessage( void ) const
243 { std::cerr << '\n' << what() << "\n\n"; }
245 //! Returns the thrown error message type.
246 virtual const Type& getType(void) const { return type_; }
248 //! Returns the thrown error message string.
249 virtual const std::string getMessage(void) const
250 { return std::string(what()); }
256 //! RtAudio error callback function prototype.
258 \param type Type of error.
259 \param errorText Error description.
261 typedef void (*RtAudioErrorCallback)( RtAudioError::Type type, const std::string &errorText );
263 // **************************************************************** //
265 // RtAudio class declaration.
267 // RtAudio is a "controller" used to select an available audio i/o
268 // interface. It presents a common API for the user to call but all
269 // functionality is implemented by the class RtApi and its
270 // subclasses. RtAudio creates an instance of an RtApi subclass
271 // based on the user's API choice. If no choice is made, RtAudio
272 // attempts to make a "logical" API selection.
274 // **************************************************************** //
278 class RTAUDIO_DLL_PUBLIC RtAudio
282 //! Audio API specifier arguments.
284 UNSPECIFIED, /*!< Search for a working compiled API. */
285 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
286 LINUX_PULSE, /*!< The Linux PulseAudio API. */
287 LINUX_OSS, /*!< The Linux Open Sound System API. */
288 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
289 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
290 WINDOWS_WASAPI, /*!< The Microsoft WASAPI API. */
291 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
292 WINDOWS_DS, /*!< The Microsoft DirectSound API. */
293 RTAUDIO_DUMMY, /*!< A compilable but non-functional API. */
294 NUM_APIS /*!< Number of values in this enum. */
297 //! The public device information structure for returning queried values.
299 bool probed; /*!< true if the device capabilities were successfully probed. */
300 std::string name; /*!< Character string device identifier. */
301 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
302 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
303 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
304 bool isDefaultOutput; /*!< true if this is the default output device. */
305 bool isDefaultInput; /*!< true if this is the default input device. */
306 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
307 unsigned int preferredSampleRate; /*!< Preferred sample rate, e.g. for WASAPI the system sample rate. */
308 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
310 // Default constructor.
312 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
313 isDefaultOutput(false), isDefaultInput(false), preferredSampleRate(0), nativeFormats(0) {}
316 //! The structure for specifying input or ouput stream parameters.
317 struct StreamParameters {
318 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
319 unsigned int nChannels; /*!< Number of channels. */
320 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
322 // Default constructor.
324 : deviceId(0), nChannels(0), firstChannel(0) {}
327 //! The structure for specifying stream options.
329 The following flags can be OR'ed together to allow a client to
330 make changes to the default stream behavior:
332 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
333 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
334 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
335 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
336 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
338 By default, RtAudio streams pass and receive audio data from the
339 client in an interleaved format. By passing the
340 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
341 data will instead be presented in non-interleaved buffers. In
342 this case, each buffer argument in the RtAudioCallback function
343 will point to a single array of data, with \c nFrames samples for
344 each channel concatenated back-to-back. For example, the first
345 sample of data for the second channel would be located at index \c
346 nFrames (assuming the \c buffer pointer was recast to the correct
347 data type for the stream).
349 Certain audio APIs offer a number of parameters that influence the
350 I/O latency of a stream. By default, RtAudio will attempt to set
351 these parameters internally for robust (glitch-free) performance
352 (though some APIs, like Windows DirectSound, make this difficult).
353 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
354 function, internal stream settings will be influenced in an attempt
355 to minimize stream latency, though possibly at the expense of stream
358 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
359 open the input and/or output stream device(s) for exclusive use.
360 Note that this is not possible with all supported audio APIs.
362 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
363 to select realtime scheduling (round-robin) for the callback thread.
364 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
365 flag is set. It defines the thread's realtime priority.
367 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
368 open the "default" PCM device when using the ALSA API. Note that this
369 will override any specified input or output device id.
371 The \c numberOfBuffers parameter can be used to control stream
372 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
373 only. A value of two is usually the smallest allowed. Larger
374 numbers can potentially result in more robust stream performance,
375 though likely at the cost of stream latency. The value set by the
376 user is replaced during execution of the RtAudio::openStream()
377 function by the value actually used by the system.
379 The \c streamName parameter can be used to set the client name
380 when using the Jack API. By default, the client name is set to
381 RtApiJack. However, if you wish to create multiple instances of
382 RtAudio with Jack, each instance must have a unique client name.
384 struct StreamOptions {
385 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
386 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
387 std::string streamName; /*!< A stream name (currently used only in Jack). */
388 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
390 // Default constructor.
392 : flags(0), numberOfBuffers(0), priority(0) {}
395 //! A static function to determine the current RtAudio version.
396 static std::string getVersion( void );
398 //! A static function to determine the available compiled audio APIs.
400 The values returned in the std::vector can be compared against
401 the enumerated list values. Note that there can be more than one
402 API compiled for certain operating systems.
404 static void getCompiledApi( std::vector<RtAudio::Api> &apis );
406 //! Return the name of a specified compiled audio API.
408 This obtains a short lower-case name used for identification purposes.
409 This value is guaranteed to remain identical across library versions.
410 If the API is unknown, this function will return the empty string.
412 static std::string getApiName( RtAudio::Api api );
414 //! Return the display name of a specified compiled audio API.
416 This obtains a long name used for display purposes.
417 If the API is unknown, this function will return the empty string.
419 static std::string getApiDisplayName( RtAudio::Api api );
421 //! Return the compiled audio API having the given name.
423 A case insensitive comparison will check the specified name
424 against the list of compiled APIs, and return the one which
425 matches. On failure, the function returns UNSPECIFIED.
427 static RtAudio::Api getCompiledApiByName( const std::string &name );
429 //! The class constructor.
431 The constructor performs minor initialization tasks. An exception
432 can be thrown if no API support is compiled.
434 If no API argument is specified and multiple API support has been
435 compiled, the default order of use is JACK, ALSA, OSS (Linux
436 systems) and ASIO, DS (Windows systems).
438 RtAudio( RtAudio::Api api=UNSPECIFIED );
442 If a stream is running or open, it will be stopped and closed
447 //! Returns the audio API specifier for the current instance of RtAudio.
448 RtAudio::Api getCurrentApi( void );
450 //! A public function that queries for the number of audio devices available.
452 This function performs a system query of available devices each time it
453 is called, thus supporting devices connected \e after instantiation. If
454 a system error occurs during processing, a warning will be issued.
456 unsigned int getDeviceCount( void );
458 //! Return an RtAudio::DeviceInfo structure for a specified device number.
461 Any device integer between 0 and getDeviceCount() - 1 is valid.
462 If an invalid argument is provided, an RtAudioError (type = INVALID_USE)
463 will be thrown. If a device is busy or otherwise unavailable, the
464 structure member "probed" will have a value of "false" and all
465 other members are undefined. If the specified device is the
466 current default input or output device, the corresponding
467 "isDefault" member will have a value of "true".
469 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
471 //! A function that returns the index of the default output device.
473 If the underlying audio API does not provide a "default
474 device", or if no devices are available, the return value will be
475 0. Note that this is a valid device identifier and it is the
476 client's responsibility to verify that a device is available
477 before attempting to open a stream.
479 unsigned int getDefaultOutputDevice( void );
481 //! A function that returns the index of the default input device.
483 If the underlying audio API does not provide a "default
484 device", or if no devices are available, the return value will be
485 0. Note that this is a valid device identifier and it is the
486 client's responsibility to verify that a device is available
487 before attempting to open a stream.
489 unsigned int getDefaultInputDevice( void );
491 //! A public function for opening a stream with the specified parameters.
493 An RtAudioError (type = SYSTEM_ERROR) is thrown if a stream cannot be
494 opened with the specified parameters or an error occurs during
495 processing. An RtAudioError (type = INVALID_USE) is thrown if any
496 invalid device ID or channel number parameters are specified.
498 \param outputParameters Specifies output stream parameters to use
499 when opening a stream, including a device ID, number of channels,
500 and starting channel number. For input-only streams, this
501 argument should be NULL. The device ID is an index value between
502 0 and getDeviceCount() - 1.
503 \param inputParameters Specifies input stream parameters to use
504 when opening a stream, including a device ID, number of channels,
505 and starting channel number. For output-only streams, this
506 argument should be NULL. The device ID is an index value between
507 0 and getDeviceCount() - 1.
508 \param format An RtAudioFormat specifying the desired sample data format.
509 \param sampleRate The desired sample rate (sample frames per second).
510 \param *bufferFrames A pointer to a value indicating the desired
511 internal buffer size in sample frames. The actual value
512 used by the device is returned via the same pointer. A
513 value of zero can be specified, in which case the lowest
514 allowable value is determined.
515 \param callback A client-defined function that will be invoked
516 when input data is available and/or output data is needed.
517 \param userData An optional pointer to data that can be accessed
518 from within the callback function.
519 \param options An optional pointer to a structure containing various
520 global stream options, including a list of OR'ed RtAudioStreamFlags
521 and a suggested number of stream buffers that can be used to
522 control stream latency. More buffers typically result in more
523 robust performance, though at a cost of greater latency. If a
524 value of zero is specified, a system-specific median value is
525 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
526 lowest allowable value is used. The actual value used is
527 returned via the structure argument. The parameter is API dependent.
528 \param errorCallback A client-defined function that will be invoked
529 when an error has occured.
531 void openStream( RtAudio::StreamParameters *outputParameters,
532 RtAudio::StreamParameters *inputParameters,
533 RtAudioFormat format, unsigned int sampleRate,
534 unsigned int *bufferFrames, RtAudioCallback callback,
535 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
537 //! A function that closes a stream and frees any associated stream memory.
539 If a stream is not open, this function issues a warning and
540 returns (no exception is thrown).
542 void closeStream( void );
544 //! A function that starts a stream.
546 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
547 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
548 stream is not open. A warning is issued if the stream is already
551 void startStream( void );
553 //! Stop a stream, allowing any samples remaining in the output queue to be played.
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 stopStream( void );
562 //! Stop a stream, discarding any samples remaining in the input/output queue.
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 abortStream( void );
571 //! Returns true if a stream is open and false if not.
572 bool isStreamOpen( void ) const;
574 //! Returns true if the stream is running and false if it is stopped or not open.
575 bool isStreamRunning( void ) const;
577 //! Returns the number of elapsed seconds since the stream was started.
579 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
581 double getStreamTime( void );
583 //! Set the stream time to a time in seconds greater than or equal to 0.0.
585 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
587 void setStreamTime( double time );
589 //! Returns the internal stream latency in sample frames.
591 The stream latency refers to delay in audio input and/or output
592 caused by internal buffering by the audio system and/or hardware.
593 For duplex streams, the returned value will represent the sum of
594 the input and output latencies. If a stream is not open, an
595 RtAudioError (type = INVALID_USE) will be thrown. If the API does not
596 report latency, the return value will be zero.
598 long getStreamLatency( void );
600 //! Returns actual sample rate in use by the stream.
602 On some systems, the sample rate used may be slightly different
603 than that specified in the stream parameters. If a stream is not
604 open, an RtAudioError (type = INVALID_USE) will be thrown.
606 unsigned int getStreamSampleRate( void );
608 //! Specify whether warning messages should be printed to stderr.
609 void showWarnings( bool value = true );
613 void openRtApi( RtAudio::Api api );
617 // Operating system dependent thread functionality.
618 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
627 typedef uintptr_t ThreadHandle;
628 typedef CRITICAL_SECTION StreamMutex;
630 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
631 // Using pthread library for various flavors of unix.
634 typedef pthread_t ThreadHandle;
635 typedef pthread_mutex_t StreamMutex;
637 #else // Setup for "dummy" behavior
639 #define __RTAUDIO_DUMMY__
640 typedef int ThreadHandle;
641 typedef int StreamMutex;
645 // This global structure type is used to pass callback information
646 // between the private RtAudio stream structure and global callback
647 // handling functions.
648 struct CallbackInfo {
649 void *object; // Used as a "this" pointer.
654 void *apiInfo; // void pointer for API specific callback information
659 // Default constructor.
661 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false), priority(0) {}
664 // **************************************************************** //
666 // RtApi class declaration.
668 // Subclasses of RtApi contain all API- and OS-specific code necessary
669 // to fully implement the RtAudio API.
671 // Note that RtApi is an abstract base class and cannot be
672 // explicitly instantiated. The class RtAudio will create an
673 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
674 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
676 // **************************************************************** //
678 #pragma pack(push, 1)
687 S24& operator = ( const int& i ) {
688 c3[0] = (i & 0x000000ff);
689 c3[1] = (i & 0x0000ff00) >> 8;
690 c3[2] = (i & 0x00ff0000) >> 16;
694 S24( const double& d ) { *this = (int) d; }
695 S24( const float& f ) { *this = (int) f; }
696 S24( const signed short& s ) { *this = (int) s; }
697 S24( const char& c ) { *this = (int) c; }
700 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
701 if (i & 0x800000) i |= ~0xffffff;
707 #if defined( HAVE_GETTIMEOFDAY )
708 #include <sys/time.h>
713 class RTAUDIO_DLL_PUBLIC RtApi
719 virtual RtAudio::Api getCurrentApi( void ) = 0;
720 virtual unsigned int getDeviceCount( void ) = 0;
721 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
722 virtual unsigned int getDefaultInputDevice( void );
723 virtual unsigned int getDefaultOutputDevice( void );
724 void openStream( RtAudio::StreamParameters *outputParameters,
725 RtAudio::StreamParameters *inputParameters,
726 RtAudioFormat format, unsigned int sampleRate,
727 unsigned int *bufferFrames, RtAudioCallback callback,
728 void *userData, RtAudio::StreamOptions *options,
729 RtAudioErrorCallback errorCallback );
730 virtual void closeStream( void );
731 virtual void startStream( void ) = 0;
732 virtual void stopStream( void ) = 0;
733 virtual void abortStream( void ) = 0;
734 long getStreamLatency( void );
735 unsigned int getStreamSampleRate( void );
736 virtual double getStreamTime( void );
737 virtual void setStreamTime( double time );
738 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
739 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
740 void showWarnings( bool value ) { showWarnings_ = value; }
745 static const unsigned int MAX_SAMPLE_RATES;
746 static const unsigned int SAMPLE_RATES[];
748 enum { FAILURE, SUCCESS };
764 // A protected structure used for buffer conversion.
768 RtAudioFormat inFormat, outFormat;
769 std::vector<int> inOffset;
770 std::vector<int> outOffset;
773 // A protected structure for audio streams.
775 unsigned int device[2]; // Playback and record, respectively.
776 void *apiHandle; // void pointer for API specific stream handle information
777 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
778 StreamState state; // STOPPED, RUNNING, or CLOSED
779 char *userBuffer[2]; // Playback and record, respectively.
781 bool doConvertBuffer[2]; // Playback and record, respectively.
782 bool userInterleaved;
783 bool deviceInterleaved[2]; // Playback and record, respectively.
784 bool doByteSwap[2]; // Playback and record, respectively.
785 unsigned int sampleRate;
786 unsigned int bufferSize;
787 unsigned int nBuffers;
788 unsigned int nUserChannels[2]; // Playback and record, respectively.
789 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
790 unsigned int channelOffset[2]; // Playback and record, respectively.
791 unsigned long latency[2]; // Playback and record, respectively.
792 RtAudioFormat userFormat;
793 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
795 CallbackInfo callbackInfo;
796 ConvertInfo convertInfo[2];
797 double streamTime; // Number of elapsed seconds since the stream started.
799 #if defined(HAVE_GETTIMEOFDAY)
800 struct timeval lastTickTimestamp;
804 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
808 typedef signed short Int16;
809 typedef signed int Int32;
810 typedef float Float32;
811 typedef double Float64;
813 std::ostringstream errorStream_;
814 std::string errorText_;
817 bool firstErrorOccurred_;
820 Protected, api-specific method that attempts to open a device
821 with the given parameters. This function MUST be implemented by
822 all subclasses. If an error is encountered during the probe, a
823 "warning" message is reported and FAILURE is returned. A
824 successful probe is indicated by a return value of SUCCESS.
826 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
827 unsigned int firstChannel, unsigned int sampleRate,
828 RtAudioFormat format, unsigned int *bufferSize,
829 RtAudio::StreamOptions *options );
831 //! A protected function used to increment the stream time.
832 void tickStreamTime( void );
834 //! Protected common method to clear an RtApiStream structure.
835 void clearStreamInfo();
838 Protected common method that throws an RtAudioError (type =
839 INVALID_USE) if a stream is not open.
841 void verifyStream( void );
843 //! Protected common error method to allow global control over error handling.
844 void error( RtAudioError::Type type );
847 Protected method used to perform format, channel number, and/or interleaving
848 conversions between the user and device buffers.
850 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
852 //! Protected common method used to perform byte-swapping on buffers.
853 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
855 //! Protected common method that returns the number of bytes for a given format.
856 unsigned int formatBytes( RtAudioFormat format );
858 //! Protected common method that sets up the parameters for buffer conversion.
859 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
862 // **************************************************************** //
864 // Inline RtAudio definitions.
866 // **************************************************************** //
868 inline RtAudio::Api RtAudio :: getCurrentApi( void ) { return rtapi_->getCurrentApi(); }
869 inline unsigned int RtAudio :: getDeviceCount( void ) { return rtapi_->getDeviceCount(); }
870 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
871 inline unsigned int RtAudio :: getDefaultInputDevice( void ) { return rtapi_->getDefaultInputDevice(); }
872 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) { return rtapi_->getDefaultOutputDevice(); }
873 inline void RtAudio :: closeStream( void ) { return rtapi_->closeStream(); }
874 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
875 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
876 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
877 inline bool RtAudio :: isStreamOpen( void ) const { return rtapi_->isStreamOpen(); }
878 inline bool RtAudio :: isStreamRunning( void ) const { return rtapi_->isStreamRunning(); }
879 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
880 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
881 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
882 inline void RtAudio :: setStreamTime( double time ) { return rtapi_->setStreamTime( time ); }
883 inline void RtAudio :: showWarnings( bool value ) { rtapi_->showWarnings( value ); }
885 // RtApi Subclass prototypes.
887 #if defined(__MACOSX_CORE__)
889 #include <CoreAudio/AudioHardware.h>
891 class RtApiCore: public RtApi
897 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
898 unsigned int getDeviceCount( void );
899 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
900 unsigned int getDefaultOutputDevice( void );
901 unsigned int getDefaultInputDevice( void );
902 void closeStream( void );
903 void startStream( void );
904 void stopStream( void );
905 void abortStream( 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( AudioDeviceID deviceId,
912 const AudioBufferList *inBufferList,
913 const AudioBufferList *outBufferList );
917 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
918 unsigned int firstChannel, unsigned int sampleRate,
919 RtAudioFormat format, unsigned int *bufferSize,
920 RtAudio::StreamOptions *options );
921 static const char* getErrorCode( OSStatus code );
926 #if defined(__UNIX_JACK__)
928 class RtApiJack: public RtApi
934 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
935 unsigned int getDeviceCount( void );
936 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
937 void closeStream( void );
938 void startStream( void );
939 void stopStream( void );
940 void abortStream( void );
942 // This function is intended for internal use only. It must be
943 // public because it is called by the internal callback handler,
944 // which is not a member of RtAudio. External use of this function
945 // will most likely produce highly undesireable results!
946 bool callbackEvent( unsigned long nframes );
950 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
951 unsigned int firstChannel, unsigned int sampleRate,
952 RtAudioFormat format, unsigned int *bufferSize,
953 RtAudio::StreamOptions *options );
955 bool shouldAutoconnect_;
960 #if defined(__WINDOWS_ASIO__)
962 class RtApiAsio: public RtApi
968 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
969 unsigned int getDeviceCount( void );
970 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
971 void closeStream( void );
972 void startStream( void );
973 void stopStream( void );
974 void abortStream( void );
976 // This function is intended for internal use only. It must be
977 // public because it is called by the internal callback handler,
978 // which is not a member of RtAudio. External use of this function
979 // will most likely produce highly undesireable results!
980 bool callbackEvent( long bufferIndex );
984 std::vector<RtAudio::DeviceInfo> devices_;
985 void saveDeviceInfo( void );
987 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
988 unsigned int firstChannel, unsigned int sampleRate,
989 RtAudioFormat format, unsigned int *bufferSize,
990 RtAudio::StreamOptions *options );
995 #if defined(__WINDOWS_DS__)
997 class RtApiDs: public RtApi
1003 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
1004 unsigned int getDeviceCount( void );
1005 unsigned int getDefaultOutputDevice( void );
1006 unsigned int getDefaultInputDevice( void );
1007 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1008 void closeStream( void );
1009 void startStream( void );
1010 void stopStream( void );
1011 void abortStream( void );
1013 // This function is intended for internal use only. It must be
1014 // public because it is called by the internal callback handler,
1015 // which is not a member of RtAudio. External use of this function
1016 // will most likely produce highly undesireable results!
1017 void callbackEvent( void );
1021 bool coInitialized_;
1022 bool buffersRolling;
1023 long duplexPrerollBytes;
1024 std::vector<struct DsDevice> dsDevices;
1025 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1026 unsigned int firstChannel, unsigned int sampleRate,
1027 RtAudioFormat format, unsigned int *bufferSize,
1028 RtAudio::StreamOptions *options );
1033 #if defined(__WINDOWS_WASAPI__)
1035 struct IMMDeviceEnumerator;
1037 class RtApiWasapi : public RtApi
1041 virtual ~RtApiWasapi();
1043 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_WASAPI; }
1044 unsigned int getDeviceCount( void );
1045 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1046 unsigned int getDefaultOutputDevice( void );
1047 unsigned int getDefaultInputDevice( void );
1048 void closeStream( void );
1049 void startStream( void );
1050 void stopStream( void );
1051 void abortStream( void );
1054 bool coInitialized_;
1055 IMMDeviceEnumerator* deviceEnumerator_;
1057 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1058 unsigned int firstChannel, unsigned int sampleRate,
1059 RtAudioFormat format, unsigned int* bufferSize,
1060 RtAudio::StreamOptions* options );
1062 static DWORD WINAPI runWasapiThread( void* wasapiPtr );
1063 static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
1064 static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
1065 void wasapiThread();
1070 #if defined(__LINUX_ALSA__)
1072 class RtApiAlsa: public RtApi
1078 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
1079 unsigned int getDeviceCount( void );
1080 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1081 void closeStream( void );
1082 void startStream( void );
1083 void stopStream( void );
1084 void abortStream( void );
1086 // This function is intended for internal use only. It must be
1087 // public because it is called by the internal callback handler,
1088 // which is not a member of RtAudio. External use of this function
1089 // will most likely produce highly undesireable results!
1090 void callbackEvent( void );
1094 std::vector<RtAudio::DeviceInfo> devices_;
1095 void saveDeviceInfo( void );
1096 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1097 unsigned int firstChannel, unsigned int sampleRate,
1098 RtAudioFormat format, unsigned int *bufferSize,
1099 RtAudio::StreamOptions *options );
1104 #if defined(__LINUX_PULSE__)
1106 class RtApiPulse: public RtApi
1110 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
1111 unsigned int getDeviceCount( void );
1112 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1113 void closeStream( void );
1114 void startStream( void );
1115 void stopStream( void );
1116 void abortStream( void );
1118 // This function is intended for internal use only. It must be
1119 // public because it is called by the internal callback handler,
1120 // which is not a member of RtAudio. External use of this function
1121 // will most likely produce highly undesireable results!
1122 void callbackEvent( void );
1126 std::vector<RtAudio::DeviceInfo> devices_;
1127 void saveDeviceInfo( void );
1128 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1129 unsigned int firstChannel, unsigned int sampleRate,
1130 RtAudioFormat format, unsigned int *bufferSize,
1131 RtAudio::StreamOptions *options );
1136 #if defined(__LINUX_OSS__)
1138 class RtApiOss: public RtApi
1144 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1145 unsigned int getDeviceCount( void );
1146 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1147 void closeStream( void );
1148 void startStream( void );
1149 void stopStream( void );
1150 void abortStream( void );
1152 // This function is intended for internal use only. It must be
1153 // public because it is called by the internal callback handler,
1154 // which is not a member of RtAudio. External use of this function
1155 // will most likely produce highly undesireable results!
1156 void callbackEvent( void );
1160 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1161 unsigned int firstChannel, unsigned int sampleRate,
1162 RtAudioFormat format, unsigned int *bufferSize,
1163 RtAudio::StreamOptions *options );
1168 #if defined(__RTAUDIO_DUMMY__)
1170 class RtApiDummy: public RtApi
1174 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtAudioError::WARNING ); }
1175 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1176 unsigned int getDeviceCount( void ) { return 0; }
1177 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1178 void closeStream( void ) {}
1179 void startStream( void ) {}
1180 void stopStream( void ) {}
1181 void abortStream( void ) {}
1185 bool probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
1186 unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
1187 RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
1188 RtAudio::StreamOptions * /*options*/ ) { return false; }
1195 // Indentation settings for Vim and Emacs
1198 // c-basic-offset: 2
1199 // indent-tabs-mode: nil
1202 // vim: et sts=2 sw=2