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 #define RTAUDIO_DLL_PUBLIC
54 #define RTAUDIO_DLL_PUBLIC __attribute__( (visibility( "default" )) )
56 #define RTAUDIO_DLL_PUBLIC
66 /*! \typedef typedef unsigned long RtAudioFormat;
67 \brief RtAudio data format type.
69 Support for signed integers and floats. Audio data fed to/from an
70 RtAudio stream is assumed to ALWAYS be in host byte order. The
71 internal routines will automatically take care of any necessary
72 byte-swapping between the host format and the soundcard. Thus,
73 endian-ness is not a concern in the following format definitions.
75 - \e RTAUDIO_SINT8: 8-bit signed integer.
76 - \e RTAUDIO_SINT16: 16-bit signed integer.
77 - \e RTAUDIO_SINT24: 24-bit signed integer.
78 - \e RTAUDIO_SINT32: 32-bit signed integer.
79 - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
80 - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
82 typedef unsigned long RtAudioFormat;
83 static const RtAudioFormat RTAUDIO_SINT8 = 0x1; // 8-bit signed integer.
84 static const RtAudioFormat RTAUDIO_SINT16 = 0x2; // 16-bit signed integer.
85 static const RtAudioFormat RTAUDIO_SINT24 = 0x4; // 24-bit signed integer.
86 static const RtAudioFormat RTAUDIO_SINT32 = 0x8; // 32-bit signed integer.
87 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
88 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
90 /*! \typedef typedef unsigned long RtAudioStreamFlags;
91 \brief RtAudio stream option flags.
93 The following flags can be OR'ed together to allow a client to
94 make changes to the default stream behavior:
96 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
97 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
98 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
99 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
100 - \e RTAUDIO_JACK_DONT_CONNECT: Do not automatically connect ports (JACK only).
102 By default, RtAudio streams pass and receive audio data from the
103 client in an interleaved format. By passing the
104 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
105 data will instead be presented in non-interleaved buffers. In
106 this case, each buffer argument in the RtAudioCallback function
107 will point to a single array of data, with \c nFrames samples for
108 each channel concatenated back-to-back. For example, the first
109 sample of data for the second channel would be located at index \c
110 nFrames (assuming the \c buffer pointer was recast to the correct
111 data type for the stream).
113 Certain audio APIs offer a number of parameters that influence the
114 I/O latency of a stream. By default, RtAudio will attempt to set
115 these parameters internally for robust (glitch-free) performance
116 (though some APIs, like Windows Direct Sound, make this difficult).
117 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
118 function, internal stream settings will be influenced in an attempt
119 to minimize stream latency, though possibly at the expense of stream
122 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
123 open the input and/or output stream device(s) for exclusive use.
124 Note that this is not possible with all supported audio APIs.
126 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
127 to select realtime scheduling (round-robin) for the callback thread.
129 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
130 open the "default" PCM device when using the ALSA API. Note that this
131 will override any specified input or output device id.
133 If the RTAUDIO_JACK_DONT_CONNECT flag is set, RtAudio will not attempt
134 to automatically connect the ports of the client to the audio device.
136 typedef unsigned int RtAudioStreamFlags;
137 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1; // Use non-interleaved buffers (default = interleaved).
138 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2; // Attempt to set stream parameters for lowest possible latency.
139 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4; // Attempt grab device and prevent use by others.
140 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
141 static const RtAudioStreamFlags RTAUDIO_ALSA_USE_DEFAULT = 0x10; // Use the "default" PCM device (ALSA only).
142 static const RtAudioStreamFlags RTAUDIO_JACK_DONT_CONNECT = 0x20; // Do not automatically connect ports (JACK only).
144 /*! \typedef typedef unsigned long RtAudioStreamStatus;
145 \brief RtAudio stream status (over- or underflow) flags.
147 Notification of a stream over- or underflow is indicated by a
148 non-zero stream \c status argument in the RtAudioCallback function.
149 The stream status can be one of the following two options,
150 depending on whether the stream is open for output and/or input:
152 - \e RTAUDIO_INPUT_OVERFLOW: Input data was discarded because of an overflow condition at the driver.
153 - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
155 typedef unsigned int RtAudioStreamStatus;
156 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver.
157 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound.
159 //! RtAudio callback function prototype.
161 All RtAudio clients must create a function of type RtAudioCallback
162 to read and/or write data from/to the audio stream. When the
163 underlying audio system is ready for new input or output data, this
164 function will be invoked.
166 \param outputBuffer For output (or duplex) streams, the client
167 should write \c nFrames of audio sample frames into this
168 buffer. This argument should be recast to the datatype
169 specified when the stream was opened. For input-only
170 streams, this argument will be NULL.
172 \param inputBuffer For input (or duplex) streams, this buffer will
173 hold \c nFrames of input audio sample frames. This
174 argument should be recast to the datatype specified when the
175 stream was opened. For output-only streams, this argument
178 \param nFrames The number of sample frames of input or output
179 data in the buffers. The actual buffer size in bytes is
180 dependent on the data type and number of channels in use.
182 \param streamTime The number of seconds that have elapsed since the
185 \param status If non-zero, this argument indicates a data overflow
186 or underflow condition for the stream. The particular
187 condition can be determined by comparison with the
188 RtAudioStreamStatus flags.
190 \param userData A pointer to optional data provided by the client
191 when opening the stream (default = NULL).
193 To continue normal stream operation, the RtAudioCallback function
194 should return a value of zero. To stop the stream and drain the
195 output buffer, the function should return a value of one. To abort
196 the stream immediately, the client should return a value of two.
198 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
199 unsigned int nFrames,
201 RtAudioStreamStatus status,
204 /************************************************************************/
205 /*! \class RtAudioError
206 \brief Exception handling class for RtAudio.
208 The RtAudioError class is quite simple but it does allow errors to be
209 "caught" by RtAudioError::Type. See the RtAudio documentation to know
210 which methods can throw an RtAudioError.
212 /************************************************************************/
214 class RTAUDIO_DLL_PUBLIC RtAudioError : public std::runtime_error
217 //! Defined RtAudioError types.
219 WARNING, /*!< A non-critical error. */
220 DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */
221 UNSPECIFIED, /*!< The default, unspecified error type. */
222 NO_DEVICES_FOUND, /*!< No devices found on system. */
223 INVALID_DEVICE, /*!< An invalid device ID was specified. */
224 MEMORY_ERROR, /*!< An error occured during memory allocation. */
225 INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */
226 INVALID_USE, /*!< The function was called incorrectly. */
227 DRIVER_ERROR, /*!< A system driver error occured. */
228 SYSTEM_ERROR, /*!< A system error occured. */
229 THREAD_ERROR /*!< A thread error occured. */
233 RtAudioError( const std::string& message,
234 Type type = RtAudioError::UNSPECIFIED )
235 : std::runtime_error(message), type_(type) {}
237 //! Prints thrown error message to stderr.
238 virtual void printMessage( void ) const
239 { std::cerr << '\n' << what() << "\n\n"; }
241 //! Returns the thrown error message type.
242 virtual const Type& getType(void) const { return type_; }
244 //! Returns the thrown error message string.
245 virtual const std::string getMessage(void) const
246 { return std::string(what()); }
252 //! RtAudio error callback function prototype.
254 \param type Type of error.
255 \param errorText Error description.
257 typedef void (*RtAudioErrorCallback)( RtAudioError::Type type, const std::string &errorText );
259 // **************************************************************** //
261 // RtAudio class declaration.
263 // RtAudio is a "controller" used to select an available audio i/o
264 // interface. It presents a common API for the user to call but all
265 // functionality is implemented by the class RtApi and its
266 // subclasses. RtAudio creates an instance of an RtApi subclass
267 // based on the user's API choice. If no choice is made, RtAudio
268 // attempts to make a "logical" API selection.
270 // **************************************************************** //
274 class RTAUDIO_DLL_PUBLIC RtAudio
278 //! Audio API specifier arguments.
280 UNSPECIFIED, /*!< Search for a working compiled API. */
281 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
282 LINUX_PULSE, /*!< The Linux PulseAudio API. */
283 LINUX_OSS, /*!< The Linux Open Sound System API. */
284 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
285 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
286 WINDOWS_WASAPI, /*!< The Microsoft WASAPI API. */
287 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
288 WINDOWS_DS, /*!< The Microsoft Direct Sound API. */
289 RTAUDIO_DUMMY /*!< A compilable but non-functional API. */
292 //! Map string identifiers for APIs to enum identifiers and display names
293 typedef std::map< std::string, std::pair<RtAudio::Api, std::string> > ApiNameMap;
295 //! The public device information structure for returning queried values.
297 bool probed; /*!< true if the device capabilities were successfully probed. */
298 std::string name; /*!< Character string device identifier. */
299 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
300 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
301 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
302 bool isDefaultOutput; /*!< true if this is the default output device. */
303 bool isDefaultInput; /*!< true if this is the default input device. */
304 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
305 unsigned int preferredSampleRate; /*!< Preferred sample rate, eg. for WASAPI the system sample rate. */
306 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
308 // Default constructor.
310 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
311 isDefaultOutput(false), isDefaultInput(false), preferredSampleRate(0), nativeFormats(0) {}
314 //! The structure for specifying input or ouput stream parameters.
315 struct StreamParameters {
316 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
317 unsigned int nChannels; /*!< Number of channels. */
318 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
320 // Default constructor.
322 : deviceId(0), nChannels(0), firstChannel(0) {}
325 //! The structure for specifying stream options.
327 The following flags can be OR'ed together to allow a client to
328 make changes to the default stream behavior:
330 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
331 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
332 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
333 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
334 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
336 By default, RtAudio streams pass and receive audio data from the
337 client in an interleaved format. By passing the
338 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
339 data will instead be presented in non-interleaved buffers. In
340 this case, each buffer argument in the RtAudioCallback function
341 will point to a single array of data, with \c nFrames samples for
342 each channel concatenated back-to-back. For example, the first
343 sample of data for the second channel would be located at index \c
344 nFrames (assuming the \c buffer pointer was recast to the correct
345 data type for the stream).
347 Certain audio APIs offer a number of parameters that influence the
348 I/O latency of a stream. By default, RtAudio will attempt to set
349 these parameters internally for robust (glitch-free) performance
350 (though some APIs, like Windows Direct Sound, make this difficult).
351 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
352 function, internal stream settings will be influenced in an attempt
353 to minimize stream latency, though possibly at the expense of stream
356 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
357 open the input and/or output stream device(s) for exclusive use.
358 Note that this is not possible with all supported audio APIs.
360 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
361 to select realtime scheduling (round-robin) for the callback thread.
362 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
363 flag is set. It defines the thread's realtime priority.
365 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
366 open the "default" PCM device when using the ALSA API. Note that this
367 will override any specified input or output device id.
369 The \c numberOfBuffers parameter can be used to control stream
370 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
371 only. A value of two is usually the smallest allowed. Larger
372 numbers can potentially result in more robust stream performance,
373 though likely at the cost of stream latency. The value set by the
374 user is replaced during execution of the RtAudio::openStream()
375 function by the value actually used by the system.
377 The \c streamName parameter can be used to set the client name
378 when using the Jack API. By default, the client name is set to
379 RtApiJack. However, if you wish to create multiple instances of
380 RtAudio with Jack, each instance must have a unique client name.
382 struct StreamOptions {
383 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
384 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
385 std::string streamName; /*!< A stream name (currently used only in Jack). */
386 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
388 // Default constructor.
390 : flags(0), numberOfBuffers(0), priority(0) {}
393 //! A static function to determine the current RtAudio version.
394 static std::string getVersion( void );
396 //! A static function to determine the available compiled audio APIs.
398 The values returned in the std::vector can be compared against
399 the enumerated list values. Note that there can be more than one
400 API compiled for certain operating systems.
402 static void getCompiledApi( std::vector<RtAudio::Api> &apis );
404 //! A static function to determine the available compiled audio APIs.
406 The values returned in the std::vector can be compared against
407 the enumerated list values. Note that there can be more than one
408 API compiled for certain operating systems.
410 static const std::vector<RtAudio::Api>& getCompiledApi();
412 //! Return the name of a specified compiled audio API.
414 This obtains a short lower-case name used for identification purposes.
415 This value is guaranteed to remain identical across library versions.
416 If the API is unknown or not compiled, this function will return
419 static const std::string getCompiledApiName( RtAudio::Api api );
421 //! Return the display name of a specified compiled audio API.
423 This obtains a long name used for display purposes.
424 If the API is unknown or not compiled, this function will return
427 static const std::string getCompiledApiDisplayName( RtAudio::Api api );
429 //! Return the compiled audio API having the given name.
431 A case insensitive comparison will check the specified name
432 against the list of compiled APIs, and return the one which
433 matches. On failure, the function returns UNSPECIFIED.
435 static RtAudio::Api getCompiledApiByName( const std::string &name );
437 //! The class constructor.
439 The constructor performs minor initialization tasks. An exception
440 can be thrown if no API support is compiled.
442 If no API argument is specified and multiple API support has been
443 compiled, the default order of use is JACK, ALSA, OSS (Linux
444 systems) and ASIO, DS (Windows systems).
446 RtAudio( RtAudio::Api api=UNSPECIFIED );
450 If a stream is running or open, it will be stopped and closed
455 //! Returns the audio API specifier for the current instance of RtAudio.
456 RtAudio::Api getCurrentApi( void );
458 //! A public function that queries for the number of audio devices available.
460 This function performs a system query of available devices each time it
461 is called, thus supporting devices connected \e after instantiation. If
462 a system error occurs during processing, a warning will be issued.
464 unsigned int getDeviceCount( void );
466 //! Return an RtAudio::DeviceInfo structure for a specified device number.
469 Any device integer between 0 and getDeviceCount() - 1 is valid.
470 If an invalid argument is provided, an RtAudioError (type = INVALID_USE)
471 will be thrown. If a device is busy or otherwise unavailable, the
472 structure member "probed" will have a value of "false" and all
473 other members are undefined. If the specified device is the
474 current default input or output device, the corresponding
475 "isDefault" member will have a value of "true".
477 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
479 //! A function that returns the index of the default output device.
481 If the underlying audio API does not provide a "default
482 device", or if no devices are available, the return value will be
483 0. Note that this is a valid device identifier and it is the
484 client's responsibility to verify that a device is available
485 before attempting to open a stream.
487 unsigned int getDefaultOutputDevice( void );
489 //! A function that returns the index of the default input device.
491 If the underlying audio API does not provide a "default
492 device", or if no devices are available, the return value will be
493 0. Note that this is a valid device identifier and it is the
494 client's responsibility to verify that a device is available
495 before attempting to open a stream.
497 unsigned int getDefaultInputDevice( void );
499 //! A public function for opening a stream with the specified parameters.
501 An RtAudioError (type = SYSTEM_ERROR) is thrown if a stream cannot be
502 opened with the specified parameters or an error occurs during
503 processing. An RtAudioError (type = INVALID_USE) is thrown if any
504 invalid device ID or channel number parameters are specified.
506 \param outputParameters Specifies output stream parameters to use
507 when opening a stream, including a device ID, number of channels,
508 and starting channel number. For input-only streams, this
509 argument should be NULL. The device ID is an index value between
510 0 and getDeviceCount() - 1.
511 \param inputParameters Specifies input stream parameters to use
512 when opening a stream, including a device ID, number of channels,
513 and starting channel number. For output-only streams, this
514 argument should be NULL. The device ID is an index value between
515 0 and getDeviceCount() - 1.
516 \param format An RtAudioFormat specifying the desired sample data format.
517 \param sampleRate The desired sample rate (sample frames per second).
518 \param *bufferFrames A pointer to a value indicating the desired
519 internal buffer size in sample frames. The actual value
520 used by the device is returned via the same pointer. A
521 value of zero can be specified, in which case the lowest
522 allowable value is determined.
523 \param callback A client-defined function that will be invoked
524 when input data is available and/or output data is needed.
525 \param userData An optional pointer to data that can be accessed
526 from within the callback function.
527 \param options An optional pointer to a structure containing various
528 global stream options, including a list of OR'ed RtAudioStreamFlags
529 and a suggested number of stream buffers that can be used to
530 control stream latency. More buffers typically result in more
531 robust performance, though at a cost of greater latency. If a
532 value of zero is specified, a system-specific median value is
533 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
534 lowest allowable value is used. The actual value used is
535 returned via the structure argument. The parameter is API dependent.
536 \param errorCallback A client-defined function that will be invoked
537 when an error has occured.
539 void openStream( RtAudio::StreamParameters *outputParameters,
540 RtAudio::StreamParameters *inputParameters,
541 RtAudioFormat format, unsigned int sampleRate,
542 unsigned int *bufferFrames, RtAudioCallback callback,
543 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
545 //! A function that closes a stream and frees any associated stream memory.
547 If a stream is not open, this function issues a warning and
548 returns (no exception is thrown).
550 void closeStream( void );
552 //! A function that starts a stream.
554 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
555 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
556 stream is not open. A warning is issued if the stream is already
559 void startStream( void );
561 //! Stop a stream, allowing any samples remaining in the output queue to be played.
563 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
564 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
565 stream is not open. A warning is issued if the stream is already
568 void stopStream( void );
570 //! Stop a stream, discarding any samples remaining in the input/output queue.
572 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
573 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
574 stream is not open. A warning is issued if the stream is already
577 void abortStream( void );
579 //! Returns true if a stream is open and false if not.
580 bool isStreamOpen( void ) const;
582 //! Returns true if the stream is running and false if it is stopped or not open.
583 bool isStreamRunning( void ) const;
585 //! Returns the number of elapsed seconds since the stream was started.
587 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
589 double getStreamTime( void );
591 //! Set the stream time to a time in seconds greater than or equal to 0.0.
593 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
595 void setStreamTime( double time );
597 //! Returns the internal stream latency in sample frames.
599 The stream latency refers to delay in audio input and/or output
600 caused by internal buffering by the audio system and/or hardware.
601 For duplex streams, the returned value will represent the sum of
602 the input and output latencies. If a stream is not open, an
603 RtAudioError (type = INVALID_USE) will be thrown. If the API does not
604 report latency, the return value will be zero.
606 long getStreamLatency( void );
608 //! Returns actual sample rate in use by the stream.
610 On some systems, the sample rate used may be slightly different
611 than that specified in the stream parameters. If a stream is not
612 open, an RtAudioError (type = INVALID_USE) will be thrown.
614 unsigned int getStreamSampleRate( void );
616 //! Specify whether warning messages should be printed to stderr.
617 void showWarnings( bool value = true );
621 //! Storage for API name map
622 static const ApiNameMap apiNames;
624 //! Storage for compiled API list
625 static const std::vector<RtAudio::Api> compiledApis;
627 void openRtApi( RtAudio::Api api );
631 // Operating system dependent thread functionality.
632 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
640 typedef uintptr_t ThreadHandle;
641 typedef CRITICAL_SECTION StreamMutex;
643 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
644 // Using pthread library for various flavors of unix.
647 typedef pthread_t ThreadHandle;
648 typedef pthread_mutex_t StreamMutex;
650 #else // Setup for "dummy" behavior
652 #define __RTAUDIO_DUMMY__
653 typedef int ThreadHandle;
654 typedef int StreamMutex;
658 // This global structure type is used to pass callback information
659 // between the private RtAudio stream structure and global callback
660 // handling functions.
661 struct CallbackInfo {
662 void *object; // Used as a "this" pointer.
667 void *apiInfo; // void pointer for API specific callback information
672 // Default constructor.
674 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false), priority(0) {}
677 // **************************************************************** //
679 // RtApi class declaration.
681 // Subclasses of RtApi contain all API- and OS-specific code necessary
682 // to fully implement the RtAudio API.
684 // Note that RtApi is an abstract base class and cannot be
685 // explicitly instantiated. The class RtAudio will create an
686 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
687 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
689 // **************************************************************** //
691 #pragma pack(push, 1)
700 S24& operator = ( const int& i ) {
701 c3[0] = (i & 0x000000ff);
702 c3[1] = (i & 0x0000ff00) >> 8;
703 c3[2] = (i & 0x00ff0000) >> 16;
707 S24( const S24& v ) { *this = v; }
708 S24( const double& d ) { *this = (int) d; }
709 S24( const float& f ) { *this = (int) f; }
710 S24( const signed short& s ) { *this = (int) s; }
711 S24( const char& c ) { *this = (int) c; }
714 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
715 if (i & 0x800000) i |= ~0xffffff;
721 #if defined( HAVE_GETTIMEOFDAY )
722 #include <sys/time.h>
727 class RTAUDIO_DLL_PUBLIC RtApi
733 virtual RtAudio::Api getCurrentApi( void ) = 0;
734 virtual unsigned int getDeviceCount( void ) = 0;
735 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
736 virtual unsigned int getDefaultInputDevice( void );
737 virtual unsigned int getDefaultOutputDevice( void );
738 void openStream( RtAudio::StreamParameters *outputParameters,
739 RtAudio::StreamParameters *inputParameters,
740 RtAudioFormat format, unsigned int sampleRate,
741 unsigned int *bufferFrames, RtAudioCallback callback,
742 void *userData, RtAudio::StreamOptions *options,
743 RtAudioErrorCallback errorCallback );
744 virtual void closeStream( void );
745 virtual void startStream( void ) = 0;
746 virtual void stopStream( void ) = 0;
747 virtual void abortStream( void ) = 0;
748 long getStreamLatency( void );
749 unsigned int getStreamSampleRate( void );
750 virtual double getStreamTime( void );
751 virtual void setStreamTime( double time );
752 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
753 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
754 void showWarnings( bool value ) { showWarnings_ = value; }
759 static const unsigned int MAX_SAMPLE_RATES;
760 static const unsigned int SAMPLE_RATES[];
762 enum { FAILURE, SUCCESS };
778 // A protected structure used for buffer conversion.
782 RtAudioFormat inFormat, outFormat;
783 std::vector<int> inOffset;
784 std::vector<int> outOffset;
787 // A protected structure for audio streams.
789 unsigned int device[2]; // Playback and record, respectively.
790 void *apiHandle; // void pointer for API specific stream handle information
791 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
792 StreamState state; // STOPPED, RUNNING, or CLOSED
793 char *userBuffer[2]; // Playback and record, respectively.
795 bool doConvertBuffer[2]; // Playback and record, respectively.
796 bool userInterleaved;
797 bool deviceInterleaved[2]; // Playback and record, respectively.
798 bool doByteSwap[2]; // Playback and record, respectively.
799 unsigned int sampleRate;
800 unsigned int bufferSize;
801 unsigned int nBuffers;
802 unsigned int nUserChannels[2]; // Playback and record, respectively.
803 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
804 unsigned int channelOffset[2]; // Playback and record, respectively.
805 unsigned long latency[2]; // Playback and record, respectively.
806 RtAudioFormat userFormat;
807 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
809 CallbackInfo callbackInfo;
810 ConvertInfo convertInfo[2];
811 double streamTime; // Number of elapsed seconds since the stream started.
813 #if defined(HAVE_GETTIMEOFDAY)
814 struct timeval lastTickTimestamp;
818 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
822 typedef signed short Int16;
823 typedef signed int Int32;
824 typedef float Float32;
825 typedef double Float64;
827 std::ostringstream errorStream_;
828 std::string errorText_;
831 bool firstErrorOccurred_;
834 Protected, api-specific method that attempts to open a device
835 with the given parameters. This function MUST be implemented by
836 all subclasses. If an error is encountered during the probe, a
837 "warning" message is reported and FAILURE is returned. A
838 successful probe is indicated by a return value of SUCCESS.
840 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
841 unsigned int firstChannel, unsigned int sampleRate,
842 RtAudioFormat format, unsigned int *bufferSize,
843 RtAudio::StreamOptions *options );
845 //! A protected function used to increment the stream time.
846 void tickStreamTime( void );
848 //! Protected common method to clear an RtApiStream structure.
849 void clearStreamInfo();
852 Protected common method that throws an RtAudioError (type =
853 INVALID_USE) if a stream is not open.
855 void verifyStream( void );
857 //! Protected common error method to allow global control over error handling.
858 void error( RtAudioError::Type type );
861 Protected method used to perform format, channel number, and/or interleaving
862 conversions between the user and device buffers.
864 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
866 //! Protected common method used to perform byte-swapping on buffers.
867 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
869 //! Protected common method that returns the number of bytes for a given format.
870 unsigned int formatBytes( RtAudioFormat format );
872 //! Protected common method that sets up the parameters for buffer conversion.
873 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
876 // **************************************************************** //
878 // Inline RtAudio definitions.
880 // **************************************************************** //
882 inline RtAudio::Api RtAudio :: getCurrentApi( void ) { return rtapi_->getCurrentApi(); }
883 inline unsigned int RtAudio :: getDeviceCount( void ) { return rtapi_->getDeviceCount(); }
884 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
885 inline unsigned int RtAudio :: getDefaultInputDevice( void ) { return rtapi_->getDefaultInputDevice(); }
886 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) { return rtapi_->getDefaultOutputDevice(); }
887 inline void RtAudio :: closeStream( void ) { return rtapi_->closeStream(); }
888 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
889 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
890 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
891 inline bool RtAudio :: isStreamOpen( void ) const { return rtapi_->isStreamOpen(); }
892 inline bool RtAudio :: isStreamRunning( void ) const { return rtapi_->isStreamRunning(); }
893 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
894 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
895 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
896 inline void RtAudio :: setStreamTime( double time ) { return rtapi_->setStreamTime( time ); }
897 inline void RtAudio :: showWarnings( bool value ) { rtapi_->showWarnings( value ); }
899 // RtApi Subclass prototypes.
901 #if defined(__MACOSX_CORE__)
903 #include <CoreAudio/AudioHardware.h>
905 class RtApiCore: public RtApi
911 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
912 unsigned int getDeviceCount( void );
913 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
914 unsigned int getDefaultOutputDevice( void );
915 unsigned int getDefaultInputDevice( void );
916 void closeStream( void );
917 void startStream( void );
918 void stopStream( void );
919 void abortStream( void );
920 long getStreamLatency( void );
922 // This function is intended for internal use only. It must be
923 // public because it is called by the internal callback handler,
924 // which is not a member of RtAudio. External use of this function
925 // will most likely produce highly undesireable results!
926 bool callbackEvent( AudioDeviceID deviceId,
927 const AudioBufferList *inBufferList,
928 const AudioBufferList *outBufferList );
932 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
933 unsigned int firstChannel, unsigned int sampleRate,
934 RtAudioFormat format, unsigned int *bufferSize,
935 RtAudio::StreamOptions *options );
936 static const char* getErrorCode( OSStatus code );
941 #if defined(__UNIX_JACK__)
943 class RtApiJack: public RtApi
949 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
950 unsigned int getDeviceCount( void );
951 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
952 void closeStream( void );
953 void startStream( void );
954 void stopStream( void );
955 void abortStream( void );
956 long getStreamLatency( void );
958 // This function is intended for internal use only. It must be
959 // public because it is called by the internal callback handler,
960 // which is not a member of RtAudio. External use of this function
961 // will most likely produce highly undesireable results!
962 bool callbackEvent( unsigned long nframes );
966 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
967 unsigned int firstChannel, unsigned int sampleRate,
968 RtAudioFormat format, unsigned int *bufferSize,
969 RtAudio::StreamOptions *options );
971 bool shouldAutoconnect_;
976 #if defined(__WINDOWS_ASIO__)
978 class RtApiAsio: public RtApi
984 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
985 unsigned int getDeviceCount( void );
986 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
987 void closeStream( void );
988 void startStream( void );
989 void stopStream( void );
990 void abortStream( void );
991 long getStreamLatency( void );
993 // This function is intended for internal use only. It must be
994 // public because it is called by the internal callback handler,
995 // which is not a member of RtAudio. External use of this function
996 // will most likely produce highly undesireable results!
997 bool callbackEvent( long bufferIndex );
1001 std::vector<RtAudio::DeviceInfo> devices_;
1002 void saveDeviceInfo( void );
1003 bool coInitialized_;
1004 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1005 unsigned int firstChannel, unsigned int sampleRate,
1006 RtAudioFormat format, unsigned int *bufferSize,
1007 RtAudio::StreamOptions *options );
1012 #if defined(__WINDOWS_DS__)
1014 class RtApiDs: public RtApi
1020 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
1021 unsigned int getDeviceCount( void );
1022 unsigned int getDefaultOutputDevice( void );
1023 unsigned int getDefaultInputDevice( void );
1024 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1025 void closeStream( void );
1026 void startStream( void );
1027 void stopStream( void );
1028 void abortStream( void );
1029 long getStreamLatency( void );
1031 // This function is intended for internal use only. It must be
1032 // public because it is called by the internal callback handler,
1033 // which is not a member of RtAudio. External use of this function
1034 // will most likely produce highly undesireable results!
1035 void callbackEvent( void );
1039 bool coInitialized_;
1040 bool buffersRolling;
1041 long duplexPrerollBytes;
1042 std::vector<struct DsDevice> dsDevices;
1043 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1044 unsigned int firstChannel, unsigned int sampleRate,
1045 RtAudioFormat format, unsigned int *bufferSize,
1046 RtAudio::StreamOptions *options );
1051 #if defined(__WINDOWS_WASAPI__)
1053 struct IMMDeviceEnumerator;
1055 class RtApiWasapi : public RtApi
1061 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_WASAPI; }
1062 unsigned int getDeviceCount( void );
1063 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1064 unsigned int getDefaultOutputDevice( void );
1065 unsigned int getDefaultInputDevice( void );
1066 void closeStream( void );
1067 void startStream( void );
1068 void stopStream( void );
1069 void abortStream( void );
1072 bool coInitialized_;
1073 IMMDeviceEnumerator* deviceEnumerator_;
1075 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1076 unsigned int firstChannel, unsigned int sampleRate,
1077 RtAudioFormat format, unsigned int* bufferSize,
1078 RtAudio::StreamOptions* options );
1080 static DWORD WINAPI runWasapiThread( void* wasapiPtr );
1081 static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
1082 static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
1083 void wasapiThread();
1088 #if defined(__LINUX_ALSA__)
1090 class RtApiAlsa: public RtApi
1096 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
1097 unsigned int getDeviceCount( void );
1098 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1099 void closeStream( void );
1100 void startStream( void );
1101 void stopStream( void );
1102 void abortStream( void );
1104 // This function is intended for internal use only. It must be
1105 // public because it is called by the internal callback handler,
1106 // which is not a member of RtAudio. External use of this function
1107 // will most likely produce highly undesireable results!
1108 void callbackEvent( void );
1112 std::vector<RtAudio::DeviceInfo> devices_;
1113 void saveDeviceInfo( void );
1114 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1115 unsigned int firstChannel, unsigned int sampleRate,
1116 RtAudioFormat format, unsigned int *bufferSize,
1117 RtAudio::StreamOptions *options );
1122 #if defined(__LINUX_PULSE__)
1124 class RtApiPulse: public RtApi
1128 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
1129 unsigned int getDeviceCount( void );
1130 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1131 void closeStream( void );
1132 void startStream( void );
1133 void stopStream( void );
1134 void abortStream( void );
1136 // This function is intended for internal use only. It must be
1137 // public because it is called by the internal callback handler,
1138 // which is not a member of RtAudio. External use of this function
1139 // will most likely produce highly undesireable results!
1140 void callbackEvent( void );
1144 std::vector<RtAudio::DeviceInfo> devices_;
1145 void saveDeviceInfo( void );
1146 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1147 unsigned int firstChannel, unsigned int sampleRate,
1148 RtAudioFormat format, unsigned int *bufferSize,
1149 RtAudio::StreamOptions *options );
1154 #if defined(__LINUX_OSS__)
1156 class RtApiOss: public RtApi
1162 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1163 unsigned int getDeviceCount( void );
1164 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1165 void closeStream( void );
1166 void startStream( void );
1167 void stopStream( void );
1168 void abortStream( void );
1170 // This function is intended for internal use only. It must be
1171 // public because it is called by the internal callback handler,
1172 // which is not a member of RtAudio. External use of this function
1173 // will most likely produce highly undesireable results!
1174 void callbackEvent( void );
1178 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1179 unsigned int firstChannel, unsigned int sampleRate,
1180 RtAudioFormat format, unsigned int *bufferSize,
1181 RtAudio::StreamOptions *options );
1186 #if defined(__RTAUDIO_DUMMY__)
1188 class RtApiDummy: public RtApi
1192 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtAudioError::WARNING ); }
1193 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1194 unsigned int getDeviceCount( void ) { return 0; }
1195 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1196 void closeStream( void ) {}
1197 void startStream( void ) {}
1198 void stopStream( void ) {}
1199 void abortStream( void ) {}
1203 bool probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
1204 unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
1205 RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
1206 RtAudio::StreamOptions * /*options*/ ) { return false; }
1213 // Indentation settings for Vim and Emacs
1216 // c-basic-offset: 2
1217 // indent-tabs-mode: nil
1220 // vim: et sts=2 sw=2