Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1015 lines
41KB

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