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
65 /*! \typedef typedef unsigned long RtAudioFormat;
66 \brief RtAudio data format type.
68 Support for signed integers and floats. Audio data fed to/from an
69 RtAudio stream is assumed to ALWAYS be in host byte order. The
70 internal routines will automatically take care of any necessary
71 byte-swapping between the host format and the soundcard. Thus,
72 endian-ness is not a concern in the following format definitions.
74 - \e RTAUDIO_SINT8: 8-bit signed integer.
75 - \e RTAUDIO_SINT16: 16-bit signed integer.
76 - \e RTAUDIO_SINT24: 24-bit signed integer.
77 - \e RTAUDIO_SINT32: 32-bit signed integer.
78 - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
79 - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
81 typedef unsigned long RtAudioFormat;
82 static const RtAudioFormat RTAUDIO_SINT8 = 0x1; // 8-bit signed integer.
83 static const RtAudioFormat RTAUDIO_SINT16 = 0x2; // 16-bit signed integer.
84 static const RtAudioFormat RTAUDIO_SINT24 = 0x4; // 24-bit signed integer.
85 static const RtAudioFormat RTAUDIO_SINT32 = 0x8; // 32-bit signed integer.
86 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
87 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
89 /*! \typedef typedef unsigned long RtAudioStreamFlags;
90 \brief RtAudio stream option flags.
92 The following flags can be OR'ed together to allow a client to
93 make changes to the default stream behavior:
95 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
96 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
97 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
98 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
99 - \e RTAUDIO_JACK_DONT_CONNECT: Do not automatically connect ports (JACK only).
101 By default, RtAudio streams pass and receive audio data from the
102 client in an interleaved format. By passing the
103 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
104 data will instead be presented in non-interleaved buffers. In
105 this case, each buffer argument in the RtAudioCallback function
106 will point to a single array of data, with \c nFrames samples for
107 each channel concatenated back-to-back. For example, the first
108 sample of data for the second channel would be located at index \c
109 nFrames (assuming the \c buffer pointer was recast to the correct
110 data type for the stream).
112 Certain audio APIs offer a number of parameters that influence the
113 I/O latency of a stream. By default, RtAudio will attempt to set
114 these parameters internally for robust (glitch-free) performance
115 (though some APIs, like Windows Direct Sound, make this difficult).
116 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
117 function, internal stream settings will be influenced in an attempt
118 to minimize stream latency, though possibly at the expense of stream
121 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
122 open the input and/or output stream device(s) for exclusive use.
123 Note that this is not possible with all supported audio APIs.
125 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
126 to select realtime scheduling (round-robin) for the callback thread.
128 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
129 open the "default" PCM device when using the ALSA API. Note that this
130 will override any specified input or output device id.
132 If the RTAUDIO_JACK_DONT_CONNECT flag is set, RtAudio will not attempt
133 to automatically connect the ports of the client to the audio device.
135 typedef unsigned int RtAudioStreamFlags;
136 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1; // Use non-interleaved buffers (default = interleaved).
137 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2; // Attempt to set stream parameters for lowest possible latency.
138 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4; // Attempt grab device and prevent use by others.
139 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
140 static const RtAudioStreamFlags RTAUDIO_ALSA_USE_DEFAULT = 0x10; // Use the "default" PCM device (ALSA only).
141 static const RtAudioStreamFlags RTAUDIO_JACK_DONT_CONNECT = 0x20; // Do not automatically connect ports (JACK only).
143 /*! \typedef typedef unsigned long RtAudioStreamStatus;
144 \brief RtAudio stream status (over- or underflow) flags.
146 Notification of a stream over- or underflow is indicated by a
147 non-zero stream \c status argument in the RtAudioCallback function.
148 The stream status can be one of the following two options,
149 depending on whether the stream is open for output and/or input:
151 - \e RTAUDIO_INPUT_OVERFLOW: Input data was discarded because of an overflow condition at the driver.
152 - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
154 typedef unsigned int RtAudioStreamStatus;
155 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver.
156 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound.
158 //! RtAudio callback function prototype.
160 All RtAudio clients must create a function of type RtAudioCallback
161 to read and/or write data from/to the audio stream. When the
162 underlying audio system is ready for new input or output data, this
163 function will be invoked.
165 \param outputBuffer For output (or duplex) streams, the client
166 should write \c nFrames of audio sample frames into this
167 buffer. This argument should be recast to the datatype
168 specified when the stream was opened. For input-only
169 streams, this argument will be NULL.
171 \param inputBuffer For input (or duplex) streams, this buffer will
172 hold \c nFrames of input audio sample frames. This
173 argument should be recast to the datatype specified when the
174 stream was opened. For output-only streams, this argument
177 \param nFrames The number of sample frames of input or output
178 data in the buffers. The actual buffer size in bytes is
179 dependent on the data type and number of channels in use.
181 \param streamTime The number of seconds that have elapsed since the
184 \param status If non-zero, this argument indicates a data overflow
185 or underflow condition for the stream. The particular
186 condition can be determined by comparison with the
187 RtAudioStreamStatus flags.
189 \param userData A pointer to optional data provided by the client
190 when opening the stream (default = NULL).
192 To continue normal stream operation, the RtAudioCallback function
193 should return a value of zero. To stop the stream and drain the
194 output buffer, the function should return a value of one. To abort
195 the stream immediately, the client should return a value of two.
197 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
198 unsigned int nFrames,
200 RtAudioStreamStatus status,
203 /************************************************************************/
204 /*! \class RtAudioError
205 \brief Exception handling class for RtAudio.
207 The RtAudioError class is quite simple but it does allow errors to be
208 "caught" by RtAudioError::Type. See the RtAudio documentation to know
209 which methods can throw an RtAudioError.
211 /************************************************************************/
213 class RTAUDIO_DLL_PUBLIC RtAudioError : public std::runtime_error
216 //! Defined RtAudioError types.
218 WARNING, /*!< A non-critical error. */
219 DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */
220 UNSPECIFIED, /*!< The default, unspecified error type. */
221 NO_DEVICES_FOUND, /*!< No devices found on system. */
222 INVALID_DEVICE, /*!< An invalid device ID was specified. */
223 MEMORY_ERROR, /*!< An error occured during memory allocation. */
224 INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */
225 INVALID_USE, /*!< The function was called incorrectly. */
226 DRIVER_ERROR, /*!< A system driver error occured. */
227 SYSTEM_ERROR, /*!< A system error occured. */
228 THREAD_ERROR /*!< A thread error occured. */
232 RtAudioError( const std::string& message,
233 Type type = RtAudioError::UNSPECIFIED )
234 : std::runtime_error(message), type_(type) {}
236 //! Prints thrown error message to stderr.
237 virtual void printMessage( void ) const
238 { std::cerr << '\n' << what() << "\n\n"; }
240 //! Returns the thrown error message type.
241 virtual const Type& getType(void) const { return type_; }
243 //! Returns the thrown error message string.
244 virtual const std::string getMessage(void) const
245 { return std::string(what()); }
251 //! RtAudio error callback function prototype.
253 \param type Type of error.
254 \param errorText Error description.
256 typedef void (*RtAudioErrorCallback)( RtAudioError::Type type, const std::string &errorText );
258 // **************************************************************** //
260 // RtAudio class declaration.
262 // RtAudio is a "controller" used to select an available audio i/o
263 // interface. It presents a common API for the user to call but all
264 // functionality is implemented by the class RtApi and its
265 // subclasses. RtAudio creates an instance of an RtApi subclass
266 // based on the user's API choice. If no choice is made, RtAudio
267 // attempts to make a "logical" API selection.
269 // **************************************************************** //
273 class RTAUDIO_DLL_PUBLIC RtAudio
277 //! Audio API specifier arguments.
279 UNSPECIFIED, /*!< Search for a working compiled API. */
280 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
281 LINUX_PULSE, /*!< The Linux PulseAudio API. */
282 LINUX_OSS, /*!< The Linux Open Sound System API. */
283 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
284 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
285 WINDOWS_WASAPI, /*!< The Microsoft WASAPI API. */
286 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
287 WINDOWS_DS, /*!< The Microsoft Direct Sound API. */
288 RTAUDIO_DUMMY, /*!< A compilable but non-functional API. */
289 NUM_APIS /*!< Number of values in this enum. */
292 //! The public device information structure for returning queried values.
294 bool probed; /*!< true if the device capabilities were successfully probed. */
295 std::string name; /*!< Character string device identifier. */
296 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
297 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
298 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
299 bool isDefaultOutput; /*!< true if this is the default output device. */
300 bool isDefaultInput; /*!< true if this is the default input device. */
301 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
302 unsigned int preferredSampleRate; /*!< Preferred sample rate, eg. for WASAPI the system sample rate. */
303 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
305 // Default constructor.
307 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
308 isDefaultOutput(false), isDefaultInput(false), preferredSampleRate(0), nativeFormats(0) {}
311 //! The structure for specifying input or ouput stream parameters.
312 struct StreamParameters {
313 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
314 unsigned int nChannels; /*!< Number of channels. */
315 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
317 // Default constructor.
319 : deviceId(0), nChannels(0), firstChannel(0) {}
322 //! The structure for specifying stream options.
324 The following flags can be OR'ed together to allow a client to
325 make changes to the default stream behavior:
327 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
328 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
329 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
330 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
331 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
333 By default, RtAudio streams pass and receive audio data from the
334 client in an interleaved format. By passing the
335 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
336 data will instead be presented in non-interleaved buffers. In
337 this case, each buffer argument in the RtAudioCallback function
338 will point to a single array of data, with \c nFrames samples for
339 each channel concatenated back-to-back. For example, the first
340 sample of data for the second channel would be located at index \c
341 nFrames (assuming the \c buffer pointer was recast to the correct
342 data type for the stream).
344 Certain audio APIs offer a number of parameters that influence the
345 I/O latency of a stream. By default, RtAudio will attempt to set
346 these parameters internally for robust (glitch-free) performance
347 (though some APIs, like Windows Direct Sound, make this difficult).
348 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
349 function, internal stream settings will be influenced in an attempt
350 to minimize stream latency, though possibly at the expense of stream
353 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
354 open the input and/or output stream device(s) for exclusive use.
355 Note that this is not possible with all supported audio APIs.
357 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
358 to select realtime scheduling (round-robin) for the callback thread.
359 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
360 flag is set. It defines the thread's realtime priority.
362 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
363 open the "default" PCM device when using the ALSA API. Note that this
364 will override any specified input or output device id.
366 The \c numberOfBuffers parameter can be used to control stream
367 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
368 only. A value of two is usually the smallest allowed. Larger
369 numbers can potentially result in more robust stream performance,
370 though likely at the cost of stream latency. The value set by the
371 user is replaced during execution of the RtAudio::openStream()
372 function by the value actually used by the system.
374 The \c streamName parameter can be used to set the client name
375 when using the Jack API. By default, the client name is set to
376 RtApiJack. However, if you wish to create multiple instances of
377 RtAudio with Jack, each instance must have a unique client name.
379 struct StreamOptions {
380 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
381 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
382 std::string streamName; /*!< A stream name (currently used only in Jack). */
383 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
385 // Default constructor.
387 : flags(0), numberOfBuffers(0), priority(0) {}
390 //! A static function to determine the current RtAudio version.
391 static std::string getVersion( void );
393 //! A static function to determine the available compiled audio APIs.
395 The values returned in the std::vector can be compared against
396 the enumerated list values. Note that there can be more than one
397 API compiled for certain operating systems.
399 static void getCompiledApi( std::vector<RtAudio::Api> &apis );
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 const std::vector<RtAudio::Api>& getCompiledApis();
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 or not compiled, this function will return
416 static const std::string getCompiledApiName( RtAudio::Api api );
418 //! Return the display name of a specified compiled audio API.
420 This obtains a long name used for display purposes.
421 If the API is unknown or not compiled, this function will return
424 static const std::string getCompiledApiDisplayName( RtAudio::Api api );
426 //! Return the compiled audio API having the given name.
428 A case insensitive comparison will check the specified name
429 against the list of compiled APIs, and return the one which
430 matches. On failure, the function returns UNSPECIFIED.
432 static RtAudio::Api getCompiledApiByName( const std::string &name );
434 //! The class constructor.
436 The constructor performs minor initialization tasks. An exception
437 can be thrown if no API support is compiled.
439 If no API argument is specified and multiple API support has been
440 compiled, the default order of use is JACK, ALSA, OSS (Linux
441 systems) and ASIO, DS (Windows systems).
443 RtAudio( RtAudio::Api api=UNSPECIFIED );
447 If a stream is running or open, it will be stopped and closed
452 //! Returns the audio API specifier for the current instance of RtAudio.
453 RtAudio::Api getCurrentApi( void );
455 //! A public function that queries for the number of audio devices available.
457 This function performs a system query of available devices each time it
458 is called, thus supporting devices connected \e after instantiation. If
459 a system error occurs during processing, a warning will be issued.
461 unsigned int getDeviceCount( void );
463 //! Return an RtAudio::DeviceInfo structure for a specified device number.
466 Any device integer between 0 and getDeviceCount() - 1 is valid.
467 If an invalid argument is provided, an RtAudioError (type = INVALID_USE)
468 will be thrown. If a device is busy or otherwise unavailable, the
469 structure member "probed" will have a value of "false" and all
470 other members are undefined. If the specified device is the
471 current default input or output device, the corresponding
472 "isDefault" member will have a value of "true".
474 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
476 //! A function that returns the index of the default output device.
478 If the underlying audio API does not provide a "default
479 device", or if no devices are available, the return value will be
480 0. Note that this is a valid device identifier and it is the
481 client's responsibility to verify that a device is available
482 before attempting to open a stream.
484 unsigned int getDefaultOutputDevice( void );
486 //! A function that returns the index of the default input device.
488 If the underlying audio API does not provide a "default
489 device", or if no devices are available, the return value will be
490 0. Note that this is a valid device identifier and it is the
491 client's responsibility to verify that a device is available
492 before attempting to open a stream.
494 unsigned int getDefaultInputDevice( void );
496 //! A public function for opening a stream with the specified parameters.
498 An RtAudioError (type = SYSTEM_ERROR) is thrown if a stream cannot be
499 opened with the specified parameters or an error occurs during
500 processing. An RtAudioError (type = INVALID_USE) is thrown if any
501 invalid device ID or channel number parameters are specified.
503 \param outputParameters Specifies output stream parameters to use
504 when opening a stream, including a device ID, number of channels,
505 and starting channel number. For input-only streams, this
506 argument should be NULL. The device ID is an index value between
507 0 and getDeviceCount() - 1.
508 \param inputParameters Specifies input stream parameters to use
509 when opening a stream, including a device ID, number of channels,
510 and starting channel number. For output-only streams, this
511 argument should be NULL. The device ID is an index value between
512 0 and getDeviceCount() - 1.
513 \param format An RtAudioFormat specifying the desired sample data format.
514 \param sampleRate The desired sample rate (sample frames per second).
515 \param *bufferFrames A pointer to a value indicating the desired
516 internal buffer size in sample frames. The actual value
517 used by the device is returned via the same pointer. A
518 value of zero can be specified, in which case the lowest
519 allowable value is determined.
520 \param callback A client-defined function that will be invoked
521 when input data is available and/or output data is needed.
522 \param userData An optional pointer to data that can be accessed
523 from within the callback function.
524 \param options An optional pointer to a structure containing various
525 global stream options, including a list of OR'ed RtAudioStreamFlags
526 and a suggested number of stream buffers that can be used to
527 control stream latency. More buffers typically result in more
528 robust performance, though at a cost of greater latency. If a
529 value of zero is specified, a system-specific median value is
530 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
531 lowest allowable value is used. The actual value used is
532 returned via the structure argument. The parameter is API dependent.
533 \param errorCallback A client-defined function that will be invoked
534 when an error has occured.
536 void openStream( RtAudio::StreamParameters *outputParameters,
537 RtAudio::StreamParameters *inputParameters,
538 RtAudioFormat format, unsigned int sampleRate,
539 unsigned int *bufferFrames, RtAudioCallback callback,
540 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
542 //! A function that closes a stream and frees any associated stream memory.
544 If a stream is not open, this function issues a warning and
545 returns (no exception is thrown).
547 void closeStream( void );
549 //! A function that starts a stream.
551 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
552 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
553 stream is not open. A warning is issued if the stream is already
556 void startStream( void );
558 //! Stop a stream, allowing any samples remaining in the output queue to be played.
560 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
561 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
562 stream is not open. A warning is issued if the stream is already
565 void stopStream( void );
567 //! Stop a stream, discarding any samples remaining in the input/output queue.
569 An RtAudioError (type = SYSTEM_ERROR) is thrown if an error occurs
570 during processing. An RtAudioError (type = INVALID_USE) is thrown if a
571 stream is not open. A warning is issued if the stream is already
574 void abortStream( void );
576 //! Returns true if a stream is open and false if not.
577 bool isStreamOpen( void ) const;
579 //! Returns true if the stream is running and false if it is stopped or not open.
580 bool isStreamRunning( void ) const;
582 //! Returns the number of elapsed seconds since the stream was started.
584 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
586 double getStreamTime( void );
588 //! Set the stream time to a time in seconds greater than or equal to 0.0.
590 If a stream is not open, an RtAudioError (type = INVALID_USE) will be thrown.
592 void setStreamTime( double time );
594 //! Returns the internal stream latency in sample frames.
596 The stream latency refers to delay in audio input and/or output
597 caused by internal buffering by the audio system and/or hardware.
598 For duplex streams, the returned value will represent the sum of
599 the input and output latencies. If a stream is not open, an
600 RtAudioError (type = INVALID_USE) will be thrown. If the API does not
601 report latency, the return value will be zero.
603 long getStreamLatency( void );
605 //! Returns actual sample rate in use by the stream.
607 On some systems, the sample rate used may be slightly different
608 than that specified in the stream parameters. If a stream is not
609 open, an RtAudioError (type = INVALID_USE) will be thrown.
611 unsigned int getStreamSampleRate( void );
613 //! Specify whether warning messages should be printed to stderr.
614 void showWarnings( bool value = true );
618 //! Storage for compiled API list
619 static const std::vector<RtAudio::Api> compiledApis;
621 void openRtApi( RtAudio::Api api );
625 // Operating system dependent thread functionality.
626 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
634 typedef uintptr_t ThreadHandle;
635 typedef CRITICAL_SECTION StreamMutex;
637 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
638 // Using pthread library for various flavors of unix.
641 typedef pthread_t ThreadHandle;
642 typedef pthread_mutex_t StreamMutex;
644 #else // Setup for "dummy" behavior
646 #define __RTAUDIO_DUMMY__
647 typedef int ThreadHandle;
648 typedef int StreamMutex;
652 // This global structure type is used to pass callback information
653 // between the private RtAudio stream structure and global callback
654 // handling functions.
655 struct CallbackInfo {
656 void *object; // Used as a "this" pointer.
661 void *apiInfo; // void pointer for API specific callback information
666 // Default constructor.
668 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false), priority(0) {}
671 // **************************************************************** //
673 // RtApi class declaration.
675 // Subclasses of RtApi contain all API- and OS-specific code necessary
676 // to fully implement the RtAudio API.
678 // Note that RtApi is an abstract base class and cannot be
679 // explicitly instantiated. The class RtAudio will create an
680 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
681 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
683 // **************************************************************** //
685 #pragma pack(push, 1)
694 S24& operator = ( const int& i ) {
695 c3[0] = (i & 0x000000ff);
696 c3[1] = (i & 0x0000ff00) >> 8;
697 c3[2] = (i & 0x00ff0000) >> 16;
701 S24( const S24& v ) { *this = v; }
702 S24( const double& d ) { *this = (int) d; }
703 S24( const float& f ) { *this = (int) f; }
704 S24( const signed short& s ) { *this = (int) s; }
705 S24( const char& c ) { *this = (int) c; }
708 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
709 if (i & 0x800000) i |= ~0xffffff;
715 #if defined( HAVE_GETTIMEOFDAY )
716 #include <sys/time.h>
721 class RTAUDIO_DLL_PUBLIC RtApi
727 virtual RtAudio::Api getCurrentApi( void ) = 0;
728 virtual unsigned int getDeviceCount( void ) = 0;
729 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
730 virtual unsigned int getDefaultInputDevice( void );
731 virtual unsigned int getDefaultOutputDevice( void );
732 void openStream( RtAudio::StreamParameters *outputParameters,
733 RtAudio::StreamParameters *inputParameters,
734 RtAudioFormat format, unsigned int sampleRate,
735 unsigned int *bufferFrames, RtAudioCallback callback,
736 void *userData, RtAudio::StreamOptions *options,
737 RtAudioErrorCallback errorCallback );
738 virtual void closeStream( void );
739 virtual void startStream( void ) = 0;
740 virtual void stopStream( void ) = 0;
741 virtual void abortStream( void ) = 0;
742 long getStreamLatency( void );
743 unsigned int getStreamSampleRate( void );
744 virtual double getStreamTime( void );
745 virtual void setStreamTime( double time );
746 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
747 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
748 void showWarnings( bool value ) { showWarnings_ = value; }
753 static const unsigned int MAX_SAMPLE_RATES;
754 static const unsigned int SAMPLE_RATES[];
756 enum { FAILURE, SUCCESS };
772 // A protected structure used for buffer conversion.
776 RtAudioFormat inFormat, outFormat;
777 std::vector<int> inOffset;
778 std::vector<int> outOffset;
781 // A protected structure for audio streams.
783 unsigned int device[2]; // Playback and record, respectively.
784 void *apiHandle; // void pointer for API specific stream handle information
785 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
786 StreamState state; // STOPPED, RUNNING, or CLOSED
787 char *userBuffer[2]; // Playback and record, respectively.
789 bool doConvertBuffer[2]; // Playback and record, respectively.
790 bool userInterleaved;
791 bool deviceInterleaved[2]; // Playback and record, respectively.
792 bool doByteSwap[2]; // Playback and record, respectively.
793 unsigned int sampleRate;
794 unsigned int bufferSize;
795 unsigned int nBuffers;
796 unsigned int nUserChannels[2]; // Playback and record, respectively.
797 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
798 unsigned int channelOffset[2]; // Playback and record, respectively.
799 unsigned long latency[2]; // Playback and record, respectively.
800 RtAudioFormat userFormat;
801 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
803 CallbackInfo callbackInfo;
804 ConvertInfo convertInfo[2];
805 double streamTime; // Number of elapsed seconds since the stream started.
807 #if defined(HAVE_GETTIMEOFDAY)
808 struct timeval lastTickTimestamp;
812 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
816 typedef signed short Int16;
817 typedef signed int Int32;
818 typedef float Float32;
819 typedef double Float64;
821 std::ostringstream errorStream_;
822 std::string errorText_;
825 bool firstErrorOccurred_;
828 Protected, api-specific method that attempts to open a device
829 with the given parameters. This function MUST be implemented by
830 all subclasses. If an error is encountered during the probe, a
831 "warning" message is reported and FAILURE is returned. A
832 successful probe is indicated by a return value of SUCCESS.
834 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
835 unsigned int firstChannel, unsigned int sampleRate,
836 RtAudioFormat format, unsigned int *bufferSize,
837 RtAudio::StreamOptions *options );
839 //! A protected function used to increment the stream time.
840 void tickStreamTime( void );
842 //! Protected common method to clear an RtApiStream structure.
843 void clearStreamInfo();
846 Protected common method that throws an RtAudioError (type =
847 INVALID_USE) if a stream is not open.
849 void verifyStream( void );
851 //! Protected common error method to allow global control over error handling.
852 void error( RtAudioError::Type type );
855 Protected method used to perform format, channel number, and/or interleaving
856 conversions between the user and device buffers.
858 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
860 //! Protected common method used to perform byte-swapping on buffers.
861 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
863 //! Protected common method that returns the number of bytes for a given format.
864 unsigned int formatBytes( RtAudioFormat format );
866 //! Protected common method that sets up the parameters for buffer conversion.
867 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
870 // **************************************************************** //
872 // Inline RtAudio definitions.
874 // **************************************************************** //
876 inline RtAudio::Api RtAudio :: getCurrentApi( void ) { return rtapi_->getCurrentApi(); }
877 inline unsigned int RtAudio :: getDeviceCount( void ) { return rtapi_->getDeviceCount(); }
878 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
879 inline unsigned int RtAudio :: getDefaultInputDevice( void ) { return rtapi_->getDefaultInputDevice(); }
880 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) { return rtapi_->getDefaultOutputDevice(); }
881 inline void RtAudio :: closeStream( void ) { return rtapi_->closeStream(); }
882 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
883 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
884 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
885 inline bool RtAudio :: isStreamOpen( void ) const { return rtapi_->isStreamOpen(); }
886 inline bool RtAudio :: isStreamRunning( void ) const { return rtapi_->isStreamRunning(); }
887 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
888 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
889 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
890 inline void RtAudio :: setStreamTime( double time ) { return rtapi_->setStreamTime( time ); }
891 inline void RtAudio :: showWarnings( bool value ) { rtapi_->showWarnings( value ); }
893 // RtApi Subclass prototypes.
895 #if defined(__MACOSX_CORE__)
897 #include <CoreAudio/AudioHardware.h>
899 class RtApiCore: public RtApi
905 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
906 unsigned int getDeviceCount( void );
907 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
908 unsigned int getDefaultOutputDevice( void );
909 unsigned int getDefaultInputDevice( void );
910 void closeStream( void );
911 void startStream( void );
912 void stopStream( void );
913 void abortStream( void );
914 long getStreamLatency( void );
916 // This function is intended for internal use only. It must be
917 // public because it is called by the internal callback handler,
918 // which is not a member of RtAudio. External use of this function
919 // will most likely produce highly undesireable results!
920 bool callbackEvent( AudioDeviceID deviceId,
921 const AudioBufferList *inBufferList,
922 const AudioBufferList *outBufferList );
926 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
927 unsigned int firstChannel, unsigned int sampleRate,
928 RtAudioFormat format, unsigned int *bufferSize,
929 RtAudio::StreamOptions *options );
930 static const char* getErrorCode( OSStatus code );
935 #if defined(__UNIX_JACK__)
937 class RtApiJack: public RtApi
943 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
944 unsigned int getDeviceCount( void );
945 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
946 void closeStream( void );
947 void startStream( void );
948 void stopStream( void );
949 void abortStream( void );
950 long getStreamLatency( void );
952 // This function is intended for internal use only. It must be
953 // public because it is called by the internal callback handler,
954 // which is not a member of RtAudio. External use of this function
955 // will most likely produce highly undesireable results!
956 bool callbackEvent( unsigned long nframes );
960 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
961 unsigned int firstChannel, unsigned int sampleRate,
962 RtAudioFormat format, unsigned int *bufferSize,
963 RtAudio::StreamOptions *options );
965 bool shouldAutoconnect_;
970 #if defined(__WINDOWS_ASIO__)
972 class RtApiAsio: public RtApi
978 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
979 unsigned int getDeviceCount( void );
980 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
981 void closeStream( void );
982 void startStream( void );
983 void stopStream( void );
984 void abortStream( void );
985 long getStreamLatency( void );
987 // This function is intended for internal use only. It must be
988 // public because it is called by the internal callback handler,
989 // which is not a member of RtAudio. External use of this function
990 // will most likely produce highly undesireable results!
991 bool callbackEvent( long bufferIndex );
995 std::vector<RtAudio::DeviceInfo> devices_;
996 void saveDeviceInfo( void );
998 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
999 unsigned int firstChannel, unsigned int sampleRate,
1000 RtAudioFormat format, unsigned int *bufferSize,
1001 RtAudio::StreamOptions *options );
1006 #if defined(__WINDOWS_DS__)
1008 class RtApiDs: public RtApi
1014 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
1015 unsigned int getDeviceCount( void );
1016 unsigned int getDefaultOutputDevice( void );
1017 unsigned int getDefaultInputDevice( void );
1018 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1019 void closeStream( void );
1020 void startStream( void );
1021 void stopStream( void );
1022 void abortStream( void );
1023 long getStreamLatency( void );
1025 // This function is intended for internal use only. It must be
1026 // public because it is called by the internal callback handler,
1027 // which is not a member of RtAudio. External use of this function
1028 // will most likely produce highly undesireable results!
1029 void callbackEvent( void );
1033 bool coInitialized_;
1034 bool buffersRolling;
1035 long duplexPrerollBytes;
1036 std::vector<struct DsDevice> dsDevices;
1037 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1038 unsigned int firstChannel, unsigned int sampleRate,
1039 RtAudioFormat format, unsigned int *bufferSize,
1040 RtAudio::StreamOptions *options );
1045 #if defined(__WINDOWS_WASAPI__)
1047 struct IMMDeviceEnumerator;
1049 class RtApiWasapi : public RtApi
1055 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_WASAPI; }
1056 unsigned int getDeviceCount( void );
1057 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1058 unsigned int getDefaultOutputDevice( void );
1059 unsigned int getDefaultInputDevice( void );
1060 void closeStream( void );
1061 void startStream( void );
1062 void stopStream( void );
1063 void abortStream( void );
1066 bool coInitialized_;
1067 IMMDeviceEnumerator* deviceEnumerator_;
1069 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1070 unsigned int firstChannel, unsigned int sampleRate,
1071 RtAudioFormat format, unsigned int* bufferSize,
1072 RtAudio::StreamOptions* options );
1074 static DWORD WINAPI runWasapiThread( void* wasapiPtr );
1075 static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
1076 static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
1077 void wasapiThread();
1082 #if defined(__LINUX_ALSA__)
1084 class RtApiAlsa: public RtApi
1090 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
1091 unsigned int getDeviceCount( void );
1092 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1093 void closeStream( void );
1094 void startStream( void );
1095 void stopStream( void );
1096 void abortStream( void );
1098 // This function is intended for internal use only. It must be
1099 // public because it is called by the internal callback handler,
1100 // which is not a member of RtAudio. External use of this function
1101 // will most likely produce highly undesireable results!
1102 void callbackEvent( void );
1106 std::vector<RtAudio::DeviceInfo> devices_;
1107 void saveDeviceInfo( void );
1108 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1109 unsigned int firstChannel, unsigned int sampleRate,
1110 RtAudioFormat format, unsigned int *bufferSize,
1111 RtAudio::StreamOptions *options );
1116 #if defined(__LINUX_PULSE__)
1118 class RtApiPulse: public RtApi
1122 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
1123 unsigned int getDeviceCount( void );
1124 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1125 void closeStream( void );
1126 void startStream( void );
1127 void stopStream( void );
1128 void abortStream( void );
1130 // This function is intended for internal use only. It must be
1131 // public because it is called by the internal callback handler,
1132 // which is not a member of RtAudio. External use of this function
1133 // will most likely produce highly undesireable results!
1134 void callbackEvent( void );
1138 std::vector<RtAudio::DeviceInfo> devices_;
1139 void saveDeviceInfo( void );
1140 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1141 unsigned int firstChannel, unsigned int sampleRate,
1142 RtAudioFormat format, unsigned int *bufferSize,
1143 RtAudio::StreamOptions *options );
1148 #if defined(__LINUX_OSS__)
1150 class RtApiOss: public RtApi
1156 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1157 unsigned int getDeviceCount( void );
1158 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1159 void closeStream( void );
1160 void startStream( void );
1161 void stopStream( void );
1162 void abortStream( void );
1164 // This function is intended for internal use only. It must be
1165 // public because it is called by the internal callback handler,
1166 // which is not a member of RtAudio. External use of this function
1167 // will most likely produce highly undesireable results!
1168 void callbackEvent( void );
1172 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1173 unsigned int firstChannel, unsigned int sampleRate,
1174 RtAudioFormat format, unsigned int *bufferSize,
1175 RtAudio::StreamOptions *options );
1180 #if defined(__RTAUDIO_DUMMY__)
1182 class RtApiDummy: public RtApi
1186 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtAudioError::WARNING ); }
1187 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1188 unsigned int getDeviceCount( void ) { return 0; }
1189 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1190 void closeStream( void ) {}
1191 void startStream( void ) {}
1192 void stopStream( void ) {}
1193 void abortStream( void ) {}
1197 bool probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
1198 unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
1199 RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
1200 RtAudio::StreamOptions * /*options*/ ) { return false; }
1207 // Indentation settings for Vim and Emacs
1210 // c-basic-offset: 2
1211 // indent-tabs-mode: nil
1214 // vim: et sts=2 sw=2