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 and ASIO) 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-2013 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 /************************************************************************/
53 static const std::string VERSION( "4.0.12" );
55 /*! \typedef typedef unsigned long RtAudioFormat;
56 \brief RtAudio data format type.
58 Support for signed integers and floats. Audio data fed to/from an
59 RtAudio stream is assumed to ALWAYS be in host byte order. The
60 internal routines will automatically take care of any necessary
61 byte-swapping between the host format and the soundcard. Thus,
62 endian-ness is not a concern in the following format definitions.
64 - \e RTAUDIO_SINT8: 8-bit signed integer.
65 - \e RTAUDIO_SINT16: 16-bit signed integer.
66 - \e RTAUDIO_SINT24: 24-bit signed integer.
67 - \e RTAUDIO_SINT32: 32-bit signed integer.
68 - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
69 - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
71 typedef unsigned long RtAudioFormat;
72 static const RtAudioFormat RTAUDIO_SINT8 = 0x1; // 8-bit signed integer.
73 static const RtAudioFormat RTAUDIO_SINT16 = 0x2; // 16-bit signed integer.
74 static const RtAudioFormat RTAUDIO_SINT24 = 0x4; // 24-bit signed integer.
75 static const RtAudioFormat RTAUDIO_SINT32 = 0x8; // 32-bit signed integer.
76 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
77 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
79 /*! \typedef typedef unsigned long RtAudioStreamFlags;
80 \brief RtAudio stream option flags.
82 The following flags can be OR'ed together to allow a client to
83 make changes to the default stream behavior:
85 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
86 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
87 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
88 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
90 By default, RtAudio streams pass and receive audio data from the
91 client in an interleaved format. By passing the
92 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
93 data will instead be presented in non-interleaved buffers. In
94 this case, each buffer argument in the RtAudioCallback function
95 will point to a single array of data, with \c nFrames samples for
96 each channel concatenated back-to-back. For example, the first
97 sample of data for the second channel would be located at index \c
98 nFrames (assuming the \c buffer pointer was recast to the correct
99 data type for the stream).
101 Certain audio APIs offer a number of parameters that influence the
102 I/O latency of a stream. By default, RtAudio will attempt to set
103 these parameters internally for robust (glitch-free) performance
104 (though some APIs, like Windows Direct Sound, make this difficult).
105 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
106 function, internal stream settings will be influenced in an attempt
107 to minimize stream latency, though possibly at the expense of stream
110 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
111 open the input and/or output stream device(s) for exclusive use.
112 Note that this is not possible with all supported audio APIs.
114 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
115 to select realtime scheduling (round-robin) for the callback thread.
117 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
118 open the "default" PCM device when using the ALSA API. Note that this
119 will override any specified input or output device id.
121 typedef unsigned int RtAudioStreamFlags;
122 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1; // Use non-interleaved buffers (default = interleaved).
123 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2; // Attempt to set stream parameters for lowest possible latency.
124 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4; // Attempt grab device and prevent use by others.
125 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
126 static const RtAudioStreamFlags RTAUDIO_ALSA_USE_DEFAULT = 0x10; // Use the "default" PCM device (ALSA only).
128 /*! \typedef typedef unsigned long RtAudioStreamStatus;
129 \brief RtAudio stream status (over- or underflow) flags.
131 Notification of a stream over- or underflow is indicated by a
132 non-zero stream \c status argument in the RtAudioCallback function.
133 The stream status can be one of the following two options,
134 depending on whether the stream is open for output and/or input:
136 - \e RTAUDIO_INPUT_OVERFLOW: Input data was discarded because of an overflow condition at the driver.
137 - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
139 typedef unsigned int RtAudioStreamStatus;
140 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver.
141 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound.
143 //! RtAudio callback function prototype.
145 All RtAudio clients must create a function of type RtAudioCallback
146 to read and/or write data from/to the audio stream. When the
147 underlying audio system is ready for new input or output data, this
148 function will be invoked.
150 \param outputBuffer For output (or duplex) streams, the client
151 should write \c nFrames of audio sample frames into this
152 buffer. This argument should be recast to the datatype
153 specified when the stream was opened. For input-only
154 streams, this argument will be NULL.
156 \param inputBuffer For input (or duplex) streams, this buffer will
157 hold \c nFrames of input audio sample frames. This
158 argument should be recast to the datatype specified when the
159 stream was opened. For output-only streams, this argument
162 \param nFrames The number of sample frames of input or output
163 data in the buffers. The actual buffer size in bytes is
164 dependent on the data type and number of channels in use.
166 \param streamTime The number of seconds that have elapsed since the
169 \param status If non-zero, this argument indicates a data overflow
170 or underflow condition for the stream. The particular
171 condition can be determined by comparison with the
172 RtAudioStreamStatus flags.
174 \param userData A pointer to optional data provided by the client
175 when opening the stream (default = NULL).
177 To continue normal stream operation, the RtAudioCallback function
178 should return a value of zero. To stop the stream and drain the
179 output buffer, the function should return a value of one. To abort
180 the stream immediately, the client should return a value of two.
182 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
183 unsigned int nFrames,
185 RtAudioStreamStatus status,
188 //! RtAudio error callback function prototype.
190 \param type Type of error.
191 \param errorText Error description.
193 typedef void (*RtAudioErrorCallback)( RtError::Type type, const std::string &errorText );
195 // **************************************************************** //
197 // RtAudio class declaration.
199 // RtAudio is a "controller" used to select an available audio i/o
200 // interface. It presents a common API for the user to call but all
201 // functionality is implemented by the class RtApi and its
202 // subclasses. RtAudio creates an instance of an RtApi subclass
203 // based on the user's API choice. If no choice is made, RtAudio
204 // attempts to make a "logical" API selection.
206 // **************************************************************** //
214 //! Audio API specifier arguments.
216 UNSPECIFIED, /*!< Search for a working compiled API. */
217 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
218 LINUX_PULSE, /*!< The Linux PulseAudio API. */
219 LINUX_OSS, /*!< The Linux Open Sound System API. */
220 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
221 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
222 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
223 WINDOWS_DS, /*!< The Microsoft Direct Sound API. */
224 RTAUDIO_DUMMY /*!< A compilable but non-functional API. */
227 //! The public device information structure for returning queried values.
229 bool probed; /*!< true if the device capabilities were successfully probed. */
230 std::string name; /*!< Character string device identifier. */
231 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
232 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
233 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
234 bool isDefaultOutput; /*!< true if this is the default output device. */
235 bool isDefaultInput; /*!< true if this is the default input device. */
236 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
237 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
239 // Default constructor.
241 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
242 isDefaultOutput(false), isDefaultInput(false), nativeFormats(0) {}
245 //! The structure for specifying input or ouput stream parameters.
246 struct StreamParameters {
247 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
248 unsigned int nChannels; /*!< Number of channels. */
249 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
251 // Default constructor.
253 : deviceId(0), nChannels(0), firstChannel(0) {}
256 //! The structure for specifying stream options.
258 The following flags can be OR'ed together to allow a client to
259 make changes to the default stream behavior:
261 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
262 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
263 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
264 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
265 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
267 By default, RtAudio streams pass and receive audio data from the
268 client in an interleaved format. By passing the
269 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
270 data will instead be presented in non-interleaved buffers. In
271 this case, each buffer argument in the RtAudioCallback function
272 will point to a single array of data, with \c nFrames samples for
273 each channel concatenated back-to-back. For example, the first
274 sample of data for the second channel would be located at index \c
275 nFrames (assuming the \c buffer pointer was recast to the correct
276 data type for the stream).
278 Certain audio APIs offer a number of parameters that influence the
279 I/O latency of a stream. By default, RtAudio will attempt to set
280 these parameters internally for robust (glitch-free) performance
281 (though some APIs, like Windows Direct Sound, make this difficult).
282 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
283 function, internal stream settings will be influenced in an attempt
284 to minimize stream latency, though possibly at the expense of stream
287 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
288 open the input and/or output stream device(s) for exclusive use.
289 Note that this is not possible with all supported audio APIs.
291 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
292 to select realtime scheduling (round-robin) for the callback thread.
293 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
294 flag is set. It defines the thread's realtime priority.
296 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
297 open the "default" PCM device when using the ALSA API. Note that this
298 will override any specified input or output device id.
300 The \c numberOfBuffers parameter can be used to control stream
301 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
302 only. A value of two is usually the smallest allowed. Larger
303 numbers can potentially result in more robust stream performance,
304 though likely at the cost of stream latency. The value set by the
305 user is replaced during execution of the RtAudio::openStream()
306 function by the value actually used by the system.
308 The \c streamName parameter can be used to set the client name
309 when using the Jack API. By default, the client name is set to
310 RtApiJack. However, if you wish to create multiple instances of
311 RtAudio with Jack, each instance must have a unique client name.
313 struct StreamOptions {
314 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
315 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
316 std::string streamName; /*!< A stream name (currently used only in Jack). */
317 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
319 // Default constructor.
321 : flags(0), numberOfBuffers(0), priority(0) {}
324 //! A static function to determine the current RtAudio version.
325 static std::string getVersion( void ) { return VERSION; }
327 //! A static function to determine the available compiled audio APIs.
329 The values returned in the std::vector can be compared against
330 the enumerated list values. Note that there can be more than one
331 API compiled for certain operating systems.
333 static void getCompiledApi( std::vector<RtAudio::Api> &apis ) throw();
335 //! The class constructor.
337 The constructor performs minor initialization tasks. No exceptions
340 If no API argument is specified and multiple API support has been
341 compiled, the default order of use is JACK, ALSA, OSS (Linux
342 systems) and ASIO, DS (Windows systems).
344 RtAudio( RtAudio::Api api=UNSPECIFIED ) throw();
348 If a stream is running or open, it will be stopped and closed
353 //! Returns the audio API specifier for the current instance of RtAudio.
354 RtAudio::Api getCurrentApi( void ) throw();
356 //! A public function that queries for the number of audio devices available.
358 This function performs a system query of available devices each time it
359 is called, thus supporting devices connected \e after instantiation. If
360 a system error occurs during processing, a warning will be issued.
362 unsigned int getDeviceCount( void ) throw();
364 //! Return an RtAudio::DeviceInfo structure for a specified device number.
367 Any device integer between 0 and getDeviceCount() - 1 is valid.
368 If an invalid argument is provided, an RtError (type = INVALID_USE)
369 will be thrown. If a device is busy or otherwise unavailable, the
370 structure member "probed" will have a value of "false" and all
371 other members are undefined. If the specified device is the
372 current default input or output device, the corresponding
373 "isDefault" member will have a value of "true".
375 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
377 //! A function that returns the index of the default output device.
379 If the underlying audio API does not provide a "default
380 device", or if no devices are available, the return value will be
381 0. Note that this is a valid device identifier and it is the
382 client's responsibility to verify that a device is available
383 before attempting to open a stream.
385 unsigned int getDefaultOutputDevice( void ) throw();
387 //! A function that returns the index of the default input device.
389 If the underlying audio API does not provide a "default
390 device", or if no devices are available, the return value will be
391 0. Note that this is a valid device identifier and it is the
392 client's responsibility to verify that a device is available
393 before attempting to open a stream.
395 unsigned int getDefaultInputDevice( void ) throw();
397 //! A public function for opening a stream with the specified parameters.
399 An RtError (type = SYSTEM_ERROR) is thrown if a stream cannot be
400 opened with the specified parameters or an error occurs during
401 processing. An RtError (type = INVALID_USE) is thrown if any
402 invalid device ID or channel number parameters are specified.
404 \param outputParameters Specifies output stream parameters to use
405 when opening a stream, including a device ID, number of channels,
406 and starting channel number. For input-only streams, this
407 argument should be NULL. The device ID is an index value between
408 0 and getDeviceCount() - 1.
409 \param inputParameters Specifies input stream parameters to use
410 when opening a stream, including a device ID, number of channels,
411 and starting channel number. For output-only streams, this
412 argument should be NULL. The device ID is an index value between
413 0 and getDeviceCount() - 1.
414 \param format An RtAudioFormat specifying the desired sample data format.
415 \param sampleRate The desired sample rate (sample frames per second).
416 \param *bufferFrames A pointer to a value indicating the desired
417 internal buffer size in sample frames. The actual value
418 used by the device is returned via the same pointer. A
419 value of zero can be specified, in which case the lowest
420 allowable value is determined.
421 \param callback A client-defined function that will be invoked
422 when input data is available and/or output data is needed.
423 \param userData An optional pointer to data that can be accessed
424 from within the callback function.
425 \param options An optional pointer to a structure containing various
426 global stream options, including a list of OR'ed RtAudioStreamFlags
427 and a suggested number of stream buffers that can be used to
428 control stream latency. More buffers typically result in more
429 robust performance, though at a cost of greater latency. If a
430 value of zero is specified, a system-specific median value is
431 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
432 lowest allowable value is used. The actual value used is
433 returned via the structure argument. The parameter is API dependent.
434 \param errorCallback A client-defined function that will be invoked
435 when an error has occured.
437 void openStream( RtAudio::StreamParameters *outputParameters,
438 RtAudio::StreamParameters *inputParameters,
439 RtAudioFormat format, unsigned int sampleRate,
440 unsigned int *bufferFrames, RtAudioCallback callback,
441 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
443 //! A function that closes a stream and frees any associated stream memory.
445 If a stream is not open, this function issues a warning and
446 returns (no exception is thrown).
448 void closeStream( void ) throw();
450 //! A function that starts a stream.
452 An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
453 during processing. An RtError (type = INVALID_USE) is thrown if a
454 stream is not open. A warning is issued if the stream is already
457 void startStream( void );
459 //! Stop a stream, allowing any samples remaining in the output queue to be played.
461 An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
462 during processing. An RtError (type = INVALID_USE) is thrown if a
463 stream is not open. A warning is issued if the stream is already
466 void stopStream( void );
468 //! Stop a stream, discarding any samples remaining in the input/output queue.
470 An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
471 during processing. An RtError (type = INVALID_USE) is thrown if a
472 stream is not open. A warning is issued if the stream is already
475 void abortStream( void );
477 //! Returns true if a stream is open and false if not.
478 bool isStreamOpen( void ) const throw();
480 //! Returns true if the stream is running and false if it is stopped or not open.
481 bool isStreamRunning( void ) const throw();
483 //! Returns the number of elapsed seconds since the stream was started.
485 If a stream is not open, an RtError (type = INVALID_USE) will be thrown.
487 double getStreamTime( void );
489 //! Returns the internal stream latency in sample frames.
491 The stream latency refers to delay in audio input and/or output
492 caused by internal buffering by the audio system and/or hardware.
493 For duplex streams, the returned value will represent the sum of
494 the input and output latencies. If a stream is not open, an
495 RtError (type = INVALID_USE) will be thrown. If the API does not
496 report latency, the return value will be zero.
498 long getStreamLatency( void );
500 //! Returns actual sample rate in use by the stream.
502 On some systems, the sample rate used may be slightly different
503 than that specified in the stream parameters. If a stream is not
504 open, an RtError (type = INVALID_USE) will be thrown.
506 unsigned int getStreamSampleRate( void );
508 //! Specify whether warning messages should be printed to stderr.
509 void showWarnings( bool value = true ) throw();
513 void openRtApi( RtAudio::Api api );
517 // Operating system dependent thread functionality.
518 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
522 typedef unsigned long ThreadHandle;
523 typedef CRITICAL_SECTION StreamMutex;
525 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
526 // Using pthread library for various flavors of unix.
529 typedef pthread_t ThreadHandle;
530 typedef pthread_mutex_t StreamMutex;
532 #else // Setup for "dummy" behavior
534 #define __RTAUDIO_DUMMY__
535 typedef int ThreadHandle;
536 typedef int StreamMutex;
540 // This global structure type is used to pass callback information
541 // between the private RtAudio stream structure and global callback
542 // handling functions.
543 struct CallbackInfo {
544 void *object; // Used as a "this" pointer.
549 void *apiInfo; // void pointer for API specific callback information
554 // Default constructor.
556 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false) {}
559 // **************************************************************** //
561 // RtApi class declaration.
563 // Subclasses of RtApi contain all API- and OS-specific code necessary
564 // to fully implement the RtAudio API.
566 // Note that RtApi is an abstract base class and cannot be
567 // explicitly instantiated. The class RtAudio will create an
568 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
569 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
571 // **************************************************************** //
573 #pragma pack(push, 1)
582 S24& operator = ( const int& i ) {
583 c3[0] = (i & 0x000000ff);
584 c3[1] = (i & 0x0000ff00) >> 8;
585 c3[2] = (i & 0x00ff0000) >> 16;
589 S24( const S24& v ) { *this = v; }
590 S24( const double& d ) { *this = (int) d; }
591 S24( const float& f ) { *this = (int) f; }
592 S24( const signed short& s ) { *this = (int) s; }
593 S24( const char& c ) { *this = (int) c; }
596 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
597 if (i & 0x800000) i |= ~0xffffff;
603 #if defined( HAVE_GETTIMEOFDAY )
604 #include <sys/time.h>
615 virtual RtAudio::Api getCurrentApi( void ) = 0;
616 virtual unsigned int getDeviceCount( void ) = 0;
617 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
618 virtual unsigned int getDefaultInputDevice( void );
619 virtual unsigned int getDefaultOutputDevice( void );
620 void openStream( RtAudio::StreamParameters *outputParameters,
621 RtAudio::StreamParameters *inputParameters,
622 RtAudioFormat format, unsigned int sampleRate,
623 unsigned int *bufferFrames, RtAudioCallback callback,
624 void *userData, RtAudio::StreamOptions *options,
625 RtAudioErrorCallback errorCallback );
626 virtual void closeStream( void );
627 virtual void startStream( void ) = 0;
628 virtual void stopStream( void ) = 0;
629 virtual void abortStream( void ) = 0;
630 long getStreamLatency( void );
631 unsigned int getStreamSampleRate( void );
632 virtual double getStreamTime( void );
633 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
634 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
635 void showWarnings( bool value ) { showWarnings_ = value; }
640 static const unsigned int MAX_SAMPLE_RATES;
641 static const unsigned int SAMPLE_RATES[];
643 enum { FAILURE, SUCCESS };
659 // A protected structure used for buffer conversion.
663 RtAudioFormat inFormat, outFormat;
664 std::vector<int> inOffset;
665 std::vector<int> outOffset;
668 // A protected structure for audio streams.
670 unsigned int device[2]; // Playback and record, respectively.
671 void *apiHandle; // void pointer for API specific stream handle information
672 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
673 StreamState state; // STOPPED, RUNNING, or CLOSED
674 char *userBuffer[2]; // Playback and record, respectively.
676 bool doConvertBuffer[2]; // Playback and record, respectively.
677 bool userInterleaved;
678 bool deviceInterleaved[2]; // Playback and record, respectively.
679 bool doByteSwap[2]; // Playback and record, respectively.
680 unsigned int sampleRate;
681 unsigned int bufferSize;
682 unsigned int nBuffers;
683 unsigned int nUserChannels[2]; // Playback and record, respectively.
684 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
685 unsigned int channelOffset[2]; // Playback and record, respectively.
686 unsigned long latency[2]; // Playback and record, respectively.
687 RtAudioFormat userFormat;
688 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
690 CallbackInfo callbackInfo;
691 ConvertInfo convertInfo[2];
692 double streamTime; // Number of elapsed seconds since the stream started.
694 #if defined(HAVE_GETTIMEOFDAY)
695 struct timeval lastTickTimestamp;
699 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
703 typedef signed short Int16;
704 typedef signed int Int32;
705 typedef float Float32;
706 typedef double Float64;
708 std::ostringstream errorStream_;
709 std::string errorText_;
714 Protected, api-specific method that attempts to open a device
715 with the given parameters. This function MUST be implemented by
716 all subclasses. If an error is encountered during the probe, a
717 "warning" message is reported and FAILURE is returned. A
718 successful probe is indicated by a return value of SUCCESS.
720 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
721 unsigned int firstChannel, unsigned int sampleRate,
722 RtAudioFormat format, unsigned int *bufferSize,
723 RtAudio::StreamOptions *options );
725 //! A protected function used to increment the stream time.
726 void tickStreamTime( void );
728 //! Protected common method to clear an RtApiStream structure.
729 void clearStreamInfo();
732 Protected common method that throws an RtError (type =
733 INVALID_USE) if a stream is not open.
735 void verifyStream( void );
737 //! Protected common error method to allow global control over error handling.
738 void error( RtError::Type type );
741 Protected method used to perform format, channel number, and/or interleaving
742 conversions between the user and device buffers.
744 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
746 //! Protected common method used to perform byte-swapping on buffers.
747 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
749 //! Protected common method that returns the number of bytes for a given format.
750 unsigned int formatBytes( RtAudioFormat format );
752 //! Protected common method that sets up the parameters for buffer conversion.
753 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
756 // **************************************************************** //
758 // Inline RtAudio definitions.
760 // **************************************************************** //
762 inline RtAudio::Api RtAudio :: getCurrentApi( void ) throw() { return rtapi_->getCurrentApi(); }
763 inline unsigned int RtAudio :: getDeviceCount( void ) throw() { return rtapi_->getDeviceCount(); }
764 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
765 inline unsigned int RtAudio :: getDefaultInputDevice( void ) throw() { return rtapi_->getDefaultInputDevice(); }
766 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) throw() { return rtapi_->getDefaultOutputDevice(); }
767 inline void RtAudio :: closeStream( void ) throw() { return rtapi_->closeStream(); }
768 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
769 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
770 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
771 inline bool RtAudio :: isStreamOpen( void ) const throw() { return rtapi_->isStreamOpen(); }
772 inline bool RtAudio :: isStreamRunning( void ) const throw() { return rtapi_->isStreamRunning(); }
773 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
774 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
775 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
776 inline void RtAudio :: showWarnings( bool value ) throw() { rtapi_->showWarnings( value ); }
778 // RtApi Subclass prototypes.
780 #if defined(__MACOSX_CORE__)
782 #include <CoreAudio/AudioHardware.h>
784 class RtApiCore: public RtApi
790 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
791 unsigned int getDeviceCount( void );
792 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
793 unsigned int getDefaultOutputDevice( void );
794 unsigned int getDefaultInputDevice( void );
795 void closeStream( void );
796 void startStream( void );
797 void stopStream( void );
798 void abortStream( void );
799 long getStreamLatency( void );
801 // This function is intended for internal use only. It must be
802 // public because it is called by the internal callback handler,
803 // which is not a member of RtAudio. External use of this function
804 // will most likely produce highly undesireable results!
805 bool callbackEvent( AudioDeviceID deviceId,
806 const AudioBufferList *inBufferList,
807 const AudioBufferList *outBufferList );
811 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
812 unsigned int firstChannel, unsigned int sampleRate,
813 RtAudioFormat format, unsigned int *bufferSize,
814 RtAudio::StreamOptions *options );
815 static const char* getErrorCode( OSStatus code );
820 #if defined(__UNIX_JACK__)
822 class RtApiJack: public RtApi
828 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
829 unsigned int getDeviceCount( void );
830 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
831 void closeStream( void );
832 void startStream( void );
833 void stopStream( void );
834 void abortStream( void );
835 long getStreamLatency( void );
837 // This function is intended for internal use only. It must be
838 // public because it is called by the internal callback handler,
839 // which is not a member of RtAudio. External use of this function
840 // will most likely produce highly undesireable results!
841 bool callbackEvent( unsigned long nframes );
845 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
846 unsigned int firstChannel, unsigned int sampleRate,
847 RtAudioFormat format, unsigned int *bufferSize,
848 RtAudio::StreamOptions *options );
853 #if defined(__WINDOWS_ASIO__)
855 class RtApiAsio: public RtApi
861 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
862 unsigned int getDeviceCount( void );
863 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
864 void closeStream( void );
865 void startStream( void );
866 void stopStream( void );
867 void abortStream( void );
868 long getStreamLatency( void );
870 // This function is intended for internal use only. It must be
871 // public because it is called by the internal callback handler,
872 // which is not a member of RtAudio. External use of this function
873 // will most likely produce highly undesireable results!
874 bool callbackEvent( long bufferIndex );
878 std::vector<RtAudio::DeviceInfo> devices_;
879 void saveDeviceInfo( void );
881 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
882 unsigned int firstChannel, unsigned int sampleRate,
883 RtAudioFormat format, unsigned int *bufferSize,
884 RtAudio::StreamOptions *options );
889 #if defined(__WINDOWS_DS__)
891 class RtApiDs: public RtApi
897 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
898 unsigned int getDeviceCount( void );
899 unsigned int getDefaultOutputDevice( void );
900 unsigned int getDefaultInputDevice( void );
901 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
902 void closeStream( void );
903 void startStream( void );
904 void stopStream( void );
905 void abortStream( void );
906 long getStreamLatency( void );
908 // This function is intended for internal use only. It must be
909 // public because it is called by the internal callback handler,
910 // which is not a member of RtAudio. External use of this function
911 // will most likely produce highly undesireable results!
912 void callbackEvent( void );
918 long duplexPrerollBytes;
919 std::vector<struct DsDevice> dsDevices;
920 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
921 unsigned int firstChannel, unsigned int sampleRate,
922 RtAudioFormat format, unsigned int *bufferSize,
923 RtAudio::StreamOptions *options );
928 #if defined(__LINUX_ALSA__)
930 class RtApiAlsa: public RtApi
936 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
937 unsigned int getDeviceCount( void );
938 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
939 void closeStream( void );
940 void startStream( void );
941 void stopStream( void );
942 void abortStream( void );
944 // This function is intended for internal use only. It must be
945 // public because it is called by the internal callback handler,
946 // which is not a member of RtAudio. External use of this function
947 // will most likely produce highly undesireable results!
948 void callbackEvent( void );
952 std::vector<RtAudio::DeviceInfo> devices_;
953 void saveDeviceInfo( void );
954 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
955 unsigned int firstChannel, unsigned int sampleRate,
956 RtAudioFormat format, unsigned int *bufferSize,
957 RtAudio::StreamOptions *options );
962 #if defined(__LINUX_PULSE__)
964 class RtApiPulse: public RtApi
968 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
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 void callbackEvent( void );
984 std::vector<RtAudio::DeviceInfo> devices_;
985 void saveDeviceInfo( void );
986 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
987 unsigned int firstChannel, unsigned int sampleRate,
988 RtAudioFormat format, unsigned int *bufferSize,
989 RtAudio::StreamOptions *options );
994 #if defined(__LINUX_OSS__)
996 class RtApiOss: public RtApi
1002 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1003 unsigned int getDeviceCount( void );
1004 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1005 void closeStream( void );
1006 void startStream( void );
1007 void stopStream( void );
1008 void abortStream( void );
1010 // This function is intended for internal use only. It must be
1011 // public because it is called by the internal callback handler,
1012 // which is not a member of RtAudio. External use of this function
1013 // will most likely produce highly undesireable results!
1014 void callbackEvent( void );
1018 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1019 unsigned int firstChannel, unsigned int sampleRate,
1020 RtAudioFormat format, unsigned int *bufferSize,
1021 RtAudio::StreamOptions *options );
1026 #if defined(__RTAUDIO_DUMMY__)
1028 class RtApiDummy: public RtApi
1032 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtError::WARNING ); }
1033 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1034 unsigned int getDeviceCount( void ) { return 0; }
1035 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1036 void closeStream( void ) {}
1037 void startStream( void ) {}
1038 void stopStream( void ) {}
1039 void abortStream( void ) {}
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*/ ) { return false; }
1053 // Indentation settings for Vim and Emacs
1056 // c-basic-offset: 2
1057 // indent-tabs-mode: nil
1060 // vim: et sts=2 sw=2