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.

435 lines
15KB

  1. /******************************************/
  2. /*
  3. RtAudio - realtime sound I/O C++ class
  4. by Gary P. Scavone, 2001-2002.
  5. */
  6. /******************************************/
  7. #if !defined(__RTAUDIO_H)
  8. #define __RTAUDIO_H
  9. #include <map>
  10. #if defined(__LINUX_ALSA__)
  11. #include <alsa/asoundlib.h>
  12. #include <pthread.h>
  13. #include <unistd.h>
  14. #define THREAD_TYPE
  15. typedef snd_pcm_t *AUDIO_HANDLE;
  16. typedef int DEVICE_ID;
  17. typedef pthread_t THREAD_HANDLE;
  18. typedef pthread_mutex_t MUTEX;
  19. #elif defined(__LINUX_OSS__)
  20. #include <pthread.h>
  21. #include <unistd.h>
  22. #define THREAD_TYPE
  23. typedef int AUDIO_HANDLE;
  24. typedef int DEVICE_ID;
  25. typedef pthread_t THREAD_HANDLE;
  26. typedef pthread_mutex_t MUTEX;
  27. #elif defined(__WINDOWS_DS__)
  28. #include <windows.h>
  29. #include <process.h>
  30. // The following struct is used to hold the extra variables
  31. // specific to the DirectSound implementation.
  32. typedef struct {
  33. void * object;
  34. void * buffer;
  35. UINT bufferPointer;
  36. } AUDIO_HANDLE;
  37. #define THREAD_TYPE __stdcall
  38. typedef LPGUID DEVICE_ID;
  39. typedef unsigned long THREAD_HANDLE;
  40. typedef CRITICAL_SECTION MUTEX;
  41. #elif defined(__IRIX_AL__)
  42. #include <dmedia/audio.h>
  43. #include <pthread.h>
  44. #include <unistd.h>
  45. #define THREAD_TYPE
  46. typedef ALport AUDIO_HANDLE;
  47. typedef int DEVICE_ID;
  48. typedef pthread_t THREAD_HANDLE;
  49. typedef pthread_mutex_t MUTEX;
  50. #endif
  51. // *************************************************** //
  52. //
  53. // RtError class declaration.
  54. //
  55. // *************************************************** //
  56. class RtError
  57. {
  58. public:
  59. enum TYPE {
  60. WARNING,
  61. DEBUG_WARNING,
  62. UNSPECIFIED,
  63. NO_DEVICES_FOUND,
  64. INVALID_DEVICE,
  65. INVALID_STREAM,
  66. MEMORY_ERROR,
  67. INVALID_PARAMETER,
  68. DRIVER_ERROR,
  69. SYSTEM_ERROR,
  70. THREAD_ERROR
  71. };
  72. protected:
  73. char error_message[256];
  74. TYPE type;
  75. public:
  76. //! The constructor.
  77. RtError(const char *p, TYPE tipe = RtError::UNSPECIFIED);
  78. //! The destructor.
  79. virtual ~RtError(void);
  80. //! Prints "thrown" error message to stdout.
  81. virtual void printMessage(void);
  82. //! Returns the "thrown" error message TYPE.
  83. virtual const TYPE& getType(void) { return type; }
  84. //! Returns the "thrown" error message string.
  85. virtual const char *getMessage(void) { return error_message; }
  86. };
  87. // *************************************************** //
  88. //
  89. // RtAudio class declaration.
  90. //
  91. // *************************************************** //
  92. class RtAudio
  93. {
  94. public:
  95. // Support for signed integers and floats. Audio data fed to/from
  96. // the tickStream() routine is assumed to ALWAYS be in host
  97. // byte order. The internal routines will automatically take care of
  98. // any necessary byte-swapping between the host format and the
  99. // soundcard. Thus, endian-ness is not a concern in the following
  100. // format definitions.
  101. typedef unsigned long RTAUDIO_FORMAT;
  102. static const RTAUDIO_FORMAT RTAUDIO_SINT8;
  103. static const RTAUDIO_FORMAT RTAUDIO_SINT16;
  104. static const RTAUDIO_FORMAT RTAUDIO_SINT24; /*!< Upper 3 bytes of 32-bit integer. */
  105. static const RTAUDIO_FORMAT RTAUDIO_SINT32;
  106. static const RTAUDIO_FORMAT RTAUDIO_FLOAT32; /*!< Normalized between plus/minus 1.0. */
  107. static const RTAUDIO_FORMAT RTAUDIO_FLOAT64; /*!< Normalized between plus/minus 1.0. */
  108. //static const int MAX_SAMPLE_RATES = 14;
  109. enum { MAX_SAMPLE_RATES = 14 };
  110. typedef int (*RTAUDIO_CALLBACK)(char *buffer, int bufferSize, void *userData);
  111. typedef struct {
  112. char name[128];
  113. DEVICE_ID id[2]; /*!< No value reported by getDeviceInfo(). */
  114. bool probed; /*!< true if the device capabilities were successfully probed. */
  115. int maxOutputChannels;
  116. int maxInputChannels;
  117. int maxDuplexChannels;
  118. int minOutputChannels;
  119. int minInputChannels;
  120. int minDuplexChannels;
  121. bool hasDuplexSupport; /*!< true if device supports duplex mode. */
  122. int nSampleRates; /*!< Number of discrete rates or -1 if range supported. */
  123. int sampleRates[MAX_SAMPLE_RATES]; /*!< Supported rates or (min, max) if range. */
  124. RTAUDIO_FORMAT nativeFormats; /*!< Bit mask of supported data formats. */
  125. } RTAUDIO_DEVICE;
  126. //! The default constructor.
  127. /*!
  128. Probes the system to make sure at least one audio
  129. input/output device is available and determines
  130. the api-specific identifier for each device found.
  131. An RtError error can be thrown if no devices are
  132. found or if a memory allocation error occurs.
  133. */
  134. RtAudio();
  135. //! A constructor which can be used to open a stream during instantiation.
  136. /*!
  137. The specified output and/or input device identifiers correspond
  138. to those enumerated via the getDeviceInfo() method. If device =
  139. 0, the default or first available devices meeting the given
  140. parameters is selected. If an output or input channel value is
  141. zero, the corresponding device value is ignored. When a stream is
  142. successfully opened, its identifier is returned via the "streamId"
  143. pointer. An RtError can be thrown if no devices are found
  144. for the given parameters, if a memory allocation error occurs, or
  145. if a driver error occurs. \sa openStream()
  146. */
  147. RtAudio(int *streamId,
  148. int outputDevice, int outputChannels,
  149. int inputDevice, int inputChannels,
  150. RTAUDIO_FORMAT format, int sampleRate,
  151. int *bufferSize, int numberOfBuffers);
  152. //! The destructor.
  153. /*!
  154. Stops and closes any open streams and devices and deallocates
  155. buffer and structure memory.
  156. */
  157. ~RtAudio();
  158. //! A public method for opening a stream with the specified parameters.
  159. /*!
  160. If successful, the opened stream ID is returned. Otherwise, an
  161. RtError is thrown.
  162. \param outputDevice: If equal to 0, the default or first device
  163. found meeting the given parameters is opened. Otherwise, the
  164. device number should correspond to one of those enumerated via
  165. the getDeviceInfo() method.
  166. \param outputChannels: The desired number of output channels. If
  167. equal to zero, the outputDevice identifier is ignored.
  168. \param inputDevice: If equal to 0, the default or first device
  169. found meeting the given parameters is opened. Otherwise, the
  170. device number should correspond to one of those enumerated via
  171. the getDeviceInfo() method.
  172. \param inputChannels: The desired number of input channels. If
  173. equal to zero, the inputDevice identifier is ignored.
  174. \param format: An RTAUDIO_FORMAT specifying the desired sample data format.
  175. \param sampleRate: The desired sample rate (sample frames per second).
  176. \param *bufferSize: A pointer value indicating the desired internal buffer
  177. size in sample frames. The actual value used by the device is
  178. returned via the same pointer. A value of zero can be specified,
  179. in which case the lowest allowable value is determined.
  180. \param numberOfBuffers: A value which can be used to help control device
  181. latency. More buffers typically result in more robust performance,
  182. though at a cost of greater latency. A value of zero can be
  183. specified, in which case the lowest allowable value is used.
  184. */
  185. int openStream(int outputDevice, int outputChannels,
  186. int inputDevice, int inputChannels,
  187. RTAUDIO_FORMAT format, int sampleRate,
  188. int *bufferSize, int numberOfBuffers);
  189. //! A public method which sets a user-defined callback function for a given stream.
  190. /*!
  191. This method assigns a callback function to a specific,
  192. previously opened stream for non-blocking stream functionality. A
  193. separate process is initiated, though the user function is called
  194. only when the stream is "running" (between calls to the
  195. startStream() and stopStream() methods, respectively). The
  196. callback process remains active for the duration of the stream and
  197. is automatically shutdown when the stream is closed (via the
  198. closeStream() method or by object destruction). The callback
  199. process can also be shutdown and the user function de-referenced
  200. through an explicit call to the cancelStreamCallback() method.
  201. Note that a single stream can use only blocking or callback
  202. functionality at the same time, though it is possible to alternate
  203. modes on the same stream through the use of the
  204. setStreamCallback() and cancelStreamCallback() methods (the
  205. blocking tickStream() method can be used before a callback is set
  206. and/or after a callback is cancelled). An RtError will be
  207. thrown for an invalid device argument.
  208. */
  209. void setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData);
  210. //! A public method which cancels a callback process and function for a given stream.
  211. /*!
  212. This method shuts down a callback process and de-references the
  213. user function for a specific stream. Callback functionality can
  214. subsequently be restarted on the stream via the
  215. setStreamCallback() method. An RtError will be thrown for an
  216. invalid device argument.
  217. */
  218. void cancelStreamCallback(int streamId);
  219. //! A public method which returns the number of audio devices found.
  220. int getDeviceCount(void);
  221. //! Fill a user-supplied RTAUDIO_DEVICE structure for a specified device.
  222. /*!
  223. Any device between 0 and getDeviceCount()-1 is valid. If a
  224. device is busy or otherwise unavailable, the structure member
  225. "probed" has a value of "false". The system default input and
  226. output devices are referenced by device identifier = 0. On
  227. systems which allow dynamic default device settings, the default
  228. devices are not identified by name (specific device enumerations
  229. are assigned device identifiers > 0). An RtError will be
  230. thrown for an invalid device argument.
  231. */
  232. void getDeviceInfo(int device, RTAUDIO_DEVICE *info);
  233. //! A public method which returns a pointer to the buffer for an open stream.
  234. /*!
  235. The user should fill and/or read the buffer data in interleaved format
  236. and then call the tickStream() method. An RtError will be
  237. thrown for an invalid stream identifier.
  238. */
  239. char * const getStreamBuffer(int streamId);
  240. //! Public method used to trigger processing of input/output data for a stream.
  241. /*!
  242. This method blocks until all buffer data is read/written. An
  243. RtError will be thrown for an invalid stream identifier or if
  244. a driver error occurs.
  245. */
  246. void tickStream(int streamId);
  247. //! Public method which closes a stream and frees any associated buffers.
  248. /*!
  249. If an invalid stream identifier is specified, this method
  250. issues a warning and returns (an RtError is not thrown).
  251. */
  252. void closeStream(int streamId);
  253. //! Public method which starts a stream.
  254. /*!
  255. An RtError will be thrown for an invalid stream identifier
  256. or if a driver error occurs.
  257. */
  258. void startStream(int streamId);
  259. //! Stop a stream, allowing any samples remaining in the queue to be played out and/or read in.
  260. /*!
  261. An RtError will be thrown for an invalid stream identifier
  262. or if a driver error occurs.
  263. */
  264. void stopStream(int streamId);
  265. //! Stop a stream, discarding any samples remaining in the input/output queue.
  266. /*!
  267. An RtError will be thrown for an invalid stream identifier
  268. or if a driver error occurs.
  269. */
  270. void abortStream(int streamId);
  271. //! Queries a stream to determine whether a call to the tickStream() method will block.
  272. /*!
  273. A return value of 0 indicates that the stream will NOT block. A positive
  274. return value indicates the number of sample frames that cannot yet be
  275. processed without blocking.
  276. */
  277. int streamWillBlock(int streamId);
  278. protected:
  279. private:
  280. static const unsigned int SAMPLE_RATES[MAX_SAMPLE_RATES];
  281. enum { FAILURE, SUCCESS };
  282. enum STREAM_MODE {
  283. PLAYBACK,
  284. RECORD,
  285. DUPLEX,
  286. UNINITIALIZED = -75
  287. };
  288. enum STREAM_STATE {
  289. STREAM_STOPPED,
  290. STREAM_RUNNING
  291. };
  292. typedef struct {
  293. int device[2]; // Playback and record, respectively.
  294. STREAM_MODE mode; // PLAYBACK, RECORD, or DUPLEX.
  295. AUDIO_HANDLE handle[2]; // Playback and record handles, respectively.
  296. STREAM_STATE state; // STOPPED or RUNNING
  297. char *userBuffer;
  298. char *deviceBuffer;
  299. bool doConvertBuffer[2]; // Playback and record, respectively.
  300. bool deInterleave[2]; // Playback and record, respectively.
  301. bool doByteSwap[2]; // Playback and record, respectively.
  302. int sampleRate;
  303. int bufferSize;
  304. int nBuffers;
  305. int nUserChannels[2]; // Playback and record, respectively.
  306. int nDeviceChannels[2]; // Playback and record channels, respectively.
  307. RTAUDIO_FORMAT userFormat;
  308. RTAUDIO_FORMAT deviceFormat[2]; // Playback and record, respectively.
  309. bool usingCallback;
  310. THREAD_HANDLE thread;
  311. MUTEX mutex;
  312. RTAUDIO_CALLBACK callback;
  313. void *userData;
  314. } RTAUDIO_STREAM;
  315. typedef signed short INT16;
  316. typedef signed int INT32;
  317. typedef float FLOAT32;
  318. typedef double FLOAT64;
  319. char message[256];
  320. int nDevices;
  321. RTAUDIO_DEVICE *devices;
  322. std::map<int, void *> streams;
  323. //! Private error method to allow global control over error handling.
  324. void error(RtError::TYPE type);
  325. /*!
  326. Private method to count the system audio devices, allocate the
  327. RTAUDIO_DEVICE structures, and probe the device capabilities.
  328. */
  329. void initialize(void);
  330. //! Private method to clear an RTAUDIO_DEVICE structure.
  331. void clearDeviceInfo(RTAUDIO_DEVICE *info);
  332. /*!
  333. Private method which attempts to fill an RTAUDIO_DEVICE
  334. structure for a given device. If an error is encountered during
  335. the probe, a "warning" message is reported and the value of
  336. "probed" remains false (no exception is thrown). A successful
  337. probe is indicated by probed = true.
  338. */
  339. void probeDeviceInfo(RTAUDIO_DEVICE *info);
  340. /*!
  341. Private method which attempts to open a device with the given parameters.
  342. If an error is encountered during the probe, a "warning" message is
  343. reported and FAILURE is returned (no exception is thrown). A
  344. successful probe is indicated by a return value of SUCCESS.
  345. */
  346. bool probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
  347. STREAM_MODE mode, int channels,
  348. int sampleRate, RTAUDIO_FORMAT format,
  349. int *bufferSize, int numberOfBuffers);
  350. /*!
  351. Private common method used to check validity of a user-passed
  352. stream ID. When the ID is valid, this method returns a pointer to
  353. an RTAUDIO_STREAM structure (in the form of a void pointer).
  354. Otherwise, an "invalid identifier" exception is thrown.
  355. */
  356. void *verifyStream(int streamId);
  357. /*!
  358. Private method used to perform format, channel number, and/or interleaving
  359. conversions between the user and device buffers.
  360. */
  361. void convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode);
  362. //! Private method used to perform byte-swapping on buffers.
  363. void byteSwapBuffer(char *buffer, int samples, RTAUDIO_FORMAT format);
  364. //! Private method which returns the number of bytes for a given format.
  365. int formatBytes(RTAUDIO_FORMAT format);
  366. };
  367. // Uncomment the following definition to have extra information spewed to stderr.
  368. //#define RTAUDIO_DEBUG
  369. #endif