Various changes in preparation for release 4.0.8
[rtaudio-cdist.git] / RtAudio.h
1 /************************************************************************/
2 /*! \class RtAudio
3     \brief Realtime audio i/o C++ classes.
4
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.
9
10     RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
11
12     RtAudio: realtime audio i/o C++ classes
13     Copyright (c) 2001-2011 Gary P. Scavone
14
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:
22
23     The above copyright notice and this permission notice shall be
24     included in all copies or substantial portions of the Software.
25
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.
30
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.
38 */
39 /************************************************************************/
40
41 /*!
42   \file RtAudio.h
43  */
44
45 // RtAudio: Version 4.0.8
46
47 #ifndef __RTAUDIO_H
48 #define __RTAUDIO_H
49
50 #include <string>
51 #include <vector>
52 #include "RtError.h"
53
54 /*! \typedef typedef unsigned long RtAudioFormat;
55     \brief RtAudio data format type.
56
57     Support for signed integers and floats.  Audio data fed to/from an
58     RtAudio stream is assumed to ALWAYS be in host byte order.  The
59     internal routines will automatically take care of any necessary
60     byte-swapping between the host format and the soundcard.  Thus,
61     endian-ness is not a concern in the following format definitions.
62     Note that 24-bit data is expected to be encapsulated in a 32-bit
63     format.
64
65     - \e RTAUDIO_SINT8:   8-bit signed integer.
66     - \e RTAUDIO_SINT16:  16-bit signed integer.
67     - \e RTAUDIO_SINT24:  Lower 3 bytes of 32-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.
71 */
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;   // Lower 3 bytes of 32-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.
79
80 /*! \typedef typedef unsigned long RtAudioStreamFlags;
81     \brief RtAudio stream option flags.
82
83     The following flags can be OR'ed together to allow a client to
84     make changes to the default stream behavior:
85
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
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).
100
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
108     performance.
109
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.
113
114     If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt 
115     to select realtime scheduling (round-robin) for the callback thread.
116 */
117 typedef unsigned int RtAudioStreamFlags;
118 static const RtAudioStreamFlags RTAUDIO_NONINTERLEAVED = 0x1;    // Use non-interleaved buffers (default = interleaved).
119 static const RtAudioStreamFlags RTAUDIO_MINIMIZE_LATENCY = 0x2;  // Attempt to set stream parameters for lowest possible latency.
120 static const RtAudioStreamFlags RTAUDIO_HOG_DEVICE = 0x4;        // Attempt grab device and prevent use by others.
121 static const RtAudioStreamFlags RTAUDIO_SCHEDULE_REALTIME = 0x8; // Try to select realtime scheduling for callback thread.
122
123 /*! \typedef typedef unsigned long RtAudioStreamStatus;
124     \brief RtAudio stream status (over- or underflow) flags.
125
126     Notification of a stream over- or underflow is indicated by a
127     non-zero stream \c status argument in the RtAudioCallback function.
128     The stream status can be one of the following two options,
129     depending on whether the stream is open for output and/or input:
130
131     - \e RTAUDIO_INPUT_OVERFLOW:   Input data was discarded because of an overflow condition at the driver.
132     - \e RTAUDIO_OUTPUT_UNDERFLOW: The output buffer ran low, likely producing a break in the output sound.
133 */
134 typedef unsigned int RtAudioStreamStatus;
135 static const RtAudioStreamStatus RTAUDIO_INPUT_OVERFLOW = 0x1;    // Input data was discarded because of an overflow condition at the driver.
136 static const RtAudioStreamStatus RTAUDIO_OUTPUT_UNDERFLOW = 0x2;  // The output buffer ran low, likely causing a gap in the output sound.
137
138 //! RtAudio callback function prototype.
139 /*!
140    All RtAudio clients must create a function of type RtAudioCallback
141    to read and/or write data from/to the audio stream.  When the
142    underlying audio system is ready for new input or output data, this
143    function will be invoked.
144
145    \param outputBuffer For output (or duplex) streams, the client
146           should write \c nFrames of audio sample frames into this
147           buffer.  This argument should be recast to the datatype
148           specified when the stream was opened.  For input-only
149           streams, this argument will be NULL.
150
151    \param inputBuffer For input (or duplex) streams, this buffer will
152           hold \c nFrames of input audio sample frames.  This
153           argument should be recast to the datatype specified when the
154           stream was opened.  For output-only streams, this argument
155           will be NULL.
156
157    \param nFrames The number of sample frames of input or output
158           data in the buffers.  The actual buffer size in bytes is
159           dependent on the data type and number of channels in use.
160
161    \param streamTime The number of seconds that have elapsed since the
162           stream was started.
163
164    \param status If non-zero, this argument indicates a data overflow
165           or underflow condition for the stream.  The particular
166           condition can be determined by comparison with the
167           RtAudioStreamStatus flags.
168
169    \param userData A pointer to optional data provided by the client
170           when opening the stream (default = NULL).
171
172    To continue normal stream operation, the RtAudioCallback function
173    should return a value of zero.  To stop the stream and drain the
174    output buffer, the function should return a value of one.  To abort
175    the stream immediately, the client should return a value of two.
176  */
177 typedef int (*RtAudioCallback)( void *outputBuffer, void *inputBuffer,
178                                 unsigned int nFrames,
179                                 double streamTime,
180                                 RtAudioStreamStatus status,
181                                 void *userData );
182
183
184 // **************************************************************** //
185 //
186 // RtAudio class declaration.
187 //
188 // RtAudio is a "controller" used to select an available audio i/o
189 // interface.  It presents a common API for the user to call but all
190 // functionality is implemented by the class RtApi and its
191 // subclasses.  RtAudio creates an instance of an RtApi subclass
192 // based on the user's API choice.  If no choice is made, RtAudio
193 // attempts to make a "logical" API selection.
194 //
195 // **************************************************************** //
196
197 class RtApi;
198
199 class RtAudio
200 {
201  public:
202
203   //! Audio API specifier arguments.
204   enum Api {
205     UNSPECIFIED,    /*!< Search for a working compiled API. */
206     LINUX_ALSA,     /*!< The Advanced Linux Sound Architecture API. */
207     LINUX_OSS,      /*!< The Linux Open Sound System API. */
208     UNIX_JACK,      /*!< The Jack Low-Latency Audio Server API. */
209     MACOSX_CORE,    /*!< Macintosh OS-X Core Audio API. */
210     WINDOWS_ASIO,   /*!< The Steinberg Audio Stream I/O API. */
211     WINDOWS_DS,     /*!< The Microsoft Direct Sound API. */
212     RTAUDIO_DUMMY   /*!< A compilable but non-functional API. */
213   };
214
215   //! The public device information structure for returning queried values.
216   struct DeviceInfo {
217     bool probed;                  /*!< true if the device capabilities were successfully probed. */
218     std::string name;             /*!< Character string device identifier. */
219     unsigned int outputChannels;  /*!< Maximum output channels supported by device. */
220     unsigned int inputChannels;   /*!< Maximum input channels supported by device. */
221     unsigned int duplexChannels;  /*!< Maximum simultaneous input/output channels supported by device. */
222     bool isDefaultOutput;         /*!< true if this is the default output device. */
223     bool isDefaultInput;          /*!< true if this is the default input device. */
224     std::vector<unsigned int> sampleRates; /*!< Supported sample rates (queried from list of standard rates). */
225     RtAudioFormat nativeFormats;  /*!< Bit mask of supported data formats. */
226
227     // Default constructor.
228     DeviceInfo()
229       :probed(false), outputChannels(0), inputChannels(0), duplexChannels(0),
230        isDefaultOutput(false), isDefaultInput(false), nativeFormats(0) {}
231   };
232
233   //! The structure for specifying input or ouput stream parameters.
234   struct StreamParameters {
235     unsigned int deviceId;     /*!< Device index (0 to getDeviceCount() - 1). */
236     unsigned int nChannels;    /*!< Number of channels. */
237     unsigned int firstChannel; /*!< First channel index on device (default = 0). */
238
239     // Default constructor.
240     StreamParameters()
241       : deviceId(0), nChannels(0), firstChannel(0) {}
242   };
243
244   //! The structure for specifying stream options.
245   /*!
246     The following flags can be OR'ed together to allow a client to
247     make changes to the default stream behavior:
248
249     - \e RTAUDIO_NONINTERLEAVED:    Use non-interleaved buffers (default = interleaved).
250     - \e RTAUDIO_MINIMIZE_LATENCY:  Attempt to set stream parameters for lowest possible latency.
251     - \e RTAUDIO_HOG_DEVICE:        Attempt grab device for exclusive use.
252     - \e RTAUDIO_SCHEDULE_REALTIME: Attempt to select realtime scheduling for callback thread.
253
254     By default, RtAudio streams pass and receive audio data from the
255     client in an interleaved format.  By passing the
256     RTAUDIO_NONINTERLEAVED flag to the openStream() function, audio
257     data will instead be presented in non-interleaved buffers.  In
258     this case, each buffer argument in the RtAudioCallback function
259     will point to a single array of data, with \c nFrames samples for
260     each channel concatenated back-to-back.  For example, the first
261     sample of data for the second channel would be located at index \c
262     nFrames (assuming the \c buffer pointer was recast to the correct
263     data type for the stream).
264
265     Certain audio APIs offer a number of parameters that influence the
266     I/O latency of a stream.  By default, RtAudio will attempt to set
267     these parameters internally for robust (glitch-free) performance
268     (though some APIs, like Windows Direct Sound, make this difficult).
269     By passing the RTAUDIO_MINIMIZE_LATENCY flag to the openStream()
270     function, internal stream settings will be influenced in an attempt
271     to minimize stream latency, though possibly at the expense of stream
272     performance.
273
274     If the RTAUDIO_HOG_DEVICE flag is set, RtAudio will attempt to
275     open the input and/or output stream device(s) for exclusive use.
276     Note that this is not possible with all supported audio APIs.
277
278     If the RTAUDIO_SCHEDULE_REALTIME flag is set, RtAudio will attempt 
279     to select realtime scheduling (round-robin) for the callback thread.
280     The \c priority parameter will only be used if the RTAUDIO_SCHEDULE_REALTIME
281     flag is set. It defines the thread's realtime priority. 
282
283     The \c numberOfBuffers parameter can be used to control stream
284     latency in the Windows DirectSound, Linux OSS, and Linux Alsa APIs
285     only.  A value of two is usually the smallest allowed.  Larger
286     numbers can potentially result in more robust stream performance,
287     though likely at the cost of stream latency.  The value set by the
288     user is replaced during execution of the RtAudio::openStream()
289     function by the value actually used by the system.
290
291     The \c streamName parameter can be used to set the client name
292     when using the Jack API.  By default, the client name is set to
293     RtApiJack.  However, if you wish to create multiple instances of
294     RtAudio with Jack, each instance must have a unique client name.
295   */
296   struct StreamOptions {
297     RtAudioStreamFlags flags;      /*!< A bit-mask of stream flags (RTAUDIO_NONINTERLEAVED, RTAUDIO_MINIMIZE_LATENCY, RTAUDIO_HOG_DEVICE). */
298     unsigned int numberOfBuffers;  /*!< Number of stream buffers. */
299     std::string streamName;        /*!< A stream name (currently used only in Jack). */
300     int priority;                  /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
301
302     // Default constructor.
303     StreamOptions()
304     : flags(0), numberOfBuffers(0), priority(0) {}
305   };
306
307   //! A static function to determine the available compiled audio APIs.
308   /*!
309     The values returned in the std::vector can be compared against
310     the enumerated list values.  Note that there can be more than one
311     API compiled for certain operating systems.
312   */
313   static void getCompiledApi( std::vector<RtAudio::Api> &apis ) throw();
314
315   //! The class constructor.
316   /*!
317     The constructor performs minor initialization tasks.  No exceptions
318     can be thrown.
319
320     If no API argument is specified and multiple API support has been
321     compiled, the default order of use is JACK, ALSA, OSS (Linux
322     systems) and ASIO, DS (Windows systems).
323   */
324   RtAudio( RtAudio::Api api=UNSPECIFIED ) throw();
325
326   //! The destructor.
327   /*!
328     If a stream is running or open, it will be stopped and closed
329     automatically.
330   */
331   ~RtAudio() throw();
332
333   //! Returns the audio API specifier for the current instance of RtAudio.
334   RtAudio::Api getCurrentApi( void ) throw();
335
336   //! A public function that queries for the number of audio devices available.
337   /*!
338     This function performs a system query of available devices each time it
339     is called, thus supporting devices connected \e after instantiation. If
340     a system error occurs during processing, a warning will be issued. 
341   */
342   unsigned int getDeviceCount( void ) throw();
343
344   //! Return an RtAudio::DeviceInfo structure for a specified device number.
345   /*!
346
347     Any device integer between 0 and getDeviceCount() - 1 is valid.
348     If an invalid argument is provided, an RtError (type = INVALID_USE)
349     will be thrown.  If a device is busy or otherwise unavailable, the
350     structure member "probed" will have a value of "false" and all
351     other members are undefined.  If the specified device is the
352     current default input or output device, the corresponding
353     "isDefault" member will have a value of "true".
354   */
355   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
356
357   //! A function that returns the index of the default output device.
358   /*!
359     If the underlying audio API does not provide a "default
360     device", or if no devices are available, the return value will be
361     0.  Note that this is a valid device identifier and it is the
362     client's responsibility to verify that a device is available
363     before attempting to open a stream.
364   */
365   unsigned int getDefaultOutputDevice( void ) throw();
366
367   //! A function that returns the index of the default input device.
368   /*!
369     If the underlying audio API does not provide a "default
370     device", or if no devices are available, the return value will be
371     0.  Note that this is a valid device identifier and it is the
372     client's responsibility to verify that a device is available
373     before attempting to open a stream.
374   */
375   unsigned int getDefaultInputDevice( void ) throw();
376
377   //! A public function for opening a stream with the specified parameters.
378   /*!
379     An RtError (type = SYSTEM_ERROR) is thrown if a stream cannot be
380     opened with the specified parameters or an error occurs during
381     processing.  An RtError (type = INVALID_USE) is thrown if any
382     invalid device ID or channel number parameters are specified.
383
384     \param outputParameters Specifies output stream parameters to use
385            when opening a stream, including a device ID, number of channels,
386            and starting channel number.  For input-only streams, this
387            argument should be NULL.  The device ID is an index value between
388            0 and getDeviceCount() - 1.
389     \param inputParameters Specifies input stream parameters to use
390            when opening a stream, including a device ID, number of channels,
391            and starting channel number.  For output-only streams, this
392            argument should be NULL.  The device ID is an index value between
393            0 and getDeviceCount() - 1.
394     \param format An RtAudioFormat specifying the desired sample data format.
395     \param sampleRate The desired sample rate (sample frames per second).
396     \param *bufferFrames A pointer to a value indicating the desired
397            internal buffer size in sample frames.  The actual value
398            used by the device is returned via the same pointer.  A
399            value of zero can be specified, in which case the lowest
400            allowable value is determined.
401     \param callback A client-defined function that will be invoked
402            when input data is available and/or output data is needed.
403     \param userData An optional pointer to data that can be accessed
404            from within the callback function.
405     \param options An optional pointer to a structure containing various
406            global stream options, including a list of OR'ed RtAudioStreamFlags
407            and a suggested number of stream buffers that can be used to 
408            control stream latency.  More buffers typically result in more
409            robust performance, though at a cost of greater latency.  If a
410            value of zero is specified, a system-specific median value is
411            chosen.  If the RTAUDIO_MINIMIZE_LATENCY flag bit is set, the
412            lowest allowable value is used.  The actual value used is
413            returned via the structure argument.  The parameter is API dependent.
414   */
415   void openStream( RtAudio::StreamParameters *outputParameters,
416                    RtAudio::StreamParameters *inputParameters,
417                    RtAudioFormat format, unsigned int sampleRate,
418                    unsigned int *bufferFrames, RtAudioCallback callback,
419                    void *userData = NULL, RtAudio::StreamOptions *options = NULL );
420
421   //! A function that closes a stream and frees any associated stream memory.
422   /*!
423     If a stream is not open, this function issues a warning and
424     returns (no exception is thrown).
425   */
426   void closeStream( void ) throw();
427
428   //! A function that starts a stream.
429   /*!
430     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
431     during processing.  An RtError (type = INVALID_USE) is thrown if a
432     stream is not open.  A warning is issued if the stream is already
433     running.
434   */
435   void startStream( void );
436
437   //! Stop a stream, allowing any samples remaining in the output queue to be played.
438   /*!
439     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
440     during processing.  An RtError (type = INVALID_USE) is thrown if a
441     stream is not open.  A warning is issued if the stream is already
442     stopped.
443   */
444   void stopStream( void );
445
446   //! Stop a stream, discarding any samples remaining in the input/output queue.
447   /*!
448     An RtError (type = SYSTEM_ERROR) is thrown if an error occurs
449     during processing.  An RtError (type = INVALID_USE) is thrown if a
450     stream is not open.  A warning is issued if the stream is already
451     stopped.
452   */
453   void abortStream( void );
454
455   //! Returns true if a stream is open and false if not.
456   bool isStreamOpen( void ) const throw();
457
458   //! Returns true if the stream is running and false if it is stopped or not open.
459   bool isStreamRunning( void ) const throw();
460
461   //! Returns the number of elapsed seconds since the stream was started.
462   /*!
463     If a stream is not open, an RtError (type = INVALID_USE) will be thrown.
464   */
465   double getStreamTime( void );
466
467   //! Returns the internal stream latency in sample frames.
468   /*!
469     The stream latency refers to delay in audio input and/or output
470     caused by internal buffering by the audio system and/or hardware.
471     For duplex streams, the returned value will represent the sum of
472     the input and output latencies.  If a stream is not open, an
473     RtError (type = INVALID_USE) will be thrown.  If the API does not
474     report latency, the return value will be zero.
475   */
476   long getStreamLatency( void );
477
478  //! Returns actual sample rate in use by the stream.
479  /*!
480    On some systems, the sample rate used may be slightly different
481    than that specified in the stream parameters.  If a stream is not
482    open, an RtError (type = INVALID_USE) will be thrown.
483  */
484   unsigned int getStreamSampleRate( void );
485
486   //! Specify whether warning messages should be printed to stderr.
487   void showWarnings( bool value = true ) throw();
488
489  protected:
490
491   void openRtApi( RtAudio::Api api );
492   RtApi *rtapi_;
493 };
494
495 // Operating system dependent thread functionality.
496 #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
497   #include <windows.h>
498   #include <process.h>
499
500   typedef unsigned long ThreadHandle;
501   typedef CRITICAL_SECTION StreamMutex;
502
503 #elif defined(__LINUX_ALSA__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
504   // Using pthread library for various flavors of unix.
505   #include <pthread.h>
506
507   typedef pthread_t ThreadHandle;
508   typedef pthread_mutex_t StreamMutex;
509
510 #else // Setup for "dummy" behavior
511
512   #define __RTAUDIO_DUMMY__
513   typedef int ThreadHandle;
514   typedef int StreamMutex;
515
516 #endif
517
518 // This global structure type is used to pass callback information
519 // between the private RtAudio stream structure and global callback
520 // handling functions.
521 struct CallbackInfo {
522   void *object;    // Used as a "this" pointer.
523   ThreadHandle thread;
524   void *callback;
525   void *userData;
526   void *apiInfo;   // void pointer for API specific callback information
527   bool isRunning;
528
529   // Default constructor.
530   CallbackInfo()
531     :object(0), callback(0), userData(0), apiInfo(0), isRunning(false) {}
532 };
533
534 // **************************************************************** //
535 //
536 // RtApi class declaration.
537 //
538 // Subclasses of RtApi contain all API- and OS-specific code necessary
539 // to fully implement the RtAudio API.
540 //
541 // Note that RtApi is an abstract base class and cannot be
542 // explicitly instantiated.  The class RtAudio will create an
543 // instance of an RtApi subclass (RtApiOss, RtApiAlsa,
544 // RtApiJack, RtApiCore, RtApiAl, RtApiDs, or RtApiAsio).
545 //
546 // **************************************************************** //
547
548 #if defined( HAVE_GETTIMEOFDAY )
549   #include <sys/time.h>
550 #endif
551
552 #include <sstream>
553
554 class RtApi
555 {
556 public:
557
558   RtApi();
559   virtual ~RtApi();
560   virtual RtAudio::Api getCurrentApi( void ) = 0;
561   virtual unsigned int getDeviceCount( void ) = 0;
562   virtual RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) = 0;
563   virtual unsigned int getDefaultInputDevice( void );
564   virtual unsigned int getDefaultOutputDevice( void );
565   void openStream( RtAudio::StreamParameters *outputParameters,
566                    RtAudio::StreamParameters *inputParameters,
567                    RtAudioFormat format, unsigned int sampleRate,
568                    unsigned int *bufferFrames, RtAudioCallback callback,
569                    void *userData, RtAudio::StreamOptions *options );
570   virtual void closeStream( void );
571   virtual void startStream( void ) = 0;
572   virtual void stopStream( void ) = 0;
573   virtual void abortStream( void ) = 0;
574   long getStreamLatency( void );
575   unsigned int getStreamSampleRate( void );
576   virtual double getStreamTime( void );
577   bool isStreamOpen( void ) const { return stream_.state != STREAM_CLOSED; };
578   bool isStreamRunning( void ) const { return stream_.state == STREAM_RUNNING; };
579   void showWarnings( bool value ) { showWarnings_ = value; };
580
581
582 protected:
583
584   static const unsigned int MAX_SAMPLE_RATES;
585   static const unsigned int SAMPLE_RATES[];
586
587   enum { FAILURE, SUCCESS };
588
589   enum StreamState {
590     STREAM_STOPPED,
591     STREAM_RUNNING,
592     STREAM_CLOSED = -50
593   };
594
595   enum StreamMode {
596     OUTPUT,
597     INPUT,
598     DUPLEX,
599     UNINITIALIZED = -75
600   };
601
602   // A protected structure used for buffer conversion.
603   struct ConvertInfo {
604     int channels;
605     int inJump, outJump;
606     RtAudioFormat inFormat, outFormat;
607     std::vector<int> inOffset;
608     std::vector<int> outOffset;
609   };
610
611   // A protected structure for audio streams.
612   struct RtApiStream {
613     unsigned int device[2];    // Playback and record, respectively.
614     void *apiHandle;           // void pointer for API specific stream handle information
615     StreamMode mode;           // OUTPUT, INPUT, or DUPLEX.
616     StreamState state;         // STOPPED, RUNNING, or CLOSED
617     char *userBuffer[2];       // Playback and record, respectively.
618     char *deviceBuffer;
619     bool doConvertBuffer[2];   // Playback and record, respectively.
620     bool userInterleaved;
621     bool deviceInterleaved[2]; // Playback and record, respectively.
622     bool doByteSwap[2];        // Playback and record, respectively.
623     unsigned int sampleRate;
624     unsigned int bufferSize;
625     unsigned int nBuffers;
626     unsigned int nUserChannels[2];    // Playback and record, respectively.
627     unsigned int nDeviceChannels[2];  // Playback and record channels, respectively.
628     unsigned int channelOffset[2];    // Playback and record, respectively.
629     unsigned long latency[2];         // Playback and record, respectively.
630     RtAudioFormat userFormat;
631     RtAudioFormat deviceFormat[2];    // Playback and record, respectively.
632     StreamMutex mutex;
633     CallbackInfo callbackInfo;
634     ConvertInfo convertInfo[2];
635     double streamTime;         // Number of elapsed seconds since the stream started.
636
637 #if defined(HAVE_GETTIMEOFDAY)
638     struct timeval lastTickTimestamp;
639 #endif
640
641     RtApiStream()
642       :apiHandle(0), deviceBuffer(0) { device[0] = 11111; device[1] = 11111; }
643   };
644
645   typedef signed short Int16;
646   typedef signed int Int32;
647   typedef float Float32;
648   typedef double Float64;
649
650   std::ostringstream errorStream_;
651   std::string errorText_;
652   bool showWarnings_;
653   RtApiStream stream_;
654
655   /*!
656     Protected, api-specific method that attempts to open a device
657     with the given parameters.  This function MUST be implemented by
658     all subclasses.  If an error is encountered during the probe, a
659     "warning" message is reported and FAILURE is returned. A
660     successful probe is indicated by a return value of SUCCESS.
661   */
662   virtual bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
663                                 unsigned int firstChannel, unsigned int sampleRate,
664                                 RtAudioFormat format, unsigned int *bufferSize,
665                                 RtAudio::StreamOptions *options );
666
667   //! A protected function used to increment the stream time.
668   void tickStreamTime( void );
669
670   //! Protected common method to clear an RtApiStream structure.
671   void clearStreamInfo();
672
673   /*!
674     Protected common method that throws an RtError (type =
675     INVALID_USE) if a stream is not open.
676   */
677   void verifyStream( void );
678
679   //! Protected common error method to allow global control over error handling.
680   void error( RtError::Type type );
681
682   /*!
683     Protected method used to perform format, channel number, and/or interleaving
684     conversions between the user and device buffers.
685   */
686   void convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info );
687
688   //! Protected common method used to perform byte-swapping on buffers.
689   void byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format );
690
691   //! Protected common method that returns the number of bytes for a given format.
692   unsigned int formatBytes( RtAudioFormat format );
693
694   //! Protected common method that sets up the parameters for buffer conversion.
695   void setConvertInfo( StreamMode mode, unsigned int firstChannel );
696 };
697
698 // **************************************************************** //
699 //
700 // Inline RtAudio definitions.
701 //
702 // **************************************************************** //
703
704 inline RtAudio::Api RtAudio :: getCurrentApi( void ) throw() { return rtapi_->getCurrentApi(); }
705 inline unsigned int RtAudio :: getDeviceCount( void ) throw() { return rtapi_->getDeviceCount(); }
706 inline RtAudio::DeviceInfo RtAudio :: getDeviceInfo( unsigned int device ) { return rtapi_->getDeviceInfo( device ); }
707 inline unsigned int RtAudio :: getDefaultInputDevice( void ) throw() { return rtapi_->getDefaultInputDevice(); }
708 inline unsigned int RtAudio :: getDefaultOutputDevice( void ) throw() { return rtapi_->getDefaultOutputDevice(); }
709 inline void RtAudio :: closeStream( void ) throw() { return rtapi_->closeStream(); }
710 inline void RtAudio :: startStream( void ) { return rtapi_->startStream(); }
711 inline void RtAudio :: stopStream( void )  { return rtapi_->stopStream(); }
712 inline void RtAudio :: abortStream( void ) { return rtapi_->abortStream(); }
713 inline bool RtAudio :: isStreamOpen( void ) const throw() { return rtapi_->isStreamOpen(); }
714 inline bool RtAudio :: isStreamRunning( void ) const throw() { return rtapi_->isStreamRunning(); }
715 inline long RtAudio :: getStreamLatency( void ) { return rtapi_->getStreamLatency(); }
716 inline unsigned int RtAudio :: getStreamSampleRate( void ) { return rtapi_->getStreamSampleRate(); };
717 inline double RtAudio :: getStreamTime( void ) { return rtapi_->getStreamTime(); }
718 inline void RtAudio :: showWarnings( bool value ) throw() { rtapi_->showWarnings( value ); }
719
720 // RtApi Subclass prototypes.
721
722 #if defined(__MACOSX_CORE__)
723
724 #include <CoreAudio/AudioHardware.h>
725
726 class RtApiCore: public RtApi
727 {
728 public:
729
730   RtApiCore();
731   ~RtApiCore();
732   RtAudio::Api getCurrentApi( void ) { return RtAudio::MACOSX_CORE; };
733   unsigned int getDeviceCount( void );
734   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
735   unsigned int getDefaultOutputDevice( void );
736   unsigned int getDefaultInputDevice( void );
737   void closeStream( void );
738   void startStream( void );
739   void stopStream( void );
740   void abortStream( void );
741   long getStreamLatency( void );
742
743   // This function is intended for internal use only.  It must be
744   // public because it is called by the internal callback handler,
745   // which is not a member of RtAudio.  External use of this function
746   // will most likely produce highly undesireable results!
747   bool callbackEvent( AudioDeviceID deviceId,
748                       const AudioBufferList *inBufferList,
749                       const AudioBufferList *outBufferList );
750
751   private:
752
753   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
754                         unsigned int firstChannel, unsigned int sampleRate,
755                         RtAudioFormat format, unsigned int *bufferSize,
756                         RtAudio::StreamOptions *options );
757   static const char* getErrorCode( OSStatus code );
758 };
759
760 #endif
761
762 #if defined(__UNIX_JACK__)
763
764 class RtApiJack: public RtApi
765 {
766 public:
767
768   RtApiJack();
769   ~RtApiJack();
770   RtAudio::Api getCurrentApi( void ) { return RtAudio::UNIX_JACK; };
771   unsigned int getDeviceCount( void );
772   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
773   void closeStream( void );
774   void startStream( void );
775   void stopStream( void );
776   void abortStream( void );
777   long getStreamLatency( void );
778
779   // This function is intended for internal use only.  It must be
780   // public because it is called by the internal callback handler,
781   // which is not a member of RtAudio.  External use of this function
782   // will most likely produce highly undesireable results!
783   bool callbackEvent( unsigned long nframes );
784
785   private:
786
787   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
788                         unsigned int firstChannel, unsigned int sampleRate,
789                         RtAudioFormat format, unsigned int *bufferSize,
790                         RtAudio::StreamOptions *options );
791 };
792
793 #endif
794
795 #if defined(__WINDOWS_ASIO__)
796
797 class RtApiAsio: public RtApi
798 {
799 public:
800
801   RtApiAsio();
802   ~RtApiAsio();
803   RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_ASIO; };
804   unsigned int getDeviceCount( void );
805   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
806   void closeStream( void );
807   void startStream( void );
808   void stopStream( void );
809   void abortStream( void );
810   long getStreamLatency( void );
811
812   // This function is intended for internal use only.  It must be
813   // public because it is called by the internal callback handler,
814   // which is not a member of RtAudio.  External use of this function
815   // will most likely produce highly undesireable results!
816   bool callbackEvent( long bufferIndex );
817
818   private:
819
820   std::vector<RtAudio::DeviceInfo> devices_;
821   void saveDeviceInfo( void );
822   bool coInitialized_;
823   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
824                         unsigned int firstChannel, unsigned int sampleRate,
825                         RtAudioFormat format, unsigned int *bufferSize,
826                         RtAudio::StreamOptions *options );
827 };
828
829 #endif
830
831 #if defined(__WINDOWS_DS__)
832
833 class RtApiDs: public RtApi
834 {
835 public:
836
837   RtApiDs();
838   ~RtApiDs();
839   RtAudio::Api getCurrentApi( void ) { return RtAudio::WINDOWS_DS; };
840   unsigned int getDeviceCount( void );
841   unsigned int getDefaultOutputDevice( void );
842   unsigned int getDefaultInputDevice( void );
843   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
844   void closeStream( void );
845   void startStream( void );
846   void stopStream( void );
847   void abortStream( void );
848   long getStreamLatency( void );
849
850   // This function is intended for internal use only.  It must be
851   // public because it is called by the internal callback handler,
852   // which is not a member of RtAudio.  External use of this function
853   // will most likely produce highly undesireable results!
854   void callbackEvent( void );
855
856   private:
857
858   bool coInitialized_;
859   bool buffersRolling;
860   long duplexPrerollBytes;
861   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
862                         unsigned int firstChannel, unsigned int sampleRate,
863                         RtAudioFormat format, unsigned int *bufferSize,
864                         RtAudio::StreamOptions *options );
865 };
866
867 #endif
868
869 #if defined(__LINUX_ALSA__)
870
871 class RtApiAlsa: public RtApi
872 {
873 public:
874
875   RtApiAlsa();
876   ~RtApiAlsa();
877   RtAudio::Api getCurrentApi() { return RtAudio::LINUX_ALSA; };
878   unsigned int getDeviceCount( void );
879   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
880   void closeStream( void );
881   void startStream( void );
882   void stopStream( void );
883   void abortStream( void );
884
885   // This function is intended for internal use only.  It must be
886   // public because it is called by the internal callback handler,
887   // which is not a member of RtAudio.  External use of this function
888   // will most likely produce highly undesireable results!
889   void callbackEvent( void );
890
891   private:
892
893   std::vector<RtAudio::DeviceInfo> devices_;
894   void saveDeviceInfo( void );
895   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
896                         unsigned int firstChannel, unsigned int sampleRate,
897                         RtAudioFormat format, unsigned int *bufferSize,
898                         RtAudio::StreamOptions *options );
899 };
900
901 #endif
902
903 #if defined(__LINUX_OSS__)
904
905 class RtApiOss: public RtApi
906 {
907 public:
908
909   RtApiOss();
910   ~RtApiOss();
911   RtAudio::Api getCurrentApi() { return RtAudio::LINUX_OSS; };
912   unsigned int getDeviceCount( void );
913   RtAudio::DeviceInfo getDeviceInfo( unsigned int device );
914   void closeStream( void );
915   void startStream( void );
916   void stopStream( void );
917   void abortStream( void );
918
919   // This function is intended for internal use only.  It must be
920   // public because it is called by the internal callback handler,
921   // which is not a member of RtAudio.  External use of this function
922   // will most likely produce highly undesireable results!
923   void callbackEvent( void );
924
925   private:
926
927   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
928                         unsigned int firstChannel, unsigned int sampleRate,
929                         RtAudioFormat format, unsigned int *bufferSize,
930                         RtAudio::StreamOptions *options );
931 };
932
933 #endif
934
935 #if defined(__RTAUDIO_DUMMY__)
936
937 class RtApiDummy: public RtApi
938 {
939 public:
940
941   RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RtError::WARNING ); };
942   RtAudio::Api getCurrentApi( void ) { return RtAudio::RTAUDIO_DUMMY; };
943   unsigned int getDeviceCount( void ) { return 0; };
944   RtAudio::DeviceInfo getDeviceInfo( unsigned int device ) { RtAudio::DeviceInfo info; return info; };
945   void closeStream( void ) {};
946   void startStream( void ) {};
947   void stopStream( void ) {};
948   void abortStream( void ) {};
949
950   private:
951
952   bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, 
953                         unsigned int firstChannel, unsigned int sampleRate,
954                         RtAudioFormat format, unsigned int *bufferSize,
955                         RtAudio::StreamOptions *options ) { return false; };
956 };
957
958 #endif
959
960 #endif
961
962 // Indentation settings for Vim and Emacs
963 //
964 // Local Variables:
965 // c-basic-offset: 2
966 // indent-tabs-mode: nil
967 // End:
968 //
969 // vim: et sts=2 sw=2