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 /************************************************************************/
54 static const std::string VERSION( "4.1.0pre" );
56 /*! \typedef typedef unsigned long RtAudioFormat;
57 \brief RtAudio data format type.
59 Support for signed integers and floats. Audio data fed to/from an
60 RtAudio stream is assumed to ALWAYS be in host byte order. The
61 internal routines will automatically take care of any necessary
62 byte-swapping between the host format and the soundcard. Thus,
63 endian-ness is not a concern in the following format definitions.
65 - \e RTAUDIO_SINT8: 8-bit signed integer.
66 - \e RTAUDIO_SINT16: 16-bit signed integer.
67 - \e RTAUDIO_SINT24: 24-bit signed integer.
68 - \e RTAUDIO_SINT32: 32-bit signed integer.
69 - \e RTAUDIO_FLOAT32: Normalized between plus/minus 1.0.
70 - \e RTAUDIO_FLOAT64: Normalized between plus/minus 1.0.
72 typedef unsigned long RtAudioFormat;
73 static const RtAudioFormat RTAUDIO_SINT8 = 0x1; // 8-bit signed integer.
74 static const RtAudioFormat RTAUDIO_SINT16 = 0x2; // 16-bit signed integer.
75 static const RtAudioFormat RTAUDIO_SINT24 = 0x4; // 24-bit signed integer.
76 static const RtAudioFormat RTAUDIO_SINT32 = 0x8; // 32-bit signed integer.
77 static const RtAudioFormat RTAUDIO_FLOAT32 = 0x10; // Normalized between plus/minus 1.0.
78 static const RtAudioFormat RTAUDIO_FLOAT64 = 0x20; // Normalized between plus/minus 1.0.
80 /*! \typedef typedef unsigned long RtAudioStreamFlags;
81 \brief RtAudio stream option flags.
83 The following flags can be OR'ed together to allow a client to
84 make changes to the default stream behavior:
86 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
87 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
88 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
89 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
91 By default, RtAudio streams pass and receive audio data from the
92 client in an interleaved format. By passing the
93 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
94 data will instead be presented in non-interleaved buffers. In
95 this case, each buffer argument in the RtAudioCallback function
96 will point to a single array of data, with \c nFrames samples for
97 each channel concatenated back-to-back. For example, the first
98 sample of data for the second channel would be located at index \c
99 nFrames (assuming the \c buffer pointer was recast to the correct
100 data type for the stream).
102 Certain audio APIs offer a number of parameters that influence the
103 I/O latency of a stream. By default, RtAudio will attempt to set
104 these parameters internally for robust (glitch-free) performance
105 (though some APIs, like Windows Direct Sound, make this difficult).
106 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
107 function, internal stream settings will be influenced in an attempt
108 to minimize stream latency, though possibly at the expense of stream
111 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
112 open the input and/or output stream device(s) for exclusive use.
113 Note that this is not possible with all supported audio APIs.
115 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
116 to select realtime scheduling (round-robin) for the callback thread.
118 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
119 open the "default" PCM device when using the ALSA API. Note that this
120 will override any specified input or output device id.
122 typedef unsigned int RtAudioStreamFlags;
123 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1; // Use non-interleaved buffers (default = interleaved).
124 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2; // Attempt to set stream parameters for lowest possible latency.
125 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4; // Attempt grab device and prevent use by others.
126 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
127 static const RtAudioStreamFlags RTAUDIO_ALSA_USE_DEFAULT = 0x10; // Use the "default" PCM device (ALSA only).
129 /*! \typedef typedef unsigned long RtAudioStreamStatus;
130 \brief RtAudio stream status (over- or underflow) flags.
132 Notification of a stream over- or underflow is indicated by a
133 non-zero stream \c status argument in the RtAudioCallback function.
134 The stream status can be one of the following two options,
135 depending on whether the stream is open for output and/or input:
137 - \e RTAUDIO_INPUT_OVERFLOW: Input data was discarded because of an overflow condition at the driver.
138 - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
140 typedef unsigned int RtAudioStreamStatus;
141 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1; // Input data was discarded because of an overflow condition at the driver.
142 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2; // The output buffer ran low, likely causing a gap in the output sound.
144 //! RtAudio callback function prototype.
146 All RtAudio clients must create a function of type RtAudioCallback
147 to read and/or write data from/to the audio stream. When the
148 underlying audio system is ready for new input or output data, this
149 function will be invoked.
151 \param outputBuffer For output (or duplex) streams, the client
152 should write \c nFrames of audio sample frames into this
153 buffer. This argument should be recast to the datatype
154 specified when the stream was opened. For input-only
155 streams, this argument will be NULL.
157 \param inputBuffer For input (or duplex) streams, this buffer will
158 hold \c nFrames of input audio sample frames. This
159 argument should be recast to the datatype specified when the
160 stream was opened. For output-only streams, this argument
163 \param nFrames The number of sample frames of input or output
164 data in the buffers. The actual buffer size in bytes is
165 dependent on the data type and number of channels in use.
167 \param streamTime The number of seconds that have elapsed since the
170 \param status If non-zero, this argument indicates a data overflow
171 or underflow condition for the stream. The particular
172 condition can be determined by comparison with the
173 RtAudioStreamStatus flags.
175 \param userData A pointer to optional data provided by the client
176 when opening the stream (default = NULL).
178 To continue normal stream operation, the RtAudioCallback function
179 should return a value of zero. To stop the stream and drain the
180 output buffer, the function should return a value of one. To abort
181 the stream immediately, the client should return a value of two.
183 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
184 unsigned int nFrames,
186 RtAudioStreamStatus status,
189 //! RtAudio error callback function prototype.
191 \param type Type of error.
192 \param errorText Error description.
194 typedef void (*RtAudioErrorCallback)( RtError::Type type, const std::string &errorText );
196 // **************************************************************** //
198 // RtAudio class declaration.
200 // RtAudio is a "controller" used to select an available audio i/o
201 // interface. It presents a common API for the user to call but all
202 // functionality is implemented by the class RtApi and its
203 // subclasses. RtAudio creates an instance of an RtApi subclass
204 // based on the user's API choice. If no choice is made, RtAudio
205 // attempts to make a "logical" API selection.
207 // **************************************************************** //
216 //! Audio API specifier arguments.
218 UNSPECIFIED, /*!< Search for a working compiled API. */
219 LINUX_ALSA, /*!< The Advanced Linux Sound Architecture API. */
220 LINUX_PULSE, /*!< The Linux PulseAudio API. */
221 LINUX_OSS, /*!< The Linux Open Sound System API. */
222 UNIX_JACK, /*!< The Jack Low-Latency Audio Server API. */
223 MACOSX_CORE, /*!< Macintosh OS-X Core Audio API. */
224 WINDOWS_ASIO, /*!< The Steinberg Audio Stream I/O API. */
225 WINDOWS_DS, /*!< The Microsoft Direct Sound API. */
226 RTAUDIO_DUMMY /*!< A compilable but non-functional API. */
229 //! The public device information structure for returning queried values.
231 bool probed; /*!< true if the device capabilities were successfully probed. */
232 std::string name; /*!< Character string device identifier. */
233 unsigned int outputChannels; /*!< Maximum output channels supported by device. */
234 unsigned int inputChannels; /*!< Maximum input channels supported by device. */
235 unsigned int duplexChannels; /*!< Maximum simultaneous input/output channels supported by device. */
236 bool isDefaultOutput; /*!< true if this is the default output device. */
237 bool isDefaultInput; /*!< true if this is the default input device. */
238 std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
239 RtAudioFormat nativeFormats; /*!< Bit mask of supported data formats. */
241 // Default constructor.
243 :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
244 isDefaultOutput(false), isDefaultInput(false), nativeFormats(0) {}
247 //! The structure for specifying input or ouput stream parameters.
248 struct StreamParameters {
249 unsigned int deviceId; /*!< Device index (0 to getDeviceCount() - 1). */
250 unsigned int nChannels; /*!< Number of channels. */
251 unsigned int firstChannel; /*!< First channel index on device (default = 0). */
253 // Default constructor.
255 : deviceId(0), nChannels(0), firstChannel(0) {}
258 //! The structure for specifying stream options.
260 The following flags can be OR'ed together to allow a client to
261 make changes to the default stream behavior:
263 - \e RTAUDIO_NONINTERLEAVED: Use non-interleaved buffers (default = interleaved).
264 - \e RTAUDIO_MINIMIZE_LATENCY: Attempt to set stream parameters for lowest possible latency.
265 - \e RTAUDIO_HOG_DEVICE: Attempt grab device for exclusive use.
266 - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
267 - \e RTAUDIO_ALSA_USE_DEFAULT: Use the "default" PCM device (ALSA only).
269 By default, RtAudio streams pass and receive audio data from the
270 client in an interleaved format. By passing the
271 RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
272 data will instead be presented in non-interleaved buffers. In
273 this case, each buffer argument in the RtAudioCallback function
274 will point to a single array of data, with \c nFrames samples for
275 each channel concatenated back-to-back. For example, the first
276 sample of data for the second channel would be located at index \c
277 nFrames (assuming the \c buffer pointer was recast to the correct
278 data type for the stream).
280 Certain audio APIs offer a number of parameters that influence the
281 I/O latency of a stream. By default, RtAudio will attempt to set
282 these parameters internally for robust (glitch-free) performance
283 (though some APIs, like Windows Direct Sound, make this difficult).
284 By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
285 function, internal stream settings will be influenced in an attempt
286 to minimize stream latency, though possibly at the expense of stream
289 If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
290 open the input and/or output stream device(s) for exclusive use.
291 Note that this is not possible with all supported audio APIs.
293 If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt
294 to select realtime scheduling (round-robin) for the callback thread.
295 The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
296 flag is set. It defines the thread's realtime priority.
298 If the RTAUDIO_ALSA_USE_DEFAULT flag is set, RtAudio will attempt to
299 open the "default" PCM device when using the ALSA API. Note that this
300 will override any specified input or output device id.
302 The \c numberOfBuffers parameter can be used to control stream
303 latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
304 only. A value of two is usually the smallest allowed. Larger
305 numbers can potentially result in more robust stream performance,
306 though likely at the cost of stream latency. The value set by the
307 user is replaced during execution of the RtAudio::openStream()
308 function by the value actually used by the system.
310 The \c streamName parameter can be used to set the client name
311 when using the Jack API. By default, the client name is set to
312 RtApiJack. However, if you wish to create multiple instances of
313 RtAudio with Jack, each instance must have a unique client name.
315 struct StreamOptions {
316 RtAudioStreamFlags flags; /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE, RTAUDIO_ALSA_USE_DEFAULT). */
317 unsigned int numberOfBuffers; /*!< Number of stream buffers. */
318 std::string streamName; /*!< A stream name (currently used only in Jack). */
319 int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
321 // Default constructor.
323 : flags(0), numberOfBuffers(0), priority(0) {}
326 //! A static function to determine the current RtAudio version.
327 static std::string getVersion( void ) { return VERSION; }
329 //! A static function to determine the available compiled audio APIs.
331 The values returned in the std::vector can be compared against
332 the enumerated list values. Note that there can be more than one
333 API compiled for certain operating systems.
335 static void getCompiledApi( std::vector<RtAudio::Api> &apis ) throw();
337 //! The class constructor.
339 The constructor performs minor initialization tasks. No exceptions
342 If no API argument is specified and multiple API support has been
343 compiled, the default order of use is JACK, ALSA, OSS (Linux
344 systems) and ASIO, DS (Windows systems).
346 RtAudio( RtAudio::Api api=UNSPECIFIED ) throw();
350 If a stream is running or open, it will be stopped and closed
355 //! Returns the audio API specifier for the current instance of RtAudio.
356 RtAudio::Api getCurrentApi( void ) throw();
358 //! A public function that queries for the number of audio devices available.
360 This function performs a system query of available devices each time it
361 is called, thus supporting devices connected \e after instantiation. If
362 a system error occurs during processing, a warning will be issued.
364 unsigned int getDeviceCount( void ) throw();
366 //! Return an RtAudio::DeviceInfo structure for a specified device number.
369 Any device integer between 0 and getDeviceCount() - 1 is valid.
370 If an invalid argument is provided, an RtError (type = INVALID_USE)
371 will be thrown. If a device is busy or otherwise unavailable, the
372 structure member "probed" will have a value of "false" and all
373 other members are undefined. If the specified device is the
374 current default input or output device, the corresponding
375 "isDefault" member will have a value of "true".
377 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
379 //! A function that returns the index of the default output device.
381 If the underlying audio API does not provide a "default
382 device", or if no devices are available, the return value will be
383 0. Note that this is a valid device identifier and it is the
384 client's responsibility to verify that a device is available
385 before attempting to open a stream.
387 unsigned int getDefaultOutputDevice( void ) throw();
389 //! A function that returns the index of the default input device.
391 If the underlying audio API does not provide a "default
392 device", or if no devices are available, the return value will be
393 0. Note that this is a valid device identifier and it is the
394 client's responsibility to verify that a device is available
395 before attempting to open a stream.
397 unsigned int getDefaultInputDevice( void ) throw();
399 //! A public function for opening a stream with the specified parameters.
401 An RtError (type = SYSTEM_ERROR) is thrown if a stream cannot be
402 opened with the specified parameters or an error occurs during
403 processing. An RtError (type = INVALID_USE) is thrown if any
404 invalid device ID or channel number parameters are specified.
406 \param outputParameters Specifies output stream parameters to use
407 when opening a stream, including a device ID, number of channels,
408 and starting channel number. For input-only streams, this
409 argument should be NULL. The device ID is an index value between
410 0 and getDeviceCount() - 1.
411 \param inputParameters Specifies input stream parameters to use
412 when opening a stream, including a device ID, number of channels,
413 and starting channel number. For output-only streams, this
414 argument should be NULL. The device ID is an index value between
415 0 and getDeviceCount() - 1.
416 \param format An RtAudioFormat specifying the desired sample data format.
417 \param sampleRate The desired sample rate (sample frames per second).
418 \param *bufferFrames A pointer to a value indicating the desired
419 internal buffer size in sample frames. The actual value
420 used by the device is returned via the same pointer. A
421 value of zero can be specified, in which case the lowest
422 allowable value is determined.
423 \param callback A client-defined function that will be invoked
424 when input data is available and/or output data is needed.
425 \param userData An optional pointer to data that can be accessed
426 from within the callback function.
427 \param options An optional pointer to a structure containing various
428 global stream options, including a list of OR'ed RtAudioStreamFlags
429 and a suggested number of stream buffers that can be used to
430 control stream latency. More buffers typically result in more
431 robust performance, though at a cost of greater latency. If a
432 value of zero is specified, a system-specific median value is
433 chosen. If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
434 lowest allowable value is used. The actual value used is
435 returned via the structure argument. The parameter is API dependent.
436 \param errorCallback A client-defined function that will be invoked
437 when an error has occured.
439 void openStream( RtAudio::StreamParameters *outputParameters,
440 RtAudio::StreamParameters *inputParameters,
441 RtAudioFormat format, unsigned int sampleRate,
442 unsigned int *bufferFrames, RtAudioCallback callback,
443 void *userData = NULL, RtAudio::StreamOptions *options = NULL, RtAudioErrorCallback errorCallback = NULL );
445 //! A function that closes a stream and frees any associated stream memory.
447 If a stream is not open, this function issues a warning and
448 returns (no exception is thrown).
450 void closeStream( void ) throw();
452 //! A function that starts a stream.
454 An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
455 during processing. An RtError (type = INVALID_USE) is thrown if a
456 stream is not open. A warning is issued if the stream is already
459 void startStream( void );
461 //! Stop a stream, allowing any samples remaining in the output queue to be played.
463 An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
464 during processing. An RtError (type = INVALID_USE) is thrown if a
465 stream is not open. A warning is issued if the stream is already
468 void stopStream( void );
470 //! Stop a stream, discarding any samples remaining in the input/output queue.
472 An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
473 during processing. An RtError (type = INVALID_USE) is thrown if a
474 stream is not open. A warning is issued if the stream is already
477 void abortStream( void );
479 //! Returns true if a stream is open and false if not.
480 bool isStreamOpen( void ) const throw();
482 //! Returns true if the stream is running and false if it is stopped or not open.
483 bool isStreamRunning( void ) const throw();
485 //! Returns the number of elapsed seconds since the stream was started.
487 If a stream is not open, an RtError (type = INVALID_USE) will be thrown.
489 double getStreamTime( void );
491 //! Returns the internal stream latency in sample frames.
493 The stream latency refers to delay in audio input and/or output
494 caused by internal buffering by the audio system and/or hardware.
495 For duplex streams, the returned value will represent the sum of
496 the input and output latencies. If a stream is not open, an
497 RtError (type = INVALID_USE) will be thrown. If the API does not
498 report latency, the return value will be zero.
500 long getStreamLatency( void );
502 //! Returns actual sample rate in use by the stream.
504 On some systems, the sample rate used may be slightly different
505 than that specified in the stream parameters. If a stream is not
506 open, an RtError (type = INVALID_USE) will be thrown.
508 unsigned int getStreamSampleRate( void );
510 //! Specify whether warning messages should be printed to stderr.
511 void showWarnings( bool value = true ) throw();
515 void openRtApi( RtAudio::Api api );
519 // Operating system dependent thread functionality.
520 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
524 typedef unsigned long ThreadHandle;
525 typedef CRITICAL_SECTION StreamMutex;
527 #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
528 // Using pthread library for various flavors of unix.
531 typedef pthread_t ThreadHandle;
532 typedef pthread_mutex_t StreamMutex;
534 #else // Setup for "dummy" behavior
536 #define __RTAUDIO_DUMMY__
537 typedef int ThreadHandle;
538 typedef int StreamMutex;
542 // This global structure type is used to pass callback information
543 // between the private RtAudio stream structure and global callback
544 // handling functions.
545 struct CallbackInfo {
546 void *object; // Used as a "this" pointer.
551 void *apiInfo; // void pointer for API specific callback information
556 // Default constructor.
558 :object(0), callback(0), userData(0), errorCallback(0), apiInfo(0), isRunning(false), doRealtime(false) {}
561 // **************************************************************** //
563 // RtApi class declaration.
565 // Subclasses of RtApi contain all API- and OS-specific code necessary
566 // to fully implement the RtAudio API.
568 // Note that RtApi is an abstract base class and cannot be
569 // explicitly instantiated. The class RtAudio will create an
570 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
571 // RtApiJack, RtApiCore, RtApiDs, or RtApiAsio).
573 // **************************************************************** //
575 #pragma pack(push, 1)
584 S24& operator = ( const int& i ) {
585 c3[0] = (i & 0x000000ff);
586 c3[1] = (i & 0x0000ff00) >> 8;
587 c3[2] = (i & 0x00ff0000) >> 16;
591 S24( const S24& v ) { *this = v; }
592 S24( const double& d ) { *this = (int) d; }
593 S24( const float& f ) { *this = (int) f; }
594 S24( const signed short& s ) { *this = (int) s; }
595 S24( const char& c ) { *this = (int) c; }
598 int i = c3[0] | (c3[1] << 8) | (c3[2] << 16);
599 if (i & 0x800000) i |= ~0xffffff;
605 #if defined( HAVE_GETTIMEOFDAY )
606 #include <sys/time.h>
617 virtual RtAudio::Api getCurrentApi( void ) = 0;
618 virtual unsigned int getDeviceCount( void ) = 0;
619 virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
620 virtual unsigned int getDefaultInputDevice( void );
621 virtual unsigned int getDefaultOutputDevice( void );
622 void openStream( RtAudio::StreamParameters *outputParameters,
623 RtAudio::StreamParameters *inputParameters,
624 RtAudioFormat format, unsigned int sampleRate,
625 unsigned int *bufferFrames, RtAudioCallback callback,
626 void *userData, RtAudio::StreamOptions *options,
627 RtAudioErrorCallback errorCallback );
628 virtual void closeStream( void );
629 virtual void startStream( void ) = 0;
630 virtual void stopStream( void ) = 0;
631 virtual void abortStream( void ) = 0;
632 long getStreamLatency( void );
633 unsigned int getStreamSampleRate( void );
634 virtual double getStreamTime( void );
635 bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; }
636 bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; }
637 void showWarnings( bool value ) { showWarnings_ = value; }
642 static const unsigned int MAX_SAMPLE_RATES;
643 static const unsigned int SAMPLE_RATES[];
645 enum { FAILURE, SUCCESS };
661 // A protected structure used for buffer conversion.
665 RtAudioFormat inFormat, outFormat;
666 std::vector<int> inOffset;
667 std::vector<int> outOffset;
670 // A protected structure for audio streams.
672 unsigned int device[2]; // Playback and record, respectively.
673 void *apiHandle; // void pointer for API specific stream handle information
674 StreamMode mode; // OUTPUT, INPUT, or DUPLEX.
675 StreamState state; // STOPPED, RUNNING, or CLOSED
676 char *userBuffer[2]; // Playback and record, respectively.
678 bool doConvertBuffer[2]; // Playback and record, respectively.
679 bool userInterleaved;
680 bool deviceInterleaved[2]; // Playback and record, respectively.
681 bool doByteSwap[2]; // Playback and record, respectively.
682 unsigned int sampleRate;
683 unsigned int bufferSize;
684 unsigned int nBuffers;
685 unsigned int nUserChannels[2]; // Playback and record, respectively.
686 unsigned int nDeviceChannels[2]; // Playback and record channels, respectively.
687 unsigned int channelOffset[2]; // Playback and record, respectively.
688 unsigned long latency[2]; // Playback and record, respectively.
689 RtAudioFormat userFormat;
690 RtAudioFormat deviceFormat[2]; // Playback and record, respectively.
692 CallbackInfo callbackInfo;
693 ConvertInfo convertInfo[2];
694 double streamTime; // Number of elapsed seconds since the stream started.
696 #if defined(HAVE_GETTIMEOFDAY)
697 struct timeval lastTickTimestamp;
701 :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
705 typedef signed short Int16;
706 typedef signed int Int32;
707 typedef float Float32;
708 typedef double Float64;
710 std::ostringstream errorStream_;
711 std::string errorText_;
716 Protected, api-specific method that attempts to open a device
717 with the given parameters. This function MUST be implemented by
718 all subclasses. If an error is encountered during the probe, a
719 "warning" message is reported and FAILURE is returned. A
720 successful probe is indicated by a return value of SUCCESS.
722 virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
723 unsigned int firstChannel, unsigned int sampleRate,
724 RtAudioFormat format, unsigned int *bufferSize,
725 RtAudio::StreamOptions *options );
727 //! A protected function used to increment the stream time.
728 void tickStreamTime( void );
730 //! Protected common method to clear an RtApiStream structure.
731 void clearStreamInfo();
734 Protected common method that throws an RtError (type =
735 INVALID_USE) if a stream is not open.
737 void verifyStream( void );
739 //! Protected common error method to allow global control over error handling.
740 void error( RtError::Type type );
743 Protected method used to perform format, channel number, and/or interleaving
744 conversions between the user and device buffers.
746 void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
748 //! Protected common method used to perform byte-swapping on buffers.
749 void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
751 //! Protected common method that returns the number of bytes for a given format.
752 unsigned int formatBytes( RtAudioFormat format );
754 //! Protected common method that sets up the parameters for buffer conversion.
755 void setConvertInfo( StreamMode mode, unsigned int firstChannel );
758 // **************************************************************** //
760 // Inline RtAudio definitions.
762 // **************************************************************** //
764 inline RtAudio::Api RtAudio :: getCurrentApi( void ) throw() { return rtapi_->getCurrentApi(); }
765 inline unsigned int RtAudio :: getDeviceCount( void ) throw() { return rtapi_->getDeviceCount(); }
766 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
767 inline unsigned int RtAudio :: getDefaultInputDevice( void ) throw() { return rtapi_->getDefaultInputDevice(); }
768 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) throw() { return rtapi_->getDefaultOutputDevice(); }
769 inline void RtAudio :: closeStream( void ) throw() { return rtapi_->closeStream(); }
770 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
771 inline void RtAudio :: stopStream( void ) { return rtapi_->stopStream(); }
772 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
773 inline bool RtAudio :: isStreamOpen( void ) const throw() { return rtapi_->isStreamOpen(); }
774 inline bool RtAudio :: isStreamRunning( void ) const throw() { return rtapi_->isStreamRunning(); }
775 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
776 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); }
777 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
778 inline void RtAudio :: showWarnings( bool value ) throw() { rtapi_->showWarnings( value ); }
780 // RtApi Subclass prototypes.
782 #if defined(__MACOSX_CORE__)
784 #include <CoreAudio/AudioHardware.h>
786 class RtApiCore: public RtApi
792 RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; }
793 unsigned int getDeviceCount( void );
794 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
795 unsigned int getDefaultOutputDevice( void );
796 unsigned int getDefaultInputDevice( void );
797 void closeStream( void );
798 void startStream( void );
799 void stopStream( void );
800 void abortStream( void );
801 long getStreamLatency( void );
803 // This function is intended for internal use only. It must be
804 // public because it is called by the internal callback handler,
805 // which is not a member of RtAudio. External use of this function
806 // will most likely produce highly undesireable results!
807 bool callbackEvent( AudioDeviceID deviceId,
808 const AudioBufferList *inBufferList,
809 const AudioBufferList *outBufferList );
813 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
814 unsigned int firstChannel, unsigned int sampleRate,
815 RtAudioFormat format, unsigned int *bufferSize,
816 RtAudio::StreamOptions *options );
817 static const char* getErrorCode( OSStatus code );
822 #if defined(__UNIX_JACK__)
824 class RtApiJack: public RtApi
830 RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; }
831 unsigned int getDeviceCount( void );
832 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
833 void closeStream( void );
834 void startStream( void );
835 void stopStream( void );
836 void abortStream( void );
837 long getStreamLatency( void );
839 // This function is intended for internal use only. It must be
840 // public because it is called by the internal callback handler,
841 // which is not a member of RtAudio. External use of this function
842 // will most likely produce highly undesireable results!
843 bool callbackEvent( unsigned long nframes );
847 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
848 unsigned int firstChannel, unsigned int sampleRate,
849 RtAudioFormat format, unsigned int *bufferSize,
850 RtAudio::StreamOptions *options );
855 #if defined(__WINDOWS_ASIO__)
857 class RtApiAsio: public RtApi
863 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; }
864 unsigned int getDeviceCount( void );
865 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
866 void closeStream( void );
867 void startStream( void );
868 void stopStream( void );
869 void abortStream( void );
870 long getStreamLatency( void );
872 // This function is intended for internal use only. It must be
873 // public because it is called by the internal callback handler,
874 // which is not a member of RtAudio. External use of this function
875 // will most likely produce highly undesireable results!
876 bool callbackEvent( long bufferIndex );
880 std::vector<RtAudio::DeviceInfo> devices_;
881 void saveDeviceInfo( void );
883 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
884 unsigned int firstChannel, unsigned int sampleRate,
885 RtAudioFormat format, unsigned int *bufferSize,
886 RtAudio::StreamOptions *options );
891 #if defined(__WINDOWS_DS__)
893 class RtApiDs: public RtApi
899 RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; }
900 unsigned int getDeviceCount( void );
901 unsigned int getDefaultOutputDevice( void );
902 unsigned int getDefaultInputDevice( void );
903 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
904 void closeStream( void );
905 void startStream( void );
906 void stopStream( void );
907 void abortStream( void );
908 long getStreamLatency( void );
910 // This function is intended for internal use only. It must be
911 // public because it is called by the internal callback handler,
912 // which is not a member of RtAudio. External use of this function
913 // will most likely produce highly undesireable results!
914 void callbackEvent( void );
920 long duplexPrerollBytes;
921 std::vector<struct DsDevice> dsDevices;
922 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
923 unsigned int firstChannel, unsigned int sampleRate,
924 RtAudioFormat format, unsigned int *bufferSize,
925 RtAudio::StreamOptions *options );
930 #if defined(__LINUX_ALSA__)
932 class RtApiAlsa: public RtApi
938 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; }
939 unsigned int getDeviceCount( void );
940 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
941 void closeStream( void );
942 void startStream( void );
943 void stopStream( void );
944 void abortStream( void );
946 // This function is intended for internal use only. It must be
947 // public because it is called by the internal callback handler,
948 // which is not a member of RtAudio. External use of this function
949 // will most likely produce highly undesireable results!
950 void callbackEvent( void );
954 std::vector<RtAudio::DeviceInfo> devices_;
955 void saveDeviceInfo( void );
956 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
957 unsigned int firstChannel, unsigned int sampleRate,
958 RtAudioFormat format, unsigned int *bufferSize,
959 RtAudio::StreamOptions *options );
964 #if defined(__LINUX_PULSE__)
966 class RtApiPulse: public RtApi
970 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_PULSE; }
971 unsigned int getDeviceCount( void );
972 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
973 void closeStream( void );
974 void startStream( void );
975 void stopStream( void );
976 void abortStream( void );
978 // This function is intended for internal use only. It must be
979 // public because it is called by the internal callback handler,
980 // which is not a member of RtAudio. External use of this function
981 // will most likely produce highly undesireable results!
982 void callbackEvent( void );
986 std::vector<RtAudio::DeviceInfo> devices_;
987 void saveDeviceInfo( void );
988 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
989 unsigned int firstChannel, unsigned int sampleRate,
990 RtAudioFormat format, unsigned int *bufferSize,
991 RtAudio::StreamOptions *options );
996 #if defined(__LINUX_OSS__)
998 class RtApiOss: public RtApi
1004 RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; }
1005 unsigned int getDeviceCount( void );
1006 RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
1007 void closeStream( void );
1008 void startStream( void );
1009 void stopStream( void );
1010 void abortStream( void );
1012 // This function is intended for internal use only. It must be
1013 // public because it is called by the internal callback handler,
1014 // which is not a member of RtAudio. External use of this function
1015 // will most likely produce highly undesireable results!
1016 void callbackEvent( void );
1020 bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
1021 unsigned int firstChannel, unsigned int sampleRate,
1022 RtAudioFormat format, unsigned int *bufferSize,
1023 RtAudio::StreamOptions *options );
1028 #if defined(__RTAUDIO_DUMMY__)
1030 class RtApiDummy: public RtApi
1034 RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtError::WARNING ); }
1035 RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; }
1036 unsigned int getDeviceCount( void ) { return 0; }
1037 RtAudio::DeviceInfo getDeviceInfo( unsigned int /*device*/ ) { RtAudio::DeviceInfo info; return info; }
1038 void closeStream( void ) {}
1039 void startStream( void ) {}
1040 void stopStream( void ) {}
1041 void abortStream( void ) {}
1045 bool probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
1046 unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
1047 RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
1048 RtAudio::StreamOptions * /*options*/ ) { return false; }
1053 /************************************************************************/
1055 \brief Exception handling class for RtAudio & RtMidi.
1057 The RtError class is quite simple but it does allow errors to be
1058 "caught" by RtError::Type. See the RtAudio and RtMidi
1059 documentation to know which methods can throw an RtError.
1062 /************************************************************************/
1064 class RtAudioError : public std::exception
1067 //! Defined RtAudioError types.
1069 WARNING, /*!< A non-critical error. */
1070 DEBUG_WARNING, /*!< A non-critical error which might be useful for debugging. */
1071 UNSPECIFIED, /*!< The default, unspecified error type. */
1072 NO_DEVICES_FOUND, /*!< No devices found on system. */
1073 INVALID_DEVICE, /*!< An invalid device ID was specified. */
1074 MEMORY_ERROR, /*!< An error occured during memory allocation. */
1075 INVALID_PARAMETER, /*!< An invalid parameter was specified to a function. */
1076 INVALID_USE, /*!< The function was called incorrectly. */
1077 DRIVER_ERROR, /*!< A system driver error occured. */
1078 SYSTEM_ERROR, /*!< A system error occured. */
1079 THREAD_ERROR /*!< A thread error occured. */
1082 //! The constructor.
1083 RtAudioError( const std::string& message, Type type = RtAudioError::UNSPECIFIED ) throw() : message_(message), type_(type) {}
1086 virtual ~RtAudioError( void ) throw() {}
1088 //! Prints thrown error message to stderr.
1089 virtual void printMessage( void ) const throw() { std::cerr << '\n' << message_ << "\n\n"; }
1091 //! Returns the thrown error message type.
1092 virtual const Type& getType(void) const throw() { return type_; }
1094 //! Returns the thrown error message string.
1095 virtual const std::string& getMessage(void) const throw() { return message_; }
1097 //! Returns the thrown error message as a c-style string.
1098 virtual const char* what( void ) const throw() { return message_.c_str(); }
1101 std::string message_;
1109 // Indentation settings for Vim and Emacs
1112 // c-basic-offset: 2
1113 // indent-tabs-mode: nil
1116 // vim: et sts=2 sw=2