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.

RtAudio.h 42KB

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