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.

7083 lines
226KB

  1. /************************************************************************/
  2. /*! \class RtAudio
  3. \brief Realtime audio i/o C++ class.
  4. RtAudio provides a common API (Application Programming Interface)
  5. for realtime audio input/output across Linux (native ALSA and
  6. OSS), SGI, Macintosh OS X (CoreAudio), and Windows (DirectSound
  7. and ASIO) operating systems.
  8. RtAudio WWW site: http://www-ccrma.stanford.edu/~gary/rtaudio/
  9. RtAudio: a realtime audio i/o C++ class
  10. Copyright (c) 2001-2002 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. requested to send the modifications to the original developer so that
  22. they can be incorporated into the canonical version.
  23. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  26. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  27. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  28. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. */
  31. /************************************************************************/
  32. #include "RtAudio.h"
  33. #include <vector>
  34. #include <stdio.h>
  35. #include <iostream.h>
  36. // Static variable definitions.
  37. const unsigned int RtAudio :: SAMPLE_RATES[] = {
  38. 4000, 5512, 8000, 9600, 11025, 16000, 22050,
  39. 32000, 44100, 48000, 88200, 96000, 176400, 192000
  40. };
  41. const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT8 = 1;
  42. const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT16 = 2;
  43. const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT24 = 4;
  44. const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT32 = 8;
  45. const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT32 = 16;
  46. const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT64 = 32;
  47. #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
  48. #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
  49. #define MUTEX_LOCK(A) EnterCriticalSection(A)
  50. #define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
  51. #else // pthread API
  52. #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
  53. #define MUTEX_LOCK(A) pthread_mutex_lock(A)
  54. #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
  55. #endif
  56. // *************************************************** //
  57. //
  58. // Public common (OS-independent) methods.
  59. //
  60. // *************************************************** //
  61. RtAudio :: RtAudio()
  62. {
  63. initialize();
  64. if (nDevices <= 0) {
  65. sprintf(message, "RtAudio: no audio devices found!");
  66. error(RtError::NO_DEVICES_FOUND);
  67. }
  68. }
  69. RtAudio :: RtAudio(int *streamId,
  70. int outputDevice, int outputChannels,
  71. int inputDevice, int inputChannels,
  72. RTAUDIO_FORMAT format, int sampleRate,
  73. int *bufferSize, int numberOfBuffers)
  74. {
  75. initialize();
  76. if (nDevices <= 0) {
  77. sprintf(message, "RtAudio: no audio devices found!");
  78. error(RtError::NO_DEVICES_FOUND);
  79. }
  80. try {
  81. *streamId = openStream(outputDevice, outputChannels, inputDevice, inputChannels,
  82. format, sampleRate, bufferSize, numberOfBuffers);
  83. }
  84. catch (RtError &exception) {
  85. // deallocate the RTAUDIO_DEVICE structures
  86. if (devices) free(devices);
  87. throw exception;
  88. }
  89. }
  90. RtAudio :: ~RtAudio()
  91. {
  92. // close any existing streams
  93. while ( streams.size() )
  94. closeStream( streams.begin()->first );
  95. // deallocate the RTAUDIO_DEVICE structures
  96. if (devices) free(devices);
  97. }
  98. int RtAudio :: openStream(int outputDevice, int outputChannels,
  99. int inputDevice, int inputChannels,
  100. RTAUDIO_FORMAT format, int sampleRate,
  101. int *bufferSize, int numberOfBuffers)
  102. {
  103. static int streamKey = 0; // Unique stream identifier ... OK for multiple instances.
  104. if (outputChannels < 1 && inputChannels < 1) {
  105. sprintf(message,"RtAudio: one or both 'channel' parameters must be greater than zero.");
  106. error(RtError::INVALID_PARAMETER);
  107. }
  108. if ( formatBytes(format) == 0 ) {
  109. sprintf(message,"RtAudio: 'format' parameter value is undefined.");
  110. error(RtError::INVALID_PARAMETER);
  111. }
  112. if ( outputChannels > 0 ) {
  113. if (outputDevice > nDevices || outputDevice < 0) {
  114. sprintf(message,"RtAudio: 'outputDevice' parameter value (%d) is invalid.", outputDevice);
  115. error(RtError::INVALID_PARAMETER);
  116. }
  117. }
  118. if ( inputChannels > 0 ) {
  119. if (inputDevice > nDevices || inputDevice < 0) {
  120. sprintf(message,"RtAudio: 'inputDevice' parameter value (%d) is invalid.", inputDevice);
  121. error(RtError::INVALID_PARAMETER);
  122. }
  123. }
  124. // Allocate a new stream structure.
  125. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) calloc(1, sizeof(RTAUDIO_STREAM));
  126. if (stream == NULL) {
  127. sprintf(message, "RtAudio: memory allocation error!");
  128. error(RtError::MEMORY_ERROR);
  129. }
  130. stream->mode = UNINITIALIZED;
  131. MUTEX_INITIALIZE(&stream->mutex);
  132. bool result = FAILURE;
  133. int device, defaultDevice = 0;
  134. STREAM_MODE mode;
  135. int channels;
  136. if ( outputChannels > 0 ) {
  137. mode = OUTPUT;
  138. channels = outputChannels;
  139. if ( outputDevice == 0 ) { // Try default device first.
  140. defaultDevice = getDefaultOutputDevice();
  141. device = defaultDevice;
  142. }
  143. else
  144. device = outputDevice - 1;
  145. for (int i=-1; i<nDevices; i++) {
  146. if (i >= 0 ) {
  147. if ( i == defaultDevice ) continue;
  148. device = i;
  149. }
  150. if (devices[device].probed == false) {
  151. // If the device wasn't successfully probed before, try it
  152. // again now.
  153. clearDeviceInfo(&devices[device]);
  154. probeDeviceInfo(&devices[device]);
  155. }
  156. if ( devices[device].probed )
  157. result = probeDeviceOpen(device, stream, mode, channels, sampleRate,
  158. format, bufferSize, numberOfBuffers);
  159. if (result == SUCCESS) break;
  160. if ( outputDevice > 0 ) break;
  161. }
  162. }
  163. if ( inputChannels > 0 && ( result == SUCCESS || outputChannels <= 0 ) ) {
  164. mode = INPUT;
  165. channels = inputChannels;
  166. if ( inputDevice == 0 ) { // Try default device first.
  167. defaultDevice = getDefaultInputDevice();
  168. device = defaultDevice;
  169. }
  170. else
  171. device = inputDevice - 1;
  172. for (int i=-1; i<nDevices; i++) {
  173. if (i >= 0 ) {
  174. if ( i == defaultDevice ) continue;
  175. device = i;
  176. }
  177. if (devices[device].probed == false) {
  178. // If the device wasn't successfully probed before, try it
  179. // again now.
  180. clearDeviceInfo(&devices[device]);
  181. probeDeviceInfo(&devices[device]);
  182. }
  183. if ( devices[device].probed )
  184. result = probeDeviceOpen(device, stream, mode, channels, sampleRate,
  185. format, bufferSize, numberOfBuffers);
  186. if (result == SUCCESS) break;
  187. if ( outputDevice > 0 ) break;
  188. }
  189. }
  190. streams[++streamKey] = (void *) stream;
  191. if ( result == SUCCESS )
  192. return streamKey;
  193. // If we get here, all attempted probes failed. Close any opened
  194. // devices and delete the allocated stream.
  195. closeStream(streamKey);
  196. if ( ( outputDevice == 0 && outputChannels > 0 )
  197. || ( inputDevice == 0 && inputChannels > 0 ) )
  198. sprintf(message,"RtAudio: no devices found for given parameters.");
  199. else
  200. sprintf(message,"RtAudio: unable to open specified device(s) with given stream parameters.");
  201. error(RtError::INVALID_PARAMETER);
  202. return -1;
  203. }
  204. int RtAudio :: getDeviceCount(void)
  205. {
  206. return nDevices;
  207. }
  208. void RtAudio :: getDeviceInfo(int device, RTAUDIO_DEVICE *info)
  209. {
  210. if (device > nDevices || device < 1) {
  211. sprintf(message, "RtAudio: invalid device specifier (%d)!", device);
  212. error(RtError::INVALID_DEVICE);
  213. }
  214. int deviceIndex = device - 1;
  215. // If the device wasn't successfully probed before, try it now (or again).
  216. if (devices[deviceIndex].probed == false) {
  217. clearDeviceInfo(&devices[deviceIndex]);
  218. probeDeviceInfo(&devices[deviceIndex]);
  219. }
  220. // Clear the info structure.
  221. memset(info, 0, sizeof(RTAUDIO_DEVICE));
  222. strncpy(info->name, devices[deviceIndex].name, 128);
  223. info->probed = devices[deviceIndex].probed;
  224. if ( info->probed == true ) {
  225. info->maxOutputChannels = devices[deviceIndex].maxOutputChannels;
  226. info->maxInputChannels = devices[deviceIndex].maxInputChannels;
  227. info->maxDuplexChannels = devices[deviceIndex].maxDuplexChannels;
  228. info->minOutputChannels = devices[deviceIndex].minOutputChannels;
  229. info->minInputChannels = devices[deviceIndex].minInputChannels;
  230. info->minDuplexChannels = devices[deviceIndex].minDuplexChannels;
  231. info->hasDuplexSupport = devices[deviceIndex].hasDuplexSupport;
  232. info->nSampleRates = devices[deviceIndex].nSampleRates;
  233. if (info->nSampleRates == -1) {
  234. info->sampleRates[0] = devices[deviceIndex].sampleRates[0];
  235. info->sampleRates[1] = devices[deviceIndex].sampleRates[1];
  236. }
  237. else {
  238. for (int i=0; i<info->nSampleRates; i++)
  239. info->sampleRates[i] = devices[deviceIndex].sampleRates[i];
  240. }
  241. info->nativeFormats = devices[deviceIndex].nativeFormats;
  242. if ( deviceIndex == getDefaultOutputDevice() ||
  243. deviceIndex == getDefaultInputDevice() )
  244. info->isDefault = true;
  245. }
  246. return;
  247. }
  248. char * const RtAudio :: getStreamBuffer(int streamId)
  249. {
  250. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  251. return stream->userBuffer;
  252. }
  253. #if defined(__LINUX_ALSA__) || defined(__LINUX_OSS__) || defined(__IRIX_AL__)
  254. extern "C" void *callbackHandler(void * ptr);
  255. void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData)
  256. {
  257. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  258. CALLBACK_INFO *info = (CALLBACK_INFO *) &stream->callbackInfo;
  259. if ( info->usingCallback ) {
  260. sprintf(message, "RtAudio: A callback is already set for this stream!");
  261. error(RtError::WARNING);
  262. return;
  263. }
  264. info->callback = (void *) callback;
  265. info->userData = userData;
  266. info->usingCallback = true;
  267. info->object = (void *) this;
  268. info->streamId = streamId;
  269. int err = pthread_create(&info->thread, NULL, callbackHandler, &stream->callbackInfo);
  270. if (err) {
  271. info->usingCallback = false;
  272. sprintf(message, "RtAudio: error starting callback thread!");
  273. error(RtError::THREAD_ERROR);
  274. }
  275. }
  276. void RtAudio :: cancelStreamCallback(int streamId)
  277. {
  278. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  279. if (stream->callbackInfo.usingCallback) {
  280. if (stream->state == STREAM_RUNNING)
  281. stopStream( streamId );
  282. MUTEX_LOCK(&stream->mutex);
  283. stream->callbackInfo.usingCallback = false;
  284. pthread_cancel(stream->callbackInfo.thread);
  285. pthread_join(stream->callbackInfo.thread, NULL);
  286. stream->callbackInfo.thread = 0;
  287. stream->callbackInfo.callback = NULL;
  288. stream->callbackInfo.userData = NULL;
  289. MUTEX_UNLOCK(&stream->mutex);
  290. }
  291. }
  292. #endif
  293. // *************************************************** //
  294. //
  295. // OS/API-specific methods.
  296. //
  297. // *************************************************** //
  298. #if defined(__MACOSX_CORE__)
  299. // The OS X CoreAudio API is designed to use a separate callback
  300. // procedure for each of its audio devices. A single RtAudio duplex
  301. // stream using two different devices is supported here, though it
  302. // cannot be guaranteed to always behave correctly because we cannot
  303. // synchronize these two callbacks. This same functionality can be
  304. // achieved with better synchrony by opening two separate streams for
  305. // the devices and using RtAudio blocking calls (i.e. tickStream()).
  306. //
  307. // The possibility of having multiple RtAudio streams accessing the
  308. // same CoreAudio device is not currently supported. The problem
  309. // involves the inability to install our callbackHandler function for
  310. // the same device more than once. I experimented with a workaround
  311. // for this, but it requires an additional buffer for mixing output
  312. // data before filling the CoreAudio device buffer. In the end, I
  313. // decided it wasn't worth supporting.
  314. //
  315. // Property listeners are currently not used. The issue is what could
  316. // be done if a critical stream parameter (buffer size, sample rate,
  317. // device disconnect) notification arrived. The listeners entail
  318. // quite a bit of extra code and most likely, a user program wouldn't
  319. // be prepared for the result anyway. Some initial listener code is
  320. // commented out.
  321. void RtAudio :: initialize(void)
  322. {
  323. OSStatus err = noErr;
  324. UInt32 dataSize;
  325. AudioDeviceID *deviceList = NULL;
  326. nDevices = 0;
  327. // Find out how many audio devices there are, if any.
  328. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &dataSize, NULL);
  329. if (err != noErr) {
  330. sprintf(message, "RtAudio: OSX error getting device info!");
  331. error(RtError::SYSTEM_ERROR);
  332. }
  333. nDevices = dataSize / sizeof(AudioDeviceID);
  334. if (nDevices == 0) return;
  335. // Allocate the RTAUDIO_DEVICE structures.
  336. devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
  337. if (devices == NULL) {
  338. sprintf(message, "RtAudio: memory allocation error!");
  339. error(RtError::MEMORY_ERROR);
  340. }
  341. // Make space for the devices we are about to get.
  342. deviceList = (AudioDeviceID *) malloc( dataSize );
  343. if (deviceList == NULL) {
  344. sprintf(message, "RtAudio: memory allocation error!");
  345. error(RtError::MEMORY_ERROR);
  346. }
  347. // Get the array of AudioDeviceIDs.
  348. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &dataSize, (void *) deviceList);
  349. if (err != noErr) {
  350. free(deviceList);
  351. sprintf(message, "RtAudio: OSX error getting device properties!");
  352. error(RtError::SYSTEM_ERROR);
  353. }
  354. // Write device identifiers to device structures and then
  355. // probe the device capabilities.
  356. for (int i=0; i<nDevices; i++) {
  357. devices[i].id[0] = deviceList[i];
  358. //probeDeviceInfo(&devices[i]);
  359. }
  360. free(deviceList);
  361. }
  362. int RtAudio :: getDefaultInputDevice(void)
  363. {
  364. AudioDeviceID id;
  365. UInt32 dataSize = sizeof( AudioDeviceID );
  366. OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultInputDevice,
  367. &dataSize, &id );
  368. if (result != noErr) {
  369. sprintf( message, "RtAudio: OSX error getting default input device." );
  370. error(RtError::WARNING);
  371. return 0;
  372. }
  373. for ( int i=0; i<nDevices; i++ ) {
  374. if ( id == devices[i].id[0] ) return i;
  375. }
  376. return 0;
  377. }
  378. int RtAudio :: getDefaultOutputDevice(void)
  379. {
  380. AudioDeviceID id;
  381. UInt32 dataSize = sizeof( AudioDeviceID );
  382. OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice,
  383. &dataSize, &id );
  384. if (result != noErr) {
  385. sprintf( message, "RtAudio: OSX error getting default output device." );
  386. error(RtError::WARNING);
  387. return 0;
  388. }
  389. for ( int i=0; i<nDevices; i++ ) {
  390. if ( id == devices[i].id[0] ) return i;
  391. }
  392. return 0;
  393. }
  394. static bool deviceSupportsFormat( AudioDeviceID id, bool isInput,
  395. AudioStreamBasicDescription *desc, bool isDuplex )
  396. {
  397. OSStatus result = noErr;
  398. UInt32 dataSize = sizeof( AudioStreamBasicDescription );
  399. result = AudioDeviceGetProperty( id, 0, isInput,
  400. kAudioDevicePropertyStreamFormatSupported,
  401. &dataSize, desc );
  402. if (result == kAudioHardwareNoError) {
  403. if ( isDuplex ) {
  404. result = AudioDeviceGetProperty( id, 0, true,
  405. kAudioDevicePropertyStreamFormatSupported,
  406. &dataSize, desc );
  407. if (result != kAudioHardwareNoError)
  408. return false;
  409. }
  410. return true;
  411. }
  412. return false;
  413. }
  414. void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
  415. {
  416. OSStatus err = noErr;
  417. // Get the device manufacturer and name.
  418. char name[256];
  419. char fullname[512];
  420. UInt32 dataSize = 256;
  421. err = AudioDeviceGetProperty( info->id[0], 0, false,
  422. kAudioDevicePropertyDeviceManufacturer,
  423. &dataSize, name );
  424. if (err != noErr) {
  425. sprintf( message, "RtAudio: OSX error getting device manufacturer." );
  426. error(RtError::DEBUG_WARNING);
  427. return;
  428. }
  429. strncpy(fullname, name, 256);
  430. strcat(fullname, ": " );
  431. dataSize = 256;
  432. err = AudioDeviceGetProperty( info->id[0], 0, false,
  433. kAudioDevicePropertyDeviceName,
  434. &dataSize, name );
  435. if (err != noErr) {
  436. sprintf( message, "RtAudio: OSX error getting device name." );
  437. error(RtError::DEBUG_WARNING);
  438. return;
  439. }
  440. strncat(fullname, name, 254);
  441. strncat(info->name, fullname, 128);
  442. // Get output channel information.
  443. unsigned int i, minChannels, maxChannels, nStreams = 0;
  444. AudioBufferList *bufferList = nil;
  445. err = AudioDeviceGetPropertyInfo( info->id[0], 0, false,
  446. kAudioDevicePropertyStreamConfiguration,
  447. &dataSize, NULL );
  448. if (err == noErr && dataSize > 0) {
  449. bufferList = (AudioBufferList *) malloc( dataSize );
  450. if (bufferList == NULL) {
  451. sprintf(message, "RtAudio: memory allocation error!");
  452. error(RtError::DEBUG_WARNING);
  453. return;
  454. }
  455. err = AudioDeviceGetProperty( info->id[0], 0, false,
  456. kAudioDevicePropertyStreamConfiguration,
  457. &dataSize, bufferList );
  458. if (err == noErr) {
  459. maxChannels = 0;
  460. minChannels = 1000;
  461. nStreams = bufferList->mNumberBuffers;
  462. for ( i=0; i<nStreams; i++ ) {
  463. maxChannels += bufferList->mBuffers[i].mNumberChannels;
  464. if ( bufferList->mBuffers[i].mNumberChannels < minChannels )
  465. minChannels = bufferList->mBuffers[i].mNumberChannels;
  466. }
  467. }
  468. }
  469. if (err != noErr || dataSize <= 0) {
  470. sprintf( message, "RtAudio: OSX error getting output channels for device (%s).", info->name );
  471. error(RtError::DEBUG_WARNING);
  472. return;
  473. }
  474. free (bufferList);
  475. if ( nStreams ) {
  476. if ( maxChannels > 0 )
  477. info->maxOutputChannels = maxChannels;
  478. if ( minChannels > 0 )
  479. info->minOutputChannels = minChannels;
  480. }
  481. // Get input channel information.
  482. bufferList = nil;
  483. err = AudioDeviceGetPropertyInfo( info->id[0], 0, true,
  484. kAudioDevicePropertyStreamConfiguration,
  485. &dataSize, NULL );
  486. if (err == noErr && dataSize > 0) {
  487. bufferList = (AudioBufferList *) malloc( dataSize );
  488. if (bufferList == NULL) {
  489. sprintf(message, "RtAudio: memory allocation error!");
  490. error(RtError::DEBUG_WARNING);
  491. return;
  492. }
  493. err = AudioDeviceGetProperty( info->id[0], 0, true,
  494. kAudioDevicePropertyStreamConfiguration,
  495. &dataSize, bufferList );
  496. if (err == noErr) {
  497. maxChannels = 0;
  498. minChannels = 1000;
  499. nStreams = bufferList->mNumberBuffers;
  500. for ( i=0; i<nStreams; i++ ) {
  501. if ( bufferList->mBuffers[i].mNumberChannels < minChannels )
  502. minChannels = bufferList->mBuffers[i].mNumberChannels;
  503. maxChannels += bufferList->mBuffers[i].mNumberChannels;
  504. }
  505. }
  506. }
  507. if (err != noErr || dataSize <= 0) {
  508. sprintf( message, "RtAudio: OSX error getting input channels for device (%s).", info->name );
  509. error(RtError::DEBUG_WARNING);
  510. return;
  511. }
  512. free (bufferList);
  513. if ( nStreams ) {
  514. if ( maxChannels > 0 )
  515. info->maxInputChannels = maxChannels;
  516. if ( minChannels > 0 )
  517. info->minInputChannels = minChannels;
  518. }
  519. // If device opens for both playback and capture, we determine the channels.
  520. if (info->maxOutputChannels > 0 && info->maxInputChannels > 0) {
  521. info->hasDuplexSupport = true;
  522. info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ?
  523. info->maxInputChannels : info->maxOutputChannels;
  524. info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ?
  525. info->minInputChannels : info->minOutputChannels;
  526. }
  527. // Probe the device sample rate and data format parameters. The
  528. // core audio query mechanism is performed on a "stream"
  529. // description, which can have a variable number of channels and
  530. // apply to input or output only.
  531. // Create a stream description structure.
  532. AudioStreamBasicDescription description;
  533. dataSize = sizeof( AudioStreamBasicDescription );
  534. memset(&description, 0, sizeof(AudioStreamBasicDescription));
  535. bool isInput = false;
  536. if ( info->maxOutputChannels == 0 ) isInput = true;
  537. bool isDuplex = false;
  538. if ( info->maxDuplexChannels > 0 ) isDuplex = true;
  539. // Determine the supported sample rates.
  540. info->nSampleRates = 0;
  541. for (i=0; i<MAX_SAMPLE_RATES; i++) {
  542. description.mSampleRate = (double) SAMPLE_RATES[i];
  543. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  544. info->sampleRates[info->nSampleRates++] = SAMPLE_RATES[i];
  545. }
  546. if (info->nSampleRates == 0) {
  547. sprintf( message, "RtAudio: No supported sample rates found for OSX device (%s).", info->name );
  548. error(RtError::DEBUG_WARNING);
  549. return;
  550. }
  551. // Check for continuous sample rate support.
  552. description.mSampleRate = kAudioStreamAnyRate;
  553. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) ) {
  554. info->sampleRates[1] = info->sampleRates[info->nSampleRates-1];
  555. info->nSampleRates = -1;
  556. }
  557. // Determine the supported data formats.
  558. info->nativeFormats = 0;
  559. description.mFormatID = kAudioFormatLinearPCM;
  560. description.mBitsPerChannel = 8;
  561. description.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsBigEndian;
  562. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  563. info->nativeFormats |= RTAUDIO_SINT8;
  564. else {
  565. description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
  566. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  567. info->nativeFormats |= RTAUDIO_SINT8;
  568. }
  569. description.mBitsPerChannel = 16;
  570. description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
  571. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  572. info->nativeFormats |= RTAUDIO_SINT16;
  573. else {
  574. description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
  575. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  576. info->nativeFormats |= RTAUDIO_SINT16;
  577. }
  578. description.mBitsPerChannel = 32;
  579. description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
  580. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  581. info->nativeFormats |= RTAUDIO_SINT32;
  582. else {
  583. description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
  584. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  585. info->nativeFormats |= RTAUDIO_SINT32;
  586. }
  587. description.mBitsPerChannel = 24;
  588. description.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsAlignedHigh | kLinearPCMFormatFlagIsBigEndian;
  589. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  590. info->nativeFormats |= RTAUDIO_SINT24;
  591. else {
  592. description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
  593. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  594. info->nativeFormats |= RTAUDIO_SINT24;
  595. }
  596. description.mBitsPerChannel = 32;
  597. description.mFormatFlags = kLinearPCMFormatFlagIsFloat | kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsBigEndian;
  598. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  599. info->nativeFormats |= RTAUDIO_FLOAT32;
  600. else {
  601. description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
  602. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  603. info->nativeFormats |= RTAUDIO_FLOAT32;
  604. }
  605. description.mBitsPerChannel = 64;
  606. description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
  607. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  608. info->nativeFormats |= RTAUDIO_FLOAT64;
  609. else {
  610. description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
  611. if ( deviceSupportsFormat( info->id[0], isInput, &description, isDuplex ) )
  612. info->nativeFormats |= RTAUDIO_FLOAT64;
  613. }
  614. // Check that we have at least one supported format.
  615. if (info->nativeFormats == 0) {
  616. sprintf(message, "RtAudio: OSX PCM device (%s) data format not supported by RtAudio.",
  617. info->name);
  618. error(RtError::DEBUG_WARNING);
  619. return;
  620. }
  621. info->probed = true;
  622. }
  623. OSStatus callbackHandler(AudioDeviceID inDevice,
  624. const AudioTimeStamp* inNow,
  625. const AudioBufferList* inInputData,
  626. const AudioTimeStamp* inInputTime,
  627. AudioBufferList* outOutputData,
  628. const AudioTimeStamp* inOutputTime,
  629. void* infoPointer)
  630. {
  631. CALLBACK_INFO *info = (CALLBACK_INFO *) infoPointer;
  632. RtAudio *object = (RtAudio *) info->object;
  633. try {
  634. object->callbackEvent( info->streamId, inDevice, (void *)inInputData, (void *)outOutputData );
  635. }
  636. catch (RtError &exception) {
  637. fprintf(stderr, "\nCallback handler error (%s)!\n\n", exception.getMessage());
  638. return kAudioHardwareUnspecifiedError;
  639. }
  640. return kAudioHardwareNoError;
  641. }
  642. /*
  643. OSStatus deviceListener(AudioDeviceID inDevice,
  644. UInt32 channel,
  645. Boolean isInput,
  646. AudioDevicePropertyID propertyID,
  647. void* infoPointer)
  648. {
  649. CALLBACK_INFO *info = (CALLBACK_INFO *) infoPointer;
  650. RtAudio *object = (RtAudio *) info->object;
  651. try {
  652. object->settingChange( info->streamId );
  653. }
  654. catch (RtError &exception) {
  655. fprintf(stderr, "\nDevice listener error (%s)!\n\n", exception.getMessage());
  656. return kAudioHardwareUnspecifiedError;
  657. }
  658. return kAudioHardwareNoError;
  659. }
  660. */
  661. bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
  662. STREAM_MODE mode, int channels,
  663. int sampleRate, RTAUDIO_FORMAT format,
  664. int *bufferSize, int numberOfBuffers)
  665. {
  666. // Check to make sure we don't already have a stream accessing this device.
  667. RTAUDIO_STREAM *streamPtr;
  668. std::map<int, void *>::const_iterator i;
  669. for ( i=streams.begin(); i!=streams.end(); ++i ) {
  670. streamPtr = (RTAUDIO_STREAM *) i->second;
  671. if ( streamPtr->device[0] == device || streamPtr->device[1] == device ) {
  672. sprintf(message, "RtAudio: no current OS X support for multiple streams accessing the same device!");
  673. error(RtError::WARNING);
  674. return FAILURE;
  675. }
  676. }
  677. // Setup for stream mode.
  678. bool isInput = false;
  679. AudioDeviceID id = devices[device].id[0];
  680. if ( mode == INPUT ) isInput = true;
  681. // Search for a stream which contains the desired number of channels.
  682. OSStatus err = noErr;
  683. UInt32 dataSize;
  684. unsigned int deviceChannels, nStreams;
  685. UInt32 iChannel = 0, iStream = 0;
  686. AudioBufferList *bufferList = nil;
  687. err = AudioDeviceGetPropertyInfo( id, 0, isInput,
  688. kAudioDevicePropertyStreamConfiguration,
  689. &dataSize, NULL );
  690. if (err == noErr && dataSize > 0) {
  691. bufferList = (AudioBufferList *) malloc( dataSize );
  692. if (bufferList == NULL) {
  693. sprintf(message, "RtAudio: memory allocation error!");
  694. error(RtError::DEBUG_WARNING);
  695. return FAILURE;
  696. }
  697. err = AudioDeviceGetProperty( id, 0, isInput,
  698. kAudioDevicePropertyStreamConfiguration,
  699. &dataSize, bufferList );
  700. if (err == noErr) {
  701. stream->deInterleave[mode] = false;
  702. nStreams = bufferList->mNumberBuffers;
  703. for ( iStream=0; iStream<nStreams; iStream++ ) {
  704. if ( bufferList->mBuffers[iStream].mNumberChannels >= (unsigned int) channels ) break;
  705. iChannel += bufferList->mBuffers[iStream].mNumberChannels;
  706. }
  707. // If we didn't find a single stream above, see if we can meet
  708. // the channel specification in mono mode (i.e. using separate
  709. // non-interleaved buffers). This can only work if there are N
  710. // consecutive one-channel streams, where N is the number of
  711. // desired channels.
  712. iChannel = 0;
  713. if ( iStream >= nStreams && nStreams >= (unsigned int) channels ) {
  714. int counter = 0;
  715. for ( iStream=0; iStream<nStreams; iStream++ ) {
  716. if ( bufferList->mBuffers[iStream].mNumberChannels == 1 )
  717. counter++;
  718. else
  719. counter = 0;
  720. if ( counter == channels ) {
  721. iStream -= channels - 1;
  722. iChannel -= channels - 1;
  723. stream->deInterleave[mode] = true;
  724. break;
  725. }
  726. iChannel += bufferList->mBuffers[iStream].mNumberChannels;
  727. }
  728. }
  729. }
  730. }
  731. if (err != noErr || dataSize <= 0) {
  732. if ( bufferList ) free( bufferList );
  733. sprintf( message, "RtAudio: OSX error getting channels for device (%s).", devices[device].name );
  734. error(RtError::DEBUG_WARNING);
  735. return FAILURE;
  736. }
  737. if (iStream >= nStreams) {
  738. free (bufferList);
  739. sprintf( message, "RtAudio: unable to find OSX audio stream on device (%s) for requested channels (%d).",
  740. devices[device].name, channels );
  741. error(RtError::DEBUG_WARNING);
  742. return FAILURE;
  743. }
  744. // This is ok even for mono mode ... it gets updated later.
  745. deviceChannels = bufferList->mBuffers[iStream].mNumberChannels;
  746. free (bufferList);
  747. // Determine the buffer size.
  748. AudioValueRange bufferRange;
  749. dataSize = sizeof(AudioValueRange);
  750. err = AudioDeviceGetProperty( id, 0, isInput,
  751. kAudioDevicePropertyBufferSizeRange,
  752. &dataSize, &bufferRange);
  753. if (err != noErr) {
  754. sprintf( message, "RtAudio: OSX error getting buffer size range for device (%s).",
  755. devices[device].name );
  756. error(RtError::DEBUG_WARNING);
  757. return FAILURE;
  758. }
  759. long bufferBytes = *bufferSize * deviceChannels * formatBytes(RTAUDIO_FLOAT32);
  760. if (bufferRange.mMinimum > bufferBytes) bufferBytes = (int) bufferRange.mMinimum;
  761. else if (bufferRange.mMaximum < bufferBytes) bufferBytes = (int) bufferRange.mMaximum;
  762. // Set the buffer size. For mono mode, I'm assuming we only need to
  763. // make this setting for the first channel.
  764. UInt32 theSize = (UInt32) bufferBytes;
  765. dataSize = sizeof( UInt32);
  766. err = AudioDeviceSetProperty(id, NULL, 0, isInput,
  767. kAudioDevicePropertyBufferSize,
  768. dataSize, &theSize);
  769. if (err != noErr) {
  770. sprintf( message, "RtAudio: OSX error setting the buffer size for device (%s).",
  771. devices[device].name );
  772. error(RtError::DEBUG_WARNING);
  773. return FAILURE;
  774. }
  775. // If attempting to setup a duplex stream, the bufferSize parameter
  776. // MUST be the same in both directions!
  777. *bufferSize = bufferBytes / ( deviceChannels * formatBytes(RTAUDIO_FLOAT32) );
  778. if ( stream->mode == OUTPUT && mode == INPUT && *bufferSize != stream->bufferSize ) {
  779. sprintf( message, "RtAudio: OSX error setting buffer size for duplex stream on device (%s).",
  780. devices[device].name );
  781. error(RtError::DEBUG_WARNING);
  782. return FAILURE;
  783. }
  784. stream->bufferSize = *bufferSize;
  785. stream->nBuffers = 1;
  786. // Set the stream format description. Do for each channel in mono mode.
  787. AudioStreamBasicDescription description;
  788. dataSize = sizeof( AudioStreamBasicDescription );
  789. if ( stream->deInterleave[mode] ) nStreams = channels;
  790. else nStreams = 1;
  791. for ( unsigned int i=0; i<nStreams; i++, iChannel++ ) {
  792. err = AudioDeviceGetProperty( id, iChannel, isInput,
  793. kAudioDevicePropertyStreamFormat,
  794. &dataSize, &description );
  795. if (err != noErr) {
  796. sprintf( message, "RtAudio: OSX error getting stream format for device (%s).", devices[device].name );
  797. error(RtError::DEBUG_WARNING);
  798. return FAILURE;
  799. }
  800. // Set the sample rate and data format id.
  801. description.mSampleRate = (double) sampleRate;
  802. description.mFormatID = kAudioFormatLinearPCM;
  803. err = AudioDeviceSetProperty( id, NULL, iChannel, isInput,
  804. kAudioDevicePropertyStreamFormat,
  805. dataSize, &description );
  806. if (err != noErr) {
  807. sprintf( message, "RtAudio: OSX error setting sample rate or data format for device (%s).", devices[device].name );
  808. error(RtError::DEBUG_WARNING);
  809. return FAILURE;
  810. }
  811. }
  812. // Check whether we need byte-swapping (assuming OS X host is big-endian).
  813. iChannel -= nStreams;
  814. err = AudioDeviceGetProperty( id, iChannel, isInput,
  815. kAudioDevicePropertyStreamFormat,
  816. &dataSize, &description );
  817. if (err != noErr) {
  818. sprintf( message, "RtAudio: OSX error getting stream format for device (%s).", devices[device].name );
  819. error(RtError::DEBUG_WARNING);
  820. return FAILURE;
  821. }
  822. stream->doByteSwap[mode] = false;
  823. if ( !description.mFormatFlags & kLinearPCMFormatFlagIsBigEndian )
  824. stream->doByteSwap[mode] = true;
  825. // From the CoreAudio documentation, PCM data must be supplied as
  826. // 32-bit floats.
  827. stream->userFormat = format;
  828. stream->deviceFormat[mode] = RTAUDIO_FLOAT32;
  829. if ( stream->deInterleave[mode] )
  830. stream->nDeviceChannels[mode] = channels;
  831. else
  832. stream->nDeviceChannels[mode] = description.mChannelsPerFrame;
  833. stream->nUserChannels[mode] = channels;
  834. // Set handle and flags for buffer conversion.
  835. stream->handle[mode] = iStream;
  836. stream->doConvertBuffer[mode] = false;
  837. if (stream->userFormat != stream->deviceFormat[mode])
  838. stream->doConvertBuffer[mode] = true;
  839. if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode])
  840. stream->doConvertBuffer[mode] = true;
  841. if (stream->nUserChannels[mode] > 1 && stream->deInterleave[mode])
  842. stream->doConvertBuffer[mode] = true;
  843. // Allocate necessary internal buffers.
  844. if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) {
  845. long buffer_bytes;
  846. if (stream->nUserChannels[0] >= stream->nUserChannels[1])
  847. buffer_bytes = stream->nUserChannels[0];
  848. else
  849. buffer_bytes = stream->nUserChannels[1];
  850. buffer_bytes *= *bufferSize * formatBytes(stream->userFormat);
  851. if (stream->userBuffer) free(stream->userBuffer);
  852. stream->userBuffer = (char *) calloc(buffer_bytes, 1);
  853. if (stream->userBuffer == NULL)
  854. goto memory_error;
  855. }
  856. if ( stream->deInterleave[mode] ) {
  857. long buffer_bytes;
  858. bool makeBuffer = true;
  859. if ( mode == OUTPUT )
  860. buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  861. else { // mode == INPUT
  862. buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
  863. if ( stream->mode == OUTPUT && stream->deviceBuffer ) {
  864. long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  865. if ( buffer_bytes < bytes_out ) makeBuffer = false;
  866. }
  867. }
  868. if ( makeBuffer ) {
  869. buffer_bytes *= *bufferSize;
  870. if (stream->deviceBuffer) free(stream->deviceBuffer);
  871. stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
  872. if (stream->deviceBuffer == NULL)
  873. goto memory_error;
  874. // If not de-interleaving, we point stream->deviceBuffer to the
  875. // OS X supplied device buffer before doing any necessary data
  876. // conversions. This presents a problem if we have a duplex
  877. // stream using one device which needs de-interleaving and
  878. // another device which doesn't. So, save a pointer to our own
  879. // device buffer in the CALLBACK_INFO structure.
  880. stream->callbackInfo.buffers = stream->deviceBuffer;
  881. }
  882. }
  883. stream->sampleRate = sampleRate;
  884. stream->device[mode] = device;
  885. stream->state = STREAM_STOPPED;
  886. stream->callbackInfo.object = (void *) this;
  887. stream->callbackInfo.waitTime = (unsigned long) (200000.0 * stream->bufferSize / stream->sampleRate);
  888. stream->callbackInfo.device[mode] = id;
  889. if ( stream->mode == OUTPUT && mode == INPUT && stream->device[0] == device )
  890. // Only one callback procedure per device.
  891. stream->mode = DUPLEX;
  892. else {
  893. err = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream->callbackInfo );
  894. if (err != noErr) {
  895. sprintf( message, "RtAudio: OSX error setting callback for device (%s).", devices[device].name );
  896. error(RtError::DEBUG_WARNING);
  897. return FAILURE;
  898. }
  899. if ( stream->mode == OUTPUT && mode == INPUT )
  900. stream->mode = DUPLEX;
  901. else
  902. stream->mode = mode;
  903. }
  904. // If we wanted to use property listeners, they would be setup here.
  905. return SUCCESS;
  906. memory_error:
  907. if (stream->userBuffer) {
  908. free(stream->userBuffer);
  909. stream->userBuffer = 0;
  910. }
  911. sprintf(message, "RtAudio: OSX error allocating buffer memory (%s).", devices[device].name);
  912. error(RtError::WARNING);
  913. return FAILURE;
  914. }
  915. void RtAudio :: cancelStreamCallback(int streamId)
  916. {
  917. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  918. if (stream->callbackInfo.usingCallback) {
  919. if (stream->state == STREAM_RUNNING)
  920. stopStream( streamId );
  921. MUTEX_LOCK(&stream->mutex);
  922. stream->callbackInfo.usingCallback = false;
  923. stream->callbackInfo.userData = NULL;
  924. stream->state = STREAM_STOPPED;
  925. stream->callbackInfo.callback = NULL;
  926. MUTEX_UNLOCK(&stream->mutex);
  927. }
  928. }
  929. void RtAudio :: closeStream(int streamId)
  930. {
  931. // We don't want an exception to be thrown here because this
  932. // function is called by our class destructor. So, do our own
  933. // streamId check.
  934. if ( streams.find( streamId ) == streams.end() ) {
  935. sprintf(message, "RtAudio: invalid stream identifier!");
  936. error(RtError::WARNING);
  937. return;
  938. }
  939. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId];
  940. AudioDeviceID id;
  941. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  942. id = devices[stream->device[0]].id[0];
  943. if (stream->state == STREAM_RUNNING)
  944. AudioDeviceStop( id, callbackHandler );
  945. AudioDeviceRemoveIOProc( id, callbackHandler );
  946. }
  947. if (stream->mode == INPUT || ( stream->mode == DUPLEX && stream->device[0] != stream->device[1]) ) {
  948. id = devices[stream->device[1]].id[0];
  949. if (stream->state == STREAM_RUNNING)
  950. AudioDeviceStop( id, callbackHandler );
  951. AudioDeviceRemoveIOProc( id, callbackHandler );
  952. }
  953. pthread_mutex_destroy(&stream->mutex);
  954. if (stream->userBuffer)
  955. free(stream->userBuffer);
  956. if ( stream->deInterleave[0] || stream->deInterleave[1] )
  957. free(stream->callbackInfo.buffers);
  958. free(stream);
  959. streams.erase(streamId);
  960. }
  961. void RtAudio :: startStream(int streamId)
  962. {
  963. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  964. MUTEX_LOCK(&stream->mutex);
  965. if (stream->state == STREAM_RUNNING)
  966. goto unlock;
  967. OSStatus err;
  968. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  969. err = AudioDeviceStart(devices[stream->device[0]].id[0], callbackHandler);
  970. if (err != noErr) {
  971. sprintf(message, "RtAudio: OSX error starting callback procedure on device (%s).",
  972. devices[stream->device[0]].name);
  973. MUTEX_UNLOCK(&stream->mutex);
  974. error(RtError::DRIVER_ERROR);
  975. }
  976. }
  977. if (stream->mode == INPUT || ( stream->mode == DUPLEX && stream->device[0] != stream->device[1]) ) {
  978. err = AudioDeviceStart(devices[stream->device[1]].id[0], callbackHandler);
  979. if (err != noErr) {
  980. sprintf(message, "RtAudio: OSX error starting input callback procedure on device (%s).",
  981. devices[stream->device[0]].name);
  982. MUTEX_UNLOCK(&stream->mutex);
  983. error(RtError::DRIVER_ERROR);
  984. }
  985. }
  986. stream->callbackInfo.streamId = streamId;
  987. stream->state = STREAM_RUNNING;
  988. stream->callbackInfo.blockTick = true;
  989. stream->callbackInfo.stopStream = false;
  990. unlock:
  991. MUTEX_UNLOCK(&stream->mutex);
  992. }
  993. void RtAudio :: stopStream(int streamId)
  994. {
  995. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  996. MUTEX_LOCK(&stream->mutex);
  997. if (stream->state == STREAM_STOPPED)
  998. goto unlock;
  999. OSStatus err;
  1000. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  1001. err = AudioDeviceStop(devices[stream->device[0]].id[0], callbackHandler);
  1002. if (err != noErr) {
  1003. sprintf(message, "RtAudio: OSX error stopping callback procedure on device (%s).",
  1004. devices[stream->device[0]].name);
  1005. MUTEX_UNLOCK(&stream->mutex);
  1006. error(RtError::DRIVER_ERROR);
  1007. }
  1008. }
  1009. if (stream->mode == INPUT || ( stream->mode == DUPLEX && stream->device[0] != stream->device[1]) ) {
  1010. err = AudioDeviceStop(devices[stream->device[1]].id[0], callbackHandler);
  1011. if (err != noErr) {
  1012. sprintf(message, "RtAudio: OSX error stopping input callback procedure on device (%s).",
  1013. devices[stream->device[0]].name);
  1014. MUTEX_UNLOCK(&stream->mutex);
  1015. error(RtError::DRIVER_ERROR);
  1016. }
  1017. }
  1018. stream->state = STREAM_STOPPED;
  1019. unlock:
  1020. MUTEX_UNLOCK(&stream->mutex);
  1021. }
  1022. void RtAudio :: abortStream(int streamId)
  1023. {
  1024. stopStream( streamId );
  1025. }
  1026. // I don't know how this function can be implemented.
  1027. int RtAudio :: streamWillBlock(int streamId)
  1028. {
  1029. sprintf(message, "RtAudio: streamWillBlock() cannot be implemented for OS X.");
  1030. error(RtError::WARNING);
  1031. return 0;
  1032. }
  1033. void RtAudio :: tickStream(int streamId)
  1034. {
  1035. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1036. if (stream->state == STREAM_STOPPED)
  1037. return;
  1038. if (stream->callbackInfo.usingCallback) {
  1039. sprintf(message, "RtAudio: tickStream() should not be used when a callback function is set!");
  1040. error(RtError::WARNING);
  1041. return;
  1042. }
  1043. // Block waiting here until the user data is processed in callbackEvent().
  1044. while ( stream->callbackInfo.blockTick )
  1045. usleep(stream->callbackInfo.waitTime);
  1046. MUTEX_LOCK(&stream->mutex);
  1047. stream->callbackInfo.blockTick = true;
  1048. MUTEX_UNLOCK(&stream->mutex);
  1049. }
  1050. void RtAudio :: callbackEvent( int streamId, DEVICE_ID deviceId, void *inData, void *outData )
  1051. {
  1052. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1053. CALLBACK_INFO *info;
  1054. AudioBufferList *inBufferList = (AudioBufferList *) inData;
  1055. AudioBufferList *outBufferList = (AudioBufferList *) outData;
  1056. if (stream->state == STREAM_STOPPED) return;
  1057. info = (CALLBACK_INFO *) &stream->callbackInfo;
  1058. if ( !info->usingCallback ) {
  1059. // Block waiting here until we get new user data in tickStream().
  1060. while ( !info->blockTick )
  1061. usleep(info->waitTime);
  1062. }
  1063. else if ( info->stopStream ) {
  1064. // Check if the stream should be stopped (via the previous user
  1065. // callback return value). We stop the stream here, rather than
  1066. // after the function call, so that output data can first be
  1067. // processed.
  1068. this->stopStream(info->streamId);
  1069. return;
  1070. }
  1071. MUTEX_LOCK(&stream->mutex);
  1072. if ( stream->mode == INPUT || ( stream->mode == DUPLEX && deviceId == info->device[1] ) ) {
  1073. if (stream->doConvertBuffer[1]) {
  1074. if ( stream->deInterleave[1] ) {
  1075. stream->deviceBuffer = (char *) stream->callbackInfo.buffers;
  1076. int bufferBytes = inBufferList->mBuffers[stream->handle[1]].mDataByteSize;
  1077. for ( int i=0; i<stream->nDeviceChannels[1]; i++ ) {
  1078. memcpy(&stream->deviceBuffer[i*bufferBytes],
  1079. inBufferList->mBuffers[stream->handle[1]+i].mData, bufferBytes );
  1080. }
  1081. }
  1082. else
  1083. stream->deviceBuffer = (char *) inBufferList->mBuffers[stream->handle[1]].mData;
  1084. if ( stream->doByteSwap[1] )
  1085. byteSwapBuffer(stream->deviceBuffer,
  1086. stream->bufferSize * stream->nDeviceChannels[1],
  1087. stream->deviceFormat[1]);
  1088. convertStreamBuffer(stream, INPUT);
  1089. }
  1090. else {
  1091. memcpy(stream->userBuffer,
  1092. inBufferList->mBuffers[stream->handle[1]].mData,
  1093. inBufferList->mBuffers[stream->handle[1]].mDataByteSize );
  1094. if (stream->doByteSwap[1])
  1095. byteSwapBuffer(stream->userBuffer,
  1096. stream->bufferSize * stream->nUserChannels[1],
  1097. stream->userFormat);
  1098. }
  1099. }
  1100. // Don't invoke the user callback if duplex mode, the input/output
  1101. // devices are different, and this function is called for the output
  1102. // device.
  1103. if ( info->usingCallback && (stream->mode != DUPLEX || deviceId == info->device[1] ) ) {
  1104. RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) info->callback;
  1105. info->stopStream = callback(stream->userBuffer, stream->bufferSize, info->userData);
  1106. }
  1107. if ( stream->mode == OUTPUT || ( stream->mode == DUPLEX && deviceId == info->device[0] ) ) {
  1108. if (stream->doConvertBuffer[0]) {
  1109. if ( !stream->deInterleave[0] )
  1110. stream->deviceBuffer = (char *) outBufferList->mBuffers[stream->handle[0]].mData;
  1111. else
  1112. stream->deviceBuffer = (char *) stream->callbackInfo.buffers;
  1113. convertStreamBuffer(stream, OUTPUT);
  1114. if ( stream->doByteSwap[0] )
  1115. byteSwapBuffer(stream->deviceBuffer,
  1116. stream->bufferSize * stream->nDeviceChannels[0],
  1117. stream->deviceFormat[0]);
  1118. if ( stream->deInterleave[0] ) {
  1119. int bufferBytes = outBufferList->mBuffers[stream->handle[0]].mDataByteSize;
  1120. for ( int i=0; i<stream->nDeviceChannels[0]; i++ ) {
  1121. memcpy(outBufferList->mBuffers[stream->handle[0]+i].mData,
  1122. &stream->deviceBuffer[i*bufferBytes], bufferBytes );
  1123. }
  1124. }
  1125. }
  1126. else {
  1127. if (stream->doByteSwap[0])
  1128. byteSwapBuffer(stream->userBuffer,
  1129. stream->bufferSize * stream->nUserChannels[0],
  1130. stream->userFormat);
  1131. memcpy(outBufferList->mBuffers[stream->handle[0]].mData,
  1132. stream->userBuffer,
  1133. outBufferList->mBuffers[stream->handle[0]].mDataByteSize );
  1134. }
  1135. }
  1136. if ( !info->usingCallback && (stream->mode != DUPLEX || deviceId == info->device[1] ) )
  1137. info->blockTick = false;
  1138. MUTEX_UNLOCK(&stream->mutex);
  1139. }
  1140. void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData)
  1141. {
  1142. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1143. stream->callbackInfo.callback = (void *) callback;
  1144. stream->callbackInfo.userData = userData;
  1145. stream->callbackInfo.usingCallback = true;
  1146. }
  1147. //******************** End of __MACOSX_CORE__ *********************//
  1148. #elif defined(__LINUX_ALSA__)
  1149. #define MAX_DEVICES 16
  1150. void RtAudio :: initialize(void)
  1151. {
  1152. int card, result, device;
  1153. char name[32];
  1154. const char *cardId;
  1155. char deviceNames[MAX_DEVICES][32];
  1156. snd_ctl_t *handle;
  1157. snd_ctl_card_info_t *info;
  1158. snd_ctl_card_info_alloca(&info);
  1159. // Count cards and devices
  1160. nDevices = 0;
  1161. card = -1;
  1162. snd_card_next(&card);
  1163. while ( card >= 0 ) {
  1164. sprintf(name, "hw:%d", card);
  1165. result = snd_ctl_open(&handle, name, 0);
  1166. if (result < 0) {
  1167. sprintf(message, "RtAudio: ALSA control open (%i): %s.", card, snd_strerror(result));
  1168. error(RtError::DEBUG_WARNING);
  1169. goto next_card;
  1170. }
  1171. result = snd_ctl_card_info(handle, info);
  1172. if (result < 0) {
  1173. sprintf(message, "RtAudio: ALSA control hardware info (%i): %s.", card, snd_strerror(result));
  1174. error(RtError::DEBUG_WARNING);
  1175. goto next_card;
  1176. }
  1177. cardId = snd_ctl_card_info_get_id(info);
  1178. device = -1;
  1179. while (1) {
  1180. result = snd_ctl_pcm_next_device(handle, &device);
  1181. if (result < 0) {
  1182. sprintf(message, "RtAudio: ALSA control next device (%i): %s.", card, snd_strerror(result));
  1183. error(RtError::DEBUG_WARNING);
  1184. break;
  1185. }
  1186. if (device < 0)
  1187. break;
  1188. if ( strlen(cardId) )
  1189. sprintf( deviceNames[nDevices++], "hw:%s,%d", cardId, device );
  1190. else
  1191. sprintf( deviceNames[nDevices++], "hw:%d,%d", card, device );
  1192. if ( nDevices > MAX_DEVICES ) break;
  1193. }
  1194. if ( nDevices > MAX_DEVICES ) break;
  1195. next_card:
  1196. snd_ctl_close(handle);
  1197. snd_card_next(&card);
  1198. }
  1199. if (nDevices == 0) return;
  1200. // Allocate the RTAUDIO_DEVICE structures.
  1201. devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
  1202. if (devices == NULL) {
  1203. sprintf(message, "RtAudio: memory allocation error!");
  1204. error(RtError::MEMORY_ERROR);
  1205. }
  1206. // Write device ascii identifiers to device structures and then
  1207. // probe the device capabilities.
  1208. for (int i=0; i<nDevices; i++) {
  1209. strncpy(devices[i].name, deviceNames[i], 32);
  1210. //probeDeviceInfo(&devices[i]);
  1211. }
  1212. }
  1213. int RtAudio :: getDefaultInputDevice(void)
  1214. {
  1215. // No ALSA API functions for default devices.
  1216. return 0;
  1217. }
  1218. int RtAudio :: getDefaultOutputDevice(void)
  1219. {
  1220. // No ALSA API functions for default devices.
  1221. return 0;
  1222. }
  1223. void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
  1224. {
  1225. int err;
  1226. int open_mode = SND_PCM_ASYNC;
  1227. snd_pcm_t *handle;
  1228. snd_ctl_t *chandle;
  1229. snd_pcm_stream_t stream;
  1230. snd_pcm_info_t *pcminfo;
  1231. snd_pcm_info_alloca(&pcminfo);
  1232. snd_pcm_hw_params_t *params;
  1233. snd_pcm_hw_params_alloca(&params);
  1234. char name[32];
  1235. char *card;
  1236. // Open the control interface for this card.
  1237. strncpy( name, info->name, 32 );
  1238. card = strtok(name, ",");
  1239. err = snd_ctl_open(&chandle, card, 0);
  1240. if (err < 0) {
  1241. sprintf(message, "RtAudio: ALSA control open (%s): %s.", card, snd_strerror(err));
  1242. error(RtError::DEBUG_WARNING);
  1243. return;
  1244. }
  1245. unsigned int dev = (unsigned int) atoi( strtok(NULL, ",") );
  1246. // First try for playback
  1247. stream = SND_PCM_STREAM_PLAYBACK;
  1248. snd_pcm_info_set_device(pcminfo, dev);
  1249. snd_pcm_info_set_subdevice(pcminfo, 0);
  1250. snd_pcm_info_set_stream(pcminfo, stream);
  1251. if ((err = snd_ctl_pcm_info(chandle, pcminfo)) < 0) {
  1252. if (err == -ENOENT) {
  1253. sprintf(message, "RtAudio: ALSA pcm device (%s) doesn't handle output!", info->name);
  1254. error(RtError::DEBUG_WARNING);
  1255. }
  1256. else {
  1257. sprintf(message, "RtAudio: ALSA snd_ctl_pcm_info error for device (%s) output: %s",
  1258. info->name, snd_strerror(err));
  1259. error(RtError::DEBUG_WARNING);
  1260. }
  1261. goto capture_probe;
  1262. }
  1263. err = snd_pcm_open(&handle, info->name, stream, open_mode | SND_PCM_NONBLOCK );
  1264. if (err < 0) {
  1265. if ( err == EBUSY )
  1266. sprintf(message, "RtAudio: ALSA pcm playback device (%s) is busy: %s.",
  1267. info->name, snd_strerror(err));
  1268. else
  1269. sprintf(message, "RtAudio: ALSA pcm playback open (%s) error: %s.",
  1270. info->name, snd_strerror(err));
  1271. error(RtError::DEBUG_WARNING);
  1272. goto capture_probe;
  1273. }
  1274. // We have an open device ... allocate the parameter structure.
  1275. err = snd_pcm_hw_params_any(handle, params);
  1276. if (err < 0) {
  1277. snd_pcm_close(handle);
  1278. sprintf(message, "RtAudio: ALSA hardware probe error (%s): %s.",
  1279. info->name, snd_strerror(err));
  1280. error(RtError::WARNING);
  1281. goto capture_probe;
  1282. }
  1283. // Get output channel information.
  1284. info->minOutputChannels = snd_pcm_hw_params_get_channels_min(params);
  1285. info->maxOutputChannels = snd_pcm_hw_params_get_channels_max(params);
  1286. snd_pcm_close(handle);
  1287. capture_probe:
  1288. // Now try for capture
  1289. stream = SND_PCM_STREAM_CAPTURE;
  1290. snd_pcm_info_set_stream(pcminfo, stream);
  1291. err = snd_ctl_pcm_info(chandle, pcminfo);
  1292. snd_ctl_close(chandle);
  1293. if ( err < 0 ) {
  1294. if (err == -ENOENT) {
  1295. sprintf(message, "RtAudio: ALSA pcm device (%s) doesn't handle input!", info->name);
  1296. error(RtError::DEBUG_WARNING);
  1297. }
  1298. else {
  1299. sprintf(message, "RtAudio: ALSA snd_ctl_pcm_info error for device (%s) input: %s",
  1300. info->name, snd_strerror(err));
  1301. error(RtError::DEBUG_WARNING);
  1302. }
  1303. if (info->maxOutputChannels == 0)
  1304. // didn't open for playback either ... device invalid
  1305. return;
  1306. goto probe_parameters;
  1307. }
  1308. err = snd_pcm_open(&handle, info->name, stream, open_mode | SND_PCM_NONBLOCK);
  1309. if (err < 0) {
  1310. if ( err == EBUSY )
  1311. sprintf(message, "RtAudio: ALSA pcm capture device (%s) is busy: %s.",
  1312. info->name, snd_strerror(err));
  1313. else
  1314. sprintf(message, "RtAudio: ALSA pcm capture open (%s) error: %s.",
  1315. info->name, snd_strerror(err));
  1316. error(RtError::DEBUG_WARNING);
  1317. if (info->maxOutputChannels == 0)
  1318. // didn't open for playback either ... device invalid
  1319. return;
  1320. goto probe_parameters;
  1321. }
  1322. // We have an open capture device ... allocate the parameter structure.
  1323. err = snd_pcm_hw_params_any(handle, params);
  1324. if (err < 0) {
  1325. snd_pcm_close(handle);
  1326. sprintf(message, "RtAudio: ALSA hardware probe error (%s): %s.",
  1327. info->name, snd_strerror(err));
  1328. error(RtError::WARNING);
  1329. if (info->maxOutputChannels > 0)
  1330. goto probe_parameters;
  1331. else
  1332. return;
  1333. }
  1334. // Get input channel information.
  1335. info->minInputChannels = snd_pcm_hw_params_get_channels_min(params);
  1336. info->maxInputChannels = snd_pcm_hw_params_get_channels_max(params);
  1337. snd_pcm_close(handle);
  1338. // If device opens for both playback and capture, we determine the channels.
  1339. if (info->maxOutputChannels == 0 || info->maxInputChannels == 0)
  1340. goto probe_parameters;
  1341. info->hasDuplexSupport = true;
  1342. info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ?
  1343. info->maxInputChannels : info->maxOutputChannels;
  1344. info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ?
  1345. info->minInputChannels : info->minOutputChannels;
  1346. probe_parameters:
  1347. // At this point, we just need to figure out the supported data
  1348. // formats and sample rates. We'll proceed by opening the device in
  1349. // the direction with the maximum number of channels, or playback if
  1350. // they are equal. This might limit our sample rate options, but so
  1351. // be it.
  1352. if (info->maxOutputChannels >= info->maxInputChannels)
  1353. stream = SND_PCM_STREAM_PLAYBACK;
  1354. else
  1355. stream = SND_PCM_STREAM_CAPTURE;
  1356. err = snd_pcm_open(&handle, info->name, stream, open_mode);
  1357. if (err < 0) {
  1358. sprintf(message, "RtAudio: ALSA pcm (%s) won't reopen during probe: %s.",
  1359. info->name, snd_strerror(err));
  1360. error(RtError::WARNING);
  1361. return;
  1362. }
  1363. // We have an open device ... allocate the parameter structure.
  1364. err = snd_pcm_hw_params_any(handle, params);
  1365. if (err < 0) {
  1366. snd_pcm_close(handle);
  1367. sprintf(message, "RtAudio: ALSA hardware reopen probe error (%s): %s.",
  1368. info->name, snd_strerror(err));
  1369. error(RtError::WARNING);
  1370. return;
  1371. }
  1372. // Test a non-standard sample rate to see if continuous rate is supported.
  1373. int dir = 0;
  1374. if (snd_pcm_hw_params_test_rate(handle, params, 35500, dir) == 0) {
  1375. // It appears that continuous sample rate support is available.
  1376. info->nSampleRates = -1;
  1377. info->sampleRates[0] = snd_pcm_hw_params_get_rate_min(params, &dir);
  1378. info->sampleRates[1] = snd_pcm_hw_params_get_rate_max(params, &dir);
  1379. }
  1380. else {
  1381. // No continuous rate support ... test our discrete set of sample rate values.
  1382. info->nSampleRates = 0;
  1383. for (int i=0; i<MAX_SAMPLE_RATES; i++) {
  1384. if (snd_pcm_hw_params_test_rate(handle, params, SAMPLE_RATES[i], dir) == 0) {
  1385. info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
  1386. info->nSampleRates++;
  1387. }
  1388. }
  1389. if (info->nSampleRates == 0) {
  1390. snd_pcm_close(handle);
  1391. return;
  1392. }
  1393. }
  1394. // Probe the supported data formats ... we don't care about endian-ness just yet
  1395. snd_pcm_format_t format;
  1396. info->nativeFormats = 0;
  1397. format = SND_PCM_FORMAT_S8;
  1398. if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
  1399. info->nativeFormats |= RTAUDIO_SINT8;
  1400. format = SND_PCM_FORMAT_S16;
  1401. if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
  1402. info->nativeFormats |= RTAUDIO_SINT16;
  1403. format = SND_PCM_FORMAT_S24;
  1404. if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
  1405. info->nativeFormats |= RTAUDIO_SINT24;
  1406. format = SND_PCM_FORMAT_S32;
  1407. if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
  1408. info->nativeFormats |= RTAUDIO_SINT32;
  1409. format = SND_PCM_FORMAT_FLOAT;
  1410. if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
  1411. info->nativeFormats |= RTAUDIO_FLOAT32;
  1412. format = SND_PCM_FORMAT_FLOAT64;
  1413. if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
  1414. info->nativeFormats |= RTAUDIO_FLOAT64;
  1415. // Check that we have at least one supported format
  1416. if (info->nativeFormats == 0) {
  1417. snd_pcm_close(handle);
  1418. sprintf(message, "RtAudio: ALSA PCM device (%s) data format not supported by RtAudio.",
  1419. info->name);
  1420. error(RtError::WARNING);
  1421. return;
  1422. }
  1423. // That's all ... close the device and return
  1424. snd_pcm_close(handle);
  1425. info->probed = true;
  1426. return;
  1427. }
  1428. bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
  1429. STREAM_MODE mode, int channels,
  1430. int sampleRate, RTAUDIO_FORMAT format,
  1431. int *bufferSize, int numberOfBuffers)
  1432. {
  1433. #if defined(__RTAUDIO_DEBUG__)
  1434. snd_output_t *out;
  1435. snd_output_stdio_attach(&out, stderr, 0);
  1436. #endif
  1437. // I'm not using the "plug" interface ... too much inconsistent behavior.
  1438. const char *name = devices[device].name;
  1439. snd_pcm_stream_t alsa_stream;
  1440. if (mode == OUTPUT)
  1441. alsa_stream = SND_PCM_STREAM_PLAYBACK;
  1442. else
  1443. alsa_stream = SND_PCM_STREAM_CAPTURE;
  1444. int err;
  1445. snd_pcm_t *handle;
  1446. int alsa_open_mode = SND_PCM_ASYNC;
  1447. err = snd_pcm_open(&handle, name, alsa_stream, alsa_open_mode);
  1448. if (err < 0) {
  1449. sprintf(message,"RtAudio: ALSA pcm device (%s) won't open: %s.",
  1450. name, snd_strerror(err));
  1451. error(RtError::WARNING);
  1452. return FAILURE;
  1453. }
  1454. // Fill the parameter structure.
  1455. snd_pcm_hw_params_t *hw_params;
  1456. snd_pcm_hw_params_alloca(&hw_params);
  1457. err = snd_pcm_hw_params_any(handle, hw_params);
  1458. if (err < 0) {
  1459. snd_pcm_close(handle);
  1460. sprintf(message, "RtAudio: ALSA error getting parameter handle (%s): %s.",
  1461. name, snd_strerror(err));
  1462. error(RtError::WARNING);
  1463. return FAILURE;
  1464. }
  1465. #if defined(__RTAUDIO_DEBUG__)
  1466. fprintf(stderr, "\nRtAudio: ALSA dump hardware params just after device open:\n\n");
  1467. snd_pcm_hw_params_dump(hw_params, out);
  1468. #endif
  1469. // Set access ... try interleaved access first, then non-interleaved
  1470. if ( !snd_pcm_hw_params_test_access( handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED) ) {
  1471. err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
  1472. }
  1473. else if ( !snd_pcm_hw_params_test_access( handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED) ) {
  1474. err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED);
  1475. stream->deInterleave[mode] = true;
  1476. }
  1477. else {
  1478. snd_pcm_close(handle);
  1479. sprintf(message, "RtAudio: ALSA device (%s) access not supported by RtAudio.", name);
  1480. error(RtError::WARNING);
  1481. return FAILURE;
  1482. }
  1483. if (err < 0) {
  1484. snd_pcm_close(handle);
  1485. sprintf(message, "RtAudio: ALSA error setting access ( (%s): %s.", name, snd_strerror(err));
  1486. error(RtError::WARNING);
  1487. return FAILURE;
  1488. }
  1489. // Determine how to set the device format.
  1490. stream->userFormat = format;
  1491. snd_pcm_format_t device_format;
  1492. if (format == RTAUDIO_SINT8)
  1493. device_format = SND_PCM_FORMAT_S8;
  1494. else if (format == RTAUDIO_SINT16)
  1495. device_format = SND_PCM_FORMAT_S16;
  1496. else if (format == RTAUDIO_SINT24)
  1497. device_format = SND_PCM_FORMAT_S24;
  1498. else if (format == RTAUDIO_SINT32)
  1499. device_format = SND_PCM_FORMAT_S32;
  1500. else if (format == RTAUDIO_FLOAT32)
  1501. device_format = SND_PCM_FORMAT_FLOAT;
  1502. else if (format == RTAUDIO_FLOAT64)
  1503. device_format = SND_PCM_FORMAT_FLOAT64;
  1504. if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
  1505. stream->deviceFormat[mode] = format;
  1506. goto set_format;
  1507. }
  1508. // The user requested format is not natively supported by the device.
  1509. device_format = SND_PCM_FORMAT_FLOAT64;
  1510. if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
  1511. stream->deviceFormat[mode] = RTAUDIO_FLOAT64;
  1512. goto set_format;
  1513. }
  1514. device_format = SND_PCM_FORMAT_FLOAT;
  1515. if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
  1516. stream->deviceFormat[mode] = RTAUDIO_FLOAT32;
  1517. goto set_format;
  1518. }
  1519. device_format = SND_PCM_FORMAT_S32;
  1520. if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
  1521. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  1522. goto set_format;
  1523. }
  1524. device_format = SND_PCM_FORMAT_S24;
  1525. if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
  1526. stream->deviceFormat[mode] = RTAUDIO_SINT24;
  1527. goto set_format;
  1528. }
  1529. device_format = SND_PCM_FORMAT_S16;
  1530. if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
  1531. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  1532. goto set_format;
  1533. }
  1534. device_format = SND_PCM_FORMAT_S8;
  1535. if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
  1536. stream->deviceFormat[mode] = RTAUDIO_SINT8;
  1537. goto set_format;
  1538. }
  1539. // If we get here, no supported format was found.
  1540. sprintf(message,"RtAudio: ALSA pcm device (%s) data format not supported by RtAudio.", name);
  1541. snd_pcm_close(handle);
  1542. error(RtError::WARNING);
  1543. return FAILURE;
  1544. set_format:
  1545. err = snd_pcm_hw_params_set_format(handle, hw_params, device_format);
  1546. if (err < 0) {
  1547. snd_pcm_close(handle);
  1548. sprintf(message, "RtAudio: ALSA error setting format (%s): %s.",
  1549. name, snd_strerror(err));
  1550. error(RtError::WARNING);
  1551. return FAILURE;
  1552. }
  1553. // Determine whether byte-swaping is necessary.
  1554. stream->doByteSwap[mode] = false;
  1555. if (device_format != SND_PCM_FORMAT_S8) {
  1556. err = snd_pcm_format_cpu_endian(device_format);
  1557. if (err == 0)
  1558. stream->doByteSwap[mode] = true;
  1559. else if (err < 0) {
  1560. snd_pcm_close(handle);
  1561. sprintf(message, "RtAudio: ALSA error getting format endian-ness (%s): %s.",
  1562. name, snd_strerror(err));
  1563. error(RtError::WARNING);
  1564. return FAILURE;
  1565. }
  1566. }
  1567. // Set the sample rate.
  1568. err = snd_pcm_hw_params_set_rate(handle, hw_params, (unsigned int)sampleRate, 0);
  1569. if (err < 0) {
  1570. snd_pcm_close(handle);
  1571. sprintf(message, "RtAudio: ALSA error setting sample rate (%d) on device (%s): %s.",
  1572. sampleRate, name, snd_strerror(err));
  1573. error(RtError::WARNING);
  1574. return FAILURE;
  1575. }
  1576. // Determine the number of channels for this device. We support a possible
  1577. // minimum device channel number > than the value requested by the user.
  1578. stream->nUserChannels[mode] = channels;
  1579. int device_channels = snd_pcm_hw_params_get_channels_max(hw_params);
  1580. if (device_channels < channels) {
  1581. snd_pcm_close(handle);
  1582. sprintf(message, "RtAudio: channels (%d) not supported by device (%s).",
  1583. channels, name);
  1584. error(RtError::WARNING);
  1585. return FAILURE;
  1586. }
  1587. device_channels = snd_pcm_hw_params_get_channels_min(hw_params);
  1588. if (device_channels < channels) device_channels = channels;
  1589. stream->nDeviceChannels[mode] = device_channels;
  1590. // Set the device channels.
  1591. err = snd_pcm_hw_params_set_channels(handle, hw_params, device_channels);
  1592. if (err < 0) {
  1593. snd_pcm_close(handle);
  1594. sprintf(message, "RtAudio: ALSA error setting channels (%d) on device (%s): %s.",
  1595. device_channels, name, snd_strerror(err));
  1596. error(RtError::WARNING);
  1597. return FAILURE;
  1598. }
  1599. // Set the buffer number, which in ALSA is referred to as the "period".
  1600. int dir;
  1601. int periods = numberOfBuffers;
  1602. // Even though the hardware might allow 1 buffer, it won't work reliably.
  1603. if (periods < 2) periods = 2;
  1604. err = snd_pcm_hw_params_get_periods_min(hw_params, &dir);
  1605. if (err > periods) periods = err;
  1606. err = snd_pcm_hw_params_get_periods_max(hw_params, &dir);
  1607. if (err < periods) periods = err;
  1608. err = snd_pcm_hw_params_set_periods(handle, hw_params, periods, 0);
  1609. if (err < 0) {
  1610. snd_pcm_close(handle);
  1611. sprintf(message, "RtAudio: ALSA error setting periods (%s): %s.",
  1612. name, snd_strerror(err));
  1613. error(RtError::WARNING);
  1614. return FAILURE;
  1615. }
  1616. // Set the buffer (or period) size.
  1617. err = snd_pcm_hw_params_get_period_size_min(hw_params, &dir);
  1618. if (err > *bufferSize) *bufferSize = err;
  1619. err = snd_pcm_hw_params_set_period_size(handle, hw_params, *bufferSize, 0);
  1620. if (err < 0) {
  1621. snd_pcm_close(handle);
  1622. sprintf(message, "RtAudio: ALSA error setting period size (%s): %s.",
  1623. name, snd_strerror(err));
  1624. error(RtError::WARNING);
  1625. return FAILURE;
  1626. }
  1627. // If attempting to setup a duplex stream, the bufferSize parameter
  1628. // MUST be the same in both directions!
  1629. if ( stream->mode == OUTPUT && mode == INPUT && *bufferSize != stream->bufferSize ) {
  1630. sprintf( message, "RtAudio: ALSA error setting buffer size for duplex stream on device (%s).",
  1631. name );
  1632. error(RtError::DEBUG_WARNING);
  1633. return FAILURE;
  1634. }
  1635. stream->bufferSize = *bufferSize;
  1636. // Install the hardware configuration
  1637. err = snd_pcm_hw_params(handle, hw_params);
  1638. if (err < 0) {
  1639. snd_pcm_close(handle);
  1640. sprintf(message, "RtAudio: ALSA error installing hardware configuration (%s): %s.",
  1641. name, snd_strerror(err));
  1642. error(RtError::WARNING);
  1643. return FAILURE;
  1644. }
  1645. #if defined(__RTAUDIO_DEBUG__)
  1646. fprintf(stderr, "\nRtAudio: ALSA dump hardware params after installation:\n\n");
  1647. snd_pcm_hw_params_dump(hw_params, out);
  1648. #endif
  1649. /*
  1650. // Install the software configuration
  1651. snd_pcm_sw_params_t *sw_params = NULL;
  1652. snd_pcm_sw_params_alloca(&sw_params);
  1653. snd_pcm_sw_params_current(handle, sw_params);
  1654. err = snd_pcm_sw_params(handle, sw_params);
  1655. if (err < 0) {
  1656. snd_pcm_close(handle);
  1657. sprintf(message, "RtAudio: ALSA error installing software configuration (%s): %s.",
  1658. name, snd_strerror(err));
  1659. error(RtError::WARNING);
  1660. return FAILURE;
  1661. }
  1662. */
  1663. // Set handle and flags for buffer conversion
  1664. stream->handle[mode] = handle;
  1665. stream->doConvertBuffer[mode] = false;
  1666. if (stream->userFormat != stream->deviceFormat[mode])
  1667. stream->doConvertBuffer[mode] = true;
  1668. if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode])
  1669. stream->doConvertBuffer[mode] = true;
  1670. if (stream->nUserChannels[mode] > 1 && stream->deInterleave[mode])
  1671. stream->doConvertBuffer[mode] = true;
  1672. // Allocate necessary internal buffers
  1673. if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) {
  1674. long buffer_bytes;
  1675. if (stream->nUserChannels[0] >= stream->nUserChannels[1])
  1676. buffer_bytes = stream->nUserChannels[0];
  1677. else
  1678. buffer_bytes = stream->nUserChannels[1];
  1679. buffer_bytes *= *bufferSize * formatBytes(stream->userFormat);
  1680. if (stream->userBuffer) free(stream->userBuffer);
  1681. stream->userBuffer = (char *) calloc(buffer_bytes, 1);
  1682. if (stream->userBuffer == NULL)
  1683. goto memory_error;
  1684. }
  1685. if ( stream->doConvertBuffer[mode] ) {
  1686. long buffer_bytes;
  1687. bool makeBuffer = true;
  1688. if ( mode == OUTPUT )
  1689. buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  1690. else { // mode == INPUT
  1691. buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
  1692. if ( stream->mode == OUTPUT && stream->deviceBuffer ) {
  1693. long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  1694. if ( buffer_bytes < bytes_out ) makeBuffer = false;
  1695. }
  1696. }
  1697. if ( makeBuffer ) {
  1698. buffer_bytes *= *bufferSize;
  1699. if (stream->deviceBuffer) free(stream->deviceBuffer);
  1700. stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
  1701. if (stream->deviceBuffer == NULL)
  1702. goto memory_error;
  1703. }
  1704. }
  1705. stream->device[mode] = device;
  1706. stream->state = STREAM_STOPPED;
  1707. if ( stream->mode == OUTPUT && mode == INPUT )
  1708. // We had already set up an output stream.
  1709. stream->mode = DUPLEX;
  1710. else
  1711. stream->mode = mode;
  1712. stream->nBuffers = periods;
  1713. stream->sampleRate = sampleRate;
  1714. return SUCCESS;
  1715. memory_error:
  1716. if (stream->handle[0]) {
  1717. snd_pcm_close(stream->handle[0]);
  1718. stream->handle[0] = 0;
  1719. }
  1720. if (stream->handle[1]) {
  1721. snd_pcm_close(stream->handle[1]);
  1722. stream->handle[1] = 0;
  1723. }
  1724. if (stream->userBuffer) {
  1725. free(stream->userBuffer);
  1726. stream->userBuffer = 0;
  1727. }
  1728. sprintf(message, "RtAudio: ALSA error allocating buffer memory (%s).", name);
  1729. error(RtError::WARNING);
  1730. return FAILURE;
  1731. }
  1732. void RtAudio :: closeStream(int streamId)
  1733. {
  1734. // We don't want an exception to be thrown here because this
  1735. // function is called by our class destructor. So, do our own
  1736. // streamId check.
  1737. if ( streams.find( streamId ) == streams.end() ) {
  1738. sprintf(message, "RtAudio: invalid stream identifier!");
  1739. error(RtError::WARNING);
  1740. return;
  1741. }
  1742. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId];
  1743. if (stream->callbackInfo.usingCallback) {
  1744. pthread_cancel(stream->callbackInfo.thread);
  1745. pthread_join(stream->callbackInfo.thread, NULL);
  1746. }
  1747. if (stream->state == STREAM_RUNNING) {
  1748. if (stream->mode == OUTPUT || stream->mode == DUPLEX)
  1749. snd_pcm_drop(stream->handle[0]);
  1750. if (stream->mode == INPUT || stream->mode == DUPLEX)
  1751. snd_pcm_drop(stream->handle[1]);
  1752. }
  1753. pthread_mutex_destroy(&stream->mutex);
  1754. if (stream->handle[0])
  1755. snd_pcm_close(stream->handle[0]);
  1756. if (stream->handle[1])
  1757. snd_pcm_close(stream->handle[1]);
  1758. if (stream->userBuffer)
  1759. free(stream->userBuffer);
  1760. if (stream->deviceBuffer)
  1761. free(stream->deviceBuffer);
  1762. free(stream);
  1763. streams.erase(streamId);
  1764. }
  1765. void RtAudio :: startStream(int streamId)
  1766. {
  1767. // This method calls snd_pcm_prepare if the device isn't already in that state.
  1768. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1769. MUTEX_LOCK(&stream->mutex);
  1770. if (stream->state == STREAM_RUNNING)
  1771. goto unlock;
  1772. int err;
  1773. snd_pcm_state_t state;
  1774. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  1775. state = snd_pcm_state(stream->handle[0]);
  1776. if (state != SND_PCM_STATE_PREPARED) {
  1777. err = snd_pcm_prepare(stream->handle[0]);
  1778. if (err < 0) {
  1779. sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.",
  1780. devices[stream->device[0]].name, snd_strerror(err));
  1781. MUTEX_UNLOCK(&stream->mutex);
  1782. error(RtError::DRIVER_ERROR);
  1783. }
  1784. }
  1785. }
  1786. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  1787. state = snd_pcm_state(stream->handle[1]);
  1788. if (state != SND_PCM_STATE_PREPARED) {
  1789. err = snd_pcm_prepare(stream->handle[1]);
  1790. if (err < 0) {
  1791. sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.",
  1792. devices[stream->device[1]].name, snd_strerror(err));
  1793. MUTEX_UNLOCK(&stream->mutex);
  1794. error(RtError::DRIVER_ERROR);
  1795. }
  1796. }
  1797. }
  1798. stream->state = STREAM_RUNNING;
  1799. unlock:
  1800. MUTEX_UNLOCK(&stream->mutex);
  1801. }
  1802. void RtAudio :: stopStream(int streamId)
  1803. {
  1804. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1805. MUTEX_LOCK(&stream->mutex);
  1806. if (stream->state == STREAM_STOPPED)
  1807. goto unlock;
  1808. int err;
  1809. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  1810. err = snd_pcm_drain(stream->handle[0]);
  1811. if (err < 0) {
  1812. sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
  1813. devices[stream->device[0]].name, snd_strerror(err));
  1814. MUTEX_UNLOCK(&stream->mutex);
  1815. error(RtError::DRIVER_ERROR);
  1816. }
  1817. }
  1818. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  1819. err = snd_pcm_drain(stream->handle[1]);
  1820. if (err < 0) {
  1821. sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
  1822. devices[stream->device[1]].name, snd_strerror(err));
  1823. MUTEX_UNLOCK(&stream->mutex);
  1824. error(RtError::DRIVER_ERROR);
  1825. }
  1826. }
  1827. stream->state = STREAM_STOPPED;
  1828. unlock:
  1829. MUTEX_UNLOCK(&stream->mutex);
  1830. }
  1831. void RtAudio :: abortStream(int streamId)
  1832. {
  1833. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1834. MUTEX_LOCK(&stream->mutex);
  1835. if (stream->state == STREAM_STOPPED)
  1836. goto unlock;
  1837. int err;
  1838. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  1839. err = snd_pcm_drop(stream->handle[0]);
  1840. if (err < 0) {
  1841. sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
  1842. devices[stream->device[0]].name, snd_strerror(err));
  1843. MUTEX_UNLOCK(&stream->mutex);
  1844. error(RtError::DRIVER_ERROR);
  1845. }
  1846. }
  1847. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  1848. err = snd_pcm_drop(stream->handle[1]);
  1849. if (err < 0) {
  1850. sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
  1851. devices[stream->device[1]].name, snd_strerror(err));
  1852. MUTEX_UNLOCK(&stream->mutex);
  1853. error(RtError::DRIVER_ERROR);
  1854. }
  1855. }
  1856. stream->state = STREAM_STOPPED;
  1857. unlock:
  1858. MUTEX_UNLOCK(&stream->mutex);
  1859. }
  1860. int RtAudio :: streamWillBlock(int streamId)
  1861. {
  1862. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1863. MUTEX_LOCK(&stream->mutex);
  1864. int err = 0, frames = 0;
  1865. if (stream->state == STREAM_STOPPED)
  1866. goto unlock;
  1867. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  1868. err = snd_pcm_avail_update(stream->handle[0]);
  1869. if (err < 0) {
  1870. sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.",
  1871. devices[stream->device[0]].name, snd_strerror(err));
  1872. MUTEX_UNLOCK(&stream->mutex);
  1873. error(RtError::DRIVER_ERROR);
  1874. }
  1875. }
  1876. frames = err;
  1877. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  1878. err = snd_pcm_avail_update(stream->handle[1]);
  1879. if (err < 0) {
  1880. sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.",
  1881. devices[stream->device[1]].name, snd_strerror(err));
  1882. MUTEX_UNLOCK(&stream->mutex);
  1883. error(RtError::DRIVER_ERROR);
  1884. }
  1885. if (frames > err) frames = err;
  1886. }
  1887. frames = stream->bufferSize - frames;
  1888. if (frames < 0) frames = 0;
  1889. unlock:
  1890. MUTEX_UNLOCK(&stream->mutex);
  1891. return frames;
  1892. }
  1893. void RtAudio :: tickStream(int streamId)
  1894. {
  1895. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  1896. int stopStream = 0;
  1897. if (stream->state == STREAM_STOPPED) {
  1898. if (stream->callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds
  1899. return;
  1900. }
  1901. else if (stream->callbackInfo.usingCallback) {
  1902. RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback;
  1903. stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData);
  1904. }
  1905. MUTEX_LOCK(&stream->mutex);
  1906. // The state might change while waiting on a mutex.
  1907. if (stream->state == STREAM_STOPPED)
  1908. goto unlock;
  1909. int err;
  1910. char *buffer;
  1911. int channels;
  1912. RTAUDIO_FORMAT format;
  1913. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  1914. // Setup parameters and do buffer conversion if necessary.
  1915. if (stream->doConvertBuffer[0]) {
  1916. convertStreamBuffer(stream, OUTPUT);
  1917. buffer = stream->deviceBuffer;
  1918. channels = stream->nDeviceChannels[0];
  1919. format = stream->deviceFormat[0];
  1920. }
  1921. else {
  1922. buffer = stream->userBuffer;
  1923. channels = stream->nUserChannels[0];
  1924. format = stream->userFormat;
  1925. }
  1926. // Do byte swapping if necessary.
  1927. if (stream->doByteSwap[0])
  1928. byteSwapBuffer(buffer, stream->bufferSize * channels, format);
  1929. // Write samples to device in interleaved/non-interleaved format.
  1930. if (stream->deInterleave[0]) {
  1931. void *bufs[channels];
  1932. size_t offset = stream->bufferSize * formatBytes(format);
  1933. for (int i=0; i<channels; i++)
  1934. bufs[i] = (void *) (buffer + (i * offset));
  1935. err = snd_pcm_writen(stream->handle[0], bufs, stream->bufferSize);
  1936. }
  1937. else
  1938. err = snd_pcm_writei(stream->handle[0], buffer, stream->bufferSize);
  1939. if (err < stream->bufferSize) {
  1940. // Either an error or underrun occured.
  1941. if (err == -EPIPE) {
  1942. snd_pcm_state_t state = snd_pcm_state(stream->handle[0]);
  1943. if (state == SND_PCM_STATE_XRUN) {
  1944. sprintf(message, "RtAudio: ALSA underrun detected.");
  1945. error(RtError::WARNING);
  1946. err = snd_pcm_prepare(stream->handle[0]);
  1947. if (err < 0) {
  1948. sprintf(message, "RtAudio: ALSA error preparing handle after underrun: %s.",
  1949. snd_strerror(err));
  1950. MUTEX_UNLOCK(&stream->mutex);
  1951. error(RtError::DRIVER_ERROR);
  1952. }
  1953. }
  1954. else {
  1955. sprintf(message, "RtAudio: ALSA error, current state is %s.",
  1956. snd_pcm_state_name(state));
  1957. MUTEX_UNLOCK(&stream->mutex);
  1958. error(RtError::DRIVER_ERROR);
  1959. }
  1960. goto unlock;
  1961. }
  1962. else {
  1963. sprintf(message, "RtAudio: ALSA audio write error for device (%s): %s.",
  1964. devices[stream->device[0]].name, snd_strerror(err));
  1965. MUTEX_UNLOCK(&stream->mutex);
  1966. error(RtError::DRIVER_ERROR);
  1967. }
  1968. }
  1969. }
  1970. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  1971. // Setup parameters.
  1972. if (stream->doConvertBuffer[1]) {
  1973. buffer = stream->deviceBuffer;
  1974. channels = stream->nDeviceChannels[1];
  1975. format = stream->deviceFormat[1];
  1976. }
  1977. else {
  1978. buffer = stream->userBuffer;
  1979. channels = stream->nUserChannels[1];
  1980. format = stream->userFormat;
  1981. }
  1982. // Read samples from device in interleaved/non-interleaved format.
  1983. if (stream->deInterleave[1]) {
  1984. void *bufs[channels];
  1985. size_t offset = stream->bufferSize * formatBytes(format);
  1986. for (int i=0; i<channels; i++)
  1987. bufs[i] = (void *) (buffer + (i * offset));
  1988. err = snd_pcm_readn(stream->handle[1], bufs, stream->bufferSize);
  1989. }
  1990. else
  1991. err = snd_pcm_readi(stream->handle[1], buffer, stream->bufferSize);
  1992. if (err < stream->bufferSize) {
  1993. // Either an error or underrun occured.
  1994. if (err == -EPIPE) {
  1995. snd_pcm_state_t state = snd_pcm_state(stream->handle[1]);
  1996. if (state == SND_PCM_STATE_XRUN) {
  1997. sprintf(message, "RtAudio: ALSA overrun detected.");
  1998. error(RtError::WARNING);
  1999. err = snd_pcm_prepare(stream->handle[1]);
  2000. if (err < 0) {
  2001. sprintf(message, "RtAudio: ALSA error preparing handle after overrun: %s.",
  2002. snd_strerror(err));
  2003. MUTEX_UNLOCK(&stream->mutex);
  2004. error(RtError::DRIVER_ERROR);
  2005. }
  2006. }
  2007. else {
  2008. sprintf(message, "RtAudio: ALSA error, current state is %s.",
  2009. snd_pcm_state_name(state));
  2010. MUTEX_UNLOCK(&stream->mutex);
  2011. error(RtError::DRIVER_ERROR);
  2012. }
  2013. goto unlock;
  2014. }
  2015. else {
  2016. sprintf(message, "RtAudio: ALSA audio read error for device (%s): %s.",
  2017. devices[stream->device[1]].name, snd_strerror(err));
  2018. MUTEX_UNLOCK(&stream->mutex);
  2019. error(RtError::DRIVER_ERROR);
  2020. }
  2021. }
  2022. // Do byte swapping if necessary.
  2023. if (stream->doByteSwap[1])
  2024. byteSwapBuffer(buffer, stream->bufferSize * channels, format);
  2025. // Do buffer conversion if necessary.
  2026. if (stream->doConvertBuffer[1])
  2027. convertStreamBuffer(stream, INPUT);
  2028. }
  2029. unlock:
  2030. MUTEX_UNLOCK(&stream->mutex);
  2031. if (stream->callbackInfo.usingCallback && stopStream)
  2032. this->stopStream(streamId);
  2033. }
  2034. extern "C" void *callbackHandler(void *ptr)
  2035. {
  2036. CALLBACK_INFO *info = (CALLBACK_INFO *) ptr;
  2037. RtAudio *object = (RtAudio *) info->object;
  2038. int stream = info->streamId;
  2039. bool *usingCallback = &info->usingCallback;
  2040. while ( *usingCallback ) {
  2041. pthread_testcancel();
  2042. try {
  2043. object->tickStream(stream);
  2044. }
  2045. catch (RtError &exception) {
  2046. fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n",
  2047. exception.getMessage());
  2048. break;
  2049. }
  2050. }
  2051. return 0;
  2052. }
  2053. //******************** End of __LINUX_ALSA__ *********************//
  2054. #elif defined(__LINUX_OSS__)
  2055. #include <sys/stat.h>
  2056. #include <sys/types.h>
  2057. #include <sys/ioctl.h>
  2058. #include <unistd.h>
  2059. #include <fcntl.h>
  2060. #include <sys/soundcard.h>
  2061. #include <errno.h>
  2062. #include <math.h>
  2063. #define DAC_NAME "/dev/dsp"
  2064. #define MAX_DEVICES 16
  2065. #define MAX_CHANNELS 16
  2066. void RtAudio :: initialize(void)
  2067. {
  2068. // Count cards and devices
  2069. nDevices = 0;
  2070. // We check /dev/dsp before probing devices. /dev/dsp is supposed to
  2071. // be a link to the "default" audio device, of the form /dev/dsp0,
  2072. // /dev/dsp1, etc... However, I've seen many cases where /dev/dsp was a
  2073. // real device, so we need to check for that. Also, sometimes the
  2074. // link is to /dev/dspx and other times just dspx. I'm not sure how
  2075. // the latter works, but it does.
  2076. char device_name[16];
  2077. struct stat dspstat;
  2078. int dsplink = -1;
  2079. int i = 0;
  2080. if (lstat(DAC_NAME, &dspstat) == 0) {
  2081. if (S_ISLNK(dspstat.st_mode)) {
  2082. i = readlink(DAC_NAME, device_name, sizeof(device_name));
  2083. if (i > 0) {
  2084. device_name[i] = '\0';
  2085. if (i > 8) { // check for "/dev/dspx"
  2086. if (!strncmp(DAC_NAME, device_name, 8))
  2087. dsplink = atoi(&device_name[8]);
  2088. }
  2089. else if (i > 3) { // check for "dspx"
  2090. if (!strncmp("dsp", device_name, 3))
  2091. dsplink = atoi(&device_name[3]);
  2092. }
  2093. }
  2094. else {
  2095. sprintf(message, "RtAudio: cannot read value of symbolic link %s.", DAC_NAME);
  2096. error(RtError::SYSTEM_ERROR);
  2097. }
  2098. }
  2099. }
  2100. else {
  2101. sprintf(message, "RtAudio: cannot stat %s.", DAC_NAME);
  2102. error(RtError::SYSTEM_ERROR);
  2103. }
  2104. // The OSS API doesn't provide a routine for determining the number
  2105. // of devices. Thus, we'll just pursue a brute force method. The
  2106. // idea is to start with /dev/dsp(0) and continue with higher device
  2107. // numbers until we reach MAX_DSP_DEVICES. This should tell us how
  2108. // many devices we have ... it is not a fullproof scheme, but hopefully
  2109. // it will work most of the time.
  2110. int fd = 0;
  2111. char names[MAX_DEVICES][16];
  2112. for (i=-1; i<MAX_DEVICES; i++) {
  2113. // Probe /dev/dsp first, since it is supposed to be the default device.
  2114. if (i == -1)
  2115. sprintf(device_name, "%s", DAC_NAME);
  2116. else if (i == dsplink)
  2117. continue; // We've aready probed this device via /dev/dsp link ... try next device.
  2118. else
  2119. sprintf(device_name, "%s%d", DAC_NAME, i);
  2120. // First try to open the device for playback, then record mode.
  2121. fd = open(device_name, O_WRONLY | O_NONBLOCK);
  2122. if (fd == -1) {
  2123. // Open device for playback failed ... either busy or doesn't exist.
  2124. if (errno != EBUSY && errno != EAGAIN) {
  2125. // Try to open for capture
  2126. fd = open(device_name, O_RDONLY | O_NONBLOCK);
  2127. if (fd == -1) {
  2128. // Open device for record failed.
  2129. if (errno != EBUSY && errno != EAGAIN)
  2130. continue;
  2131. else {
  2132. sprintf(message, "RtAudio: OSS record device (%s) is busy.", device_name);
  2133. error(RtError::WARNING);
  2134. // still count it for now
  2135. }
  2136. }
  2137. }
  2138. else {
  2139. sprintf(message, "RtAudio: OSS playback device (%s) is busy.", device_name);
  2140. error(RtError::WARNING);
  2141. // still count it for now
  2142. }
  2143. }
  2144. if (fd >= 0) close(fd);
  2145. strncpy(names[nDevices], device_name, 16);
  2146. nDevices++;
  2147. }
  2148. if (nDevices == 0) return;
  2149. // Allocate the RTAUDIO_DEVICE structures.
  2150. devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
  2151. if (devices == NULL) {
  2152. sprintf(message, "RtAudio: memory allocation error!");
  2153. error(RtError::MEMORY_ERROR);
  2154. }
  2155. // Write device ascii identifiers to device control structure and then probe capabilities.
  2156. for (i=0; i<nDevices; i++) {
  2157. strncpy(devices[i].name, names[i], 16);
  2158. //probeDeviceInfo(&devices[i]);
  2159. }
  2160. return;
  2161. }
  2162. int RtAudio :: getDefaultInputDevice(void)
  2163. {
  2164. // No OSS API functions for default devices.
  2165. return 0;
  2166. }
  2167. int RtAudio :: getDefaultOutputDevice(void)
  2168. {
  2169. // No OSS API functions for default devices.
  2170. return 0;
  2171. }
  2172. void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
  2173. {
  2174. int i, fd, channels, mask;
  2175. // The OSS API doesn't provide a means for probing the capabilities
  2176. // of devices. Thus, we'll just pursue a brute force method.
  2177. // First try for playback
  2178. fd = open(info->name, O_WRONLY | O_NONBLOCK);
  2179. if (fd == -1) {
  2180. // Open device failed ... either busy or doesn't exist
  2181. if (errno == EBUSY || errno == EAGAIN)
  2182. sprintf(message, "RtAudio: OSS playback device (%s) is busy and cannot be probed.",
  2183. info->name);
  2184. else
  2185. sprintf(message, "RtAudio: OSS playback device (%s) open error.", info->name);
  2186. error(RtError::DEBUG_WARNING);
  2187. goto capture_probe;
  2188. }
  2189. // We have an open device ... see how many channels it can handle
  2190. for (i=MAX_CHANNELS; i>0; i--) {
  2191. channels = i;
  2192. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1) {
  2193. // This would normally indicate some sort of hardware error, but under ALSA's
  2194. // OSS emulation, it sometimes indicates an invalid channel value. Further,
  2195. // the returned channel value is not changed. So, we'll ignore the possible
  2196. // hardware error.
  2197. continue; // try next channel number
  2198. }
  2199. // Check to see whether the device supports the requested number of channels
  2200. if (channels != i ) continue; // try next channel number
  2201. // If here, we found the largest working channel value
  2202. break;
  2203. }
  2204. info->maxOutputChannels = i;
  2205. // Now find the minimum number of channels it can handle
  2206. for (i=1; i<=info->maxOutputChannels; i++) {
  2207. channels = i;
  2208. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
  2209. continue; // try next channel number
  2210. // If here, we found the smallest working channel value
  2211. break;
  2212. }
  2213. info->minOutputChannels = i;
  2214. close(fd);
  2215. capture_probe:
  2216. // Now try for capture
  2217. fd = open(info->name, O_RDONLY | O_NONBLOCK);
  2218. if (fd == -1) {
  2219. // Open device for capture failed ... either busy or doesn't exist
  2220. if (errno == EBUSY || errno == EAGAIN)
  2221. sprintf(message, "RtAudio: OSS capture device (%s) is busy and cannot be probed.",
  2222. info->name);
  2223. else
  2224. sprintf(message, "RtAudio: OSS capture device (%s) open error.", info->name);
  2225. error(RtError::DEBUG_WARNING);
  2226. if (info->maxOutputChannels == 0)
  2227. // didn't open for playback either ... device invalid
  2228. return;
  2229. goto probe_parameters;
  2230. }
  2231. // We have the device open for capture ... see how many channels it can handle
  2232. for (i=MAX_CHANNELS; i>0; i--) {
  2233. channels = i;
  2234. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) {
  2235. continue; // as above
  2236. }
  2237. // If here, we found a working channel value
  2238. break;
  2239. }
  2240. info->maxInputChannels = i;
  2241. // Now find the minimum number of channels it can handle
  2242. for (i=1; i<=info->maxInputChannels; i++) {
  2243. channels = i;
  2244. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
  2245. continue; // try next channel number
  2246. // If here, we found the smallest working channel value
  2247. break;
  2248. }
  2249. info->minInputChannels = i;
  2250. close(fd);
  2251. if (info->maxOutputChannels == 0 && info->maxInputChannels == 0) {
  2252. sprintf(message, "RtAudio: OSS device (%s) reports zero channels for input and output.",
  2253. info->name);
  2254. error(RtError::DEBUG_WARNING);
  2255. return;
  2256. }
  2257. // If device opens for both playback and capture, we determine the channels.
  2258. if (info->maxOutputChannels == 0 || info->maxInputChannels == 0)
  2259. goto probe_parameters;
  2260. fd = open(info->name, O_RDWR | O_NONBLOCK);
  2261. if (fd == -1)
  2262. goto probe_parameters;
  2263. ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
  2264. ioctl(fd, SNDCTL_DSP_GETCAPS, &mask);
  2265. if (mask & DSP_CAP_DUPLEX) {
  2266. info->hasDuplexSupport = true;
  2267. // We have the device open for duplex ... see how many channels it can handle
  2268. for (i=MAX_CHANNELS; i>0; i--) {
  2269. channels = i;
  2270. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
  2271. continue; // as above
  2272. // If here, we found a working channel value
  2273. break;
  2274. }
  2275. info->maxDuplexChannels = i;
  2276. // Now find the minimum number of channels it can handle
  2277. for (i=1; i<=info->maxDuplexChannels; i++) {
  2278. channels = i;
  2279. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
  2280. continue; // try next channel number
  2281. // If here, we found the smallest working channel value
  2282. break;
  2283. }
  2284. info->minDuplexChannels = i;
  2285. }
  2286. close(fd);
  2287. probe_parameters:
  2288. // At this point, we need to figure out the supported data formats
  2289. // and sample rates. We'll proceed by openning the device in the
  2290. // direction with the maximum number of channels, or playback if
  2291. // they are equal. This might limit our sample rate options, but so
  2292. // be it.
  2293. if (info->maxOutputChannels >= info->maxInputChannels) {
  2294. fd = open(info->name, O_WRONLY | O_NONBLOCK);
  2295. channels = info->maxOutputChannels;
  2296. }
  2297. else {
  2298. fd = open(info->name, O_RDONLY | O_NONBLOCK);
  2299. channels = info->maxInputChannels;
  2300. }
  2301. if (fd == -1) {
  2302. // We've got some sort of conflict ... abort
  2303. sprintf(message, "RtAudio: OSS device (%s) won't reopen during probe.",
  2304. info->name);
  2305. error(RtError::DEBUG_WARNING);
  2306. return;
  2307. }
  2308. // We have an open device ... set to maximum channels.
  2309. i = channels;
  2310. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) {
  2311. // We've got some sort of conflict ... abort
  2312. close(fd);
  2313. sprintf(message, "RtAudio: OSS device (%s) won't revert to previous channel setting.",
  2314. info->name);
  2315. error(RtError::DEBUG_WARNING);
  2316. return;
  2317. }
  2318. if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) {
  2319. close(fd);
  2320. sprintf(message, "RtAudio: OSS device (%s) can't get supported audio formats.",
  2321. info->name);
  2322. error(RtError::DEBUG_WARNING);
  2323. return;
  2324. }
  2325. // Probe the supported data formats ... we don't care about endian-ness just yet.
  2326. int format;
  2327. info->nativeFormats = 0;
  2328. #if defined (AFMT_S32_BE)
  2329. // This format does not seem to be in the 2.4 kernel version of OSS soundcard.h
  2330. if (mask & AFMT_S32_BE) {
  2331. format = AFMT_S32_BE;
  2332. info->nativeFormats |= RTAUDIO_SINT32;
  2333. }
  2334. #endif
  2335. #if defined (AFMT_S32_LE)
  2336. /* This format is not in the 2.4.4 kernel version of OSS soundcard.h */
  2337. if (mask & AFMT_S32_LE) {
  2338. format = AFMT_S32_LE;
  2339. info->nativeFormats |= RTAUDIO_SINT32;
  2340. }
  2341. #endif
  2342. if (mask & AFMT_S8) {
  2343. format = AFMT_S8;
  2344. info->nativeFormats |= RTAUDIO_SINT8;
  2345. }
  2346. if (mask & AFMT_S16_BE) {
  2347. format = AFMT_S16_BE;
  2348. info->nativeFormats |= RTAUDIO_SINT16;
  2349. }
  2350. if (mask & AFMT_S16_LE) {
  2351. format = AFMT_S16_LE;
  2352. info->nativeFormats |= RTAUDIO_SINT16;
  2353. }
  2354. // Check that we have at least one supported format
  2355. if (info->nativeFormats == 0) {
  2356. close(fd);
  2357. sprintf(message, "RtAudio: OSS device (%s) data format not supported by RtAudio.",
  2358. info->name);
  2359. error(RtError::DEBUG_WARNING);
  2360. return;
  2361. }
  2362. // Set the format
  2363. i = format;
  2364. if (ioctl(fd, SNDCTL_DSP_SETFMT, &format) == -1 || format != i) {
  2365. close(fd);
  2366. sprintf(message, "RtAudio: OSS device (%s) error setting data format.",
  2367. info->name);
  2368. error(RtError::DEBUG_WARNING);
  2369. return;
  2370. }
  2371. // Probe the supported sample rates ... first get lower limit
  2372. int speed = 1;
  2373. if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) {
  2374. // If we get here, we're probably using an ALSA driver with OSS-emulation,
  2375. // which doesn't conform to the OSS specification. In this case,
  2376. // we'll probe our predefined list of sample rates for working values.
  2377. info->nSampleRates = 0;
  2378. for (i=0; i<MAX_SAMPLE_RATES; i++) {
  2379. speed = SAMPLE_RATES[i];
  2380. if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) != -1) {
  2381. info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
  2382. info->nSampleRates++;
  2383. }
  2384. }
  2385. if (info->nSampleRates == 0) {
  2386. close(fd);
  2387. return;
  2388. }
  2389. goto finished;
  2390. }
  2391. info->sampleRates[0] = speed;
  2392. // Now get upper limit
  2393. speed = 1000000;
  2394. if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) {
  2395. close(fd);
  2396. sprintf(message, "RtAudio: OSS device (%s) error setting sample rate.",
  2397. info->name);
  2398. error(RtError::DEBUG_WARNING);
  2399. return;
  2400. }
  2401. info->sampleRates[1] = speed;
  2402. info->nSampleRates = -1;
  2403. finished: // That's all ... close the device and return
  2404. close(fd);
  2405. info->probed = true;
  2406. return;
  2407. }
  2408. bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
  2409. STREAM_MODE mode, int channels,
  2410. int sampleRate, RTAUDIO_FORMAT format,
  2411. int *bufferSize, int numberOfBuffers)
  2412. {
  2413. int buffers, buffer_bytes, device_channels, device_format;
  2414. int srate, temp, fd;
  2415. const char *name = devices[device].name;
  2416. if (mode == OUTPUT)
  2417. fd = open(name, O_WRONLY | O_NONBLOCK);
  2418. else { // mode == INPUT
  2419. if (stream->mode == OUTPUT && stream->device[0] == device) {
  2420. // We just set the same device for playback ... close and reopen for duplex (OSS only).
  2421. close(stream->handle[0]);
  2422. stream->handle[0] = 0;
  2423. // First check that the number previously set channels is the same.
  2424. if (stream->nUserChannels[0] != channels) {
  2425. sprintf(message, "RtAudio: input/output channels must be equal for OSS duplex device (%s).", name);
  2426. goto error;
  2427. }
  2428. fd = open(name, O_RDWR | O_NONBLOCK);
  2429. }
  2430. else
  2431. fd = open(name, O_RDONLY | O_NONBLOCK);
  2432. }
  2433. if (fd == -1) {
  2434. if (errno == EBUSY || errno == EAGAIN)
  2435. sprintf(message, "RtAudio: OSS device (%s) is busy and cannot be opened.",
  2436. name);
  2437. else
  2438. sprintf(message, "RtAudio: OSS device (%s) cannot be opened.", name);
  2439. goto error;
  2440. }
  2441. // Now reopen in blocking mode.
  2442. close(fd);
  2443. if (mode == OUTPUT)
  2444. fd = open(name, O_WRONLY | O_SYNC);
  2445. else { // mode == INPUT
  2446. if (stream->mode == OUTPUT && stream->device[0] == device)
  2447. fd = open(name, O_RDWR | O_SYNC);
  2448. else
  2449. fd = open(name, O_RDONLY | O_SYNC);
  2450. }
  2451. if (fd == -1) {
  2452. sprintf(message, "RtAudio: OSS device (%s) cannot be opened.", name);
  2453. goto error;
  2454. }
  2455. // Get the sample format mask
  2456. int mask;
  2457. if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) {
  2458. close(fd);
  2459. sprintf(message, "RtAudio: OSS device (%s) can't get supported audio formats.",
  2460. name);
  2461. goto error;
  2462. }
  2463. // Determine how to set the device format.
  2464. stream->userFormat = format;
  2465. device_format = -1;
  2466. stream->doByteSwap[mode] = false;
  2467. if (format == RTAUDIO_SINT8) {
  2468. if (mask & AFMT_S8) {
  2469. device_format = AFMT_S8;
  2470. stream->deviceFormat[mode] = RTAUDIO_SINT8;
  2471. }
  2472. }
  2473. else if (format == RTAUDIO_SINT16) {
  2474. if (mask & AFMT_S16_NE) {
  2475. device_format = AFMT_S16_NE;
  2476. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  2477. }
  2478. #if BYTE_ORDER == LITTLE_ENDIAN
  2479. else if (mask & AFMT_S16_BE) {
  2480. device_format = AFMT_S16_BE;
  2481. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  2482. stream->doByteSwap[mode] = true;
  2483. }
  2484. #else
  2485. else if (mask & AFMT_S16_LE) {
  2486. device_format = AFMT_S16_LE;
  2487. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  2488. stream->doByteSwap[mode] = true;
  2489. }
  2490. #endif
  2491. }
  2492. #if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE)
  2493. else if (format == RTAUDIO_SINT32) {
  2494. if (mask & AFMT_S32_NE) {
  2495. device_format = AFMT_S32_NE;
  2496. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  2497. }
  2498. #if BYTE_ORDER == LITTLE_ENDIAN
  2499. else if (mask & AFMT_S32_BE) {
  2500. device_format = AFMT_S32_BE;
  2501. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  2502. stream->doByteSwap[mode] = true;
  2503. }
  2504. #else
  2505. else if (mask & AFMT_S32_LE) {
  2506. device_format = AFMT_S32_LE;
  2507. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  2508. stream->doByteSwap[mode] = true;
  2509. }
  2510. #endif
  2511. }
  2512. #endif
  2513. if (device_format == -1) {
  2514. // The user requested format is not natively supported by the device.
  2515. if (mask & AFMT_S16_NE) {
  2516. device_format = AFMT_S16_NE;
  2517. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  2518. }
  2519. #if BYTE_ORDER == LITTLE_ENDIAN
  2520. else if (mask & AFMT_S16_BE) {
  2521. device_format = AFMT_S16_BE;
  2522. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  2523. stream->doByteSwap[mode] = true;
  2524. }
  2525. #else
  2526. else if (mask & AFMT_S16_LE) {
  2527. device_format = AFMT_S16_LE;
  2528. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  2529. stream->doByteSwap[mode] = true;
  2530. }
  2531. #endif
  2532. #if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE)
  2533. else if (mask & AFMT_S32_NE) {
  2534. device_format = AFMT_S32_NE;
  2535. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  2536. }
  2537. #if BYTE_ORDER == LITTLE_ENDIAN
  2538. else if (mask & AFMT_S32_BE) {
  2539. device_format = AFMT_S32_BE;
  2540. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  2541. stream->doByteSwap[mode] = true;
  2542. }
  2543. #else
  2544. else if (mask & AFMT_S32_LE) {
  2545. device_format = AFMT_S32_LE;
  2546. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  2547. stream->doByteSwap[mode] = true;
  2548. }
  2549. #endif
  2550. #endif
  2551. else if (mask & AFMT_S8) {
  2552. device_format = AFMT_S8;
  2553. stream->deviceFormat[mode] = RTAUDIO_SINT8;
  2554. }
  2555. }
  2556. if (stream->deviceFormat[mode] == 0) {
  2557. // This really shouldn't happen ...
  2558. close(fd);
  2559. sprintf(message, "RtAudio: OSS device (%s) data format not supported by RtAudio.",
  2560. name);
  2561. goto error;
  2562. }
  2563. // Determine the number of channels for this device. Note that the
  2564. // channel value requested by the user might be < min_X_Channels.
  2565. stream->nUserChannels[mode] = channels;
  2566. device_channels = channels;
  2567. if (mode == OUTPUT) {
  2568. if (channels < devices[device].minOutputChannels)
  2569. device_channels = devices[device].minOutputChannels;
  2570. }
  2571. else { // mode == INPUT
  2572. if (stream->mode == OUTPUT && stream->device[0] == device) {
  2573. // We're doing duplex setup here.
  2574. if (channels < devices[device].minDuplexChannels)
  2575. device_channels = devices[device].minDuplexChannels;
  2576. }
  2577. else {
  2578. if (channels < devices[device].minInputChannels)
  2579. device_channels = devices[device].minInputChannels;
  2580. }
  2581. }
  2582. stream->nDeviceChannels[mode] = device_channels;
  2583. // Attempt to set the buffer size. According to OSS, the minimum
  2584. // number of buffers is two. The supposed minimum buffer size is 16
  2585. // bytes, so that will be our lower bound. The argument to this
  2586. // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
  2587. // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
  2588. // We'll check the actual value used near the end of the setup
  2589. // procedure.
  2590. buffer_bytes = *bufferSize * formatBytes(stream->deviceFormat[mode]) * device_channels;
  2591. if (buffer_bytes < 16) buffer_bytes = 16;
  2592. buffers = numberOfBuffers;
  2593. if (buffers < 2) buffers = 2;
  2594. temp = ((int) buffers << 16) + (int)(log10((double)buffer_bytes)/log10(2.0));
  2595. if (ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &temp)) {
  2596. close(fd);
  2597. sprintf(message, "RtAudio: OSS error setting fragment size for device (%s).",
  2598. name);
  2599. goto error;
  2600. }
  2601. stream->nBuffers = buffers;
  2602. // Set the data format.
  2603. temp = device_format;
  2604. if (ioctl(fd, SNDCTL_DSP_SETFMT, &device_format) == -1 || device_format != temp) {
  2605. close(fd);
  2606. sprintf(message, "RtAudio: OSS error setting data format for device (%s).",
  2607. name);
  2608. goto error;
  2609. }
  2610. // Set the number of channels.
  2611. temp = device_channels;
  2612. if (ioctl(fd, SNDCTL_DSP_CHANNELS, &device_channels) == -1 || device_channels != temp) {
  2613. close(fd);
  2614. sprintf(message, "RtAudio: OSS error setting %d channels on device (%s).",
  2615. temp, name);
  2616. goto error;
  2617. }
  2618. // Set the sample rate.
  2619. srate = sampleRate;
  2620. temp = srate;
  2621. if (ioctl(fd, SNDCTL_DSP_SPEED, &srate) == -1) {
  2622. close(fd);
  2623. sprintf(message, "RtAudio: OSS error setting sample rate = %d on device (%s).",
  2624. temp, name);
  2625. goto error;
  2626. }
  2627. // Verify the sample rate setup worked.
  2628. if (abs(srate - temp) > 100) {
  2629. close(fd);
  2630. sprintf(message, "RtAudio: OSS error ... audio device (%s) doesn't support sample rate of %d.",
  2631. name, temp);
  2632. goto error;
  2633. }
  2634. stream->sampleRate = sampleRate;
  2635. if (ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &buffer_bytes) == -1) {
  2636. close(fd);
  2637. sprintf(message, "RtAudio: OSS error getting buffer size for device (%s).",
  2638. name);
  2639. goto error;
  2640. }
  2641. // Save buffer size (in sample frames).
  2642. *bufferSize = buffer_bytes / (formatBytes(stream->deviceFormat[mode]) * device_channels);
  2643. stream->bufferSize = *bufferSize;
  2644. if (mode == INPUT && stream->mode == OUTPUT &&
  2645. stream->device[0] == device) {
  2646. // We're doing duplex setup here.
  2647. stream->deviceFormat[0] = stream->deviceFormat[1];
  2648. stream->nDeviceChannels[0] = device_channels;
  2649. }
  2650. // Set flags for buffer conversion
  2651. stream->doConvertBuffer[mode] = false;
  2652. if (stream->userFormat != stream->deviceFormat[mode])
  2653. stream->doConvertBuffer[mode] = true;
  2654. if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode])
  2655. stream->doConvertBuffer[mode] = true;
  2656. // Allocate necessary internal buffers
  2657. if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) {
  2658. long buffer_bytes;
  2659. if (stream->nUserChannels[0] >= stream->nUserChannels[1])
  2660. buffer_bytes = stream->nUserChannels[0];
  2661. else
  2662. buffer_bytes = stream->nUserChannels[1];
  2663. buffer_bytes *= *bufferSize * formatBytes(stream->userFormat);
  2664. if (stream->userBuffer) free(stream->userBuffer);
  2665. stream->userBuffer = (char *) calloc(buffer_bytes, 1);
  2666. if (stream->userBuffer == NULL) {
  2667. close(fd);
  2668. sprintf(message, "RtAudio: OSS error allocating user buffer memory (%s).",
  2669. name);
  2670. goto error;
  2671. }
  2672. }
  2673. if ( stream->doConvertBuffer[mode] ) {
  2674. long buffer_bytes;
  2675. bool makeBuffer = true;
  2676. if ( mode == OUTPUT )
  2677. buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  2678. else { // mode == INPUT
  2679. buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
  2680. if ( stream->mode == OUTPUT && stream->deviceBuffer ) {
  2681. long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  2682. if ( buffer_bytes < bytes_out ) makeBuffer = false;
  2683. }
  2684. }
  2685. if ( makeBuffer ) {
  2686. buffer_bytes *= *bufferSize;
  2687. if (stream->deviceBuffer) free(stream->deviceBuffer);
  2688. stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
  2689. if (stream->deviceBuffer == NULL) {
  2690. close(fd);
  2691. free(stream->userBuffer);
  2692. sprintf(message, "RtAudio: OSS error allocating device buffer memory (%s).",
  2693. name);
  2694. goto error;
  2695. }
  2696. }
  2697. }
  2698. stream->device[mode] = device;
  2699. stream->handle[mode] = fd;
  2700. stream->state = STREAM_STOPPED;
  2701. if ( stream->mode == OUTPUT && mode == INPUT ) {
  2702. stream->mode = DUPLEX;
  2703. if (stream->device[0] == device)
  2704. stream->handle[0] = fd;
  2705. }
  2706. else
  2707. stream->mode = mode;
  2708. return SUCCESS;
  2709. error:
  2710. if (stream->handle[0]) {
  2711. close(stream->handle[0]);
  2712. stream->handle[0] = 0;
  2713. }
  2714. error(RtError::WARNING);
  2715. return FAILURE;
  2716. }
  2717. void RtAudio :: closeStream(int streamId)
  2718. {
  2719. // We don't want an exception to be thrown here because this
  2720. // function is called by our class destructor. So, do our own
  2721. // streamId check.
  2722. if ( streams.find( streamId ) == streams.end() ) {
  2723. sprintf(message, "RtAudio: invalid stream identifier!");
  2724. error(RtError::WARNING);
  2725. return;
  2726. }
  2727. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId];
  2728. if (stream->callbackInfo.usingCallback) {
  2729. pthread_cancel(stream->callbackInfo.thread);
  2730. pthread_join(stream->callbackInfo.thread, NULL);
  2731. }
  2732. if (stream->state == STREAM_RUNNING) {
  2733. if (stream->mode == OUTPUT || stream->mode == DUPLEX)
  2734. ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0);
  2735. if (stream->mode == INPUT || stream->mode == DUPLEX)
  2736. ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0);
  2737. }
  2738. pthread_mutex_destroy(&stream->mutex);
  2739. if (stream->handle[0])
  2740. close(stream->handle[0]);
  2741. if (stream->handle[1])
  2742. close(stream->handle[1]);
  2743. if (stream->userBuffer)
  2744. free(stream->userBuffer);
  2745. if (stream->deviceBuffer)
  2746. free(stream->deviceBuffer);
  2747. free(stream);
  2748. streams.erase(streamId);
  2749. }
  2750. void RtAudio :: startStream(int streamId)
  2751. {
  2752. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  2753. MUTEX_LOCK(&stream->mutex);
  2754. stream->state = STREAM_RUNNING;
  2755. // No need to do anything else here ... OSS automatically starts
  2756. // when fed samples.
  2757. MUTEX_UNLOCK(&stream->mutex);
  2758. }
  2759. void RtAudio :: stopStream(int streamId)
  2760. {
  2761. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  2762. MUTEX_LOCK(&stream->mutex);
  2763. if (stream->state == STREAM_STOPPED)
  2764. goto unlock;
  2765. int err;
  2766. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  2767. err = ioctl(stream->handle[0], SNDCTL_DSP_SYNC, 0);
  2768. if (err < -1) {
  2769. sprintf(message, "RtAudio: OSS error stopping device (%s).",
  2770. devices[stream->device[0]].name);
  2771. error(RtError::DRIVER_ERROR);
  2772. }
  2773. }
  2774. else {
  2775. err = ioctl(stream->handle[1], SNDCTL_DSP_SYNC, 0);
  2776. if (err < -1) {
  2777. sprintf(message, "RtAudio: OSS error stopping device (%s).",
  2778. devices[stream->device[1]].name);
  2779. error(RtError::DRIVER_ERROR);
  2780. }
  2781. }
  2782. stream->state = STREAM_STOPPED;
  2783. unlock:
  2784. MUTEX_UNLOCK(&stream->mutex);
  2785. }
  2786. void RtAudio :: abortStream(int streamId)
  2787. {
  2788. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  2789. MUTEX_LOCK(&stream->mutex);
  2790. if (stream->state == STREAM_STOPPED)
  2791. goto unlock;
  2792. int err;
  2793. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  2794. err = ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0);
  2795. if (err < -1) {
  2796. sprintf(message, "RtAudio: OSS error aborting device (%s).",
  2797. devices[stream->device[0]].name);
  2798. error(RtError::DRIVER_ERROR);
  2799. }
  2800. }
  2801. else {
  2802. err = ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0);
  2803. if (err < -1) {
  2804. sprintf(message, "RtAudio: OSS error aborting device (%s).",
  2805. devices[stream->device[1]].name);
  2806. error(RtError::DRIVER_ERROR);
  2807. }
  2808. }
  2809. stream->state = STREAM_STOPPED;
  2810. unlock:
  2811. MUTEX_UNLOCK(&stream->mutex);
  2812. }
  2813. int RtAudio :: streamWillBlock(int streamId)
  2814. {
  2815. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  2816. MUTEX_LOCK(&stream->mutex);
  2817. int bytes = 0, channels = 0, frames = 0;
  2818. if (stream->state == STREAM_STOPPED)
  2819. goto unlock;
  2820. audio_buf_info info;
  2821. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  2822. ioctl(stream->handle[0], SNDCTL_DSP_GETOSPACE, &info);
  2823. bytes = info.bytes;
  2824. channels = stream->nDeviceChannels[0];
  2825. }
  2826. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  2827. ioctl(stream->handle[1], SNDCTL_DSP_GETISPACE, &info);
  2828. if (stream->mode == DUPLEX ) {
  2829. bytes = (bytes < info.bytes) ? bytes : info.bytes;
  2830. channels = stream->nDeviceChannels[0];
  2831. }
  2832. else {
  2833. bytes = info.bytes;
  2834. channels = stream->nDeviceChannels[1];
  2835. }
  2836. }
  2837. frames = (int) (bytes / (channels * formatBytes(stream->deviceFormat[0])));
  2838. frames -= stream->bufferSize;
  2839. if (frames < 0) frames = 0;
  2840. unlock:
  2841. MUTEX_UNLOCK(&stream->mutex);
  2842. return frames;
  2843. }
  2844. void RtAudio :: tickStream(int streamId)
  2845. {
  2846. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  2847. int stopStream = 0;
  2848. if (stream->state == STREAM_STOPPED) {
  2849. if (stream->callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds
  2850. return;
  2851. }
  2852. else if (stream->callbackInfo.usingCallback) {
  2853. RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback;
  2854. stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData);
  2855. }
  2856. MUTEX_LOCK(&stream->mutex);
  2857. // The state might change while waiting on a mutex.
  2858. if (stream->state == STREAM_STOPPED)
  2859. goto unlock;
  2860. int result;
  2861. char *buffer;
  2862. int samples;
  2863. RTAUDIO_FORMAT format;
  2864. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  2865. // Setup parameters and do buffer conversion if necessary.
  2866. if (stream->doConvertBuffer[0]) {
  2867. convertStreamBuffer(stream, OUTPUT);
  2868. buffer = stream->deviceBuffer;
  2869. samples = stream->bufferSize * stream->nDeviceChannels[0];
  2870. format = stream->deviceFormat[0];
  2871. }
  2872. else {
  2873. buffer = stream->userBuffer;
  2874. samples = stream->bufferSize * stream->nUserChannels[0];
  2875. format = stream->userFormat;
  2876. }
  2877. // Do byte swapping if necessary.
  2878. if (stream->doByteSwap[0])
  2879. byteSwapBuffer(buffer, samples, format);
  2880. // Write samples to device.
  2881. result = write(stream->handle[0], buffer, samples * formatBytes(format));
  2882. if (result == -1) {
  2883. // This could be an underrun, but the basic OSS API doesn't provide a means for determining that.
  2884. sprintf(message, "RtAudio: OSS audio write error for device (%s).",
  2885. devices[stream->device[0]].name);
  2886. error(RtError::DRIVER_ERROR);
  2887. }
  2888. }
  2889. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  2890. // Setup parameters.
  2891. if (stream->doConvertBuffer[1]) {
  2892. buffer = stream->deviceBuffer;
  2893. samples = stream->bufferSize * stream->nDeviceChannels[1];
  2894. format = stream->deviceFormat[1];
  2895. }
  2896. else {
  2897. buffer = stream->userBuffer;
  2898. samples = stream->bufferSize * stream->nUserChannels[1];
  2899. format = stream->userFormat;
  2900. }
  2901. // Read samples from device.
  2902. result = read(stream->handle[1], buffer, samples * formatBytes(format));
  2903. if (result == -1) {
  2904. // This could be an overrun, but the basic OSS API doesn't provide a means for determining that.
  2905. sprintf(message, "RtAudio: OSS audio read error for device (%s).",
  2906. devices[stream->device[1]].name);
  2907. error(RtError::DRIVER_ERROR);
  2908. }
  2909. // Do byte swapping if necessary.
  2910. if (stream->doByteSwap[1])
  2911. byteSwapBuffer(buffer, samples, format);
  2912. // Do buffer conversion if necessary.
  2913. if (stream->doConvertBuffer[1])
  2914. convertStreamBuffer(stream, INPUT);
  2915. }
  2916. unlock:
  2917. MUTEX_UNLOCK(&stream->mutex);
  2918. if (stream->callbackInfo.usingCallback && stopStream)
  2919. this->stopStream(streamId);
  2920. }
  2921. extern "C" void *callbackHandler(void *ptr)
  2922. {
  2923. CALLBACK_INFO *info = (CALLBACK_INFO *) ptr;
  2924. RtAudio *object = (RtAudio *) info->object;
  2925. int stream = info->streamId;
  2926. bool *usingCallback = &info->usingCallback;
  2927. while ( *usingCallback ) {
  2928. pthread_testcancel();
  2929. try {
  2930. object->tickStream(stream);
  2931. }
  2932. catch (RtError &exception) {
  2933. fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n",
  2934. exception.getMessage());
  2935. break;
  2936. }
  2937. }
  2938. return 0;
  2939. }
  2940. //******************** End of __LINUX_OSS__ *********************//
  2941. #elif defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2942. // The ASIO API is designed around a callback scheme, so this
  2943. // implementation is similar to that used for OS X CoreAudio. The
  2944. // primary constraint with ASIO is that it only allows access to a
  2945. // single driver at a time. Thus, it is not possible to have more
  2946. // than one simultaneous RtAudio stream.
  2947. //
  2948. // This implementation also requires a number of external ASIO files
  2949. // and a few global variables. The ASIO callback scheme does not
  2950. // allow for the passing of user data, so we must create a global
  2951. // pointer to our callbackInfo structure.
  2952. #include "asio/asiosys.h"
  2953. #include "asio/asio.h"
  2954. #include "asio/asiodrivers.h"
  2955. #include <math.h>
  2956. AsioDrivers drivers;
  2957. ASIOCallbacks asioCallbacks;
  2958. CALLBACK_INFO *asioCallbackInfo;
  2959. ASIODriverInfo driverInfo;
  2960. void RtAudio :: initialize(void)
  2961. {
  2962. nDevices = drivers.asioGetNumDev();
  2963. if (nDevices <= 0) return;
  2964. // Allocate the RTAUDIO_DEVICE structures.
  2965. devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
  2966. if (devices == NULL) {
  2967. sprintf(message, "RtAudio: memory allocation error!");
  2968. error(RtError::MEMORY_ERROR);
  2969. }
  2970. // Write device driver names to device structures and then probe the
  2971. // device capabilities.
  2972. for (int i=0; i<nDevices; i++) {
  2973. if ( drivers.asioGetDriverName( i, devices[i].name, 128 ) == 0 )
  2974. //probeDeviceInfo(&devices[i]);
  2975. ;
  2976. else {
  2977. sprintf(message, "RtAudio: error getting ASIO driver name for device index %d!", i);
  2978. error(RtError::WARNING);
  2979. }
  2980. }
  2981. drivers.removeCurrentDriver();
  2982. driverInfo.asioVersion = 2;
  2983. // See note in DirectSound implementation about GetDesktopWindow().
  2984. driverInfo.sysRef = GetForegroundWindow();
  2985. }
  2986. int RtAudio :: getDefaultInputDevice(void)
  2987. {
  2988. return 0;
  2989. }
  2990. int RtAudio :: getDefaultOutputDevice(void)
  2991. {
  2992. return 0;
  2993. }
  2994. void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
  2995. {
  2996. // Don't probe if a stream is already open.
  2997. if ( streams.size() > 0 ) {
  2998. sprintf(message, "RtAudio: unable to probe ASIO driver while a stream is open.");
  2999. error(RtError::DEBUG_WARNING);
  3000. return;
  3001. }
  3002. if ( !drivers.loadDriver( info->name ) ) {
  3003. sprintf(message, "RtAudio: ASIO error loading driver (%s).", info->name);
  3004. error(RtError::DEBUG_WARNING);
  3005. return;
  3006. }
  3007. ASIOError result = ASIOInit( &driverInfo );
  3008. if ( result != ASE_OK ) {
  3009. char details[32];
  3010. if ( result == ASE_HWMalfunction )
  3011. sprintf(details, "hardware malfunction");
  3012. else if ( result == ASE_NoMemory )
  3013. sprintf(details, "no memory");
  3014. else if ( result == ASE_NotPresent )
  3015. sprintf(details, "driver/hardware not present");
  3016. else
  3017. sprintf(details, "unspecified");
  3018. sprintf(message, "RtAudio: ASIO error (%s) initializing driver (%s).", details, info->name);
  3019. error(RtError::DEBUG_WARNING);
  3020. return;
  3021. }
  3022. // Determine the device channel information.
  3023. long inputChannels, outputChannels;
  3024. result = ASIOGetChannels( &inputChannels, &outputChannels );
  3025. if ( result != ASE_OK ) {
  3026. drivers.removeCurrentDriver();
  3027. sprintf(message, "RtAudio: ASIO error getting input/output channel count (%s).", info->name);
  3028. error(RtError::DEBUG_WARNING);
  3029. return;
  3030. }
  3031. info->maxOutputChannels = outputChannels;
  3032. if ( outputChannels > 0 ) info->minOutputChannels = 1;
  3033. info->maxInputChannels = inputChannels;
  3034. if ( inputChannels > 0 ) info->minInputChannels = 1;
  3035. // If device opens for both playback and capture, we determine the channels.
  3036. if (info->maxOutputChannels > 0 && info->maxInputChannels > 0) {
  3037. info->hasDuplexSupport = true;
  3038. info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ?
  3039. info->maxInputChannels : info->maxOutputChannels;
  3040. info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ?
  3041. info->minInputChannels : info->minOutputChannels;
  3042. }
  3043. // Determine the supported sample rates.
  3044. info->nSampleRates = 0;
  3045. for (int i=0; i<MAX_SAMPLE_RATES; i++) {
  3046. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  3047. if ( result == ASE_OK )
  3048. info->sampleRates[info->nSampleRates++] = SAMPLE_RATES[i];
  3049. }
  3050. if (info->nSampleRates == 0) {
  3051. drivers.removeCurrentDriver();
  3052. sprintf( message, "RtAudio: No supported sample rates found for ASIO driver (%s).", info->name );
  3053. error(RtError::DEBUG_WARNING);
  3054. return;
  3055. }
  3056. // Determine supported data types ... just check first channel and assume rest are the same.
  3057. ASIOChannelInfo channelInfo;
  3058. channelInfo.channel = 0;
  3059. channelInfo.isInput = true;
  3060. if ( info->maxInputChannels <= 0 ) channelInfo.isInput = false;
  3061. result = ASIOGetChannelInfo( &channelInfo );
  3062. if ( result != ASE_OK ) {
  3063. drivers.removeCurrentDriver();
  3064. sprintf(message, "RtAudio: ASIO error getting driver (%s) channel information.", info->name);
  3065. error(RtError::DEBUG_WARNING);
  3066. return;
  3067. }
  3068. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  3069. info->nativeFormats |= RTAUDIO_SINT16;
  3070. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  3071. info->nativeFormats |= RTAUDIO_SINT32;
  3072. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  3073. info->nativeFormats |= RTAUDIO_FLOAT32;
  3074. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  3075. info->nativeFormats |= RTAUDIO_FLOAT64;
  3076. // Check that we have at least one supported format.
  3077. if (info->nativeFormats == 0) {
  3078. drivers.removeCurrentDriver();
  3079. sprintf(message, "RtAudio: ASIO driver (%s) data format not supported by RtAudio.",
  3080. info->name);
  3081. error(RtError::DEBUG_WARNING);
  3082. return;
  3083. }
  3084. info->probed = true;
  3085. drivers.removeCurrentDriver();
  3086. }
  3087. void bufferSwitch(long index, ASIOBool processNow)
  3088. {
  3089. RtAudio *object = (RtAudio *) asioCallbackInfo->object;
  3090. try {
  3091. object->callbackEvent( asioCallbackInfo->streamId, index, (void *)NULL, (void *)NULL );
  3092. }
  3093. catch (RtError &exception) {
  3094. fprintf(stderr, "\nCallback handler error (%s)!\n\n", exception.getMessage());
  3095. return;
  3096. }
  3097. return;
  3098. }
  3099. void sampleRateChanged(ASIOSampleRate sRate)
  3100. {
  3101. // The ASIO documentation says that this usually only happens during
  3102. // external sync. Audio processing is not stopped by the driver,
  3103. // actual sample rate might not have even changed, maybe only the
  3104. // sample rate status of an AES/EBU or S/PDIF digital input at the
  3105. // audio device.
  3106. RtAudio *object = (RtAudio *) asioCallbackInfo->object;
  3107. try {
  3108. object->stopStream( asioCallbackInfo->streamId );
  3109. }
  3110. catch (RtError &exception) {
  3111. fprintf(stderr, "\nRtAudio: sampleRateChanged() error (%s)!\n\n", exception.getMessage());
  3112. return;
  3113. }
  3114. fprintf(stderr, "\nRtAudio: ASIO driver reports sample rate changed to %d ... stream stopped!!!", (int) sRate);
  3115. }
  3116. long asioMessages(long selector, long value, void* message, double* opt)
  3117. {
  3118. long ret = 0;
  3119. switch(selector) {
  3120. case kAsioSelectorSupported:
  3121. if(value == kAsioResetRequest
  3122. || value == kAsioEngineVersion
  3123. || value == kAsioResyncRequest
  3124. || value == kAsioLatenciesChanged
  3125. // The following three were added for ASIO 2.0, you don't
  3126. // necessarily have to support them.
  3127. || value == kAsioSupportsTimeInfo
  3128. || value == kAsioSupportsTimeCode
  3129. || value == kAsioSupportsInputMonitor)
  3130. ret = 1L;
  3131. break;
  3132. case kAsioResetRequest:
  3133. // Defer the task and perform the reset of the driver during the
  3134. // next "safe" situation. You cannot reset the driver right now,
  3135. // as this code is called from the driver. Reset the driver is
  3136. // done by completely destruct is. I.e. ASIOStop(),
  3137. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  3138. // driver again.
  3139. fprintf(stderr, "\nRtAudio: ASIO driver reset requested!!!");
  3140. ret = 1L;
  3141. break;
  3142. case kAsioResyncRequest:
  3143. // This informs the application that the driver encountered some
  3144. // non-fatal data loss. It is used for synchronization purposes
  3145. // of different media. Added mainly to work around the Win16Mutex
  3146. // problems in Windows 95/98 with the Windows Multimedia system,
  3147. // which could lose data because the Mutex was held too long by
  3148. // another thread. However a driver can issue it in other
  3149. // situations, too.
  3150. fprintf(stderr, "\nRtAudio: ASIO driver resync requested!!!");
  3151. ret = 1L;
  3152. break;
  3153. case kAsioLatenciesChanged:
  3154. // This will inform the host application that the drivers were
  3155. // latencies changed. Beware, it this does not mean that the
  3156. // buffer sizes have changed! You might need to update internal
  3157. // delay data.
  3158. fprintf(stderr, "\nRtAudio: ASIO driver latency may have changed!!!");
  3159. ret = 1L;
  3160. break;
  3161. case kAsioEngineVersion:
  3162. // Return the supported ASIO version of the host application. If
  3163. // a host application does not implement this selector, ASIO 1.0
  3164. // is assumed by the driver.
  3165. ret = 2L;
  3166. break;
  3167. case kAsioSupportsTimeInfo:
  3168. // Informs the driver whether the
  3169. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  3170. // For compatibility with ASIO 1.0 drivers the host application
  3171. // should always support the "old" bufferSwitch method, too.
  3172. ret = 0;
  3173. break;
  3174. case kAsioSupportsTimeCode:
  3175. // Informs the driver wether application is interested in time
  3176. // code info. If an application does not need to know about time
  3177. // code, the driver has less work to do.
  3178. ret = 0;
  3179. break;
  3180. }
  3181. return ret;
  3182. }
  3183. bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
  3184. STREAM_MODE mode, int channels,
  3185. int sampleRate, RTAUDIO_FORMAT format,
  3186. int *bufferSize, int numberOfBuffers)
  3187. {
  3188. // Don't attempt to load another driver if a stream is already open.
  3189. if ( streams.size() > 0 ) {
  3190. sprintf(message, "RtAudio: unable to load ASIO driver while a stream is open.");
  3191. error(RtError::WARNING);
  3192. return FAILURE;
  3193. }
  3194. // For ASIO, a duplex stream MUST use the same driver.
  3195. if ( mode == INPUT && stream->mode == OUTPUT && stream->device[0] != device ) {
  3196. sprintf(message, "RtAudio: ASIO duplex stream must use the same device for input and output.");
  3197. error(RtError::WARNING);
  3198. return FAILURE;
  3199. }
  3200. // Only load the driver once for duplex stream.
  3201. ASIOError result;
  3202. if ( mode != INPUT || stream->mode != OUTPUT ) {
  3203. if ( !drivers.loadDriver( devices[device].name ) ) {
  3204. sprintf(message, "RtAudio: ASIO error loading driver (%s).", devices[device].name);
  3205. error(RtError::DEBUG_WARNING);
  3206. return FAILURE;
  3207. }
  3208. result = ASIOInit( &driverInfo );
  3209. if ( result != ASE_OK ) {
  3210. char details[32];
  3211. if ( result == ASE_HWMalfunction )
  3212. sprintf(details, "hardware malfunction");
  3213. else if ( result == ASE_NoMemory )
  3214. sprintf(details, "no memory");
  3215. else if ( result == ASE_NotPresent )
  3216. sprintf(details, "driver/hardware not present");
  3217. else
  3218. sprintf(details, "unspecified");
  3219. sprintf(message, "RtAudio: ASIO error (%s) initializing driver (%s).", details, devices[device].name);
  3220. error(RtError::DEBUG_WARNING);
  3221. return FAILURE;
  3222. }
  3223. }
  3224. // Check the device channel count.
  3225. long inputChannels, outputChannels;
  3226. result = ASIOGetChannels( &inputChannels, &outputChannels );
  3227. if ( result != ASE_OK ) {
  3228. drivers.removeCurrentDriver();
  3229. sprintf(message, "RtAudio: ASIO error getting input/output channel count (%s).",
  3230. devices[device].name);
  3231. error(RtError::DEBUG_WARNING);
  3232. return FAILURE;
  3233. }
  3234. if ( ( mode == OUTPUT && channels > outputChannels) ||
  3235. ( mode == INPUT && channels > inputChannels) ) {
  3236. drivers.removeCurrentDriver();
  3237. sprintf(message, "RtAudio: ASIO driver (%s) does not support requested channel count (%d).",
  3238. devices[device].name, channels);
  3239. error(RtError::DEBUG_WARNING);
  3240. return FAILURE;
  3241. }
  3242. stream->nDeviceChannels[mode] = channels;
  3243. stream->nUserChannels[mode] = channels;
  3244. // Verify the sample rate is supported.
  3245. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  3246. if ( result != ASE_OK ) {
  3247. drivers.removeCurrentDriver();
  3248. sprintf(message, "RtAudio: ASIO driver (%s) does not support requested sample rate (%d).",
  3249. devices[device].name, sampleRate);
  3250. error(RtError::DEBUG_WARNING);
  3251. return FAILURE;
  3252. }
  3253. // Set the sample rate.
  3254. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  3255. if ( result != ASE_OK ) {
  3256. drivers.removeCurrentDriver();
  3257. sprintf(message, "RtAudio: ASIO driver (%s) error setting sample rate (%d).",
  3258. devices[device].name, sampleRate);
  3259. error(RtError::DEBUG_WARNING);
  3260. return FAILURE;
  3261. }
  3262. // Determine the driver data type.
  3263. ASIOChannelInfo channelInfo;
  3264. channelInfo.channel = 0;
  3265. if ( mode == OUTPUT ) channelInfo.isInput = false;
  3266. else channelInfo.isInput = true;
  3267. result = ASIOGetChannelInfo( &channelInfo );
  3268. if ( result != ASE_OK ) {
  3269. drivers.removeCurrentDriver();
  3270. sprintf(message, "RtAudio: ASIO driver (%s) error getting data format.",
  3271. devices[device].name);
  3272. error(RtError::DEBUG_WARNING);
  3273. return FAILURE;
  3274. }
  3275. // Assuming WINDOWS host is always little-endian.
  3276. stream->doByteSwap[mode] = false;
  3277. stream->userFormat = format;
  3278. stream->deviceFormat[mode] = 0;
  3279. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  3280. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  3281. if ( channelInfo.type == ASIOSTInt16MSB ) stream->doByteSwap[mode] = true;
  3282. }
  3283. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  3284. stream->deviceFormat[mode] = RTAUDIO_SINT32;
  3285. if ( channelInfo.type == ASIOSTInt32MSB ) stream->doByteSwap[mode] = true;
  3286. }
  3287. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  3288. stream->deviceFormat[mode] = RTAUDIO_FLOAT32;
  3289. if ( channelInfo.type == ASIOSTFloat32MSB ) stream->doByteSwap[mode] = true;
  3290. }
  3291. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  3292. stream->deviceFormat[mode] = RTAUDIO_FLOAT64;
  3293. if ( channelInfo.type == ASIOSTFloat64MSB ) stream->doByteSwap[mode] = true;
  3294. }
  3295. if ( stream->deviceFormat[mode] == 0 ) {
  3296. drivers.removeCurrentDriver();
  3297. sprintf(message, "RtAudio: ASIO driver (%s) data format not supported by RtAudio.",
  3298. devices[device].name);
  3299. error(RtError::DEBUG_WARNING);
  3300. return FAILURE;
  3301. }
  3302. // Set the buffer size. For a duplex stream, this will end up
  3303. // setting the buffer size based on the input constraints, which
  3304. // should be ok.
  3305. long minSize, maxSize, preferSize, granularity;
  3306. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  3307. if ( result != ASE_OK ) {
  3308. drivers.removeCurrentDriver();
  3309. sprintf(message, "RtAudio: ASIO driver (%s) error getting buffer size.",
  3310. devices[device].name);
  3311. error(RtError::DEBUG_WARNING);
  3312. return FAILURE;
  3313. }
  3314. if ( *bufferSize < minSize ) *bufferSize = minSize;
  3315. else if ( *bufferSize > maxSize ) *bufferSize = maxSize;
  3316. else if ( granularity == -1 ) {
  3317. // Make sure bufferSize is a power of two.
  3318. double power = log10( *bufferSize ) / log10( 2.0 );
  3319. *bufferSize = pow( 2.0, floor(power+0.5) );
  3320. if ( *bufferSize < minSize ) *bufferSize = minSize;
  3321. else if ( *bufferSize > maxSize ) *bufferSize = maxSize;
  3322. else *bufferSize = preferSize;
  3323. }
  3324. if ( mode == INPUT && stream->mode == OUTPUT && stream->bufferSize != *bufferSize )
  3325. cout << "possible input/output buffersize discrepancy" << endl;
  3326. stream->bufferSize = *bufferSize;
  3327. stream->nBuffers = 2;
  3328. // ASIO always uses deinterleaved channels.
  3329. stream->deInterleave[mode] = true;
  3330. // Create the ASIO internal buffers. Since RtAudio sets up input
  3331. // and output separately, we'll have to dispose of previously
  3332. // created output buffers for a duplex stream.
  3333. if ( mode == INPUT && stream->mode == OUTPUT ) {
  3334. free(stream->callbackInfo.buffers);
  3335. result = ASIODisposeBuffers();
  3336. if ( result != ASE_OK ) {
  3337. drivers.removeCurrentDriver();
  3338. sprintf(message, "RtAudio: ASIO driver (%s) error disposing previously allocated buffers.",
  3339. devices[device].name);
  3340. error(RtError::DEBUG_WARNING);
  3341. return FAILURE;
  3342. }
  3343. }
  3344. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  3345. int i, nChannels = stream->nDeviceChannels[0] + stream->nDeviceChannels[1];
  3346. stream->callbackInfo.buffers = 0;
  3347. ASIOBufferInfo *bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  3348. stream->callbackInfo.buffers = (void *) bufferInfos;
  3349. ASIOBufferInfo *infos = bufferInfos;
  3350. for ( i=0; i<stream->nDeviceChannels[1]; i++, infos++ ) {
  3351. infos->isInput = ASIOTrue;
  3352. infos->channelNum = i;
  3353. infos->buffers[0] = infos->buffers[1] = 0;
  3354. }
  3355. for ( i=0; i<stream->nDeviceChannels[0]; i++, infos++ ) {
  3356. infos->isInput = ASIOFalse;
  3357. infos->channelNum = i;
  3358. infos->buffers[0] = infos->buffers[1] = 0;
  3359. }
  3360. // Set up the ASIO callback structure and create the ASIO data buffers.
  3361. asioCallbacks.bufferSwitch = &bufferSwitch;
  3362. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  3363. asioCallbacks.asioMessage = &asioMessages;
  3364. asioCallbacks.bufferSwitchTimeInfo = NULL;
  3365. result = ASIOCreateBuffers( bufferInfos, nChannels, stream->bufferSize, &asioCallbacks);
  3366. if ( result != ASE_OK ) {
  3367. drivers.removeCurrentDriver();
  3368. sprintf(message, "RtAudio: ASIO driver (%s) error creating buffers.",
  3369. devices[device].name);
  3370. error(RtError::DEBUG_WARNING);
  3371. return FAILURE;
  3372. }
  3373. // Set flags for buffer conversion.
  3374. stream->doConvertBuffer[mode] = false;
  3375. if (stream->userFormat != stream->deviceFormat[mode])
  3376. stream->doConvertBuffer[mode] = true;
  3377. if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode])
  3378. stream->doConvertBuffer[mode] = true;
  3379. if (stream->nUserChannels[mode] > 1 && stream->deInterleave[mode])
  3380. stream->doConvertBuffer[mode] = true;
  3381. // Allocate necessary internal buffers
  3382. if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) {
  3383. long buffer_bytes;
  3384. if (stream->nUserChannels[0] >= stream->nUserChannels[1])
  3385. buffer_bytes = stream->nUserChannels[0];
  3386. else
  3387. buffer_bytes = stream->nUserChannels[1];
  3388. buffer_bytes *= *bufferSize * formatBytes(stream->userFormat);
  3389. if (stream->userBuffer) free(stream->userBuffer);
  3390. stream->userBuffer = (char *) calloc(buffer_bytes, 1);
  3391. if (stream->userBuffer == NULL)
  3392. goto memory_error;
  3393. }
  3394. if ( stream->doConvertBuffer[mode] ) {
  3395. long buffer_bytes;
  3396. bool makeBuffer = true;
  3397. if ( mode == OUTPUT )
  3398. buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  3399. else { // mode == INPUT
  3400. buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
  3401. if ( stream->mode == OUTPUT && stream->deviceBuffer ) {
  3402. long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  3403. if ( buffer_bytes < bytes_out ) makeBuffer = false;
  3404. }
  3405. }
  3406. if ( makeBuffer ) {
  3407. buffer_bytes *= *bufferSize;
  3408. if (stream->deviceBuffer) free(stream->deviceBuffer);
  3409. stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
  3410. if (stream->deviceBuffer == NULL)
  3411. goto memory_error;
  3412. }
  3413. }
  3414. stream->device[mode] = device;
  3415. stream->state = STREAM_STOPPED;
  3416. if ( stream->mode == OUTPUT && mode == INPUT )
  3417. // We had already set up an output stream.
  3418. stream->mode = DUPLEX;
  3419. else
  3420. stream->mode = mode;
  3421. stream->sampleRate = sampleRate;
  3422. asioCallbackInfo = &stream->callbackInfo;
  3423. stream->callbackInfo.object = (void *) this;
  3424. stream->callbackInfo.waitTime = (unsigned long) (200.0 * stream->bufferSize / stream->sampleRate);
  3425. return SUCCESS;
  3426. memory_error:
  3427. ASIODisposeBuffers();
  3428. drivers.removeCurrentDriver();
  3429. if (stream->callbackInfo.buffers)
  3430. free(stream->callbackInfo.buffers);
  3431. stream->callbackInfo.buffers = 0;
  3432. if (stream->userBuffer) {
  3433. free(stream->userBuffer);
  3434. stream->userBuffer = 0;
  3435. }
  3436. sprintf(message, "RtAudio: error allocating buffer memory (%s).",
  3437. devices[device].name);
  3438. error(RtError::WARNING);
  3439. return FAILURE;
  3440. }
  3441. void RtAudio :: cancelStreamCallback(int streamId)
  3442. {
  3443. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  3444. if (stream->callbackInfo.usingCallback) {
  3445. if (stream->state == STREAM_RUNNING)
  3446. stopStream( streamId );
  3447. MUTEX_LOCK(&stream->mutex);
  3448. stream->callbackInfo.usingCallback = false;
  3449. stream->callbackInfo.userData = NULL;
  3450. stream->state = STREAM_STOPPED;
  3451. stream->callbackInfo.callback = NULL;
  3452. MUTEX_UNLOCK(&stream->mutex);
  3453. }
  3454. }
  3455. void RtAudio :: closeStream(int streamId)
  3456. {
  3457. // We don't want an exception to be thrown here because this
  3458. // function is called by our class destructor. So, do our own
  3459. // streamId check.
  3460. if ( streams.find( streamId ) == streams.end() ) {
  3461. sprintf(message, "RtAudio: invalid stream identifier!");
  3462. error(RtError::WARNING);
  3463. return;
  3464. }
  3465. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId];
  3466. if (stream->state == STREAM_RUNNING)
  3467. ASIOStop();
  3468. ASIODisposeBuffers();
  3469. //ASIOExit();
  3470. drivers.removeCurrentDriver();
  3471. DeleteCriticalSection(&stream->mutex);
  3472. if (stream->callbackInfo.buffers)
  3473. free(stream->callbackInfo.buffers);
  3474. if (stream->userBuffer)
  3475. free(stream->userBuffer);
  3476. if (stream->deviceBuffer)
  3477. free(stream->deviceBuffer);
  3478. free(stream);
  3479. streams.erase(streamId);
  3480. }
  3481. void RtAudio :: startStream(int streamId)
  3482. {
  3483. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  3484. MUTEX_LOCK(&stream->mutex);
  3485. if (stream->state == STREAM_RUNNING) {
  3486. MUTEX_UNLOCK(&stream->mutex);
  3487. return;
  3488. }
  3489. stream->callbackInfo.blockTick = true;
  3490. stream->callbackInfo.stopStream = false;
  3491. stream->callbackInfo.streamId = streamId;
  3492. ASIOError result = ASIOStart();
  3493. if ( result != ASE_OK ) {
  3494. sprintf(message, "RtAudio: ASIO error starting device (%s).",
  3495. devices[stream->device[0]].name);
  3496. MUTEX_UNLOCK(&stream->mutex);
  3497. error(RtError::DRIVER_ERROR);
  3498. }
  3499. stream->state = STREAM_RUNNING;
  3500. MUTEX_UNLOCK(&stream->mutex);
  3501. }
  3502. void RtAudio :: stopStream(int streamId)
  3503. {
  3504. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  3505. MUTEX_LOCK(&stream->mutex);
  3506. if (stream->state == STREAM_STOPPED) {
  3507. MUTEX_UNLOCK(&stream->mutex);
  3508. return;
  3509. }
  3510. ASIOError result = ASIOStop();
  3511. if ( result != ASE_OK ) {
  3512. sprintf(message, "RtAudio: ASIO error stopping device (%s).",
  3513. devices[stream->device[0]].name);
  3514. MUTEX_UNLOCK(&stream->mutex);
  3515. error(RtError::DRIVER_ERROR);
  3516. }
  3517. stream->state = STREAM_STOPPED;
  3518. MUTEX_UNLOCK(&stream->mutex);
  3519. }
  3520. void RtAudio :: abortStream(int streamId)
  3521. {
  3522. stopStream( streamId );
  3523. }
  3524. // I don't know how this function can be implemented.
  3525. int RtAudio :: streamWillBlock(int streamId)
  3526. {
  3527. sprintf(message, "RtAudio: streamWillBlock() cannot be implemented for ASIO.");
  3528. error(RtError::WARNING);
  3529. return 0;
  3530. }
  3531. void RtAudio :: tickStream(int streamId)
  3532. {
  3533. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  3534. if (stream->state == STREAM_STOPPED)
  3535. return;
  3536. if (stream->callbackInfo.usingCallback) {
  3537. sprintf(message, "RtAudio: tickStream() should not be used when a callback function is set!");
  3538. error(RtError::WARNING);
  3539. return;
  3540. }
  3541. // Block waiting here until the user data is processed in callbackEvent().
  3542. while ( stream->callbackInfo.blockTick )
  3543. Sleep(stream->callbackInfo.waitTime);
  3544. MUTEX_LOCK(&stream->mutex);
  3545. stream->callbackInfo.blockTick = true;
  3546. MUTEX_UNLOCK(&stream->mutex);
  3547. }
  3548. void RtAudio :: callbackEvent(int streamId, int bufferIndex, void *inData, void *outData)
  3549. {
  3550. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  3551. CALLBACK_INFO *info = asioCallbackInfo;
  3552. if ( !info->usingCallback ) {
  3553. // Block waiting here until we get new user data in tickStream().
  3554. while ( !info->blockTick )
  3555. Sleep(info->waitTime);
  3556. }
  3557. else if ( info->stopStream ) {
  3558. // Check if the stream should be stopped (via the previous user
  3559. // callback return value). We stop the stream here, rather than
  3560. // after the function call, so that output data can first be
  3561. // processed.
  3562. this->stopStream(asioCallbackInfo->streamId);
  3563. return;
  3564. }
  3565. MUTEX_LOCK(&stream->mutex);
  3566. int nChannels = stream->nDeviceChannels[0] + stream->nDeviceChannels[1];
  3567. int bufferBytes;
  3568. ASIOBufferInfo *bufferInfos = (ASIOBufferInfo *) info->buffers;
  3569. if ( stream->mode == INPUT || stream->mode == DUPLEX ) {
  3570. bufferBytes = stream->bufferSize * formatBytes(stream->deviceFormat[1]);
  3571. if (stream->doConvertBuffer[1]) {
  3572. // Always interleave ASIO input data.
  3573. for ( int i=0; i<stream->nDeviceChannels[1]; i++, bufferInfos++ )
  3574. memcpy(&stream->deviceBuffer[i*bufferBytes], bufferInfos->buffers[bufferIndex], bufferBytes );
  3575. if ( stream->doByteSwap[1] )
  3576. byteSwapBuffer(stream->deviceBuffer,
  3577. stream->bufferSize * stream->nDeviceChannels[1],
  3578. stream->deviceFormat[1]);
  3579. convertStreamBuffer(stream, INPUT);
  3580. }
  3581. else { // single channel only
  3582. memcpy(stream->userBuffer, bufferInfos->buffers[bufferIndex], bufferBytes );
  3583. if (stream->doByteSwap[1])
  3584. byteSwapBuffer(stream->userBuffer,
  3585. stream->bufferSize * stream->nUserChannels[1],
  3586. stream->userFormat);
  3587. }
  3588. }
  3589. if ( info->usingCallback ) {
  3590. RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) info->callback;
  3591. if ( callback(stream->userBuffer, stream->bufferSize, info->userData) )
  3592. info->stopStream = true;
  3593. }
  3594. if ( stream->mode == OUTPUT || stream->mode == DUPLEX ) {
  3595. bufferBytes = stream->bufferSize * formatBytes(stream->deviceFormat[0]);
  3596. if (stream->doConvertBuffer[0]) {
  3597. convertStreamBuffer(stream, OUTPUT);
  3598. if ( stream->doByteSwap[0] )
  3599. byteSwapBuffer(stream->deviceBuffer,
  3600. stream->bufferSize * stream->nDeviceChannels[0],
  3601. stream->deviceFormat[0]);
  3602. // Always de-interleave ASIO output data.
  3603. for ( int i=0; i<stream->nDeviceChannels[0]; i++, bufferInfos++ ) {
  3604. memcpy(bufferInfos->buffers[bufferIndex],
  3605. &stream->deviceBuffer[i*bufferBytes], bufferBytes );
  3606. }
  3607. }
  3608. else { // single channel only
  3609. if (stream->doByteSwap[0])
  3610. byteSwapBuffer(stream->userBuffer,
  3611. stream->bufferSize * stream->nUserChannels[0],
  3612. stream->userFormat);
  3613. memcpy(bufferInfos->buffers[bufferIndex], stream->userBuffer, bufferBytes );
  3614. }
  3615. }
  3616. if ( !info->usingCallback )
  3617. info->blockTick = false;
  3618. MUTEX_UNLOCK(&stream->mutex);
  3619. }
  3620. void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData)
  3621. {
  3622. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  3623. stream->callbackInfo.callback = (void *) callback;
  3624. stream->callbackInfo.userData = userData;
  3625. stream->callbackInfo.usingCallback = true;
  3626. }
  3627. //******************** End of __WINDOWS_ASIO__ *********************//
  3628. #elif defined(__WINDOWS_DS__) // Windows DirectSound API
  3629. #include <dsound.h>
  3630. // Declarations for utility functions, callbacks, and structures
  3631. // specific to the DirectSound implementation.
  3632. static bool CALLBACK deviceCountCallback(LPGUID lpguid,
  3633. LPCSTR lpcstrDescription,
  3634. LPCSTR lpcstrModule,
  3635. LPVOID lpContext);
  3636. static bool CALLBACK deviceInfoCallback(LPGUID lpguid,
  3637. LPCSTR lpcstrDescription,
  3638. LPCSTR lpcstrModule,
  3639. LPVOID lpContext);
  3640. static bool CALLBACK defaultDeviceCallback(LPGUID lpguid,
  3641. LPCSTR lpcstrDescription,
  3642. LPCSTR lpcstrModule,
  3643. LPVOID lpContext);
  3644. static bool CALLBACK deviceIdCallback(LPGUID lpguid,
  3645. LPCSTR lpcstrDescription,
  3646. LPCSTR lpcstrModule,
  3647. LPVOID lpContext);
  3648. static char* getErrorString(int code);
  3649. struct enum_info {
  3650. char name[64];
  3651. LPGUID id;
  3652. bool isInput;
  3653. bool isValid;
  3654. };
  3655. int RtAudio :: getDefaultInputDevice(void)
  3656. {
  3657. enum_info info;
  3658. info.name[0] = '\0';
  3659. // Enumerate through devices to find the default output.
  3660. HRESULT result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)defaultDeviceCallback, &info);
  3661. if ( FAILED(result) ) {
  3662. sprintf(message, "RtAudio: Error performing default input device enumeration: %s.",
  3663. getErrorString(result));
  3664. error(RtError::WARNING);
  3665. return 0;
  3666. }
  3667. for ( int i=0; i<nDevices; i++ )
  3668. if ( strncmp( devices[i].name, info.name, 64 ) == 0 ) return i;
  3669. return 0;
  3670. }
  3671. int RtAudio :: getDefaultOutputDevice(void)
  3672. {
  3673. enum_info info;
  3674. info.name[0] = '\0';
  3675. // Enumerate through devices to find the default output.
  3676. HRESULT result = DirectSoundEnumerate((LPDSENUMCALLBACK)defaultDeviceCallback, &info);
  3677. if ( FAILED(result) ) {
  3678. sprintf(message, "RtAudio: Error performing default output device enumeration: %s.",
  3679. getErrorString(result));
  3680. error(RtError::WARNING);
  3681. return 0;
  3682. }
  3683. for ( int i=0; i<nDevices; i++ )
  3684. if ( strncmp(devices[i].name, info.name, 64 ) == 0 ) return i;
  3685. return 0;
  3686. }
  3687. void RtAudio :: initialize(void)
  3688. {
  3689. int i, ins = 0, outs = 0, count = 0;
  3690. HRESULT result;
  3691. nDevices = 0;
  3692. // Count DirectSound devices.
  3693. result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &outs);
  3694. if ( FAILED(result) ) {
  3695. sprintf(message, "RtAudio: Unable to enumerate through sound playback devices: %s.",
  3696. getErrorString(result));
  3697. error(RtError::DRIVER_ERROR);
  3698. }
  3699. // Count DirectSoundCapture devices.
  3700. result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &ins);
  3701. if ( FAILED(result) ) {
  3702. sprintf(message, "RtAudio: Unable to enumerate through sound capture devices: %s.",
  3703. getErrorString(result));
  3704. error(RtError::DRIVER_ERROR);
  3705. }
  3706. count = ins + outs;
  3707. if (count == 0) return;
  3708. std::vector<enum_info> info(count);
  3709. for (i=0; i<count; i++) {
  3710. info[i].name[0] = '\0';
  3711. if (i < outs) info[i].isInput = false;
  3712. else info[i].isInput = true;
  3713. }
  3714. // Get playback device info and check capabilities.
  3715. result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceInfoCallback, &info[0]);
  3716. if ( FAILED(result) ) {
  3717. sprintf(message, "RtAudio: Unable to enumerate through sound playback devices: %s.",
  3718. getErrorString(result));
  3719. error(RtError::DRIVER_ERROR);
  3720. }
  3721. // Get capture device info and check capabilities.
  3722. result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceInfoCallback, &info[0]);
  3723. if ( FAILED(result) ) {
  3724. sprintf(message, "RtAudio: Unable to enumerate through sound capture devices: %s.",
  3725. getErrorString(result));
  3726. error(RtError::DRIVER_ERROR);
  3727. }
  3728. // Parse the devices and check validity. Devices are considered
  3729. // invalid if they cannot be opened, they report < 1 supported
  3730. // channels, or they report no supported data (capture only).
  3731. for (i=0; i<count; i++)
  3732. if ( info[i].isValid ) nDevices++;
  3733. if (nDevices == 0) return;
  3734. // Allocate the RTAUDIO_DEVICE structures.
  3735. devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
  3736. if (devices == NULL) {
  3737. sprintf(message, "RtAudio: memory allocation error!");
  3738. error(RtError::MEMORY_ERROR);
  3739. }
  3740. // Copy the names to our devices structures.
  3741. int index = 0;
  3742. for (i=0; i<count; i++) {
  3743. if ( info[i].isValid )
  3744. strncpy(devices[index++].name, info[i].name, 64);
  3745. }
  3746. //for (i=0;i<nDevices; i++)
  3747. //probeDeviceInfo(&devices[i]);
  3748. return;
  3749. }
  3750. void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
  3751. {
  3752. enum_info dsinfo;
  3753. strncpy( dsinfo.name, info->name, 64 );
  3754. dsinfo.isValid = false;
  3755. // Enumerate through input devices to find the id (if it exists).
  3756. HRESULT result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
  3757. if ( FAILED(result) ) {
  3758. sprintf(message, "RtAudio: Error performing input device id enumeration: %s.",
  3759. getErrorString(result));
  3760. error(RtError::WARNING);
  3761. return;
  3762. }
  3763. // Do capture probe first.
  3764. if ( dsinfo.isValid == false )
  3765. goto playback_probe;
  3766. LPDIRECTSOUNDCAPTURE input;
  3767. result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
  3768. if ( FAILED(result) ) {
  3769. sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.",
  3770. info->name, getErrorString(result));
  3771. error(RtError::WARNING);
  3772. goto playback_probe;
  3773. }
  3774. DSCCAPS in_caps;
  3775. in_caps.dwSize = sizeof(in_caps);
  3776. result = input->GetCaps( &in_caps );
  3777. if ( FAILED(result) ) {
  3778. input->Release();
  3779. sprintf(message, "RtAudio: Could not get DirectSound capture capabilities (%s): %s.",
  3780. info->name, getErrorString(result));
  3781. error(RtError::WARNING);
  3782. goto playback_probe;
  3783. }
  3784. // Get input channel information.
  3785. info->minInputChannels = 1;
  3786. info->maxInputChannels = in_caps.dwChannels;
  3787. // Get sample rate and format information.
  3788. if( in_caps.dwChannels == 2 ) {
  3789. if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->nativeFormats |= RTAUDIO_SINT16;
  3790. if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->nativeFormats |= RTAUDIO_SINT16;
  3791. if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->nativeFormats |= RTAUDIO_SINT16;
  3792. if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->nativeFormats |= RTAUDIO_SINT8;
  3793. if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->nativeFormats |= RTAUDIO_SINT8;
  3794. if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->nativeFormats |= RTAUDIO_SINT8;
  3795. if ( info->nativeFormats & RTAUDIO_SINT16 ) {
  3796. if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->sampleRates[info->nSampleRates++] = 11025;
  3797. if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->sampleRates[info->nSampleRates++] = 22050;
  3798. if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->sampleRates[info->nSampleRates++] = 44100;
  3799. }
  3800. else if ( info->nativeFormats & RTAUDIO_SINT8 ) {
  3801. if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->sampleRates[info->nSampleRates++] = 11025;
  3802. if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->sampleRates[info->nSampleRates++] = 22050;
  3803. if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->sampleRates[info->nSampleRates++] = 44100;
  3804. }
  3805. }
  3806. else if ( in_caps.dwChannels == 1 ) {
  3807. if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->nativeFormats |= RTAUDIO_SINT16;
  3808. if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->nativeFormats |= RTAUDIO_SINT16;
  3809. if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->nativeFormats |= RTAUDIO_SINT16;
  3810. if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->nativeFormats |= RTAUDIO_SINT8;
  3811. if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->nativeFormats |= RTAUDIO_SINT8;
  3812. if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->nativeFormats |= RTAUDIO_SINT8;
  3813. if ( info->nativeFormats & RTAUDIO_SINT16 ) {
  3814. if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->sampleRates[info->nSampleRates++] = 11025;
  3815. if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->sampleRates[info->nSampleRates++] = 22050;
  3816. if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->sampleRates[info->nSampleRates++] = 44100;
  3817. }
  3818. else if ( info->nativeFormats & RTAUDIO_SINT8 ) {
  3819. if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->sampleRates[info->nSampleRates++] = 11025;
  3820. if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->sampleRates[info->nSampleRates++] = 22050;
  3821. if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->sampleRates[info->nSampleRates++] = 44100;
  3822. }
  3823. }
  3824. else info->minInputChannels = 0; // technically, this would be an error
  3825. input->Release();
  3826. playback_probe:
  3827. dsinfo.isValid = false;
  3828. // Enumerate through output devices to find the id (if it exists).
  3829. result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
  3830. if ( FAILED(result) ) {
  3831. sprintf(message, "RtAudio: Error performing output device id enumeration: %s.",
  3832. getErrorString(result));
  3833. error(RtError::WARNING);
  3834. return;
  3835. }
  3836. // Now do playback probe.
  3837. if ( dsinfo.isValid == false )
  3838. goto check_parameters;
  3839. LPDIRECTSOUND output;
  3840. DSCAPS out_caps;
  3841. result = DirectSoundCreate( dsinfo.id, &output, NULL );
  3842. if ( FAILED(result) ) {
  3843. sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.",
  3844. info->name, getErrorString(result));
  3845. error(RtError::WARNING);
  3846. goto check_parameters;
  3847. }
  3848. out_caps.dwSize = sizeof(out_caps);
  3849. result = output->GetCaps( &out_caps );
  3850. if ( FAILED(result) ) {
  3851. output->Release();
  3852. sprintf(message, "RtAudio: Could not get DirectSound playback capabilities (%s): %s.",
  3853. info->name, getErrorString(result));
  3854. error(RtError::WARNING);
  3855. goto check_parameters;
  3856. }
  3857. // Get output channel information.
  3858. info->minOutputChannels = 1;
  3859. info->maxOutputChannels = ( out_caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  3860. // Get sample rate information. Use capture device rate information
  3861. // if it exists.
  3862. if ( info->nSampleRates == 0 ) {
  3863. info->sampleRates[0] = (int) out_caps.dwMinSecondarySampleRate;
  3864. info->sampleRates[1] = (int) out_caps.dwMaxSecondarySampleRate;
  3865. if ( out_caps.dwFlags & DSCAPS_CONTINUOUSRATE )
  3866. info->nSampleRates = -1;
  3867. else if ( out_caps.dwMinSecondarySampleRate == out_caps.dwMaxSecondarySampleRate ) {
  3868. if ( out_caps.dwMinSecondarySampleRate == 0 ) {
  3869. // This is a bogus driver report ... fake the range and cross
  3870. // your fingers.
  3871. info->sampleRates[0] = 11025;
  3872. info->sampleRates[1] = 48000;
  3873. info->nSampleRates = -1; /* continuous range */
  3874. sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using defaults (%s).",
  3875. info->name);
  3876. error(RtError::DEBUG_WARNING);
  3877. }
  3878. else {
  3879. info->nSampleRates = 1;
  3880. }
  3881. }
  3882. else if ( (out_caps.dwMinSecondarySampleRate < 1000.0) &&
  3883. (out_caps.dwMaxSecondarySampleRate > 50000.0) ) {
  3884. // This is a bogus driver report ... support for only two
  3885. // distant rates. We'll assume this is a range.
  3886. info->nSampleRates = -1;
  3887. sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using range (%s).",
  3888. info->name);
  3889. error(RtError::WARNING);
  3890. }
  3891. else info->nSampleRates = 2;
  3892. }
  3893. else {
  3894. // Check input rates against output rate range
  3895. for ( int i=info->nSampleRates-1; i>=0; i-- ) {
  3896. if ( info->sampleRates[i] <= out_caps.dwMaxSecondarySampleRate )
  3897. break;
  3898. info->nSampleRates--;
  3899. }
  3900. while ( info->sampleRates[0] < out_caps.dwMinSecondarySampleRate ) {
  3901. info->nSampleRates--;
  3902. for ( int i=0; i<info->nSampleRates; i++)
  3903. info->sampleRates[i] = info->sampleRates[i+1];
  3904. if ( info->nSampleRates <= 0 ) break;
  3905. }
  3906. }
  3907. // Get format information.
  3908. if ( out_caps.dwFlags & DSCAPS_PRIMARY16BIT ) info->nativeFormats |= RTAUDIO_SINT16;
  3909. if ( out_caps.dwFlags & DSCAPS_PRIMARY8BIT ) info->nativeFormats |= RTAUDIO_SINT8;
  3910. output->Release();
  3911. check_parameters:
  3912. if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 )
  3913. return;
  3914. if ( info->nSampleRates == 0 || info->nativeFormats == 0 )
  3915. return;
  3916. // Determine duplex status.
  3917. if (info->maxInputChannels < info->maxOutputChannels)
  3918. info->maxDuplexChannels = info->maxInputChannels;
  3919. else
  3920. info->maxDuplexChannels = info->maxOutputChannels;
  3921. if (info->minInputChannels < info->minOutputChannels)
  3922. info->minDuplexChannels = info->minInputChannels;
  3923. else
  3924. info->minDuplexChannels = info->minOutputChannels;
  3925. if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true;
  3926. else info->hasDuplexSupport = false;
  3927. info->probed = true;
  3928. return;
  3929. }
  3930. bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
  3931. STREAM_MODE mode, int channels,
  3932. int sampleRate, RTAUDIO_FORMAT format,
  3933. int *bufferSize, int numberOfBuffers)
  3934. {
  3935. HRESULT result;
  3936. HWND hWnd = GetForegroundWindow();
  3937. // According to a note in PortAudio, using GetDesktopWindow()
  3938. // instead of GetForegroundWindow() is supposed to avoid problems
  3939. // that occur when the application's window is not the foreground
  3940. // window. Also, if the application window closes before the
  3941. // DirectSound buffer, DirectSound can crash. However, for console
  3942. // applications, no sound was produced when using GetDesktopWindow().
  3943. long buffer_size;
  3944. LPVOID audioPtr;
  3945. DWORD dataLen;
  3946. int nBuffers;
  3947. // Check the numberOfBuffers parameter and limit the lowest value to
  3948. // two. This is a judgement call and a value of two is probably too
  3949. // low for capture, but it should work for playback.
  3950. if (numberOfBuffers < 2)
  3951. nBuffers = 2;
  3952. else
  3953. nBuffers = numberOfBuffers;
  3954. // Define the wave format structure (16-bit PCM, srate, channels)
  3955. WAVEFORMATEX waveFormat;
  3956. ZeroMemory(&waveFormat, sizeof(WAVEFORMATEX));
  3957. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  3958. waveFormat.nChannels = channels;
  3959. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  3960. // Determine the data format.
  3961. if ( devices[device].nativeFormats ) { // 8-bit and/or 16-bit support
  3962. if ( format == RTAUDIO_SINT8 ) {
  3963. if ( devices[device].nativeFormats & RTAUDIO_SINT8 )
  3964. waveFormat.wBitsPerSample = 8;
  3965. else
  3966. waveFormat.wBitsPerSample = 16;
  3967. }
  3968. else {
  3969. if ( devices[device].nativeFormats & RTAUDIO_SINT16 )
  3970. waveFormat.wBitsPerSample = 16;
  3971. else
  3972. waveFormat.wBitsPerSample = 8;
  3973. }
  3974. }
  3975. else {
  3976. sprintf(message, "RtAudio: no reported data formats for DirectSound device (%s).",
  3977. devices[device].name);
  3978. error(RtError::DEBUG_WARNING);
  3979. return FAILURE;
  3980. }
  3981. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  3982. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  3983. enum_info dsinfo;
  3984. strncpy( dsinfo.name, devices[device].name, 64 );
  3985. dsinfo.isValid = false;
  3986. if ( mode == OUTPUT ) {
  3987. if ( devices[device].maxOutputChannels < channels )
  3988. return FAILURE;
  3989. // Enumerate through output devices to find the id (if it exists).
  3990. result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
  3991. if ( FAILED(result) ) {
  3992. sprintf(message, "RtAudio: Error performing output device id enumeration: %s.",
  3993. getErrorString(result));
  3994. error(RtError::DEBUG_WARNING);
  3995. return FAILURE;
  3996. }
  3997. if ( dsinfo.isValid == false ) {
  3998. sprintf(message, "RtAudio: DS output device (%s) id not found!", devices[device].name);
  3999. error(RtError::DEBUG_WARNING);
  4000. return FAILURE;
  4001. }
  4002. LPGUID id = dsinfo.id;
  4003. LPDIRECTSOUND object;
  4004. LPDIRECTSOUNDBUFFER buffer;
  4005. DSBUFFERDESC bufferDescription;
  4006. result = DirectSoundCreate( id, &object, NULL );
  4007. if ( FAILED(result) ) {
  4008. sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.",
  4009. devices[device].name, getErrorString(result));
  4010. error(RtError::DEBUG_WARNING);
  4011. return FAILURE;
  4012. }
  4013. // Set cooperative level to DSSCL_EXCLUSIVE
  4014. result = object->SetCooperativeLevel(hWnd, DSSCL_EXCLUSIVE);
  4015. if ( FAILED(result) ) {
  4016. object->Release();
  4017. sprintf(message, "RtAudio: Unable to set DirectSound cooperative level (%s): %s.",
  4018. devices[device].name, getErrorString(result));
  4019. error(RtError::WARNING);
  4020. return FAILURE;
  4021. }
  4022. // Even though we will write to the secondary buffer, we need to
  4023. // access the primary buffer to set the correct output format.
  4024. // The default is 8-bit, 22 kHz!
  4025. // Setup the DS primary buffer description.
  4026. ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC));
  4027. bufferDescription.dwSize = sizeof(DSBUFFERDESC);
  4028. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  4029. // Obtain the primary buffer
  4030. result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
  4031. if ( FAILED(result) ) {
  4032. object->Release();
  4033. sprintf(message, "RtAudio: Unable to access DS primary buffer (%s): %s.",
  4034. devices[device].name, getErrorString(result));
  4035. error(RtError::WARNING);
  4036. return FAILURE;
  4037. }
  4038. // Set the primary DS buffer sound format.
  4039. result = buffer->SetFormat(&waveFormat);
  4040. if ( FAILED(result) ) {
  4041. object->Release();
  4042. sprintf(message, "RtAudio: Unable to set DS primary buffer format (%s): %s.",
  4043. devices[device].name, getErrorString(result));
  4044. error(RtError::WARNING);
  4045. return FAILURE;
  4046. }
  4047. // Setup the secondary DS buffer description.
  4048. buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8;
  4049. ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC));
  4050. bufferDescription.dwSize = sizeof(DSBUFFERDESC);
  4051. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4052. DSBCAPS_GETCURRENTPOSITION2 |
  4053. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  4054. bufferDescription.dwBufferBytes = buffer_size;
  4055. bufferDescription.lpwfxFormat = &waveFormat;
  4056. // Try to create the secondary DS buffer. If that doesn't work,
  4057. // try to use software mixing. Otherwise, there's a problem.
  4058. result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
  4059. if ( FAILED(result) ) {
  4060. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4061. DSBCAPS_GETCURRENTPOSITION2 |
  4062. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  4063. result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
  4064. if ( FAILED(result) ) {
  4065. object->Release();
  4066. sprintf(message, "RtAudio: Unable to create secondary DS buffer (%s): %s.",
  4067. devices[device].name, getErrorString(result));
  4068. error(RtError::WARNING);
  4069. return FAILURE;
  4070. }
  4071. }
  4072. // Get the buffer size ... might be different from what we specified.
  4073. DSBCAPS dsbcaps;
  4074. dsbcaps.dwSize = sizeof(DSBCAPS);
  4075. buffer->GetCaps(&dsbcaps);
  4076. buffer_size = dsbcaps.dwBufferBytes;
  4077. // Lock the DS buffer
  4078. result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0);
  4079. if ( FAILED(result) ) {
  4080. object->Release();
  4081. sprintf(message, "RtAudio: Unable to lock DS buffer (%s): %s.",
  4082. devices[device].name, getErrorString(result));
  4083. error(RtError::WARNING);
  4084. return FAILURE;
  4085. }
  4086. // Zero the DS buffer
  4087. ZeroMemory(audioPtr, dataLen);
  4088. // Unlock the DS buffer
  4089. result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
  4090. if ( FAILED(result) ) {
  4091. object->Release();
  4092. sprintf(message, "RtAudio: Unable to unlock DS buffer(%s): %s.",
  4093. devices[device].name, getErrorString(result));
  4094. error(RtError::WARNING);
  4095. return FAILURE;
  4096. }
  4097. stream->handle[0].object = (void *) object;
  4098. stream->handle[0].buffer = (void *) buffer;
  4099. stream->nDeviceChannels[0] = channels;
  4100. }
  4101. if ( mode == INPUT ) {
  4102. if ( devices[device].maxInputChannels < channels )
  4103. return FAILURE;
  4104. // Enumerate through input devices to find the id (if it exists).
  4105. result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
  4106. if ( FAILED(result) ) {
  4107. sprintf(message, "RtAudio: Error performing input device id enumeration: %s.",
  4108. getErrorString(result));
  4109. error(RtError::DEBUG_WARNING);
  4110. return FAILURE;
  4111. }
  4112. if ( dsinfo.isValid == false ) {
  4113. sprintf(message, "RtAudio: DS input device (%s) id not found!", devices[device].name);
  4114. error(RtError::DEBUG_WARNING);
  4115. return FAILURE;
  4116. }
  4117. LPGUID id = dsinfo.id;
  4118. LPDIRECTSOUNDCAPTURE object;
  4119. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  4120. DSCBUFFERDESC bufferDescription;
  4121. result = DirectSoundCaptureCreate( id, &object, NULL );
  4122. if ( FAILED(result) ) {
  4123. sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.",
  4124. devices[device].name, getErrorString(result));
  4125. error(RtError::WARNING);
  4126. return FAILURE;
  4127. }
  4128. // Setup the secondary DS buffer description.
  4129. buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8;
  4130. ZeroMemory(&bufferDescription, sizeof(DSCBUFFERDESC));
  4131. bufferDescription.dwSize = sizeof(DSCBUFFERDESC);
  4132. bufferDescription.dwFlags = 0;
  4133. bufferDescription.dwReserved = 0;
  4134. bufferDescription.dwBufferBytes = buffer_size;
  4135. bufferDescription.lpwfxFormat = &waveFormat;
  4136. // Create the capture buffer.
  4137. result = object->CreateCaptureBuffer(&bufferDescription, &buffer, NULL);
  4138. if ( FAILED(result) ) {
  4139. object->Release();
  4140. sprintf(message, "RtAudio: Unable to create DS capture buffer (%s): %s.",
  4141. devices[device].name, getErrorString(result));
  4142. error(RtError::WARNING);
  4143. return FAILURE;
  4144. }
  4145. // Lock the capture buffer
  4146. result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0);
  4147. if ( FAILED(result) ) {
  4148. object->Release();
  4149. sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.",
  4150. devices[device].name, getErrorString(result));
  4151. error(RtError::WARNING);
  4152. return FAILURE;
  4153. }
  4154. // Zero the buffer
  4155. ZeroMemory(audioPtr, dataLen);
  4156. // Unlock the buffer
  4157. result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
  4158. if ( FAILED(result) ) {
  4159. object->Release();
  4160. sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.",
  4161. devices[device].name, getErrorString(result));
  4162. error(RtError::WARNING);
  4163. return FAILURE;
  4164. }
  4165. stream->handle[1].object = (void *) object;
  4166. stream->handle[1].buffer = (void *) buffer;
  4167. stream->nDeviceChannels[1] = channels;
  4168. }
  4169. stream->userFormat = format;
  4170. if ( waveFormat.wBitsPerSample == 8 )
  4171. stream->deviceFormat[mode] = RTAUDIO_SINT8;
  4172. else
  4173. stream->deviceFormat[mode] = RTAUDIO_SINT16;
  4174. stream->nUserChannels[mode] = channels;
  4175. *bufferSize = buffer_size / (channels * nBuffers * waveFormat.wBitsPerSample / 8);
  4176. stream->bufferSize = *bufferSize;
  4177. // Set flags for buffer conversion
  4178. stream->doConvertBuffer[mode] = false;
  4179. if (stream->userFormat != stream->deviceFormat[mode])
  4180. stream->doConvertBuffer[mode] = true;
  4181. if (stream->nUserChannels[mode] < stream->nDeviceChannels[mode])
  4182. stream->doConvertBuffer[mode] = true;
  4183. // Allocate necessary internal buffers
  4184. if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) {
  4185. long buffer_bytes;
  4186. if (stream->nUserChannels[0] >= stream->nUserChannels[1])
  4187. buffer_bytes = stream->nUserChannels[0];
  4188. else
  4189. buffer_bytes = stream->nUserChannels[1];
  4190. buffer_bytes *= *bufferSize * formatBytes(stream->userFormat);
  4191. if (stream->userBuffer) free(stream->userBuffer);
  4192. stream->userBuffer = (char *) calloc(buffer_bytes, 1);
  4193. if (stream->userBuffer == NULL)
  4194. goto memory_error;
  4195. }
  4196. if ( stream->doConvertBuffer[mode] ) {
  4197. long buffer_bytes;
  4198. bool makeBuffer = true;
  4199. if ( mode == OUTPUT )
  4200. buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  4201. else { // mode == INPUT
  4202. buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
  4203. if ( stream->mode == OUTPUT && stream->deviceBuffer ) {
  4204. long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  4205. if ( buffer_bytes < bytes_out ) makeBuffer = false;
  4206. }
  4207. }
  4208. if ( makeBuffer ) {
  4209. buffer_bytes *= *bufferSize;
  4210. if (stream->deviceBuffer) free(stream->deviceBuffer);
  4211. stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
  4212. if (stream->deviceBuffer == NULL)
  4213. goto memory_error;
  4214. }
  4215. }
  4216. stream->device[mode] = device;
  4217. stream->state = STREAM_STOPPED;
  4218. if ( stream->mode == OUTPUT && mode == INPUT )
  4219. // We had already set up an output stream.
  4220. stream->mode = DUPLEX;
  4221. else
  4222. stream->mode = mode;
  4223. stream->nBuffers = nBuffers;
  4224. stream->sampleRate = sampleRate;
  4225. return SUCCESS;
  4226. memory_error:
  4227. if (stream->handle[0].object) {
  4228. LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object;
  4229. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
  4230. if (buffer) {
  4231. buffer->Release();
  4232. stream->handle[0].buffer = NULL;
  4233. }
  4234. object->Release();
  4235. stream->handle[0].object = NULL;
  4236. }
  4237. if (stream->handle[1].object) {
  4238. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object;
  4239. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
  4240. if (buffer) {
  4241. buffer->Release();
  4242. stream->handle[1].buffer = NULL;
  4243. }
  4244. object->Release();
  4245. stream->handle[1].object = NULL;
  4246. }
  4247. if (stream->userBuffer) {
  4248. free(stream->userBuffer);
  4249. stream->userBuffer = 0;
  4250. }
  4251. sprintf(message, "RtAudio: error allocating buffer memory (%s).",
  4252. devices[device].name);
  4253. error(RtError::WARNING);
  4254. return FAILURE;
  4255. }
  4256. void RtAudio :: cancelStreamCallback(int streamId)
  4257. {
  4258. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  4259. if (stream->callbackInfo.usingCallback) {
  4260. if (stream->state == STREAM_RUNNING)
  4261. stopStream( streamId );
  4262. MUTEX_LOCK(&stream->mutex);
  4263. stream->callbackInfo.usingCallback = false;
  4264. WaitForSingleObject( (HANDLE)stream->callbackInfo.thread, INFINITE );
  4265. CloseHandle( (HANDLE)stream->callbackInfo.thread );
  4266. stream->callbackInfo.thread = 0;
  4267. stream->callbackInfo.callback = NULL;
  4268. stream->callbackInfo.userData = NULL;
  4269. MUTEX_UNLOCK(&stream->mutex);
  4270. }
  4271. }
  4272. void RtAudio :: closeStream(int streamId)
  4273. {
  4274. // We don't want an exception to be thrown here because this
  4275. // function is called by our class destructor. So, do our own
  4276. // streamId check.
  4277. if ( streams.find( streamId ) == streams.end() ) {
  4278. sprintf(message, "RtAudio: invalid stream identifier!");
  4279. error(RtError::WARNING);
  4280. return;
  4281. }
  4282. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId];
  4283. if (stream->callbackInfo.usingCallback) {
  4284. stream->callbackInfo.usingCallback = false;
  4285. WaitForSingleObject( (HANDLE)stream->callbackInfo.thread, INFINITE );
  4286. CloseHandle( (HANDLE)stream->callbackInfo.thread );
  4287. }
  4288. DeleteCriticalSection(&stream->mutex);
  4289. if (stream->handle[0].object) {
  4290. LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object;
  4291. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
  4292. if (buffer) {
  4293. buffer->Stop();
  4294. buffer->Release();
  4295. }
  4296. object->Release();
  4297. }
  4298. if (stream->handle[1].object) {
  4299. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object;
  4300. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
  4301. if (buffer) {
  4302. buffer->Stop();
  4303. buffer->Release();
  4304. }
  4305. object->Release();
  4306. }
  4307. if (stream->userBuffer)
  4308. free(stream->userBuffer);
  4309. if (stream->deviceBuffer)
  4310. free(stream->deviceBuffer);
  4311. free(stream);
  4312. streams.erase(streamId);
  4313. }
  4314. void RtAudio :: startStream(int streamId)
  4315. {
  4316. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  4317. MUTEX_LOCK(&stream->mutex);
  4318. if (stream->state == STREAM_RUNNING)
  4319. goto unlock;
  4320. HRESULT result;
  4321. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  4322. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
  4323. result = buffer->Play(0, 0, DSBPLAY_LOOPING );
  4324. if ( FAILED(result) ) {
  4325. sprintf(message, "RtAudio: Unable to start DS buffer (%s): %s.",
  4326. devices[stream->device[0]].name, getErrorString(result));
  4327. error(RtError::DRIVER_ERROR);
  4328. }
  4329. }
  4330. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  4331. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
  4332. result = buffer->Start(DSCBSTART_LOOPING );
  4333. if ( FAILED(result) ) {
  4334. sprintf(message, "RtAudio: Unable to start DS capture buffer (%s): %s.",
  4335. devices[stream->device[1]].name, getErrorString(result));
  4336. error(RtError::DRIVER_ERROR);
  4337. }
  4338. }
  4339. stream->state = STREAM_RUNNING;
  4340. unlock:
  4341. MUTEX_UNLOCK(&stream->mutex);
  4342. }
  4343. void RtAudio :: stopStream(int streamId)
  4344. {
  4345. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  4346. MUTEX_LOCK(&stream->mutex);
  4347. if (stream->state == STREAM_STOPPED) {
  4348. MUTEX_UNLOCK(&stream->mutex);
  4349. return;
  4350. }
  4351. // There is no specific DirectSound API call to "drain" a buffer
  4352. // before stopping. We can hack this for playback by writing zeroes
  4353. // for another bufferSize * nBuffers frames. For capture, the
  4354. // concept is less clear so we'll repeat what we do in the
  4355. // abortStream() case.
  4356. HRESULT result;
  4357. DWORD dsBufferSize;
  4358. LPVOID buffer1 = NULL;
  4359. LPVOID buffer2 = NULL;
  4360. DWORD bufferSize1 = 0;
  4361. DWORD bufferSize2 = 0;
  4362. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  4363. DWORD currentPos, safePos;
  4364. long buffer_bytes = stream->bufferSize * stream->nDeviceChannels[0];
  4365. buffer_bytes *= formatBytes(stream->deviceFormat[0]);
  4366. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
  4367. UINT nextWritePos = stream->handle[0].bufferPointer;
  4368. dsBufferSize = buffer_bytes * stream->nBuffers;
  4369. // Write zeroes for nBuffer counts.
  4370. for (int i=0; i<stream->nBuffers; i++) {
  4371. // Find out where the read and "safe write" pointers are.
  4372. result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
  4373. if ( FAILED(result) ) {
  4374. sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
  4375. devices[stream->device[0]].name, getErrorString(result));
  4376. error(RtError::DRIVER_ERROR);
  4377. }
  4378. if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset
  4379. DWORD endWrite = nextWritePos + buffer_bytes;
  4380. // Check whether the entire write region is behind the play pointer.
  4381. while ( currentPos < endWrite ) {
  4382. float millis = (endWrite - currentPos) * 900.0;
  4383. millis /= ( formatBytes(stream->deviceFormat[0]) * stream->sampleRate);
  4384. if ( millis < 1.0 ) millis = 1.0;
  4385. Sleep( (DWORD) millis );
  4386. // Wake up, find out where we are now
  4387. result = dsBuffer->GetCurrentPosition( &currentPos, &safePos );
  4388. if ( FAILED(result) ) {
  4389. sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
  4390. devices[stream->device[0]].name, getErrorString(result));
  4391. error(RtError::DRIVER_ERROR);
  4392. }
  4393. if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset
  4394. }
  4395. // Lock free space in the buffer
  4396. result = dsBuffer->Lock (nextWritePos, buffer_bytes, &buffer1,
  4397. &bufferSize1, &buffer2, &bufferSize2, 0);
  4398. if ( FAILED(result) ) {
  4399. sprintf(message, "RtAudio: Unable to lock DS buffer during playback (%s): %s.",
  4400. devices[stream->device[0]].name, getErrorString(result));
  4401. error(RtError::DRIVER_ERROR);
  4402. }
  4403. // Zero the free space
  4404. ZeroMemory(buffer1, bufferSize1);
  4405. if (buffer2 != NULL) ZeroMemory(buffer2, bufferSize2);
  4406. // Update our buffer offset and unlock sound buffer
  4407. dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2);
  4408. if ( FAILED(result) ) {
  4409. sprintf(message, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.",
  4410. devices[stream->device[0]].name, getErrorString(result));
  4411. error(RtError::DRIVER_ERROR);
  4412. }
  4413. nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize;
  4414. stream->handle[0].bufferPointer = nextWritePos;
  4415. }
  4416. // If we play again, start at the beginning of the buffer.
  4417. stream->handle[0].bufferPointer = 0;
  4418. }
  4419. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  4420. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
  4421. buffer1 = NULL;
  4422. bufferSize1 = 0;
  4423. result = buffer->Stop();
  4424. if ( FAILED(result) ) {
  4425. sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s",
  4426. devices[stream->device[1]].name, getErrorString(result));
  4427. error(RtError::DRIVER_ERROR);
  4428. }
  4429. dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1];
  4430. dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers;
  4431. // Lock the buffer and clear it so that if we start to play again,
  4432. // we won't have old data playing.
  4433. result = buffer->Lock(0, dsBufferSize, &buffer1, &bufferSize1, NULL, NULL, 0);
  4434. if ( FAILED(result) ) {
  4435. sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.",
  4436. devices[stream->device[1]].name, getErrorString(result));
  4437. error(RtError::DRIVER_ERROR);
  4438. }
  4439. // Zero the DS buffer
  4440. ZeroMemory(buffer1, bufferSize1);
  4441. // Unlock the DS buffer
  4442. result = buffer->Unlock(buffer1, bufferSize1, NULL, 0);
  4443. if ( FAILED(result) ) {
  4444. sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.",
  4445. devices[stream->device[1]].name, getErrorString(result));
  4446. error(RtError::DRIVER_ERROR);
  4447. }
  4448. // If we start recording again, we must begin at beginning of buffer.
  4449. stream->handle[1].bufferPointer = 0;
  4450. }
  4451. stream->state = STREAM_STOPPED;
  4452. MUTEX_UNLOCK(&stream->mutex);
  4453. }
  4454. void RtAudio :: abortStream(int streamId)
  4455. {
  4456. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  4457. MUTEX_LOCK(&stream->mutex);
  4458. if (stream->state == STREAM_STOPPED)
  4459. goto unlock;
  4460. HRESULT result;
  4461. long dsBufferSize;
  4462. LPVOID audioPtr;
  4463. DWORD dataLen;
  4464. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  4465. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
  4466. result = buffer->Stop();
  4467. if ( FAILED(result) ) {
  4468. sprintf(message, "RtAudio: Unable to stop DS buffer (%s): %s",
  4469. devices[stream->device[0]].name, getErrorString(result));
  4470. error(RtError::DRIVER_ERROR);
  4471. }
  4472. dsBufferSize = stream->bufferSize * stream->nDeviceChannels[0];
  4473. dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers;
  4474. // Lock the buffer and clear it so that if we start to play again,
  4475. // we won't have old data playing.
  4476. result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0);
  4477. if ( FAILED(result) ) {
  4478. sprintf(message, "RtAudio: Unable to lock DS buffer (%s): %s.",
  4479. devices[stream->device[0]].name, getErrorString(result));
  4480. error(RtError::DRIVER_ERROR);
  4481. }
  4482. // Zero the DS buffer
  4483. ZeroMemory(audioPtr, dataLen);
  4484. // Unlock the DS buffer
  4485. result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
  4486. if ( FAILED(result) ) {
  4487. sprintf(message, "RtAudio: Unable to unlock DS buffer (%s): %s.",
  4488. devices[stream->device[0]].name, getErrorString(result));
  4489. error(RtError::DRIVER_ERROR);
  4490. }
  4491. // If we start playing again, we must begin at beginning of buffer.
  4492. stream->handle[0].bufferPointer = 0;
  4493. }
  4494. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  4495. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
  4496. audioPtr = NULL;
  4497. dataLen = 0;
  4498. result = buffer->Stop();
  4499. if ( FAILED(result) ) {
  4500. sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s",
  4501. devices[stream->device[1]].name, getErrorString(result));
  4502. error(RtError::DRIVER_ERROR);
  4503. }
  4504. dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1];
  4505. dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers;
  4506. // Lock the buffer and clear it so that if we start to play again,
  4507. // we won't have old data playing.
  4508. result = buffer->Lock(0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0);
  4509. if ( FAILED(result) ) {
  4510. sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.",
  4511. devices[stream->device[1]].name, getErrorString(result));
  4512. error(RtError::DRIVER_ERROR);
  4513. }
  4514. // Zero the DS buffer
  4515. ZeroMemory(audioPtr, dataLen);
  4516. // Unlock the DS buffer
  4517. result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
  4518. if ( FAILED(result) ) {
  4519. sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.",
  4520. devices[stream->device[1]].name, getErrorString(result));
  4521. error(RtError::DRIVER_ERROR);
  4522. }
  4523. // If we start recording again, we must begin at beginning of buffer.
  4524. stream->handle[1].bufferPointer = 0;
  4525. }
  4526. stream->state = STREAM_STOPPED;
  4527. unlock:
  4528. MUTEX_UNLOCK(&stream->mutex);
  4529. }
  4530. int RtAudio :: streamWillBlock(int streamId)
  4531. {
  4532. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  4533. MUTEX_LOCK(&stream->mutex);
  4534. int channels;
  4535. int frames = 0;
  4536. if (stream->state == STREAM_STOPPED)
  4537. goto unlock;
  4538. HRESULT result;
  4539. DWORD currentPos, safePos;
  4540. channels = 1;
  4541. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  4542. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
  4543. UINT nextWritePos = stream->handle[0].bufferPointer;
  4544. channels = stream->nDeviceChannels[0];
  4545. DWORD dsBufferSize = stream->bufferSize * channels;
  4546. dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers;
  4547. // Find out where the read and "safe write" pointers are.
  4548. result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
  4549. if ( FAILED(result) ) {
  4550. sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
  4551. devices[stream->device[0]].name, getErrorString(result));
  4552. error(RtError::DRIVER_ERROR);
  4553. }
  4554. if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset
  4555. frames = currentPos - nextWritePos;
  4556. frames /= channels * formatBytes(stream->deviceFormat[0]);
  4557. }
  4558. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  4559. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
  4560. UINT nextReadPos = stream->handle[1].bufferPointer;
  4561. channels = stream->nDeviceChannels[1];
  4562. DWORD dsBufferSize = stream->bufferSize * channels;
  4563. dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers;
  4564. // Find out where the write and "safe read" pointers are.
  4565. result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
  4566. if ( FAILED(result) ) {
  4567. sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.",
  4568. devices[stream->device[1]].name, getErrorString(result));
  4569. error(RtError::DRIVER_ERROR);
  4570. }
  4571. if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset
  4572. if (stream->mode == DUPLEX ) {
  4573. // Take largest value of the two.
  4574. int temp = safePos - nextReadPos;
  4575. temp /= channels * formatBytes(stream->deviceFormat[1]);
  4576. frames = ( temp > frames ) ? temp : frames;
  4577. }
  4578. else {
  4579. frames = safePos - nextReadPos;
  4580. frames /= channels * formatBytes(stream->deviceFormat[1]);
  4581. }
  4582. }
  4583. frames = stream->bufferSize - frames;
  4584. if (frames < 0) frames = 0;
  4585. unlock:
  4586. MUTEX_UNLOCK(&stream->mutex);
  4587. return frames;
  4588. }
  4589. void RtAudio :: tickStream(int streamId)
  4590. {
  4591. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  4592. int stopStream = 0;
  4593. if (stream->state == STREAM_STOPPED) {
  4594. if (stream->callbackInfo.usingCallback) Sleep(50); // sleep 50 milliseconds
  4595. return;
  4596. }
  4597. else if (stream->callbackInfo.usingCallback) {
  4598. RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback;
  4599. stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData);
  4600. }
  4601. MUTEX_LOCK(&stream->mutex);
  4602. // The state might change while waiting on a mutex.
  4603. if (stream->state == STREAM_STOPPED) {
  4604. MUTEX_UNLOCK(&stream->mutex);
  4605. return;
  4606. }
  4607. HRESULT result;
  4608. DWORD currentPos, safePos;
  4609. LPVOID buffer1 = NULL;
  4610. LPVOID buffer2 = NULL;
  4611. DWORD bufferSize1 = 0;
  4612. DWORD bufferSize2 = 0;
  4613. char *buffer;
  4614. long buffer_bytes;
  4615. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  4616. // Setup parameters and do buffer conversion if necessary.
  4617. if (stream->doConvertBuffer[0]) {
  4618. convertStreamBuffer(stream, OUTPUT);
  4619. buffer = stream->deviceBuffer;
  4620. buffer_bytes = stream->bufferSize * stream->nDeviceChannels[0];
  4621. buffer_bytes *= formatBytes(stream->deviceFormat[0]);
  4622. }
  4623. else {
  4624. buffer = stream->userBuffer;
  4625. buffer_bytes = stream->bufferSize * stream->nUserChannels[0];
  4626. buffer_bytes *= formatBytes(stream->userFormat);
  4627. }
  4628. // No byte swapping necessary in DirectSound implementation.
  4629. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
  4630. UINT nextWritePos = stream->handle[0].bufferPointer;
  4631. DWORD dsBufferSize = buffer_bytes * stream->nBuffers;
  4632. // Find out where the read and "safe write" pointers are.
  4633. result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
  4634. if ( FAILED(result) ) {
  4635. sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
  4636. devices[stream->device[0]].name, getErrorString(result));
  4637. error(RtError::DRIVER_ERROR);
  4638. }
  4639. if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset
  4640. DWORD endWrite = nextWritePos + buffer_bytes;
  4641. // Check whether the entire write region is behind the play pointer.
  4642. while ( currentPos < endWrite ) {
  4643. // If we are here, then we must wait until the play pointer gets
  4644. // beyond the write region. The approach here is to use the
  4645. // Sleep() function to suspend operation until safePos catches
  4646. // up. Calculate number of milliseconds to wait as:
  4647. // time = distance * (milliseconds/second) * fudgefactor /
  4648. // ((bytes/sample) * (samples/second))
  4649. // A "fudgefactor" less than 1 is used because it was found
  4650. // that sleeping too long was MUCH worse than sleeping for
  4651. // several shorter periods.
  4652. float millis = (endWrite - currentPos) * 900.0;
  4653. millis /= ( formatBytes(stream->deviceFormat[0]) * stream->sampleRate);
  4654. if ( millis < 1.0 ) millis = 1.0;
  4655. Sleep( (DWORD) millis );
  4656. // Wake up, find out where we are now
  4657. result = dsBuffer->GetCurrentPosition( &currentPos, &safePos );
  4658. if ( FAILED(result) ) {
  4659. sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
  4660. devices[stream->device[0]].name, getErrorString(result));
  4661. error(RtError::DRIVER_ERROR);
  4662. }
  4663. if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset
  4664. }
  4665. // Lock free space in the buffer
  4666. result = dsBuffer->Lock (nextWritePos, buffer_bytes, &buffer1,
  4667. &bufferSize1, &buffer2, &bufferSize2, 0);
  4668. if ( FAILED(result) ) {
  4669. sprintf(message, "RtAudio: Unable to lock DS buffer during playback (%s): %s.",
  4670. devices[stream->device[0]].name, getErrorString(result));
  4671. error(RtError::DRIVER_ERROR);
  4672. }
  4673. // Copy our buffer into the DS buffer
  4674. CopyMemory(buffer1, buffer, bufferSize1);
  4675. if (buffer2 != NULL) CopyMemory(buffer2, buffer+bufferSize1, bufferSize2);
  4676. // Update our buffer offset and unlock sound buffer
  4677. dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2);
  4678. if ( FAILED(result) ) {
  4679. sprintf(message, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.",
  4680. devices[stream->device[0]].name, getErrorString(result));
  4681. error(RtError::DRIVER_ERROR);
  4682. }
  4683. nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize;
  4684. stream->handle[0].bufferPointer = nextWritePos;
  4685. }
  4686. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  4687. // Setup parameters.
  4688. if (stream->doConvertBuffer[1]) {
  4689. buffer = stream->deviceBuffer;
  4690. buffer_bytes = stream->bufferSize * stream->nDeviceChannels[1];
  4691. buffer_bytes *= formatBytes(stream->deviceFormat[1]);
  4692. }
  4693. else {
  4694. buffer = stream->userBuffer;
  4695. buffer_bytes = stream->bufferSize * stream->nUserChannels[1];
  4696. buffer_bytes *= formatBytes(stream->userFormat);
  4697. }
  4698. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
  4699. UINT nextReadPos = stream->handle[1].bufferPointer;
  4700. DWORD dsBufferSize = buffer_bytes * stream->nBuffers;
  4701. // Find out where the write and "safe read" pointers are.
  4702. result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
  4703. if ( FAILED(result) ) {
  4704. sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.",
  4705. devices[stream->device[1]].name, getErrorString(result));
  4706. error(RtError::DRIVER_ERROR);
  4707. }
  4708. if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset
  4709. DWORD endRead = nextReadPos + buffer_bytes;
  4710. // Check whether the entire write region is behind the play pointer.
  4711. while ( safePos < endRead ) {
  4712. // See comments for playback.
  4713. float millis = (endRead - safePos) * 900.0;
  4714. millis /= ( formatBytes(stream->deviceFormat[1]) * stream->sampleRate);
  4715. if ( millis < 1.0 ) millis = 1.0;
  4716. Sleep( (DWORD) millis );
  4717. // Wake up, find out where we are now
  4718. result = dsBuffer->GetCurrentPosition( &currentPos, &safePos );
  4719. if ( FAILED(result) ) {
  4720. sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.",
  4721. devices[stream->device[1]].name, getErrorString(result));
  4722. error(RtError::DRIVER_ERROR);
  4723. }
  4724. if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset
  4725. }
  4726. // Lock free space in the buffer
  4727. result = dsBuffer->Lock (nextReadPos, buffer_bytes, &buffer1,
  4728. &bufferSize1, &buffer2, &bufferSize2, 0);
  4729. if ( FAILED(result) ) {
  4730. sprintf(message, "RtAudio: Unable to lock DS buffer during capture (%s): %s.",
  4731. devices[stream->device[1]].name, getErrorString(result));
  4732. error(RtError::DRIVER_ERROR);
  4733. }
  4734. // Copy our buffer into the DS buffer
  4735. CopyMemory(buffer, buffer1, bufferSize1);
  4736. if (buffer2 != NULL) CopyMemory(buffer+bufferSize1, buffer2, bufferSize2);
  4737. // Update our buffer offset and unlock sound buffer
  4738. nextReadPos = (nextReadPos + bufferSize1 + bufferSize2) % dsBufferSize;
  4739. dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2);
  4740. if ( FAILED(result) ) {
  4741. sprintf(message, "RtAudio: Unable to unlock DS buffer during capture (%s): %s.",
  4742. devices[stream->device[1]].name, getErrorString(result));
  4743. error(RtError::DRIVER_ERROR);
  4744. }
  4745. stream->handle[1].bufferPointer = nextReadPos;
  4746. // No byte swapping necessary in DirectSound implementation.
  4747. // Do buffer conversion if necessary.
  4748. if (stream->doConvertBuffer[1])
  4749. convertStreamBuffer(stream, INPUT);
  4750. }
  4751. MUTEX_UNLOCK(&stream->mutex);
  4752. if (stream->callbackInfo.usingCallback && stopStream)
  4753. this->stopStream(streamId);
  4754. }
  4755. // Definitions for utility functions and callbacks
  4756. // specific to the DirectSound implementation.
  4757. extern "C" unsigned __stdcall callbackHandler(void *ptr)
  4758. {
  4759. CALLBACK_INFO *info = (CALLBACK_INFO *) ptr;
  4760. RtAudio *object = (RtAudio *) info->object;
  4761. int stream = info->streamId;
  4762. bool *usingCallback = &info->usingCallback;
  4763. while ( *usingCallback ) {
  4764. try {
  4765. object->tickStream(stream);
  4766. }
  4767. catch (RtError &exception) {
  4768. fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n",
  4769. exception.getMessage());
  4770. break;
  4771. }
  4772. }
  4773. _endthreadex( 0 );
  4774. return 0;
  4775. }
  4776. void RtAudio :: setStreamCallback(int streamId, RTAUDIO_CALLBACK callback, void *userData)
  4777. {
  4778. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  4779. CALLBACK_INFO *info = (CALLBACK_INFO *) &stream->callbackInfo;
  4780. if ( info->usingCallback ) {
  4781. sprintf(message, "RtAudio: A callback is already set for this stream!");
  4782. error(RtError::WARNING);
  4783. return;
  4784. }
  4785. info->callback = (void *) callback;
  4786. info->userData = userData;
  4787. info->usingCallback = true;
  4788. info->object = (void *) this;
  4789. info->streamId = streamId;
  4790. unsigned thread_id;
  4791. info->thread = _beginthreadex(NULL, 0, &callbackHandler,
  4792. &stream->callbackInfo, 0, &thread_id);
  4793. if (info->thread == 0) {
  4794. info->usingCallback = false;
  4795. sprintf(message, "RtAudio: error starting callback thread!");
  4796. error(RtError::THREAD_ERROR);
  4797. }
  4798. // When spawning multiple threads in quick succession, it appears to be
  4799. // necessary to wait a bit for each to initialize ... another windoism!
  4800. Sleep(1);
  4801. }
  4802. static bool CALLBACK deviceCountCallback(LPGUID lpguid,
  4803. LPCSTR lpcstrDescription,
  4804. LPCSTR lpcstrModule,
  4805. LPVOID lpContext)
  4806. {
  4807. int *pointer = ((int *) lpContext);
  4808. (*pointer)++;
  4809. return true;
  4810. }
  4811. static bool CALLBACK deviceInfoCallback(LPGUID lpguid,
  4812. LPCSTR lpcstrDescription,
  4813. LPCSTR lpcstrModule,
  4814. LPVOID lpContext)
  4815. {
  4816. enum_info *info = ((enum_info *) lpContext);
  4817. while (strlen(info->name) > 0) info++;
  4818. strncpy(info->name, lpcstrDescription, 64);
  4819. info->id = lpguid;
  4820. HRESULT hr;
  4821. info->isValid = false;
  4822. if (info->isInput == true) {
  4823. DSCCAPS caps;
  4824. LPDIRECTSOUNDCAPTURE object;
  4825. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  4826. if( hr != DS_OK ) return true;
  4827. caps.dwSize = sizeof(caps);
  4828. hr = object->GetCaps( &caps );
  4829. if( hr == DS_OK ) {
  4830. if (caps.dwChannels > 0 && caps.dwFormats > 0)
  4831. info->isValid = true;
  4832. }
  4833. object->Release();
  4834. }
  4835. else {
  4836. DSCAPS caps;
  4837. LPDIRECTSOUND object;
  4838. hr = DirectSoundCreate( lpguid, &object, NULL );
  4839. if( hr != DS_OK ) return true;
  4840. caps.dwSize = sizeof(caps);
  4841. hr = object->GetCaps( &caps );
  4842. if( hr == DS_OK ) {
  4843. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  4844. info->isValid = true;
  4845. }
  4846. object->Release();
  4847. }
  4848. return true;
  4849. }
  4850. static bool CALLBACK defaultDeviceCallback(LPGUID lpguid,
  4851. LPCSTR lpcstrDescription,
  4852. LPCSTR lpcstrModule,
  4853. LPVOID lpContext)
  4854. {
  4855. enum_info *info = ((enum_info *) lpContext);
  4856. if ( lpguid == NULL ) {
  4857. strncpy(info->name, lpcstrDescription, 64);
  4858. return false;
  4859. }
  4860. return true;
  4861. }
  4862. static bool CALLBACK deviceIdCallback(LPGUID lpguid,
  4863. LPCSTR lpcstrDescription,
  4864. LPCSTR lpcstrModule,
  4865. LPVOID lpContext)
  4866. {
  4867. enum_info *info = ((enum_info *) lpContext);
  4868. if ( strncmp( info->name, lpcstrDescription, 64 ) == 0 ) {
  4869. info->id = lpguid;
  4870. info->isValid = true;
  4871. return false;
  4872. }
  4873. return true;
  4874. }
  4875. static char* getErrorString(int code)
  4876. {
  4877. switch (code) {
  4878. case DSERR_ALLOCATED:
  4879. return "Direct Sound already allocated";
  4880. case DSERR_CONTROLUNAVAIL:
  4881. return "Direct Sound control unavailable";
  4882. case DSERR_INVALIDPARAM:
  4883. return "Direct Sound invalid parameter";
  4884. case DSERR_INVALIDCALL:
  4885. return "Direct Sound invalid call";
  4886. case DSERR_GENERIC:
  4887. return "Direct Sound generic error";
  4888. case DSERR_PRIOLEVELNEEDED:
  4889. return "Direct Sound Priority level needed";
  4890. case DSERR_OUTOFMEMORY:
  4891. return "Direct Sound out of memory";
  4892. case DSERR_BADFORMAT:
  4893. return "Direct Sound bad format";
  4894. case DSERR_UNSUPPORTED:
  4895. return "Direct Sound unsupported error";
  4896. case DSERR_NODRIVER:
  4897. return "Direct Sound no driver error";
  4898. case DSERR_ALREADYINITIALIZED:
  4899. return "Direct Sound already initialized";
  4900. case DSERR_NOAGGREGATION:
  4901. return "Direct Sound no aggregation";
  4902. case DSERR_BUFFERLOST:
  4903. return "Direct Sound buffer lost";
  4904. case DSERR_OTHERAPPHASPRIO:
  4905. return "Direct Sound other app has priority";
  4906. case DSERR_UNINITIALIZED:
  4907. return "Direct Sound uninitialized";
  4908. default:
  4909. return "Direct Sound unknown error";
  4910. }
  4911. }
  4912. //******************** End of __WINDOWS_DS__ *********************//
  4913. #elif defined(__IRIX_AL__) // SGI's AL API for IRIX
  4914. #include <unistd.h>
  4915. #include <errno.h>
  4916. void RtAudio :: initialize(void)
  4917. {
  4918. // Count cards and devices
  4919. nDevices = 0;
  4920. // Determine the total number of input and output devices.
  4921. nDevices = alQueryValues(AL_SYSTEM, AL_DEVICES, 0, 0, 0, 0);
  4922. if (nDevices < 0) {
  4923. sprintf(message, "RtAudio: AL error counting devices: %s.",
  4924. alGetErrorString(oserror()));
  4925. error(RtError::DRIVER_ERROR);
  4926. }
  4927. if (nDevices <= 0) return;
  4928. ALvalue *vls = (ALvalue *) new ALvalue[nDevices];
  4929. // Allocate the RTAUDIO_DEVICE structures.
  4930. devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
  4931. if (devices == NULL) {
  4932. sprintf(message, "RtAudio: memory allocation error!");
  4933. error(RtError::MEMORY_ERROR);
  4934. }
  4935. // Write device ascii identifiers and resource ids to device info
  4936. // structure.
  4937. char name[32];
  4938. int outs, ins, i;
  4939. ALpv pvs[1];
  4940. pvs[0].param = AL_NAME;
  4941. pvs[0].value.ptr = name;
  4942. pvs[0].sizeIn = 32;
  4943. outs = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, vls, nDevices, 0, 0);
  4944. if (outs < 0) {
  4945. sprintf(message, "RtAudio: AL error getting output devices: %s.",
  4946. alGetErrorString(oserror()));
  4947. error(RtError::DRIVER_ERROR);
  4948. }
  4949. for (i=0; i<outs; i++) {
  4950. if (alGetParams(vls[i].i, pvs, 1) < 0) {
  4951. sprintf(message, "RtAudio: AL error querying output devices: %s.",
  4952. alGetErrorString(oserror()));
  4953. error(RtError::DRIVER_ERROR);
  4954. }
  4955. strncpy(devices[i].name, name, 32);
  4956. devices[i].id[0] = vls[i].i;
  4957. }
  4958. ins = alQueryValues(AL_SYSTEM, AL_DEFAULT_INPUT, &vls[outs], nDevices-outs, 0, 0);
  4959. if (ins < 0) {
  4960. sprintf(message, "RtAudio: AL error getting input devices: %s.",
  4961. alGetErrorString(oserror()));
  4962. error(RtError::DRIVER_ERROR);
  4963. }
  4964. for (i=outs; i<ins+outs; i++) {
  4965. if (alGetParams(vls[i].i, pvs, 1) < 0) {
  4966. sprintf(message, "RtAudio: AL error querying input devices: %s.",
  4967. alGetErrorString(oserror()));
  4968. error(RtError::DRIVER_ERROR);
  4969. }
  4970. strncpy(devices[i].name, name, 32);
  4971. devices[i].id[1] = vls[i].i;
  4972. }
  4973. delete [] vls;
  4974. return;
  4975. }
  4976. int RtAudio :: getDefaultInputDevice(void)
  4977. {
  4978. ALvalue value;
  4979. int result = alQueryValues(AL_SYSTEM, AL_DEFAULT_INPUT, &value, 1, 0, 0);
  4980. if (result < 0) {
  4981. sprintf(message, "RtAudio: AL error getting default input device id: %s.",
  4982. alGetErrorString(oserror()));
  4983. error(RtError::WARNING);
  4984. }
  4985. else {
  4986. for ( int i=0; i<nDevices; i++ )
  4987. if ( devices[i].id[1] == value.i ) return i;
  4988. }
  4989. return 0;
  4990. }
  4991. int RtAudio :: getDefaultOutputDevice(void)
  4992. {
  4993. ALvalue value;
  4994. int result = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, &value, 1, 0, 0);
  4995. if (result < 0) {
  4996. sprintf(message, "RtAudio: AL error getting default output device id: %s.",
  4997. alGetErrorString(oserror()));
  4998. error(RtError::WARNING);
  4999. }
  5000. else {
  5001. for ( int i=0; i<nDevices; i++ )
  5002. if ( devices[i].id[0] == value.i ) return i;
  5003. }
  5004. return 0;
  5005. }
  5006. void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
  5007. {
  5008. int resource, result, i;
  5009. ALvalue value;
  5010. ALparamInfo pinfo;
  5011. // Get output resource ID if it exists.
  5012. resource = info->id[0];
  5013. if (resource > 0) {
  5014. // Probe output device parameters.
  5015. result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0);
  5016. if (result < 0) {
  5017. sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.",
  5018. info->name, alGetErrorString(oserror()));
  5019. error(RtError::WARNING);
  5020. }
  5021. else {
  5022. info->maxOutputChannels = value.i;
  5023. info->minOutputChannels = 1;
  5024. }
  5025. result = alGetParamInfo(resource, AL_RATE, &pinfo);
  5026. if (result < 0) {
  5027. sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.",
  5028. info->name, alGetErrorString(oserror()));
  5029. error(RtError::WARNING);
  5030. }
  5031. else {
  5032. info->nSampleRates = 0;
  5033. for (i=0; i<MAX_SAMPLE_RATES; i++) {
  5034. if ( SAMPLE_RATES[i] >= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) {
  5035. info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
  5036. info->nSampleRates++;
  5037. }
  5038. }
  5039. }
  5040. // The AL library supports all our formats, except 24-bit and 32-bit ints.
  5041. info->nativeFormats = (RTAUDIO_FORMAT) 51;
  5042. }
  5043. // Now get input resource ID if it exists.
  5044. resource = info->id[1];
  5045. if (resource > 0) {
  5046. // Probe input device parameters.
  5047. result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0);
  5048. if (result < 0) {
  5049. sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.",
  5050. info->name, alGetErrorString(oserror()));
  5051. error(RtError::WARNING);
  5052. }
  5053. else {
  5054. info->maxInputChannels = value.i;
  5055. info->minInputChannels = 1;
  5056. }
  5057. result = alGetParamInfo(resource, AL_RATE, &pinfo);
  5058. if (result < 0) {
  5059. sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.",
  5060. info->name, alGetErrorString(oserror()));
  5061. error(RtError::WARNING);
  5062. }
  5063. else {
  5064. // In the case of the default device, these values will
  5065. // overwrite the rates determined for the output device. Since
  5066. // the input device is most likely to be more limited than the
  5067. // output device, this is ok.
  5068. info->nSampleRates = 0;
  5069. for (i=0; i<MAX_SAMPLE_RATES; i++) {
  5070. if ( SAMPLE_RATES[i] >= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) {
  5071. info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
  5072. info->nSampleRates++;
  5073. }
  5074. }
  5075. }
  5076. // The AL library supports all our formats, except 24-bit and 32-bit ints.
  5077. info->nativeFormats = (RTAUDIO_FORMAT) 51;
  5078. }
  5079. if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 )
  5080. return;
  5081. if ( info->nSampleRates == 0 )
  5082. return;
  5083. // Determine duplex status.
  5084. if (info->maxInputChannels < info->maxOutputChannels)
  5085. info->maxDuplexChannels = info->maxInputChannels;
  5086. else
  5087. info->maxDuplexChannels = info->maxOutputChannels;
  5088. if (info->minInputChannels < info->minOutputChannels)
  5089. info->minDuplexChannels = info->minInputChannels;
  5090. else
  5091. info->minDuplexChannels = info->minOutputChannels;
  5092. if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true;
  5093. else info->hasDuplexSupport = false;
  5094. info->probed = true;
  5095. return;
  5096. }
  5097. bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
  5098. STREAM_MODE mode, int channels,
  5099. int sampleRate, RTAUDIO_FORMAT format,
  5100. int *bufferSize, int numberOfBuffers)
  5101. {
  5102. int result, resource, nBuffers;
  5103. ALconfig al_config;
  5104. ALport port;
  5105. ALpv pvs[2];
  5106. // Get a new ALconfig structure.
  5107. al_config = alNewConfig();
  5108. if ( !al_config ) {
  5109. sprintf(message,"RtAudio: can't get AL config: %s.",
  5110. alGetErrorString(oserror()));
  5111. error(RtError::WARNING);
  5112. return FAILURE;
  5113. }
  5114. // Set the channels.
  5115. result = alSetChannels(al_config, channels);
  5116. if ( result < 0 ) {
  5117. sprintf(message,"RtAudio: can't set %d channels in AL config: %s.",
  5118. channels, alGetErrorString(oserror()));
  5119. error(RtError::WARNING);
  5120. return FAILURE;
  5121. }
  5122. // Attempt to set the queue size. The al API doesn't provide a
  5123. // means for querying the minimum/maximum buffer size of a device,
  5124. // so if the specified size doesn't work, take whatever the
  5125. // al_config structure returns.
  5126. if ( numberOfBuffers < 1 )
  5127. nBuffers = 1;
  5128. else
  5129. nBuffers = numberOfBuffers;
  5130. long buffer_size = *bufferSize * nBuffers;
  5131. result = alSetQueueSize(al_config, buffer_size); // in sample frames
  5132. if ( result < 0 ) {
  5133. // Get the buffer size specified by the al_config and try that.
  5134. buffer_size = alGetQueueSize(al_config);
  5135. result = alSetQueueSize(al_config, buffer_size);
  5136. if ( result < 0 ) {
  5137. sprintf(message,"RtAudio: can't set buffer size (%ld) in AL config: %s.",
  5138. buffer_size, alGetErrorString(oserror()));
  5139. error(RtError::WARNING);
  5140. return FAILURE;
  5141. }
  5142. *bufferSize = buffer_size / nBuffers;
  5143. }
  5144. // Set the data format.
  5145. stream->userFormat = format;
  5146. stream->deviceFormat[mode] = format;
  5147. if (format == RTAUDIO_SINT8) {
  5148. result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP);
  5149. result = alSetWidth(al_config, AL_SAMPLE_8);
  5150. }
  5151. else if (format == RTAUDIO_SINT16) {
  5152. result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP);
  5153. result = alSetWidth(al_config, AL_SAMPLE_16);
  5154. }
  5155. else if (format == RTAUDIO_SINT24) {
  5156. // Our 24-bit format assumes the upper 3 bytes of a 4 byte word.
  5157. // The AL library uses the lower 3 bytes, so we'll need to do our
  5158. // own conversion.
  5159. result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT);
  5160. stream->deviceFormat[mode] = RTAUDIO_FLOAT32;
  5161. }
  5162. else if (format == RTAUDIO_SINT32) {
  5163. // The AL library doesn't seem to support the 32-bit integer
  5164. // format, so we'll need to do our own conversion.
  5165. result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT);
  5166. stream->deviceFormat[mode] = RTAUDIO_FLOAT32;
  5167. }
  5168. else if (format == RTAUDIO_FLOAT32)
  5169. result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT);
  5170. else if (format == RTAUDIO_FLOAT64)
  5171. result = alSetSampFmt(al_config, AL_SAMPFMT_DOUBLE);
  5172. if ( result == -1 ) {
  5173. sprintf(message,"RtAudio: AL error setting sample format in AL config: %s.",
  5174. alGetErrorString(oserror()));
  5175. error(RtError::WARNING);
  5176. return FAILURE;
  5177. }
  5178. if (mode == OUTPUT) {
  5179. // Set our device.
  5180. if (device == 0)
  5181. resource = AL_DEFAULT_OUTPUT;
  5182. else
  5183. resource = devices[device].id[0];
  5184. result = alSetDevice(al_config, resource);
  5185. if ( result == -1 ) {
  5186. sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.",
  5187. devices[device].name, alGetErrorString(oserror()));
  5188. error(RtError::WARNING);
  5189. return FAILURE;
  5190. }
  5191. // Open the port.
  5192. port = alOpenPort("RtAudio Output Port", "w", al_config);
  5193. if( !port ) {
  5194. sprintf(message,"RtAudio: AL error opening output port: %s.",
  5195. alGetErrorString(oserror()));
  5196. error(RtError::WARNING);
  5197. return FAILURE;
  5198. }
  5199. // Set the sample rate
  5200. pvs[0].param = AL_MASTER_CLOCK;
  5201. pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE;
  5202. pvs[1].param = AL_RATE;
  5203. pvs[1].value.ll = alDoubleToFixed((double)sampleRate);
  5204. result = alSetParams(resource, pvs, 2);
  5205. if ( result < 0 ) {
  5206. alClosePort(port);
  5207. sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.",
  5208. sampleRate, devices[device].name, alGetErrorString(oserror()));
  5209. error(RtError::WARNING);
  5210. return FAILURE;
  5211. }
  5212. }
  5213. else { // mode == INPUT
  5214. // Set our device.
  5215. if (device == 0)
  5216. resource = AL_DEFAULT_INPUT;
  5217. else
  5218. resource = devices[device].id[1];
  5219. result = alSetDevice(al_config, resource);
  5220. if ( result == -1 ) {
  5221. sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.",
  5222. devices[device].name, alGetErrorString(oserror()));
  5223. error(RtError::WARNING);
  5224. return FAILURE;
  5225. }
  5226. // Open the port.
  5227. port = alOpenPort("RtAudio Output Port", "r", al_config);
  5228. if( !port ) {
  5229. sprintf(message,"RtAudio: AL error opening input port: %s.",
  5230. alGetErrorString(oserror()));
  5231. error(RtError::WARNING);
  5232. return FAILURE;
  5233. }
  5234. // Set the sample rate
  5235. pvs[0].param = AL_MASTER_CLOCK;
  5236. pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE;
  5237. pvs[1].param = AL_RATE;
  5238. pvs[1].value.ll = alDoubleToFixed((double)sampleRate);
  5239. result = alSetParams(resource, pvs, 2);
  5240. if ( result < 0 ) {
  5241. alClosePort(port);
  5242. sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.",
  5243. sampleRate, devices[device].name, alGetErrorString(oserror()));
  5244. error(RtError::WARNING);
  5245. return FAILURE;
  5246. }
  5247. }
  5248. alFreeConfig(al_config);
  5249. stream->nUserChannels[mode] = channels;
  5250. stream->nDeviceChannels[mode] = channels;
  5251. // Set handle and flags for buffer conversion
  5252. stream->handle[mode] = port;
  5253. stream->doConvertBuffer[mode] = false;
  5254. if (stream->userFormat != stream->deviceFormat[mode])
  5255. stream->doConvertBuffer[mode] = true;
  5256. // Allocate necessary internal buffers
  5257. if ( stream->nUserChannels[0] != stream->nUserChannels[1] ) {
  5258. long buffer_bytes;
  5259. if (stream->nUserChannels[0] >= stream->nUserChannels[1])
  5260. buffer_bytes = stream->nUserChannels[0];
  5261. else
  5262. buffer_bytes = stream->nUserChannels[1];
  5263. buffer_bytes *= *bufferSize * formatBytes(stream->userFormat);
  5264. if (stream->userBuffer) free(stream->userBuffer);
  5265. stream->userBuffer = (char *) calloc(buffer_bytes, 1);
  5266. if (stream->userBuffer == NULL)
  5267. goto memory_error;
  5268. }
  5269. if ( stream->doConvertBuffer[mode] ) {
  5270. long buffer_bytes;
  5271. bool makeBuffer = true;
  5272. if ( mode == OUTPUT )
  5273. buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  5274. else { // mode == INPUT
  5275. buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
  5276. if ( stream->mode == OUTPUT && stream->deviceBuffer ) {
  5277. long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
  5278. if ( buffer_bytes < bytes_out ) makeBuffer = false;
  5279. }
  5280. }
  5281. if ( makeBuffer ) {
  5282. buffer_bytes *= *bufferSize;
  5283. if (stream->deviceBuffer) free(stream->deviceBuffer);
  5284. stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
  5285. if (stream->deviceBuffer == NULL)
  5286. goto memory_error;
  5287. }
  5288. }
  5289. stream->device[mode] = device;
  5290. stream->state = STREAM_STOPPED;
  5291. if ( stream->mode == OUTPUT && mode == INPUT )
  5292. // We had already set up an output stream.
  5293. stream->mode = DUPLEX;
  5294. else
  5295. stream->mode = mode;
  5296. stream->nBuffers = nBuffers;
  5297. stream->bufferSize = *bufferSize;
  5298. stream->sampleRate = sampleRate;
  5299. return SUCCESS;
  5300. memory_error:
  5301. if (stream->handle[0]) {
  5302. alClosePort(stream->handle[0]);
  5303. stream->handle[0] = 0;
  5304. }
  5305. if (stream->handle[1]) {
  5306. alClosePort(stream->handle[1]);
  5307. stream->handle[1] = 0;
  5308. }
  5309. if (stream->userBuffer) {
  5310. free(stream->userBuffer);
  5311. stream->userBuffer = 0;
  5312. }
  5313. sprintf(message, "RtAudio: ALSA error allocating buffer memory for device (%s).",
  5314. devices[device].name);
  5315. error(RtError::WARNING);
  5316. return FAILURE;
  5317. }
  5318. void RtAudio :: closeStream(int streamId)
  5319. {
  5320. // We don't want an exception to be thrown here because this
  5321. // function is called by our class destructor. So, do our own
  5322. // streamId check.
  5323. if ( streams.find( streamId ) == streams.end() ) {
  5324. sprintf(message, "RtAudio: invalid stream identifier!");
  5325. error(RtError::WARNING);
  5326. return;
  5327. }
  5328. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamId];
  5329. if (stream->callbackInfo.usingCallback) {
  5330. pthread_cancel(stream->callbackInfo.thread);
  5331. pthread_join(stream->callbackInfo.thread, NULL);
  5332. }
  5333. pthread_mutex_destroy(&stream->mutex);
  5334. if (stream->handle[0])
  5335. alClosePort(stream->handle[0]);
  5336. if (stream->handle[1])
  5337. alClosePort(stream->handle[1]);
  5338. if (stream->userBuffer)
  5339. free(stream->userBuffer);
  5340. if (stream->deviceBuffer)
  5341. free(stream->deviceBuffer);
  5342. free(stream);
  5343. streams.erase(streamId);
  5344. }
  5345. void RtAudio :: startStream(int streamId)
  5346. {
  5347. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  5348. if (stream->state == STREAM_RUNNING)
  5349. return;
  5350. // The AL port is ready as soon as it is opened.
  5351. stream->state = STREAM_RUNNING;
  5352. }
  5353. void RtAudio :: stopStream(int streamId)
  5354. {
  5355. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  5356. MUTEX_LOCK(&stream->mutex);
  5357. if (stream->state == STREAM_STOPPED)
  5358. goto unlock;
  5359. int result;
  5360. int buffer_size = stream->bufferSize * stream->nBuffers;
  5361. if (stream->mode == OUTPUT || stream->mode == DUPLEX)
  5362. alZeroFrames(stream->handle[0], buffer_size);
  5363. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  5364. result = alDiscardFrames(stream->handle[1], buffer_size);
  5365. if (result == -1) {
  5366. sprintf(message, "RtAudio: AL error draining stream device (%s): %s.",
  5367. devices[stream->device[1]].name, alGetErrorString(oserror()));
  5368. error(RtError::DRIVER_ERROR);
  5369. }
  5370. }
  5371. stream->state = STREAM_STOPPED;
  5372. unlock:
  5373. MUTEX_UNLOCK(&stream->mutex);
  5374. }
  5375. void RtAudio :: abortStream(int streamId)
  5376. {
  5377. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  5378. MUTEX_LOCK(&stream->mutex);
  5379. if (stream->state == STREAM_STOPPED)
  5380. goto unlock;
  5381. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  5382. int buffer_size = stream->bufferSize * stream->nBuffers;
  5383. int result = alDiscardFrames(stream->handle[0], buffer_size);
  5384. if (result == -1) {
  5385. sprintf(message, "RtAudio: AL error aborting stream device (%s): %s.",
  5386. devices[stream->device[0]].name, alGetErrorString(oserror()));
  5387. error(RtError::DRIVER_ERROR);
  5388. }
  5389. }
  5390. // There is no clear action to take on the input stream, since the
  5391. // port will continue to run in any event.
  5392. stream->state = STREAM_STOPPED;
  5393. unlock:
  5394. MUTEX_UNLOCK(&stream->mutex);
  5395. }
  5396. int RtAudio :: streamWillBlock(int streamId)
  5397. {
  5398. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  5399. MUTEX_LOCK(&stream->mutex);
  5400. int frames = 0;
  5401. if (stream->state == STREAM_STOPPED)
  5402. goto unlock;
  5403. int err = 0;
  5404. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  5405. err = alGetFillable(stream->handle[0]);
  5406. if (err < 0) {
  5407. sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.",
  5408. devices[stream->device[0]].name, alGetErrorString(oserror()));
  5409. error(RtError::DRIVER_ERROR);
  5410. }
  5411. }
  5412. frames = err;
  5413. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  5414. err = alGetFilled(stream->handle[1]);
  5415. if (err < 0) {
  5416. sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.",
  5417. devices[stream->device[1]].name, alGetErrorString(oserror()));
  5418. error(RtError::DRIVER_ERROR);
  5419. }
  5420. if (frames > err) frames = err;
  5421. }
  5422. frames = stream->bufferSize - frames;
  5423. if (frames < 0) frames = 0;
  5424. unlock:
  5425. MUTEX_UNLOCK(&stream->mutex);
  5426. return frames;
  5427. }
  5428. void RtAudio :: tickStream(int streamId)
  5429. {
  5430. RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamId);
  5431. int stopStream = 0;
  5432. if (stream->state == STREAM_STOPPED) {
  5433. if (stream->callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds
  5434. return;
  5435. }
  5436. else if (stream->callbackInfo.usingCallback) {
  5437. RTAUDIO_CALLBACK callback = (RTAUDIO_CALLBACK) stream->callbackInfo.callback;
  5438. stopStream = callback(stream->userBuffer, stream->bufferSize, stream->callbackInfo.userData);
  5439. }
  5440. MUTEX_LOCK(&stream->mutex);
  5441. // The state might change while waiting on a mutex.
  5442. if (stream->state == STREAM_STOPPED)
  5443. goto unlock;
  5444. char *buffer;
  5445. int channels;
  5446. RTAUDIO_FORMAT format;
  5447. if (stream->mode == OUTPUT || stream->mode == DUPLEX) {
  5448. // Setup parameters and do buffer conversion if necessary.
  5449. if (stream->doConvertBuffer[0]) {
  5450. convertStreamBuffer(stream, OUTPUT);
  5451. buffer = stream->deviceBuffer;
  5452. channels = stream->nDeviceChannels[0];
  5453. format = stream->deviceFormat[0];
  5454. }
  5455. else {
  5456. buffer = stream->userBuffer;
  5457. channels = stream->nUserChannels[0];
  5458. format = stream->userFormat;
  5459. }
  5460. // Do byte swapping if necessary.
  5461. if (stream->doByteSwap[0])
  5462. byteSwapBuffer(buffer, stream->bufferSize * channels, format);
  5463. // Write interleaved samples to device.
  5464. alWriteFrames(stream->handle[0], buffer, stream->bufferSize);
  5465. }
  5466. if (stream->mode == INPUT || stream->mode == DUPLEX) {
  5467. // Setup parameters.
  5468. if (stream->doConvertBuffer[1]) {
  5469. buffer = stream->deviceBuffer;
  5470. channels = stream->nDeviceChannels[1];
  5471. format = stream->deviceFormat[1];
  5472. }
  5473. else {
  5474. buffer = stream->userBuffer;
  5475. channels = stream->nUserChannels[1];
  5476. format = stream->userFormat;
  5477. }
  5478. // Read interleaved samples from device.
  5479. alReadFrames(stream->handle[1], buffer, stream->bufferSize);
  5480. // Do byte swapping if necessary.
  5481. if (stream->doByteSwap[1])
  5482. byteSwapBuffer(buffer, stream->bufferSize * channels, format);
  5483. // Do buffer conversion if necessary.
  5484. if (stream->doConvertBuffer[1])
  5485. convertStreamBuffer(stream, INPUT);
  5486. }
  5487. unlock:
  5488. MUTEX_UNLOCK(&stream->mutex);
  5489. if (stream->callbackInfo.usingCallback && stopStream)
  5490. this->stopStream(streamId);
  5491. }
  5492. extern "C" void *callbackHandler(void *ptr)
  5493. {
  5494. CALLBACK_INFO *info = (CALLBACK_INFO *) ptr;
  5495. RtAudio *object = (RtAudio *) info->object;
  5496. int stream = info->streamId;
  5497. bool *usingCallback = &info->usingCallback;
  5498. while ( *usingCallback ) {
  5499. pthread_testcancel();
  5500. try {
  5501. object->tickStream(stream);
  5502. }
  5503. catch (RtError &exception) {
  5504. fprintf(stderr, "\nRtAudio: Callback thread error (%s) ... closing thread.\n\n",
  5505. exception.getMessage());
  5506. break;
  5507. }
  5508. }
  5509. return 0;
  5510. }
  5511. //******************** End of __IRIX_AL__ *********************//
  5512. #endif
  5513. // *************************************************** //
  5514. //
  5515. // Private common (OS-independent) RtAudio methods.
  5516. //
  5517. // *************************************************** //
  5518. // This method can be modified to control the behavior of error
  5519. // message reporting and throwing.
  5520. void RtAudio :: error(RtError::TYPE type)
  5521. {
  5522. if (type == RtError::WARNING) {
  5523. fprintf(stderr, "\n%s\n\n", message);
  5524. }
  5525. else if (type == RtError::DEBUG_WARNING) {
  5526. #if defined(__RTAUDIO_DEBUG__)
  5527. fprintf(stderr, "\n%s\n\n", message);
  5528. #endif
  5529. }
  5530. else {
  5531. fprintf(stderr, "\n%s\n\n", message);
  5532. throw RtError(message, type);
  5533. }
  5534. }
  5535. void *RtAudio :: verifyStream(int streamId)
  5536. {
  5537. // Verify the stream key.
  5538. if ( streams.find( streamId ) == streams.end() ) {
  5539. sprintf(message, "RtAudio: invalid stream identifier!");
  5540. error(RtError::INVALID_STREAM);
  5541. }
  5542. return streams[streamId];
  5543. }
  5544. void RtAudio :: clearDeviceInfo(RTAUDIO_DEVICE *info)
  5545. {
  5546. // Don't clear the name or DEVICE_ID fields here ... they are
  5547. // typically set prior to a call of this function.
  5548. info->probed = false;
  5549. info->maxOutputChannels = 0;
  5550. info->maxInputChannels = 0;
  5551. info->maxDuplexChannels = 0;
  5552. info->minOutputChannels = 0;
  5553. info->minInputChannels = 0;
  5554. info->minDuplexChannels = 0;
  5555. info->hasDuplexSupport = false;
  5556. info->nSampleRates = 0;
  5557. for (int i=0; i<MAX_SAMPLE_RATES; i++)
  5558. info->sampleRates[i] = 0;
  5559. info->nativeFormats = 0;
  5560. }
  5561. int RtAudio :: formatBytes(RTAUDIO_FORMAT format)
  5562. {
  5563. if (format == RTAUDIO_SINT16)
  5564. return 2;
  5565. else if (format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 ||
  5566. format == RTAUDIO_FLOAT32)
  5567. return 4;
  5568. else if (format == RTAUDIO_FLOAT64)
  5569. return 8;
  5570. else if (format == RTAUDIO_SINT8)
  5571. return 1;
  5572. sprintf(message,"RtAudio: undefined format in formatBytes().");
  5573. error(RtError::WARNING);
  5574. return 0;
  5575. }
  5576. void RtAudio :: convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode)
  5577. {
  5578. // This method does format conversion, input/output channel compensation, and
  5579. // data interleaving/deinterleaving. 24-bit integers are assumed to occupy
  5580. // the upper three bytes of a 32-bit integer.
  5581. int j, jump_in, jump_out, channels;
  5582. RTAUDIO_FORMAT format_in, format_out;
  5583. char *input, *output;
  5584. if (mode == INPUT) { // convert device to user buffer
  5585. input = stream->deviceBuffer;
  5586. output = stream->userBuffer;
  5587. jump_in = stream->nDeviceChannels[1];
  5588. jump_out = stream->nUserChannels[1];
  5589. format_in = stream->deviceFormat[1];
  5590. format_out = stream->userFormat;
  5591. }
  5592. else { // convert user to device buffer
  5593. input = stream->userBuffer;
  5594. output = stream->deviceBuffer;
  5595. jump_in = stream->nUserChannels[0];
  5596. jump_out = stream->nDeviceChannels[0];
  5597. format_in = stream->userFormat;
  5598. format_out = stream->deviceFormat[0];
  5599. // clear our device buffer when in/out duplex device channels are different
  5600. if ( stream->mode == DUPLEX &&
  5601. stream->nDeviceChannels[0] != stream->nDeviceChannels[1] )
  5602. memset(output, 0, stream->bufferSize * jump_out * formatBytes(format_out));
  5603. }
  5604. channels = (jump_in < jump_out) ? jump_in : jump_out;
  5605. // Set up the interleave/deinterleave offsets
  5606. std::vector<int> offset_in(channels);
  5607. std::vector<int> offset_out(channels);
  5608. if (mode == INPUT && stream->deInterleave[1]) {
  5609. for (int k=0; k<channels; k++) {
  5610. offset_in[k] = k * stream->bufferSize;
  5611. offset_out[k] = k;
  5612. jump_in = 1;
  5613. }
  5614. }
  5615. else if (mode == OUTPUT && stream->deInterleave[0]) {
  5616. for (int k=0; k<channels; k++) {
  5617. offset_in[k] = k;
  5618. offset_out[k] = k * stream->bufferSize;
  5619. jump_out = 1;
  5620. }
  5621. }
  5622. else {
  5623. for (int k=0; k<channels; k++) {
  5624. offset_in[k] = k;
  5625. offset_out[k] = k;
  5626. }
  5627. }
  5628. if (format_out == RTAUDIO_FLOAT64) {
  5629. FLOAT64 scale;
  5630. FLOAT64 *out = (FLOAT64 *)output;
  5631. if (format_in == RTAUDIO_SINT8) {
  5632. signed char *in = (signed char *)input;
  5633. scale = 1.0 / 128.0;
  5634. for (int i=0; i<stream->bufferSize; i++) {
  5635. for (j=0; j<channels; j++) {
  5636. out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
  5637. out[offset_out[j]] *= scale;
  5638. }
  5639. in += jump_in;
  5640. out += jump_out;
  5641. }
  5642. }
  5643. else if (format_in == RTAUDIO_SINT16) {
  5644. INT16 *in = (INT16 *)input;
  5645. scale = 1.0 / 32768.0;
  5646. for (int i=0; i<stream->bufferSize; i++) {
  5647. for (j=0; j<channels; j++) {
  5648. out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
  5649. out[offset_out[j]] *= scale;
  5650. }
  5651. in += jump_in;
  5652. out += jump_out;
  5653. }
  5654. }
  5655. else if (format_in == RTAUDIO_SINT24) {
  5656. INT32 *in = (INT32 *)input;
  5657. scale = 1.0 / 2147483648.0;
  5658. for (int i=0; i<stream->bufferSize; i++) {
  5659. for (j=0; j<channels; j++) {
  5660. out[offset_out[j]] = (FLOAT64) (in[offset_in[j]] & 0xffffff00);
  5661. out[offset_out[j]] *= scale;
  5662. }
  5663. in += jump_in;
  5664. out += jump_out;
  5665. }
  5666. }
  5667. else if (format_in == RTAUDIO_SINT32) {
  5668. INT32 *in = (INT32 *)input;
  5669. scale = 1.0 / 2147483648.0;
  5670. for (int i=0; i<stream->bufferSize; i++) {
  5671. for (j=0; j<channels; j++) {
  5672. out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
  5673. out[offset_out[j]] *= scale;
  5674. }
  5675. in += jump_in;
  5676. out += jump_out;
  5677. }
  5678. }
  5679. else if (format_in == RTAUDIO_FLOAT32) {
  5680. FLOAT32 *in = (FLOAT32 *)input;
  5681. for (int i=0; i<stream->bufferSize; i++) {
  5682. for (j=0; j<channels; j++) {
  5683. out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
  5684. }
  5685. in += jump_in;
  5686. out += jump_out;
  5687. }
  5688. }
  5689. else if (format_in == RTAUDIO_FLOAT64) {
  5690. // Channel compensation and/or (de)interleaving only.
  5691. FLOAT64 *in = (FLOAT64 *)input;
  5692. for (int i=0; i<stream->bufferSize; i++) {
  5693. for (j=0; j<channels; j++) {
  5694. out[offset_out[j]] = in[offset_in[j]];
  5695. }
  5696. in += jump_in;
  5697. out += jump_out;
  5698. }
  5699. }
  5700. }
  5701. else if (format_out == RTAUDIO_FLOAT32) {
  5702. FLOAT32 scale;
  5703. FLOAT32 *out = (FLOAT32 *)output;
  5704. if (format_in == RTAUDIO_SINT8) {
  5705. signed char *in = (signed char *)input;
  5706. scale = 1.0 / 128.0;
  5707. for (int i=0; i<stream->bufferSize; i++) {
  5708. for (j=0; j<channels; j++) {
  5709. out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
  5710. out[offset_out[j]] *= scale;
  5711. }
  5712. in += jump_in;
  5713. out += jump_out;
  5714. }
  5715. }
  5716. else if (format_in == RTAUDIO_SINT16) {
  5717. INT16 *in = (INT16 *)input;
  5718. scale = 1.0 / 32768.0;
  5719. for (int i=0; i<stream->bufferSize; i++) {
  5720. for (j=0; j<channels; j++) {
  5721. out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
  5722. out[offset_out[j]] *= scale;
  5723. }
  5724. in += jump_in;
  5725. out += jump_out;
  5726. }
  5727. }
  5728. else if (format_in == RTAUDIO_SINT24) {
  5729. INT32 *in = (INT32 *)input;
  5730. scale = 1.0 / 2147483648.0;
  5731. for (int i=0; i<stream->bufferSize; i++) {
  5732. for (j=0; j<channels; j++) {
  5733. out[offset_out[j]] = (FLOAT32) (in[offset_in[j]] & 0xffffff00);
  5734. out[offset_out[j]] *= scale;
  5735. }
  5736. in += jump_in;
  5737. out += jump_out;
  5738. }
  5739. }
  5740. else if (format_in == RTAUDIO_SINT32) {
  5741. INT32 *in = (INT32 *)input;
  5742. scale = 1.0 / 2147483648.0;
  5743. for (int i=0; i<stream->bufferSize; i++) {
  5744. for (j=0; j<channels; j++) {
  5745. out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
  5746. out[offset_out[j]] *= scale;
  5747. }
  5748. in += jump_in;
  5749. out += jump_out;
  5750. }
  5751. }
  5752. else if (format_in == RTAUDIO_FLOAT32) {
  5753. // Channel compensation and/or (de)interleaving only.
  5754. FLOAT32 *in = (FLOAT32 *)input;
  5755. for (int i=0; i<stream->bufferSize; i++) {
  5756. for (j=0; j<channels; j++) {
  5757. out[offset_out[j]] = in[offset_in[j]];
  5758. }
  5759. in += jump_in;
  5760. out += jump_out;
  5761. }
  5762. }
  5763. else if (format_in == RTAUDIO_FLOAT64) {
  5764. FLOAT64 *in = (FLOAT64 *)input;
  5765. for (int i=0; i<stream->bufferSize; i++) {
  5766. for (j=0; j<channels; j++) {
  5767. out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
  5768. }
  5769. in += jump_in;
  5770. out += jump_out;
  5771. }
  5772. }
  5773. }
  5774. else if (format_out == RTAUDIO_SINT32) {
  5775. INT32 *out = (INT32 *)output;
  5776. if (format_in == RTAUDIO_SINT8) {
  5777. signed char *in = (signed char *)input;
  5778. for (int i=0; i<stream->bufferSize; i++) {
  5779. for (j=0; j<channels; j++) {
  5780. out[offset_out[j]] = (INT32) in[offset_in[j]];
  5781. out[offset_out[j]] <<= 24;
  5782. }
  5783. in += jump_in;
  5784. out += jump_out;
  5785. }
  5786. }
  5787. else if (format_in == RTAUDIO_SINT16) {
  5788. INT16 *in = (INT16 *)input;
  5789. for (int i=0; i<stream->bufferSize; i++) {
  5790. for (j=0; j<channels; j++) {
  5791. out[offset_out[j]] = (INT32) in[offset_in[j]];
  5792. out[offset_out[j]] <<= 16;
  5793. }
  5794. in += jump_in;
  5795. out += jump_out;
  5796. }
  5797. }
  5798. else if (format_in == RTAUDIO_SINT24) {
  5799. INT32 *in = (INT32 *)input;
  5800. for (int i=0; i<stream->bufferSize; i++) {
  5801. for (j=0; j<channels; j++) {
  5802. out[offset_out[j]] = (INT32) in[offset_in[j]];
  5803. }
  5804. in += jump_in;
  5805. out += jump_out;
  5806. }
  5807. }
  5808. else if (format_in == RTAUDIO_SINT32) {
  5809. // Channel compensation and/or (de)interleaving only.
  5810. INT32 *in = (INT32 *)input;
  5811. for (int i=0; i<stream->bufferSize; i++) {
  5812. for (j=0; j<channels; j++) {
  5813. out[offset_out[j]] = in[offset_in[j]];
  5814. }
  5815. in += jump_in;
  5816. out += jump_out;
  5817. }
  5818. }
  5819. else if (format_in == RTAUDIO_FLOAT32) {
  5820. FLOAT32 *in = (FLOAT32 *)input;
  5821. for (int i=0; i<stream->bufferSize; i++) {
  5822. for (j=0; j<channels; j++) {
  5823. out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
  5824. }
  5825. in += jump_in;
  5826. out += jump_out;
  5827. }
  5828. }
  5829. else if (format_in == RTAUDIO_FLOAT64) {
  5830. FLOAT64 *in = (FLOAT64 *)input;
  5831. for (int i=0; i<stream->bufferSize; i++) {
  5832. for (j=0; j<channels; j++) {
  5833. out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
  5834. }
  5835. in += jump_in;
  5836. out += jump_out;
  5837. }
  5838. }
  5839. }
  5840. else if (format_out == RTAUDIO_SINT24) {
  5841. INT32 *out = (INT32 *)output;
  5842. if (format_in == RTAUDIO_SINT8) {
  5843. signed char *in = (signed char *)input;
  5844. for (int i=0; i<stream->bufferSize; i++) {
  5845. for (j=0; j<channels; j++) {
  5846. out[offset_out[j]] = (INT32) in[offset_in[j]];
  5847. out[offset_out[j]] <<= 24;
  5848. }
  5849. in += jump_in;
  5850. out += jump_out;
  5851. }
  5852. }
  5853. else if (format_in == RTAUDIO_SINT16) {
  5854. INT16 *in = (INT16 *)input;
  5855. for (int i=0; i<stream->bufferSize; i++) {
  5856. for (j=0; j<channels; j++) {
  5857. out[offset_out[j]] = (INT32) in[offset_in[j]];
  5858. out[offset_out[j]] <<= 16;
  5859. }
  5860. in += jump_in;
  5861. out += jump_out;
  5862. }
  5863. }
  5864. else if (format_in == RTAUDIO_SINT24) {
  5865. // Channel compensation and/or (de)interleaving only.
  5866. INT32 *in = (INT32 *)input;
  5867. for (int i=0; i<stream->bufferSize; i++) {
  5868. for (j=0; j<channels; j++) {
  5869. out[offset_out[j]] = in[offset_in[j]];
  5870. }
  5871. in += jump_in;
  5872. out += jump_out;
  5873. }
  5874. }
  5875. else if (format_in == RTAUDIO_SINT32) {
  5876. INT32 *in = (INT32 *)input;
  5877. for (int i=0; i<stream->bufferSize; i++) {
  5878. for (j=0; j<channels; j++) {
  5879. out[offset_out[j]] = (INT32) (in[offset_in[j]] & 0xffffff00);
  5880. }
  5881. in += jump_in;
  5882. out += jump_out;
  5883. }
  5884. }
  5885. else if (format_in == RTAUDIO_FLOAT32) {
  5886. FLOAT32 *in = (FLOAT32 *)input;
  5887. for (int i=0; i<stream->bufferSize; i++) {
  5888. for (j=0; j<channels; j++) {
  5889. out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
  5890. }
  5891. in += jump_in;
  5892. out += jump_out;
  5893. }
  5894. }
  5895. else if (format_in == RTAUDIO_FLOAT64) {
  5896. FLOAT64 *in = (FLOAT64 *)input;
  5897. for (int i=0; i<stream->bufferSize; i++) {
  5898. for (j=0; j<channels; j++) {
  5899. out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
  5900. }
  5901. in += jump_in;
  5902. out += jump_out;
  5903. }
  5904. }
  5905. }
  5906. else if (format_out == RTAUDIO_SINT16) {
  5907. INT16 *out = (INT16 *)output;
  5908. if (format_in == RTAUDIO_SINT8) {
  5909. signed char *in = (signed char *)input;
  5910. for (int i=0; i<stream->bufferSize; i++) {
  5911. for (j=0; j<channels; j++) {
  5912. out[offset_out[j]] = (INT16) in[offset_in[j]];
  5913. out[offset_out[j]] <<= 8;
  5914. }
  5915. in += jump_in;
  5916. out += jump_out;
  5917. }
  5918. }
  5919. else if (format_in == RTAUDIO_SINT16) {
  5920. // Channel compensation and/or (de)interleaving only.
  5921. INT16 *in = (INT16 *)input;
  5922. for (int i=0; i<stream->bufferSize; i++) {
  5923. for (j=0; j<channels; j++) {
  5924. out[offset_out[j]] = in[offset_in[j]];
  5925. }
  5926. in += jump_in;
  5927. out += jump_out;
  5928. }
  5929. }
  5930. else if (format_in == RTAUDIO_SINT24) {
  5931. INT32 *in = (INT32 *)input;
  5932. for (int i=0; i<stream->bufferSize; i++) {
  5933. for (j=0; j<channels; j++) {
  5934. out[offset_out[j]] = (INT16) ((in[offset_in[j]] >> 16) & 0x0000ffff);
  5935. }
  5936. in += jump_in;
  5937. out += jump_out;
  5938. }
  5939. }
  5940. else if (format_in == RTAUDIO_SINT32) {
  5941. INT32 *in = (INT32 *)input;
  5942. for (int i=0; i<stream->bufferSize; i++) {
  5943. for (j=0; j<channels; j++) {
  5944. out[offset_out[j]] = (INT16) ((in[offset_in[j]] >> 16) & 0x0000ffff);
  5945. }
  5946. in += jump_in;
  5947. out += jump_out;
  5948. }
  5949. }
  5950. else if (format_in == RTAUDIO_FLOAT32) {
  5951. FLOAT32 *in = (FLOAT32 *)input;
  5952. for (int i=0; i<stream->bufferSize; i++) {
  5953. for (j=0; j<channels; j++) {
  5954. out[offset_out[j]] = (INT16) (in[offset_in[j]] * 32767.0);
  5955. }
  5956. in += jump_in;
  5957. out += jump_out;
  5958. }
  5959. }
  5960. else if (format_in == RTAUDIO_FLOAT64) {
  5961. FLOAT64 *in = (FLOAT64 *)input;
  5962. for (int i=0; i<stream->bufferSize; i++) {
  5963. for (j=0; j<channels; j++) {
  5964. out[offset_out[j]] = (INT16) (in[offset_in[j]] * 32767.0);
  5965. }
  5966. in += jump_in;
  5967. out += jump_out;
  5968. }
  5969. }
  5970. }
  5971. else if (format_out == RTAUDIO_SINT8) {
  5972. signed char *out = (signed char *)output;
  5973. if (format_in == RTAUDIO_SINT8) {
  5974. // Channel compensation and/or (de)interleaving only.
  5975. signed char *in = (signed char *)input;
  5976. for (int i=0; i<stream->bufferSize; i++) {
  5977. for (j=0; j<channels; j++) {
  5978. out[offset_out[j]] = in[offset_in[j]];
  5979. }
  5980. in += jump_in;
  5981. out += jump_out;
  5982. }
  5983. }
  5984. if (format_in == RTAUDIO_SINT16) {
  5985. INT16 *in = (INT16 *)input;
  5986. for (int i=0; i<stream->bufferSize; i++) {
  5987. for (j=0; j<channels; j++) {
  5988. out[offset_out[j]] = (signed char) ((in[offset_in[j]] >> 8) & 0x00ff);
  5989. }
  5990. in += jump_in;
  5991. out += jump_out;
  5992. }
  5993. }
  5994. else if (format_in == RTAUDIO_SINT24) {
  5995. INT32 *in = (INT32 *)input;
  5996. for (int i=0; i<stream->bufferSize; i++) {
  5997. for (j=0; j<channels; j++) {
  5998. out[offset_out[j]] = (signed char) ((in[offset_in[j]] >> 24) & 0x000000ff);
  5999. }
  6000. in += jump_in;
  6001. out += jump_out;
  6002. }
  6003. }
  6004. else if (format_in == RTAUDIO_SINT32) {
  6005. INT32 *in = (INT32 *)input;
  6006. for (int i=0; i<stream->bufferSize; i++) {
  6007. for (j=0; j<channels; j++) {
  6008. out[offset_out[j]] = (signed char) ((in[offset_in[j]] >> 24) & 0x000000ff);
  6009. }
  6010. in += jump_in;
  6011. out += jump_out;
  6012. }
  6013. }
  6014. else if (format_in == RTAUDIO_FLOAT32) {
  6015. FLOAT32 *in = (FLOAT32 *)input;
  6016. for (int i=0; i<stream->bufferSize; i++) {
  6017. for (j=0; j<channels; j++) {
  6018. out[offset_out[j]] = (signed char) (in[offset_in[j]] * 127.0);
  6019. }
  6020. in += jump_in;
  6021. out += jump_out;
  6022. }
  6023. }
  6024. else if (format_in == RTAUDIO_FLOAT64) {
  6025. FLOAT64 *in = (FLOAT64 *)input;
  6026. for (int i=0; i<stream->bufferSize; i++) {
  6027. for (j=0; j<channels; j++) {
  6028. out[offset_out[j]] = (signed char) (in[offset_in[j]] * 127.0);
  6029. }
  6030. in += jump_in;
  6031. out += jump_out;
  6032. }
  6033. }
  6034. }
  6035. }
  6036. void RtAudio :: byteSwapBuffer(char *buffer, int samples, RTAUDIO_FORMAT format)
  6037. {
  6038. register char val;
  6039. register char *ptr;
  6040. ptr = buffer;
  6041. if (format == RTAUDIO_SINT16) {
  6042. for (int i=0; i<samples; i++) {
  6043. // Swap 1st and 2nd bytes.
  6044. val = *(ptr);
  6045. *(ptr) = *(ptr+1);
  6046. *(ptr+1) = val;
  6047. // Increment 2 bytes.
  6048. ptr += 2;
  6049. }
  6050. }
  6051. else if (format == RTAUDIO_SINT24 ||
  6052. format == RTAUDIO_SINT32 ||
  6053. format == RTAUDIO_FLOAT32) {
  6054. for (int i=0; i<samples; i++) {
  6055. // Swap 1st and 4th bytes.
  6056. val = *(ptr);
  6057. *(ptr) = *(ptr+3);
  6058. *(ptr+3) = val;
  6059. // Swap 2nd and 3rd bytes.
  6060. ptr += 1;
  6061. val = *(ptr);
  6062. *(ptr) = *(ptr+1);
  6063. *(ptr+1) = val;
  6064. // Increment 4 bytes.
  6065. ptr += 4;
  6066. }
  6067. }
  6068. else if (format == RTAUDIO_FLOAT64) {
  6069. for (int i=0; i<samples; i++) {
  6070. // Swap 1st and 8th bytes
  6071. val = *(ptr);
  6072. *(ptr) = *(ptr+7);
  6073. *(ptr+7) = val;
  6074. // Swap 2nd and 7th bytes
  6075. ptr += 1;
  6076. val = *(ptr);
  6077. *(ptr) = *(ptr+5);
  6078. *(ptr+5) = val;
  6079. // Swap 3rd and 6th bytes
  6080. ptr += 1;
  6081. val = *(ptr);
  6082. *(ptr) = *(ptr+3);
  6083. *(ptr+3) = val;
  6084. // Swap 4th and 5th bytes
  6085. ptr += 1;
  6086. val = *(ptr);
  6087. *(ptr) = *(ptr+1);
  6088. *(ptr+1) = val;
  6089. // Increment 8 bytes.
  6090. ptr += 8;
  6091. }
  6092. }
  6093. }
  6094. // *************************************************** //
  6095. //
  6096. // RtError class definition.
  6097. //
  6098. // *************************************************** //
  6099. RtError :: RtError(const char *p, TYPE tipe)
  6100. {
  6101. type = tipe;
  6102. strncpy(error_message, p, 256);
  6103. }
  6104. RtError :: ~RtError()
  6105. {
  6106. }
  6107. void RtError :: printMessage()
  6108. {
  6109. printf("\n%s\n\n", error_message);
  6110. }