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.

7844 lines
266KB

  1. /************************************************************************/
  2. /*! \class RtAudio
  3. \brief Realtime audio i/o C++ classes.
  4. RtAudio provides a common API (Application Programming Interface)
  5. for realtime audio input/output across Linux (native ALSA, Jack,
  6. and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
  7. (DirectSound and ASIO) operating systems.
  8. RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
  9. RtAudio: realtime audio i/o C++ classes
  10. Copyright (c) 2001-2009 Gary P. Scavone
  11. Permission is hereby granted, free of charge, to any person
  12. obtaining a copy of this software and associated documentation files
  13. (the "Software"), to deal in the Software without restriction,
  14. including without limitation the rights to use, copy, modify, merge,
  15. publish, distribute, sublicense, and/or sell copies of the Software,
  16. and to permit persons to whom the Software is furnished to do so,
  17. subject to the following conditions:
  18. The above copyright notice and this permission notice shall be
  19. included in all copies or substantial portions of the Software.
  20. Any person wishing to distribute modifications to the Software is
  21. asked to send the modifications to the original developer so that
  22. they can be incorporated into the canonical version. This is,
  23. however, not a binding provision of this license.
  24. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  27. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  28. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  29. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. */
  32. /************************************************************************/
  33. // RtAudio: Version 4.0.5
  34. #include "RtAudio.h"
  35. #include <iostream>
  36. // Static variable definitions.
  37. const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
  38. const unsigned int RtApi::SAMPLE_RATES[] = {
  39. 4000, 5512, 8000, 9600, 11025, 16000, 22050,
  40. 32000, 44100, 48000, 88200, 96000, 176400, 192000
  41. };
  42. #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
  43. #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
  44. #define MUTEX_DESTROY(A) DeleteCriticalSection(A)
  45. #define MUTEX_LOCK(A) EnterCriticalSection(A)
  46. #define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
  47. #elif defined(__LINUX_ALSA__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
  48. // pthread API
  49. #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
  50. #define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
  51. #define MUTEX_LOCK(A) pthread_mutex_lock(A)
  52. #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
  53. #else
  54. #define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions
  55. #define MUTEX_DESTROY(A) abs(*A) // dummy definitions
  56. #endif
  57. // *************************************************** //
  58. //
  59. // RtAudio definitions.
  60. //
  61. // *************************************************** //
  62. void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis ) throw()
  63. {
  64. apis.clear();
  65. // The order here will control the order of RtAudio's API search in
  66. // the constructor.
  67. #if defined(__UNIX_JACK__)
  68. apis.push_back( UNIX_JACK );
  69. #endif
  70. #if defined(__LINUX_ALSA__)
  71. apis.push_back( LINUX_ALSA );
  72. #endif
  73. #if defined(__LINUX_OSS__)
  74. apis.push_back( LINUX_OSS );
  75. #endif
  76. #if defined(__WINDOWS_ASIO__)
  77. apis.push_back( WINDOWS_ASIO );
  78. #endif
  79. #if defined(__WINDOWS_DS__)
  80. apis.push_back( WINDOWS_DS );
  81. #endif
  82. #if defined(__MACOSX_CORE__)
  83. apis.push_back( MACOSX_CORE );
  84. #endif
  85. #if defined(__RTAUDIO_DUMMY__)
  86. apis.push_back( RTAUDIO_DUMMY );
  87. #endif
  88. }
  89. void RtAudio :: openRtApi( RtAudio::Api api )
  90. {
  91. #if defined(__UNIX_JACK__)
  92. if ( api == UNIX_JACK )
  93. rtapi_ = new RtApiJack();
  94. #endif
  95. #if defined(__LINUX_ALSA__)
  96. if ( api == LINUX_ALSA )
  97. rtapi_ = new RtApiAlsa();
  98. #endif
  99. #if defined(__LINUX_OSS__)
  100. if ( api == LINUX_OSS )
  101. rtapi_ = new RtApiOss();
  102. #endif
  103. #if defined(__WINDOWS_ASIO__)
  104. if ( api == WINDOWS_ASIO )
  105. rtapi_ = new RtApiAsio();
  106. #endif
  107. #if defined(__WINDOWS_DS__)
  108. if ( api == WINDOWS_DS )
  109. rtapi_ = new RtApiDs();
  110. #endif
  111. #if defined(__MACOSX_CORE__)
  112. if ( api == MACOSX_CORE )
  113. rtapi_ = new RtApiCore();
  114. #endif
  115. #if defined(__RTAUDIO_DUMMY__)
  116. if ( api == RTAUDIO_DUMMY )
  117. rtapi_ = new RtApiDummy();
  118. #endif
  119. }
  120. RtAudio :: RtAudio( RtAudio::Api api ) throw()
  121. {
  122. rtapi_ = 0;
  123. if ( api != UNSPECIFIED ) {
  124. // Attempt to open the specified API.
  125. openRtApi( api );
  126. if ( rtapi_ ) return;
  127. // No compiled support for specified API value. Issue a debug
  128. // warning and continue as if no API was specified.
  129. std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;
  130. }
  131. // Iterate through the compiled APIs and return as soon as we find
  132. // one with at least one device or we reach the end of the list.
  133. std::vector< RtAudio::Api > apis;
  134. getCompiledApi( apis );
  135. for ( unsigned int i=0; i<apis.size(); i++ ) {
  136. openRtApi( apis[i] );
  137. if ( rtapi_->getDeviceCount() ) break;
  138. }
  139. if ( rtapi_ ) return;
  140. // It should not be possible to get here because the preprocessor
  141. // definition __RTAUDIO_DUMMY__ is automatically defined if no
  142. // API-specific definitions are passed to the compiler. But just in
  143. // case something weird happens, we'll print out an error message.
  144. std::cerr << "\nRtAudio: no compiled API support found ... critical error!!\n\n";
  145. }
  146. RtAudio :: ~RtAudio() throw()
  147. {
  148. delete rtapi_;
  149. }
  150. void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
  151. RtAudio::StreamParameters *inputParameters,
  152. RtAudioFormat format, unsigned int sampleRate,
  153. unsigned int *bufferFrames,
  154. RtAudioCallback callback, void *userData,
  155. RtAudio::StreamOptions *options )
  156. {
  157. return rtapi_->openStream( outputParameters, inputParameters, format,
  158. sampleRate, bufferFrames, callback,
  159. userData, options );
  160. }
  161. // *************************************************** //
  162. //
  163. // Public RtApi definitions (see end of file for
  164. // private or protected utility functions).
  165. //
  166. // *************************************************** //
  167. RtApi :: RtApi()
  168. {
  169. stream_.state = STREAM_CLOSED;
  170. stream_.mode = UNINITIALIZED;
  171. stream_.apiHandle = 0;
  172. stream_.userBuffer[0] = 0;
  173. stream_.userBuffer[1] = 0;
  174. MUTEX_INITIALIZE( &stream_.mutex );
  175. showWarnings_ = true;
  176. }
  177. RtApi :: ~RtApi()
  178. {
  179. MUTEX_DESTROY( &stream_.mutex );
  180. }
  181. void RtApi :: openStream( RtAudio::StreamParameters *oParams,
  182. RtAudio::StreamParameters *iParams,
  183. RtAudioFormat format, unsigned int sampleRate,
  184. unsigned int *bufferFrames,
  185. RtAudioCallback callback, void *userData,
  186. RtAudio::StreamOptions *options )
  187. {
  188. if ( stream_.state != STREAM_CLOSED ) {
  189. errorText_ = "RtApi::openStream: a stream is already open!";
  190. error( RtError::INVALID_USE );
  191. }
  192. if ( oParams && oParams->nChannels < 1 ) {
  193. errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
  194. error( RtError::INVALID_USE );
  195. }
  196. if ( iParams && iParams->nChannels < 1 ) {
  197. errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
  198. error( RtError::INVALID_USE );
  199. }
  200. if ( oParams == NULL && iParams == NULL ) {
  201. errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
  202. error( RtError::INVALID_USE );
  203. }
  204. if ( formatBytes(format) == 0 ) {
  205. errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
  206. error( RtError::INVALID_USE );
  207. }
  208. unsigned int nDevices = getDeviceCount();
  209. unsigned int oChannels = 0;
  210. if ( oParams ) {
  211. oChannels = oParams->nChannels;
  212. if ( oParams->deviceId >= nDevices ) {
  213. errorText_ = "RtApi::openStream: output device parameter value is invalid.";
  214. error( RtError::INVALID_USE );
  215. }
  216. }
  217. unsigned int iChannels = 0;
  218. if ( iParams ) {
  219. iChannels = iParams->nChannels;
  220. if ( iParams->deviceId >= nDevices ) {
  221. errorText_ = "RtApi::openStream: input device parameter value is invalid.";
  222. error( RtError::INVALID_USE );
  223. }
  224. }
  225. clearStreamInfo();
  226. bool result;
  227. if ( oChannels > 0 ) {
  228. result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
  229. sampleRate, format, bufferFrames, options );
  230. if ( result == false ) error( RtError::SYSTEM_ERROR );
  231. }
  232. if ( iChannels > 0 ) {
  233. result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
  234. sampleRate, format, bufferFrames, options );
  235. if ( result == false ) {
  236. if ( oChannels > 0 ) closeStream();
  237. error( RtError::SYSTEM_ERROR );
  238. }
  239. }
  240. stream_.callbackInfo.callback = (void *) callback;
  241. stream_.callbackInfo.userData = userData;
  242. if ( options ) options->numberOfBuffers = stream_.nBuffers;
  243. stream_.state = STREAM_STOPPED;
  244. }
  245. unsigned int RtApi :: getDefaultInputDevice( void )
  246. {
  247. // Should be implemented in subclasses if possible.
  248. return 0;
  249. }
  250. unsigned int RtApi :: getDefaultOutputDevice( void )
  251. {
  252. // Should be implemented in subclasses if possible.
  253. return 0;
  254. }
  255. void RtApi :: closeStream( void )
  256. {
  257. // MUST be implemented in subclasses!
  258. return;
  259. }
  260. bool RtApi :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  261. unsigned int firstChannel, unsigned int sampleRate,
  262. RtAudioFormat format, unsigned int *bufferSize,
  263. RtAudio::StreamOptions *options )
  264. {
  265. // MUST be implemented in subclasses!
  266. return FAILURE;
  267. }
  268. void RtApi :: tickStreamTime( void )
  269. {
  270. // Subclasses that do not provide their own implementation of
  271. // getStreamTime should call this function once per buffer I/O to
  272. // provide basic stream time support.
  273. stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
  274. #if defined( HAVE_GETTIMEOFDAY )
  275. gettimeofday( &stream_.lastTickTimestamp, NULL );
  276. #endif
  277. }
  278. long RtApi :: getStreamLatency( void )
  279. {
  280. verifyStream();
  281. long totalLatency = 0;
  282. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  283. totalLatency = stream_.latency[0];
  284. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  285. totalLatency += stream_.latency[1];
  286. return totalLatency;
  287. }
  288. double RtApi :: getStreamTime( void )
  289. {
  290. verifyStream();
  291. #if defined( HAVE_GETTIMEOFDAY )
  292. // Return a very accurate estimate of the stream time by
  293. // adding in the elapsed time since the last tick.
  294. struct timeval then;
  295. struct timeval now;
  296. if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
  297. return stream_.streamTime;
  298. gettimeofday( &now, NULL );
  299. then = stream_.lastTickTimestamp;
  300. return stream_.streamTime +
  301. ((now.tv_sec + 0.000001 * now.tv_usec) -
  302. (then.tv_sec + 0.000001 * then.tv_usec));
  303. #else
  304. return stream_.streamTime;
  305. #endif
  306. }
  307. unsigned int RtApi :: getStreamSampleRate( void )
  308. {
  309. verifyStream();
  310. return stream_.sampleRate;
  311. }
  312. // *************************************************** //
  313. //
  314. // OS/API-specific methods.
  315. //
  316. // *************************************************** //
  317. #if defined(__MACOSX_CORE__)
  318. // The OS X CoreAudio API is designed to use a separate callback
  319. // procedure for each of its audio devices. A single RtAudio duplex
  320. // stream using two different devices is supported here, though it
  321. // cannot be guaranteed to always behave correctly because we cannot
  322. // synchronize these two callbacks.
  323. //
  324. // A property listener is installed for over/underrun information.
  325. // However, no functionality is currently provided to allow property
  326. // listeners to trigger user handlers because it is unclear what could
  327. // be done if a critical stream parameter (buffer size, sample rate,
  328. // device disconnect) notification arrived. The listeners entail
  329. // quite a bit of extra code and most likely, a user program wouldn't
  330. // be prepared for the result anyway. However, we do provide a flag
  331. // to the client callback function to inform of an over/underrun.
  332. //
  333. // The mechanism for querying and setting system parameters was
  334. // updated (and perhaps simplified) in OS-X version 10.4. However,
  335. // since 10.4 support is not necessarily available to all users, I've
  336. // decided not to update the respective code at this time. Perhaps
  337. // this will happen when Apple makes 10.4 free for everyone. :-)
  338. // A structure to hold various information related to the CoreAudio API
  339. // implementation.
  340. struct CoreHandle {
  341. AudioDeviceID id[2]; // device ids
  342. AudioDeviceIOProcID procId[2];
  343. UInt32 iStream[2]; // device stream index (or first if using multiple)
  344. UInt32 nStreams[2]; // number of streams to use
  345. bool xrun[2];
  346. char *deviceBuffer;
  347. pthread_cond_t condition;
  348. int drainCounter; // Tracks callback counts when draining
  349. bool internalDrain; // Indicates if stop is initiated from callback or not.
  350. CoreHandle()
  351. :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  352. };
  353. RtApiCore :: RtApiCore()
  354. {
  355. // Nothing to do here.
  356. }
  357. RtApiCore :: ~RtApiCore()
  358. {
  359. // The subclass destructor gets called before the base class
  360. // destructor, so close an existing stream before deallocating
  361. // apiDeviceId memory.
  362. if ( stream_.state != STREAM_CLOSED ) closeStream();
  363. }
  364. unsigned int RtApiCore :: getDeviceCount( void )
  365. {
  366. // Find out how many audio devices there are, if any.
  367. UInt32 dataSize;
  368. OSStatus result = AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices, &dataSize, NULL );
  369. if ( result != noErr ) {
  370. errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
  371. error( RtError::WARNING );
  372. return 0;
  373. }
  374. return dataSize / sizeof( AudioDeviceID );
  375. }
  376. unsigned int RtApiCore :: getDefaultInputDevice( void )
  377. {
  378. unsigned int nDevices = getDeviceCount();
  379. if ( nDevices <= 1 ) return 0;
  380. AudioDeviceID id;
  381. UInt32 dataSize = sizeof( AudioDeviceID );
  382. OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultInputDevice,
  383. &dataSize, &id );
  384. if ( result != noErr ) {
  385. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
  386. error( RtError::WARNING );
  387. return 0;
  388. }
  389. dataSize *= nDevices;
  390. AudioDeviceID deviceList[ nDevices ];
  391. result = AudioHardwareGetProperty( kAudioHardwarePropertyDevices, &dataSize, (void *) &deviceList );
  392. if ( result != noErr ) {
  393. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
  394. error( RtError::WARNING );
  395. return 0;
  396. }
  397. for ( unsigned int i=0; i<nDevices; i++ )
  398. if ( id == deviceList[i] ) return i;
  399. errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
  400. error( RtError::WARNING );
  401. return 0;
  402. }
  403. unsigned int RtApiCore :: getDefaultOutputDevice( void )
  404. {
  405. unsigned int nDevices = getDeviceCount();
  406. if ( nDevices <= 1 ) return 0;
  407. AudioDeviceID id;
  408. UInt32 dataSize = sizeof( AudioDeviceID );
  409. OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice,
  410. &dataSize, &id );
  411. if ( result != noErr ) {
  412. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
  413. error( RtError::WARNING );
  414. return 0;
  415. }
  416. dataSize *= nDevices;
  417. AudioDeviceID deviceList[ nDevices ];
  418. result = AudioHardwareGetProperty( kAudioHardwarePropertyDevices, &dataSize, (void *) &deviceList );
  419. if ( result != noErr ) {
  420. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
  421. error( RtError::WARNING );
  422. return 0;
  423. }
  424. for ( unsigned int i=0; i<nDevices; i++ )
  425. if ( id == deviceList[i] ) return i;
  426. errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
  427. error( RtError::WARNING );
  428. return 0;
  429. }
  430. RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
  431. {
  432. RtAudio::DeviceInfo info;
  433. info.probed = false;
  434. // Get device ID
  435. unsigned int nDevices = getDeviceCount();
  436. if ( nDevices == 0 ) {
  437. errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
  438. error( RtError::INVALID_USE );
  439. }
  440. if ( device >= nDevices ) {
  441. errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
  442. error( RtError::INVALID_USE );
  443. }
  444. AudioDeviceID deviceList[ nDevices ];
  445. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  446. OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDevices, &dataSize, (void *) &deviceList );
  447. if ( result != noErr ) {
  448. errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
  449. error( RtError::WARNING );
  450. return info;
  451. }
  452. AudioDeviceID id = deviceList[ device ];
  453. // Get the device name.
  454. info.name.erase();
  455. char name[256];
  456. dataSize = 256;
  457. result = AudioDeviceGetProperty( id, 0, false,
  458. kAudioDevicePropertyDeviceManufacturer,
  459. &dataSize, name );
  460. if ( result != noErr ) {
  461. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
  462. errorText_ = errorStream_.str();
  463. error( RtError::WARNING );
  464. return info;
  465. }
  466. info.name.append( (const char *)name, strlen(name) );
  467. info.name.append( ": " );
  468. dataSize = 256;
  469. result = AudioDeviceGetProperty( id, 0, false,
  470. kAudioDevicePropertyDeviceName,
  471. &dataSize, name );
  472. if ( result != noErr ) {
  473. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
  474. errorText_ = errorStream_.str();
  475. error( RtError::WARNING );
  476. return info;
  477. }
  478. info.name.append( (const char *)name, strlen(name) );
  479. // Get the output stream "configuration".
  480. AudioBufferList *bufferList = nil;
  481. result = AudioDeviceGetPropertyInfo( id, 0, false,
  482. kAudioDevicePropertyStreamConfiguration,
  483. &dataSize, NULL );
  484. if (result != noErr || dataSize == 0) {
  485. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";
  486. errorText_ = errorStream_.str();
  487. error( RtError::WARNING );
  488. return info;
  489. }
  490. // Allocate the AudioBufferList.
  491. bufferList = (AudioBufferList *) malloc( dataSize );
  492. if ( bufferList == NULL ) {
  493. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
  494. error( RtError::WARNING );
  495. return info;
  496. }
  497. result = AudioDeviceGetProperty( id, 0, false,
  498. kAudioDevicePropertyStreamConfiguration,
  499. &dataSize, bufferList );
  500. if ( result != noErr ) {
  501. free( bufferList );
  502. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";
  503. errorText_ = errorStream_.str();
  504. error( RtError::WARNING );
  505. return info;
  506. }
  507. // Get output channel information.
  508. unsigned int i, nStreams = bufferList->mNumberBuffers;
  509. for ( i=0; i<nStreams; i++ )
  510. info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
  511. free( bufferList );
  512. // Get the input stream "configuration".
  513. result = AudioDeviceGetPropertyInfo( id, 0, true,
  514. kAudioDevicePropertyStreamConfiguration,
  515. &dataSize, NULL );
  516. if (result != noErr || dataSize == 0) {
  517. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";
  518. errorText_ = errorStream_.str();
  519. error( RtError::WARNING );
  520. return info;
  521. }
  522. // Allocate the AudioBufferList.
  523. bufferList = (AudioBufferList *) malloc( dataSize );
  524. if ( bufferList == NULL ) {
  525. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
  526. error( RtError::WARNING );
  527. return info;
  528. }
  529. result = AudioDeviceGetProperty( id, 0, true,
  530. kAudioDevicePropertyStreamConfiguration,
  531. &dataSize, bufferList );
  532. if ( result != noErr ) {
  533. free( bufferList );
  534. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";
  535. errorText_ = errorStream_.str();
  536. error( RtError::WARNING );
  537. return info;
  538. }
  539. // Get input channel information.
  540. nStreams = bufferList->mNumberBuffers;
  541. for ( i=0; i<nStreams; i++ )
  542. info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
  543. free( bufferList );
  544. // If device opens for both playback and capture, we determine the channels.
  545. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  546. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  547. // Probe the device sample rates.
  548. bool isInput = false;
  549. if ( info.outputChannels == 0 ) isInput = true;
  550. // Determine the supported sample rates.
  551. result = AudioDeviceGetPropertyInfo( id, 0, isInput,
  552. kAudioDevicePropertyAvailableNominalSampleRates,
  553. &dataSize, NULL );
  554. if ( result != kAudioHardwareNoError || dataSize == 0 ) {
  555. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
  556. errorText_ = errorStream_.str();
  557. error( RtError::WARNING );
  558. return info;
  559. }
  560. UInt32 nRanges = dataSize / sizeof( AudioValueRange );
  561. AudioValueRange rangeList[ nRanges ];
  562. result = AudioDeviceGetProperty( id, 0, isInput,
  563. kAudioDevicePropertyAvailableNominalSampleRates,
  564. &dataSize, &rangeList );
  565. if ( result != kAudioHardwareNoError ) {
  566. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
  567. errorText_ = errorStream_.str();
  568. error( RtError::WARNING );
  569. return info;
  570. }
  571. Float64 minimumRate = 100000000.0, maximumRate = 0.0;
  572. for ( UInt32 i=0; i<nRanges; i++ ) {
  573. if ( rangeList[i].mMinimum < minimumRate ) minimumRate = rangeList[i].mMinimum;
  574. if ( rangeList[i].mMaximum > maximumRate ) maximumRate = rangeList[i].mMaximum;
  575. }
  576. info.sampleRates.clear();
  577. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  578. if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate )
  579. info.sampleRates.push_back( SAMPLE_RATES[k] );
  580. }
  581. if ( info.sampleRates.size() == 0 ) {
  582. errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
  583. errorText_ = errorStream_.str();
  584. error( RtError::WARNING );
  585. return info;
  586. }
  587. // CoreAudio always uses 32-bit floating point data for PCM streams.
  588. // Thus, any other "physical" formats supported by the device are of
  589. // no interest to the client.
  590. info.nativeFormats = RTAUDIO_FLOAT32;
  591. if ( getDefaultOutputDevice() == device )
  592. info.isDefaultOutput = true;
  593. if ( getDefaultInputDevice() == device )
  594. info.isDefaultInput = true;
  595. info.probed = true;
  596. return info;
  597. }
  598. OSStatus callbackHandler( AudioDeviceID inDevice,
  599. const AudioTimeStamp* inNow,
  600. const AudioBufferList* inInputData,
  601. const AudioTimeStamp* inInputTime,
  602. AudioBufferList* outOutputData,
  603. const AudioTimeStamp* inOutputTime,
  604. void* infoPointer )
  605. {
  606. CallbackInfo *info = (CallbackInfo *) infoPointer;
  607. RtApiCore *object = (RtApiCore *) info->object;
  608. if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
  609. return kAudioHardwareUnspecifiedError;
  610. else
  611. return kAudioHardwareNoError;
  612. }
  613. OSStatus deviceListener( AudioDeviceID inDevice,
  614. UInt32 channel,
  615. Boolean isInput,
  616. AudioDevicePropertyID propertyID,
  617. void* handlePointer )
  618. {
  619. CoreHandle *handle = (CoreHandle *) handlePointer;
  620. if ( propertyID == kAudioDeviceProcessorOverload ) {
  621. if ( isInput )
  622. handle->xrun[1] = true;
  623. else
  624. handle->xrun[0] = true;
  625. }
  626. return kAudioHardwareNoError;
  627. }
  628. static bool hasProperty( AudioDeviceID id, UInt32 channel, bool isInput, AudioDevicePropertyID property )
  629. {
  630. OSStatus result = AudioDeviceGetPropertyInfo( id, channel, isInput, property, NULL, NULL );
  631. return result == 0;
  632. }
  633. bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  634. unsigned int firstChannel, unsigned int sampleRate,
  635. RtAudioFormat format, unsigned int *bufferSize,
  636. RtAudio::StreamOptions *options )
  637. {
  638. // Get device ID
  639. unsigned int nDevices = getDeviceCount();
  640. if ( nDevices == 0 ) {
  641. // This should not happen because a check is made before this function is called.
  642. errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
  643. return FAILURE;
  644. }
  645. if ( device >= nDevices ) {
  646. // This should not happen because a check is made before this function is called.
  647. errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
  648. return FAILURE;
  649. }
  650. AudioDeviceID deviceList[ nDevices ];
  651. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  652. OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDevices, &dataSize, (void *) &deviceList );
  653. if ( result != noErr ) {
  654. errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
  655. return FAILURE;
  656. }
  657. AudioDeviceID id = deviceList[ device ];
  658. // Setup for stream mode.
  659. bool isInput = false;
  660. if ( mode == INPUT ) isInput = true;
  661. // Set or disable "hog" mode.
  662. dataSize = sizeof( UInt32 );
  663. UInt32 doHog = 0;
  664. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) doHog = 1;
  665. result = AudioHardwareSetProperty( kAudioHardwarePropertyHogModeIsAllowed, dataSize, &doHog );
  666. if ( result != noErr ) {
  667. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";
  668. errorText_ = errorStream_.str();
  669. return FAILURE;
  670. }
  671. // Get the stream "configuration".
  672. AudioBufferList *bufferList;
  673. result = AudioDeviceGetPropertyInfo( id, 0, isInput,
  674. kAudioDevicePropertyStreamConfiguration,
  675. &dataSize, NULL );
  676. if (result != noErr || dataSize == 0) {
  677. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";
  678. errorText_ = errorStream_.str();
  679. return FAILURE;
  680. }
  681. // Allocate the AudioBufferList.
  682. bufferList = (AudioBufferList *) malloc( dataSize );
  683. if ( bufferList == NULL ) {
  684. errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
  685. return FAILURE;
  686. }
  687. result = AudioDeviceGetProperty( id, 0, isInput,
  688. kAudioDevicePropertyStreamConfiguration,
  689. &dataSize, bufferList );
  690. if ( result != noErr ) {
  691. free( bufferList );
  692. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";
  693. errorText_ = errorStream_.str();
  694. return FAILURE;
  695. }
  696. // Search for one or more streams that contain the desired number of
  697. // channels. CoreAudio devices can have an arbitrary number of
  698. // streams and each stream can have an arbitrary number of channels.
  699. // For each stream, a single buffer of interleaved samples is
  700. // provided. RtAudio prefers the use of one stream of interleaved
  701. // data or multiple consecutive single-channel streams. However, we
  702. // now support multiple consecutive multi-channel streams of
  703. // interleaved data as well.
  704. UInt32 iStream, offsetCounter = firstChannel;
  705. UInt32 nStreams = bufferList->mNumberBuffers;
  706. bool monoMode = false;
  707. bool foundStream = false;
  708. // First check that the device supports the requested number of
  709. // channels.
  710. UInt32 deviceChannels = 0;
  711. for ( iStream=0; iStream<nStreams; iStream++ )
  712. deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
  713. if ( deviceChannels < ( channels + firstChannel ) ) {
  714. free( bufferList );
  715. errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";
  716. errorText_ = errorStream_.str();
  717. return FAILURE;
  718. }
  719. // Look for a single stream meeting our needs.
  720. UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;
  721. for ( iStream=0; iStream<nStreams; iStream++ ) {
  722. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  723. if ( streamChannels >= channels + offsetCounter ) {
  724. firstStream = iStream;
  725. channelOffset = offsetCounter;
  726. foundStream = true;
  727. break;
  728. }
  729. if ( streamChannels > offsetCounter ) break;
  730. offsetCounter -= streamChannels;
  731. }
  732. // If we didn't find a single stream above, then we should be able
  733. // to meet the channel specification with multiple streams.
  734. if ( foundStream == false ) {
  735. monoMode = true;
  736. offsetCounter = firstChannel;
  737. for ( iStream=0; iStream<nStreams; iStream++ ) {
  738. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  739. if ( streamChannels > offsetCounter ) break;
  740. offsetCounter -= streamChannels;
  741. }
  742. firstStream = iStream;
  743. channelOffset = offsetCounter;
  744. Int32 channelCounter = channels + offsetCounter - streamChannels;
  745. if ( streamChannels > 1 ) monoMode = false;
  746. while ( channelCounter > 0 ) {
  747. streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
  748. if ( streamChannels > 1 ) monoMode = false;
  749. channelCounter -= streamChannels;
  750. streamCount++;
  751. }
  752. }
  753. free( bufferList );
  754. // Determine the buffer size.
  755. AudioValueRange bufferRange;
  756. dataSize = sizeof( AudioValueRange );
  757. result = AudioDeviceGetProperty( id, 0, isInput,
  758. kAudioDevicePropertyBufferFrameSizeRange,
  759. &dataSize, &bufferRange );
  760. if ( result != noErr ) {
  761. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ").";
  762. errorText_ = errorStream_.str();
  763. return FAILURE;
  764. }
  765. if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  766. else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMaximum;
  767. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  768. // Set the buffer size. For multiple streams, I'm assuming we only
  769. // need to make this setting for the master channel.
  770. UInt32 theSize = (UInt32) *bufferSize;
  771. dataSize = sizeof( UInt32 );
  772. result = AudioDeviceSetProperty( id, NULL, 0, isInput,
  773. kAudioDevicePropertyBufferFrameSize,
  774. dataSize, &theSize );
  775. if ( result != noErr ) {
  776. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ").";
  777. errorText_ = errorStream_.str();
  778. return FAILURE;
  779. }
  780. // If attempting to setup a duplex stream, the bufferSize parameter
  781. // MUST be the same in both directions!
  782. *bufferSize = theSize;
  783. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  784. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";
  785. errorText_ = errorStream_.str();
  786. return FAILURE;
  787. }
  788. stream_.bufferSize = *bufferSize;
  789. stream_.nBuffers = 1;
  790. // Get the stream ID(s) so we can set the stream format. We'll have
  791. // to do this for each stream.
  792. AudioStreamID streamIDs[ nStreams ];
  793. dataSize = nStreams * sizeof( AudioStreamID );
  794. result = AudioDeviceGetProperty( id, 0, isInput,
  795. kAudioDevicePropertyStreams,
  796. &dataSize, &streamIDs );
  797. if ( result != noErr ) {
  798. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream ID(s) for device (" << device << ").";
  799. errorText_ = errorStream_.str();
  800. return FAILURE;
  801. }
  802. // Now set the stream format. Also, check the physical format of the
  803. // device and change that if necessary.
  804. AudioStreamBasicDescription description;
  805. dataSize = sizeof( AudioStreamBasicDescription );
  806. bool updateFormat;
  807. for ( UInt32 i=0; i<streamCount; i++ ) {
  808. result = AudioStreamGetProperty( streamIDs[firstStream+i], 0,
  809. kAudioStreamPropertyVirtualFormat,
  810. &dataSize, &description );
  811. if ( result != noErr ) {
  812. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ").";
  813. errorText_ = errorStream_.str();
  814. return FAILURE;
  815. }
  816. // Set the sample rate and data format id. However, only make the
  817. // change if the sample rate is not within 1.0 of the desired
  818. // rate and the format is not linear pcm.
  819. updateFormat = false;
  820. if ( fabs( description.mSampleRate - (double)sampleRate ) > 1.0 ) {
  821. description.mSampleRate = (double) sampleRate;
  822. updateFormat = true;
  823. }
  824. if ( description.mFormatID != kAudioFormatLinearPCM ) {
  825. description.mFormatID = kAudioFormatLinearPCM;
  826. updateFormat = true;
  827. }
  828. if ( updateFormat ) {
  829. result = AudioStreamSetProperty( streamIDs[firstStream+i], NULL, 0,
  830. kAudioStreamPropertyVirtualFormat,
  831. dataSize, &description );
  832. if ( result != noErr ) {
  833. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ").";
  834. errorText_ = errorStream_.str();
  835. return FAILURE;
  836. }
  837. }
  838. // Now check the physical format.
  839. result = AudioStreamGetProperty( streamIDs[firstStream+i], 0,
  840. kAudioStreamPropertyPhysicalFormat,
  841. &dataSize, &description );
  842. if ( result != noErr ) {
  843. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ").";
  844. errorText_ = errorStream_.str();
  845. return FAILURE;
  846. }
  847. if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 24 ) {
  848. description.mFormatID = kAudioFormatLinearPCM;
  849. AudioStreamBasicDescription testDescription = description;
  850. unsigned long formatFlags;
  851. // We'll try higher bit rates first and then work our way down.
  852. testDescription.mBitsPerChannel = 32;
  853. formatFlags = description.mFormatFlags | kLinearPCMFormatFlagIsFloat & ~kLinearPCMFormatFlagIsSignedInteger;
  854. testDescription.mFormatFlags = formatFlags;
  855. result = AudioStreamSetProperty( streamIDs[firstStream+i], NULL, 0, kAudioStreamPropertyPhysicalFormat, dataSize, &testDescription );
  856. if ( result == noErr ) continue;
  857. testDescription = description;
  858. testDescription.mBitsPerChannel = 32;
  859. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger) & ~kLinearPCMFormatFlagIsFloat;
  860. testDescription.mFormatFlags = formatFlags;
  861. result = AudioStreamSetProperty( streamIDs[firstStream+i], NULL, 0, kAudioStreamPropertyPhysicalFormat, dataSize, &testDescription );
  862. if ( result == noErr ) continue;
  863. testDescription = description;
  864. testDescription.mBitsPerChannel = 24;
  865. testDescription.mFormatFlags = formatFlags;
  866. result = AudioStreamSetProperty( streamIDs[firstStream+i], NULL, 0, kAudioStreamPropertyPhysicalFormat, dataSize, &testDescription );
  867. if ( result == noErr ) continue;
  868. testDescription = description;
  869. testDescription.mBitsPerChannel = 16;
  870. testDescription.mFormatFlags = formatFlags;
  871. result = AudioStreamSetProperty( streamIDs[firstStream+i], NULL, 0, kAudioStreamPropertyPhysicalFormat, dataSize, &testDescription );
  872. if ( result == noErr ) continue;
  873. testDescription = description;
  874. testDescription.mBitsPerChannel = 8;
  875. testDescription.mFormatFlags = formatFlags;
  876. result = AudioStreamSetProperty( streamIDs[firstStream+i], NULL, 0, kAudioStreamPropertyPhysicalFormat, dataSize, &testDescription );
  877. if ( result != noErr ) {
  878. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ").";
  879. errorText_ = errorStream_.str();
  880. return FAILURE;
  881. }
  882. }
  883. }
  884. // Get the stream latency. There can be latency in both the device
  885. // and the stream. First, attempt to get the device latency on the
  886. // master channel or the first open channel. Errors that might
  887. // occur here are not deemed critical.
  888. // ***** CHECK THIS ***** //
  889. UInt32 latency, channel = 0;
  890. dataSize = sizeof( UInt32 );
  891. AudioDevicePropertyID property = kAudioDevicePropertyLatency;
  892. if ( hasProperty( id, channel, isInput, property ) == true ) {
  893. result = AudioDeviceGetProperty( id, channel, isInput, property, &dataSize, &latency );
  894. if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;
  895. else {
  896. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";
  897. errorText_ = errorStream_.str();
  898. error( RtError::WARNING );
  899. }
  900. }
  901. // Now try to get the stream latency. For multiple streams, I assume the
  902. // latency is equal for each.
  903. result = AudioStreamGetProperty( streamIDs[firstStream], 0, property, &dataSize, &latency );
  904. if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] += latency;
  905. else {
  906. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream latency for device (" << device << ").";
  907. errorText_ = errorStream_.str();
  908. error( RtError::WARNING );
  909. }
  910. // Byte-swapping: According to AudioHardware.h, the stream data will
  911. // always be presented in native-endian format, so we should never
  912. // need to byte swap.
  913. stream_.doByteSwap[mode] = false;
  914. // From the CoreAudio documentation, PCM data must be supplied as
  915. // 32-bit floats.
  916. stream_.userFormat = format;
  917. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  918. if ( streamCount == 1 )
  919. stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
  920. else // multiple streams
  921. stream_.nDeviceChannels[mode] = channels;
  922. stream_.nUserChannels[mode] = channels;
  923. stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
  924. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  925. else stream_.userInterleaved = true;
  926. stream_.deviceInterleaved[mode] = true;
  927. if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;
  928. // Set flags for buffer conversion.
  929. stream_.doConvertBuffer[mode] = false;
  930. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  931. stream_.doConvertBuffer[mode] = true;
  932. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  933. stream_.doConvertBuffer[mode] = true;
  934. if ( streamCount == 1 ) {
  935. if ( stream_.nUserChannels[mode] > 1 &&
  936. stream_.userInterleaved != stream_.deviceInterleaved[mode] )
  937. stream_.doConvertBuffer[mode] = true;
  938. }
  939. else if ( monoMode && stream_.userInterleaved )
  940. stream_.doConvertBuffer[mode] = true;
  941. // Allocate our CoreHandle structure for the stream.
  942. CoreHandle *handle = 0;
  943. if ( stream_.apiHandle == 0 ) {
  944. try {
  945. handle = new CoreHandle;
  946. }
  947. catch ( std::bad_alloc& ) {
  948. errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
  949. goto error;
  950. }
  951. if ( pthread_cond_init( &handle->condition, NULL ) ) {
  952. errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
  953. goto error;
  954. }
  955. stream_.apiHandle = (void *) handle;
  956. }
  957. else
  958. handle = (CoreHandle *) stream_.apiHandle;
  959. handle->iStream[mode] = firstStream;
  960. handle->nStreams[mode] = streamCount;
  961. handle->id[mode] = id;
  962. // Allocate necessary internal buffers.
  963. unsigned long bufferBytes;
  964. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  965. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  966. if ( stream_.userBuffer[mode] == NULL ) {
  967. errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
  968. goto error;
  969. }
  970. // If possible, we will make use of the CoreAudio stream buffers as
  971. // "device buffers". However, we can't do this if using multiple
  972. // streams.
  973. if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {
  974. bool makeBuffer = true;
  975. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  976. if ( mode == INPUT ) {
  977. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  978. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  979. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  980. }
  981. }
  982. if ( makeBuffer ) {
  983. bufferBytes *= *bufferSize;
  984. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  985. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  986. if ( stream_.deviceBuffer == NULL ) {
  987. errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
  988. goto error;
  989. }
  990. }
  991. }
  992. stream_.sampleRate = sampleRate;
  993. stream_.device[mode] = device;
  994. stream_.state = STREAM_STOPPED;
  995. stream_.callbackInfo.object = (void *) this;
  996. // Setup the buffer conversion information structure.
  997. if ( stream_.doConvertBuffer[mode] ) {
  998. if ( streamCount > 1 ) setConvertInfo( mode, 0 );
  999. else setConvertInfo( mode, channelOffset );
  1000. }
  1001. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device )
  1002. // Only one callback procedure per device.
  1003. stream_.mode = DUPLEX;
  1004. else {
  1005. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1006. result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );
  1007. #else
  1008. // deprecated in favor of AudioDeviceCreateIOProcID()
  1009. result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
  1010. #endif
  1011. if ( result != noErr ) {
  1012. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";
  1013. errorText_ = errorStream_.str();
  1014. goto error;
  1015. }
  1016. if ( stream_.mode == OUTPUT && mode == INPUT )
  1017. stream_.mode = DUPLEX;
  1018. else
  1019. stream_.mode = mode;
  1020. }
  1021. // Setup the device property listener for over/underload.
  1022. result = AudioDeviceAddPropertyListener( id, 0, isInput,
  1023. kAudioDeviceProcessorOverload,
  1024. deviceListener, (void *) handle );
  1025. return SUCCESS;
  1026. error:
  1027. if ( handle ) {
  1028. pthread_cond_destroy( &handle->condition );
  1029. delete handle;
  1030. stream_.apiHandle = 0;
  1031. }
  1032. for ( int i=0; i<2; i++ ) {
  1033. if ( stream_.userBuffer[i] ) {
  1034. free( stream_.userBuffer[i] );
  1035. stream_.userBuffer[i] = 0;
  1036. }
  1037. }
  1038. if ( stream_.deviceBuffer ) {
  1039. free( stream_.deviceBuffer );
  1040. stream_.deviceBuffer = 0;
  1041. }
  1042. return FAILURE;
  1043. }
  1044. void RtApiCore :: closeStream( void )
  1045. {
  1046. if ( stream_.state == STREAM_CLOSED ) {
  1047. errorText_ = "RtApiCore::closeStream(): no open stream to close!";
  1048. error( RtError::WARNING );
  1049. return;
  1050. }
  1051. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1052. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1053. if ( stream_.state == STREAM_RUNNING )
  1054. AudioDeviceStop( handle->id[0], callbackHandler );
  1055. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1056. AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );
  1057. #else
  1058. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1059. AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );
  1060. #endif
  1061. }
  1062. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1063. if ( stream_.state == STREAM_RUNNING )
  1064. AudioDeviceStop( handle->id[1], callbackHandler );
  1065. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1066. AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );
  1067. #else
  1068. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1069. AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );
  1070. #endif
  1071. }
  1072. for ( int i=0; i<2; i++ ) {
  1073. if ( stream_.userBuffer[i] ) {
  1074. free( stream_.userBuffer[i] );
  1075. stream_.userBuffer[i] = 0;
  1076. }
  1077. }
  1078. if ( stream_.deviceBuffer ) {
  1079. free( stream_.deviceBuffer );
  1080. stream_.deviceBuffer = 0;
  1081. }
  1082. // Destroy pthread condition variable.
  1083. pthread_cond_destroy( &handle->condition );
  1084. delete handle;
  1085. stream_.apiHandle = 0;
  1086. stream_.mode = UNINITIALIZED;
  1087. stream_.state = STREAM_CLOSED;
  1088. }
  1089. void RtApiCore :: startStream( void )
  1090. {
  1091. verifyStream();
  1092. if ( stream_.state == STREAM_RUNNING ) {
  1093. errorText_ = "RtApiCore::startStream(): the stream is already running!";
  1094. error( RtError::WARNING );
  1095. return;
  1096. }
  1097. MUTEX_LOCK( &stream_.mutex );
  1098. OSStatus result = noErr;
  1099. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1100. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1101. result = AudioDeviceStart( handle->id[0], callbackHandler );
  1102. if ( result != noErr ) {
  1103. errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ").";
  1104. errorText_ = errorStream_.str();
  1105. goto unlock;
  1106. }
  1107. }
  1108. if ( stream_.mode == INPUT ||
  1109. ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1110. result = AudioDeviceStart( handle->id[1], callbackHandler );
  1111. if ( result != noErr ) {
  1112. errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";
  1113. errorText_ = errorStream_.str();
  1114. goto unlock;
  1115. }
  1116. }
  1117. handle->drainCounter = 0;
  1118. handle->internalDrain = false;
  1119. stream_.state = STREAM_RUNNING;
  1120. unlock:
  1121. MUTEX_UNLOCK( &stream_.mutex );
  1122. if ( result == noErr ) return;
  1123. error( RtError::SYSTEM_ERROR );
  1124. }
  1125. void RtApiCore :: stopStream( void )
  1126. {
  1127. verifyStream();
  1128. if ( stream_.state == STREAM_STOPPED ) {
  1129. errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
  1130. error( RtError::WARNING );
  1131. return;
  1132. }
  1133. MUTEX_LOCK( &stream_.mutex );
  1134. if ( stream_.state == STREAM_STOPPED ) {
  1135. MUTEX_UNLOCK( &stream_.mutex );
  1136. return;
  1137. }
  1138. OSStatus result = noErr;
  1139. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1140. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1141. if ( handle->drainCounter == 0 ) {
  1142. handle->drainCounter = 1;
  1143. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  1144. }
  1145. result = AudioDeviceStop( handle->id[0], callbackHandler );
  1146. if ( result != noErr ) {
  1147. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";
  1148. errorText_ = errorStream_.str();
  1149. goto unlock;
  1150. }
  1151. }
  1152. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1153. result = AudioDeviceStop( handle->id[1], callbackHandler );
  1154. if ( result != noErr ) {
  1155. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";
  1156. errorText_ = errorStream_.str();
  1157. goto unlock;
  1158. }
  1159. }
  1160. stream_.state = STREAM_STOPPED;
  1161. unlock:
  1162. MUTEX_UNLOCK( &stream_.mutex );
  1163. if ( result == noErr ) return;
  1164. error( RtError::SYSTEM_ERROR );
  1165. }
  1166. void RtApiCore :: abortStream( void )
  1167. {
  1168. verifyStream();
  1169. if ( stream_.state == STREAM_STOPPED ) {
  1170. errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
  1171. error( RtError::WARNING );
  1172. return;
  1173. }
  1174. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1175. handle->drainCounter = 1;
  1176. stopStream();
  1177. }
  1178. bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
  1179. const AudioBufferList *inBufferList,
  1180. const AudioBufferList *outBufferList )
  1181. {
  1182. if ( stream_.state == STREAM_STOPPED ) return SUCCESS;
  1183. if ( stream_.state == STREAM_CLOSED ) {
  1184. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  1185. error( RtError::WARNING );
  1186. return FAILURE;
  1187. }
  1188. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  1189. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1190. // Check if we were draining the stream and signal is finished.
  1191. if ( handle->drainCounter > 3 ) {
  1192. if ( handle->internalDrain == false )
  1193. pthread_cond_signal( &handle->condition );
  1194. else
  1195. stopStream();
  1196. return SUCCESS;
  1197. }
  1198. MUTEX_LOCK( &stream_.mutex );
  1199. // The state might change while waiting on a mutex.
  1200. if ( stream_.state == STREAM_STOPPED ) {
  1201. MUTEX_UNLOCK( &stream_.mutex );
  1202. return SUCCESS;
  1203. }
  1204. AudioDeviceID outputDevice = handle->id[0];
  1205. // Invoke user callback to get fresh output data UNLESS we are
  1206. // draining stream or duplex mode AND the input/output devices are
  1207. // different AND this function is called for the input device.
  1208. if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {
  1209. RtAudioCallback callback = (RtAudioCallback) info->callback;
  1210. double streamTime = getStreamTime();
  1211. RtAudioStreamStatus status = 0;
  1212. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  1213. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  1214. handle->xrun[0] = false;
  1215. }
  1216. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  1217. status |= RTAUDIO_INPUT_OVERFLOW;
  1218. handle->xrun[1] = false;
  1219. }
  1220. handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  1221. stream_.bufferSize, streamTime, status, info->userData );
  1222. if ( handle->drainCounter == 2 ) {
  1223. MUTEX_UNLOCK( &stream_.mutex );
  1224. abortStream();
  1225. return SUCCESS;
  1226. }
  1227. else if ( handle->drainCounter == 1 )
  1228. handle->internalDrain = true;
  1229. }
  1230. if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {
  1231. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  1232. if ( handle->nStreams[0] == 1 ) {
  1233. memset( outBufferList->mBuffers[handle->iStream[0]].mData,
  1234. 0,
  1235. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1236. }
  1237. else { // fill multiple streams with zeros
  1238. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1239. memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1240. 0,
  1241. outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );
  1242. }
  1243. }
  1244. }
  1245. else if ( handle->nStreams[0] == 1 ) {
  1246. if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer
  1247. convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,
  1248. stream_.userBuffer[0], stream_.convertInfo[0] );
  1249. }
  1250. else { // copy from user buffer
  1251. memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,
  1252. stream_.userBuffer[0],
  1253. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1254. }
  1255. }
  1256. else { // fill multiple streams
  1257. Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];
  1258. if ( stream_.doConvertBuffer[0] ) {
  1259. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  1260. inBuffer = (Float32 *) stream_.deviceBuffer;
  1261. }
  1262. if ( stream_.deviceInterleaved[0] == false ) { // mono mode
  1263. UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
  1264. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1265. memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1266. (void *)&inBuffer[i*stream_.bufferSize], bufferBytes );
  1267. }
  1268. }
  1269. else { // fill multiple multi-channel streams with interleaved data
  1270. UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
  1271. Float32 *out, *in;
  1272. bool inInterleaved = ( stream_.userInterleaved ) ? true : false;
  1273. UInt32 inChannels = stream_.nUserChannels[0];
  1274. if ( stream_.doConvertBuffer[0] ) {
  1275. inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1276. inChannels = stream_.nDeviceChannels[0];
  1277. }
  1278. if ( inInterleaved ) inOffset = 1;
  1279. else inOffset = stream_.bufferSize;
  1280. channelsLeft = inChannels;
  1281. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1282. in = inBuffer;
  1283. out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;
  1284. streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;
  1285. outJump = 0;
  1286. // Account for possible channel offset in first stream
  1287. if ( i == 0 && stream_.channelOffset[0] > 0 ) {
  1288. streamChannels -= stream_.channelOffset[0];
  1289. outJump = stream_.channelOffset[0];
  1290. out += outJump;
  1291. }
  1292. // Account for possible unfilled channels at end of the last stream
  1293. if ( streamChannels > channelsLeft ) {
  1294. outJump = streamChannels - channelsLeft;
  1295. streamChannels = channelsLeft;
  1296. }
  1297. // Determine input buffer offsets and skips
  1298. if ( inInterleaved ) {
  1299. inJump = inChannels;
  1300. in += inChannels - channelsLeft;
  1301. }
  1302. else {
  1303. inJump = 1;
  1304. in += (inChannels - channelsLeft) * inOffset;
  1305. }
  1306. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1307. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1308. *out++ = in[j*inOffset];
  1309. }
  1310. out += outJump;
  1311. in += inJump;
  1312. }
  1313. channelsLeft -= streamChannels;
  1314. }
  1315. }
  1316. }
  1317. if ( handle->drainCounter ) {
  1318. handle->drainCounter++;
  1319. goto unlock;
  1320. }
  1321. }
  1322. AudioDeviceID inputDevice;
  1323. inputDevice = handle->id[1];
  1324. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {
  1325. if ( handle->nStreams[1] == 1 ) {
  1326. if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer
  1327. convertBuffer( stream_.userBuffer[1],
  1328. (char *) inBufferList->mBuffers[handle->iStream[1]].mData,
  1329. stream_.convertInfo[1] );
  1330. }
  1331. else { // copy to user buffer
  1332. memcpy( stream_.userBuffer[1],
  1333. inBufferList->mBuffers[handle->iStream[1]].mData,
  1334. inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );
  1335. }
  1336. }
  1337. else { // read from multiple streams
  1338. Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];
  1339. if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;
  1340. if ( stream_.deviceInterleaved[1] == false ) { // mono mode
  1341. UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
  1342. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1343. memcpy( (void *)&outBuffer[i*stream_.bufferSize],
  1344. inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );
  1345. }
  1346. }
  1347. else { // read from multiple multi-channel streams
  1348. UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
  1349. Float32 *out, *in;
  1350. bool outInterleaved = ( stream_.userInterleaved ) ? true : false;
  1351. UInt32 outChannels = stream_.nUserChannels[1];
  1352. if ( stream_.doConvertBuffer[1] ) {
  1353. outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1354. outChannels = stream_.nDeviceChannels[1];
  1355. }
  1356. if ( outInterleaved ) outOffset = 1;
  1357. else outOffset = stream_.bufferSize;
  1358. channelsLeft = outChannels;
  1359. for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {
  1360. out = outBuffer;
  1361. in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;
  1362. streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;
  1363. inJump = 0;
  1364. // Account for possible channel offset in first stream
  1365. if ( i == 0 && stream_.channelOffset[1] > 0 ) {
  1366. streamChannels -= stream_.channelOffset[1];
  1367. inJump = stream_.channelOffset[1];
  1368. in += inJump;
  1369. }
  1370. // Account for possible unread channels at end of the last stream
  1371. if ( streamChannels > channelsLeft ) {
  1372. inJump = streamChannels - channelsLeft;
  1373. streamChannels = channelsLeft;
  1374. }
  1375. // Determine output buffer offsets and skips
  1376. if ( outInterleaved ) {
  1377. outJump = outChannels;
  1378. out += outChannels - channelsLeft;
  1379. }
  1380. else {
  1381. outJump = 1;
  1382. out += (outChannels - channelsLeft) * outOffset;
  1383. }
  1384. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1385. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1386. out[j*outOffset] = *in++;
  1387. }
  1388. out += outJump;
  1389. in += inJump;
  1390. }
  1391. channelsLeft -= streamChannels;
  1392. }
  1393. }
  1394. if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer
  1395. convertBuffer( stream_.userBuffer[1],
  1396. stream_.deviceBuffer,
  1397. stream_.convertInfo[1] );
  1398. }
  1399. }
  1400. }
  1401. unlock:
  1402. MUTEX_UNLOCK( &stream_.mutex );
  1403. RtApi::tickStreamTime();
  1404. return SUCCESS;
  1405. }
  1406. const char* RtApiCore :: getErrorCode( OSStatus code )
  1407. {
  1408. switch( code ) {
  1409. case kAudioHardwareNotRunningError:
  1410. return "kAudioHardwareNotRunningError";
  1411. case kAudioHardwareUnspecifiedError:
  1412. return "kAudioHardwareUnspecifiedError";
  1413. case kAudioHardwareUnknownPropertyError:
  1414. return "kAudioHardwareUnknownPropertyError";
  1415. case kAudioHardwareBadPropertySizeError:
  1416. return "kAudioHardwareBadPropertySizeError";
  1417. case kAudioHardwareIllegalOperationError:
  1418. return "kAudioHardwareIllegalOperationError";
  1419. case kAudioHardwareBadObjectError:
  1420. return "kAudioHardwareBadObjectError";
  1421. case kAudioHardwareBadDeviceError:
  1422. return "kAudioHardwareBadDeviceError";
  1423. case kAudioHardwareBadStreamError:
  1424. return "kAudioHardwareBadStreamError";
  1425. case kAudioHardwareUnsupportedOperationError:
  1426. return "kAudioHardwareUnsupportedOperationError";
  1427. case kAudioDeviceUnsupportedFormatError:
  1428. return "kAudioDeviceUnsupportedFormatError";
  1429. case kAudioDevicePermissionsError:
  1430. return "kAudioDevicePermissionsError";
  1431. default:
  1432. return "CoreAudio unknown error";
  1433. }
  1434. }
  1435. //******************** End of __MACOSX_CORE__ *********************//
  1436. #endif
  1437. #if defined(__UNIX_JACK__)
  1438. // JACK is a low-latency audio server, originally written for the
  1439. // GNU/Linux operating system and now also ported to OS-X. It can
  1440. // connect a number of different applications to an audio device, as
  1441. // well as allowing them to share audio between themselves.
  1442. //
  1443. // When using JACK with RtAudio, "devices" refer to JACK clients that
  1444. // have ports connected to the server. The JACK server is typically
  1445. // started in a terminal as follows:
  1446. //
  1447. // .jackd -d alsa -d hw:0
  1448. //
  1449. // or through an interface program such as qjackctl. Many of the
  1450. // parameters normally set for a stream are fixed by the JACK server
  1451. // and can be specified when the JACK server is started. In
  1452. // particular,
  1453. //
  1454. // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
  1455. //
  1456. // specifies a sample rate of 44100 Hz, a buffer size of 512 sample
  1457. // frames, and number of buffers = 4. Once the server is running, it
  1458. // is not possible to override these values. If the values are not
  1459. // specified in the command-line, the JACK server uses default values.
  1460. //
  1461. // The JACK server does not have to be running when an instance of
  1462. // RtApiJack is created, though the function getDeviceCount() will
  1463. // report 0 devices found until JACK has been started. When no
  1464. // devices are available (i.e., the JACK server is not running), a
  1465. // stream cannot be opened.
  1466. #include <jack/jack.h>
  1467. #include <unistd.h>
  1468. // A structure to hold various information related to the Jack API
  1469. // implementation.
  1470. struct JackHandle {
  1471. jack_client_t *client;
  1472. jack_port_t **ports[2];
  1473. std::string deviceName[2];
  1474. bool xrun[2];
  1475. pthread_cond_t condition;
  1476. int drainCounter; // Tracks callback counts when draining
  1477. bool internalDrain; // Indicates if stop is initiated from callback or not.
  1478. JackHandle()
  1479. :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
  1480. };
  1481. RtApiJack :: RtApiJack()
  1482. {
  1483. // Nothing to do here.
  1484. }
  1485. RtApiJack :: ~RtApiJack()
  1486. {
  1487. if ( stream_.state != STREAM_CLOSED ) closeStream();
  1488. }
  1489. unsigned int RtApiJack :: getDeviceCount( void )
  1490. {
  1491. // See if we can become a jack client.
  1492. jack_options_t options = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption;
  1493. jack_status_t *status = NULL;
  1494. jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );
  1495. if ( client == 0 ) return 0;
  1496. const char **ports;
  1497. std::string port, previousPort;
  1498. unsigned int nChannels = 0, nDevices = 0;
  1499. ports = jack_get_ports( client, NULL, NULL, 0 );
  1500. if ( ports ) {
  1501. // Parse the port names up to the first colon (:).
  1502. size_t iColon = 0;
  1503. do {
  1504. port = (char *) ports[ nChannels ];
  1505. iColon = port.find(":");
  1506. if ( iColon != std::string::npos ) {
  1507. port = port.substr( 0, iColon + 1 );
  1508. if ( port != previousPort ) {
  1509. nDevices++;
  1510. previousPort = port;
  1511. }
  1512. }
  1513. } while ( ports[++nChannels] );
  1514. free( ports );
  1515. }
  1516. jack_client_close( client );
  1517. return nDevices;
  1518. }
  1519. RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
  1520. {
  1521. RtAudio::DeviceInfo info;
  1522. info.probed = false;
  1523. jack_options_t options = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption
  1524. jack_status_t *status = NULL;
  1525. jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );
  1526. if ( client == 0 ) {
  1527. errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
  1528. error( RtError::WARNING );
  1529. return info;
  1530. }
  1531. const char **ports;
  1532. std::string port, previousPort;
  1533. unsigned int nPorts = 0, nDevices = 0;
  1534. ports = jack_get_ports( client, NULL, NULL, 0 );
  1535. if ( ports ) {
  1536. // Parse the port names up to the first colon (:).
  1537. size_t iColon = 0;
  1538. do {
  1539. port = (char *) ports[ nPorts ];
  1540. iColon = port.find(":");
  1541. if ( iColon != std::string::npos ) {
  1542. port = port.substr( 0, iColon );
  1543. if ( port != previousPort ) {
  1544. if ( nDevices == device ) info.name = port;
  1545. nDevices++;
  1546. previousPort = port;
  1547. }
  1548. }
  1549. } while ( ports[++nPorts] );
  1550. free( ports );
  1551. }
  1552. if ( device >= nDevices ) {
  1553. errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
  1554. error( RtError::INVALID_USE );
  1555. }
  1556. // Get the current jack server sample rate.
  1557. info.sampleRates.clear();
  1558. info.sampleRates.push_back( jack_get_sample_rate( client ) );
  1559. // Count the available ports containing the client name as device
  1560. // channels. Jack "input ports" equal RtAudio output channels.
  1561. unsigned int nChannels = 0;
  1562. ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsInput );
  1563. if ( ports ) {
  1564. while ( ports[ nChannels ] ) nChannels++;
  1565. free( ports );
  1566. info.outputChannels = nChannels;
  1567. }
  1568. // Jack "output ports" equal RtAudio input channels.
  1569. nChannels = 0;
  1570. ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsOutput );
  1571. if ( ports ) {
  1572. while ( ports[ nChannels ] ) nChannels++;
  1573. free( ports );
  1574. info.inputChannels = nChannels;
  1575. }
  1576. if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
  1577. jack_client_close(client);
  1578. errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
  1579. error( RtError::WARNING );
  1580. return info;
  1581. }
  1582. // If device opens for both playback and capture, we determine the channels.
  1583. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  1584. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  1585. // Jack always uses 32-bit floats.
  1586. info.nativeFormats = RTAUDIO_FLOAT32;
  1587. // Jack doesn't provide default devices so we'll use the first available one.
  1588. if ( device == 0 && info.outputChannels > 0 )
  1589. info.isDefaultOutput = true;
  1590. if ( device == 0 && info.inputChannels > 0 )
  1591. info.isDefaultInput = true;
  1592. jack_client_close(client);
  1593. info.probed = true;
  1594. return info;
  1595. }
  1596. int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
  1597. {
  1598. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1599. RtApiJack *object = (RtApiJack *) info->object;
  1600. if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
  1601. return 0;
  1602. }
  1603. void jackShutdown( void *infoPointer )
  1604. {
  1605. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1606. RtApiJack *object = (RtApiJack *) info->object;
  1607. // Check current stream state. If stopped, then we'll assume this
  1608. // was called as a result of a call to RtApiJack::stopStream (the
  1609. // deactivation of a client handle causes this function to be called).
  1610. // If not, we'll assume the Jack server is shutting down or some
  1611. // other problem occurred and we should close the stream.
  1612. if ( object->isStreamRunning() == false ) return;
  1613. object->closeStream();
  1614. std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
  1615. }
  1616. int jackXrun( void *infoPointer )
  1617. {
  1618. JackHandle *handle = (JackHandle *) infoPointer;
  1619. if ( handle->ports[0] ) handle->xrun[0] = true;
  1620. if ( handle->ports[1] ) handle->xrun[1] = true;
  1621. return 0;
  1622. }
  1623. bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  1624. unsigned int firstChannel, unsigned int sampleRate,
  1625. RtAudioFormat format, unsigned int *bufferSize,
  1626. RtAudio::StreamOptions *options )
  1627. {
  1628. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1629. // Look for jack server and try to become a client (only do once per stream).
  1630. jack_client_t *client = 0;
  1631. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
  1632. jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption;
  1633. jack_status_t *status = NULL;
  1634. if ( options && !options->streamName.empty() )
  1635. client = jack_client_open( options->streamName.c_str(), jackoptions, status );
  1636. else
  1637. client = jack_client_open( "RtApiJack", jackoptions, status );
  1638. if ( client == 0 ) {
  1639. errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
  1640. error( RtError::WARNING );
  1641. return FAILURE;
  1642. }
  1643. }
  1644. else {
  1645. // The handle must have been created on an earlier pass.
  1646. client = handle->client;
  1647. }
  1648. const char **ports;
  1649. std::string port, previousPort, deviceName;
  1650. unsigned int nPorts = 0, nDevices = 0;
  1651. ports = jack_get_ports( client, NULL, NULL, 0 );
  1652. if ( ports ) {
  1653. // Parse the port names up to the first colon (:).
  1654. size_t iColon = 0;
  1655. do {
  1656. port = (char *) ports[ nPorts ];
  1657. iColon = port.find(":");
  1658. if ( iColon != std::string::npos ) {
  1659. port = port.substr( 0, iColon );
  1660. if ( port != previousPort ) {
  1661. if ( nDevices == device ) deviceName = port;
  1662. nDevices++;
  1663. previousPort = port;
  1664. }
  1665. }
  1666. } while ( ports[++nPorts] );
  1667. free( ports );
  1668. }
  1669. if ( device >= nDevices ) {
  1670. errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
  1671. return FAILURE;
  1672. }
  1673. // Count the available ports containing the client name as device
  1674. // channels. Jack "input ports" equal RtAudio output channels.
  1675. unsigned int nChannels = 0;
  1676. unsigned long flag = JackPortIsInput;
  1677. if ( mode == INPUT ) flag = JackPortIsOutput;
  1678. ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
  1679. if ( ports ) {
  1680. while ( ports[ nChannels ] ) nChannels++;
  1681. free( ports );
  1682. }
  1683. // Compare the jack ports for specified client to the requested number of channels.
  1684. if ( nChannels < (channels + firstChannel) ) {
  1685. errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
  1686. errorText_ = errorStream_.str();
  1687. return FAILURE;
  1688. }
  1689. // Check the jack server sample rate.
  1690. unsigned int jackRate = jack_get_sample_rate( client );
  1691. if ( sampleRate != jackRate ) {
  1692. jack_client_close( client );
  1693. errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
  1694. errorText_ = errorStream_.str();
  1695. return FAILURE;
  1696. }
  1697. stream_.sampleRate = jackRate;
  1698. // Get the latency of the JACK port.
  1699. ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
  1700. if ( ports[ firstChannel ] )
  1701. stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
  1702. free( ports );
  1703. // The jack server always uses 32-bit floating-point data.
  1704. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1705. stream_.userFormat = format;
  1706. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1707. else stream_.userInterleaved = true;
  1708. // Jack always uses non-interleaved buffers.
  1709. stream_.deviceInterleaved[mode] = false;
  1710. // Jack always provides host byte-ordered data.
  1711. stream_.doByteSwap[mode] = false;
  1712. // Get the buffer size. The buffer size and number of buffers
  1713. // (periods) is set when the jack server is started.
  1714. stream_.bufferSize = (int) jack_get_buffer_size( client );
  1715. *bufferSize = stream_.bufferSize;
  1716. stream_.nDeviceChannels[mode] = channels;
  1717. stream_.nUserChannels[mode] = channels;
  1718. // Set flags for buffer conversion.
  1719. stream_.doConvertBuffer[mode] = false;
  1720. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1721. stream_.doConvertBuffer[mode] = true;
  1722. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  1723. stream_.nUserChannels[mode] > 1 )
  1724. stream_.doConvertBuffer[mode] = true;
  1725. // Allocate our JackHandle structure for the stream.
  1726. if ( handle == 0 ) {
  1727. try {
  1728. handle = new JackHandle;
  1729. }
  1730. catch ( std::bad_alloc& ) {
  1731. errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
  1732. goto error;
  1733. }
  1734. if ( pthread_cond_init(&handle->condition, NULL) ) {
  1735. errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
  1736. goto error;
  1737. }
  1738. stream_.apiHandle = (void *) handle;
  1739. handle->client = client;
  1740. }
  1741. handle->deviceName[mode] = deviceName;
  1742. // Allocate necessary internal buffers.
  1743. unsigned long bufferBytes;
  1744. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  1745. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1746. if ( stream_.userBuffer[mode] == NULL ) {
  1747. errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
  1748. goto error;
  1749. }
  1750. if ( stream_.doConvertBuffer[mode] ) {
  1751. bool makeBuffer = true;
  1752. if ( mode == OUTPUT )
  1753. bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1754. else { // mode == INPUT
  1755. bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
  1756. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1757. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
  1758. if ( bufferBytes < bytesOut ) makeBuffer = false;
  1759. }
  1760. }
  1761. if ( makeBuffer ) {
  1762. bufferBytes *= *bufferSize;
  1763. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1764. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1765. if ( stream_.deviceBuffer == NULL ) {
  1766. errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
  1767. goto error;
  1768. }
  1769. }
  1770. }
  1771. // Allocate memory for the Jack ports (channels) identifiers.
  1772. handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
  1773. if ( handle->ports[mode] == NULL ) {
  1774. errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
  1775. goto error;
  1776. }
  1777. stream_.device[mode] = device;
  1778. stream_.channelOffset[mode] = firstChannel;
  1779. stream_.state = STREAM_STOPPED;
  1780. stream_.callbackInfo.object = (void *) this;
  1781. if ( stream_.mode == OUTPUT && mode == INPUT )
  1782. // We had already set up the stream for output.
  1783. stream_.mode = DUPLEX;
  1784. else {
  1785. stream_.mode = mode;
  1786. jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
  1787. jack_set_xrun_callback( handle->client, jackXrun, (void *) &handle );
  1788. jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
  1789. }
  1790. // Register our ports.
  1791. char label[64];
  1792. if ( mode == OUTPUT ) {
  1793. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1794. snprintf( label, 64, "outport %d", i );
  1795. handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
  1796. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
  1797. }
  1798. }
  1799. else {
  1800. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1801. snprintf( label, 64, "inport %d", i );
  1802. handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
  1803. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
  1804. }
  1805. }
  1806. // Setup the buffer conversion information structure. We don't use
  1807. // buffers to do channel offsets, so we override that parameter
  1808. // here.
  1809. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  1810. return SUCCESS;
  1811. error:
  1812. if ( handle ) {
  1813. pthread_cond_destroy( &handle->condition );
  1814. jack_client_close( handle->client );
  1815. if ( handle->ports[0] ) free( handle->ports[0] );
  1816. if ( handle->ports[1] ) free( handle->ports[1] );
  1817. delete handle;
  1818. stream_.apiHandle = 0;
  1819. }
  1820. for ( int i=0; i<2; i++ ) {
  1821. if ( stream_.userBuffer[i] ) {
  1822. free( stream_.userBuffer[i] );
  1823. stream_.userBuffer[i] = 0;
  1824. }
  1825. }
  1826. if ( stream_.deviceBuffer ) {
  1827. free( stream_.deviceBuffer );
  1828. stream_.deviceBuffer = 0;
  1829. }
  1830. return FAILURE;
  1831. }
  1832. void RtApiJack :: closeStream( void )
  1833. {
  1834. if ( stream_.state == STREAM_CLOSED ) {
  1835. errorText_ = "RtApiJack::closeStream(): no open stream to close!";
  1836. error( RtError::WARNING );
  1837. return;
  1838. }
  1839. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1840. if ( handle ) {
  1841. if ( stream_.state == STREAM_RUNNING )
  1842. jack_deactivate( handle->client );
  1843. jack_client_close( handle->client );
  1844. }
  1845. if ( handle ) {
  1846. if ( handle->ports[0] ) free( handle->ports[0] );
  1847. if ( handle->ports[1] ) free( handle->ports[1] );
  1848. pthread_cond_destroy( &handle->condition );
  1849. delete handle;
  1850. stream_.apiHandle = 0;
  1851. }
  1852. for ( int i=0; i<2; i++ ) {
  1853. if ( stream_.userBuffer[i] ) {
  1854. free( stream_.userBuffer[i] );
  1855. stream_.userBuffer[i] = 0;
  1856. }
  1857. }
  1858. if ( stream_.deviceBuffer ) {
  1859. free( stream_.deviceBuffer );
  1860. stream_.deviceBuffer = 0;
  1861. }
  1862. stream_.mode = UNINITIALIZED;
  1863. stream_.state = STREAM_CLOSED;
  1864. }
  1865. void RtApiJack :: startStream( void )
  1866. {
  1867. verifyStream();
  1868. if ( stream_.state == STREAM_RUNNING ) {
  1869. errorText_ = "RtApiJack::startStream(): the stream is already running!";
  1870. error( RtError::WARNING );
  1871. return;
  1872. }
  1873. MUTEX_LOCK(&stream_.mutex);
  1874. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1875. int result = jack_activate( handle->client );
  1876. if ( result ) {
  1877. errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
  1878. goto unlock;
  1879. }
  1880. const char **ports;
  1881. // Get the list of available ports.
  1882. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1883. result = 1;
  1884. ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), NULL, JackPortIsInput);
  1885. if ( ports == NULL) {
  1886. errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
  1887. goto unlock;
  1888. }
  1889. // Now make the port connections. Since RtAudio wasn't designed to
  1890. // allow the user to select particular channels of a device, we'll
  1891. // just open the first "nChannels" ports with offset.
  1892. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1893. result = 1;
  1894. if ( ports[ stream_.channelOffset[0] + i ] )
  1895. result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
  1896. if ( result ) {
  1897. free( ports );
  1898. errorText_ = "RtApiJack::startStream(): error connecting output ports!";
  1899. goto unlock;
  1900. }
  1901. }
  1902. free(ports);
  1903. }
  1904. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  1905. result = 1;
  1906. ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), NULL, JackPortIsOutput );
  1907. if ( ports == NULL) {
  1908. errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
  1909. goto unlock;
  1910. }
  1911. // Now make the port connections. See note above.
  1912. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1913. result = 1;
  1914. if ( ports[ stream_.channelOffset[1] + i ] )
  1915. result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
  1916. if ( result ) {
  1917. free( ports );
  1918. errorText_ = "RtApiJack::startStream(): error connecting input ports!";
  1919. goto unlock;
  1920. }
  1921. }
  1922. free(ports);
  1923. }
  1924. handle->drainCounter = 0;
  1925. handle->internalDrain = false;
  1926. stream_.state = STREAM_RUNNING;
  1927. unlock:
  1928. MUTEX_UNLOCK(&stream_.mutex);
  1929. if ( result == 0 ) return;
  1930. error( RtError::SYSTEM_ERROR );
  1931. }
  1932. void RtApiJack :: stopStream( void )
  1933. {
  1934. verifyStream();
  1935. if ( stream_.state == STREAM_STOPPED ) {
  1936. errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
  1937. error( RtError::WARNING );
  1938. return;
  1939. }
  1940. MUTEX_LOCK( &stream_.mutex );
  1941. if ( stream_.state == STREAM_STOPPED ) {
  1942. MUTEX_UNLOCK( &stream_.mutex );
  1943. return;
  1944. }
  1945. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1946. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1947. if ( handle->drainCounter == 0 ) {
  1948. handle->drainCounter = 1;
  1949. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  1950. }
  1951. }
  1952. jack_deactivate( handle->client );
  1953. stream_.state = STREAM_STOPPED;
  1954. MUTEX_UNLOCK( &stream_.mutex );
  1955. }
  1956. void RtApiJack :: abortStream( void )
  1957. {
  1958. verifyStream();
  1959. if ( stream_.state == STREAM_STOPPED ) {
  1960. errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
  1961. error( RtError::WARNING );
  1962. return;
  1963. }
  1964. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1965. handle->drainCounter = 1;
  1966. stopStream();
  1967. }
  1968. bool RtApiJack :: callbackEvent( unsigned long nframes )
  1969. {
  1970. if ( stream_.state == STREAM_STOPPED ) return SUCCESS;
  1971. if ( stream_.state == STREAM_CLOSED ) {
  1972. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  1973. error( RtError::WARNING );
  1974. return FAILURE;
  1975. }
  1976. if ( stream_.bufferSize != nframes ) {
  1977. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
  1978. error( RtError::WARNING );
  1979. return FAILURE;
  1980. }
  1981. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  1982. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1983. // Check if we were draining the stream and signal is finished.
  1984. if ( handle->drainCounter > 3 ) {
  1985. if ( handle->internalDrain == false )
  1986. pthread_cond_signal( &handle->condition );
  1987. else
  1988. stopStream();
  1989. return SUCCESS;
  1990. }
  1991. MUTEX_LOCK( &stream_.mutex );
  1992. // The state might change while waiting on a mutex.
  1993. if ( stream_.state == STREAM_STOPPED ) {
  1994. MUTEX_UNLOCK( &stream_.mutex );
  1995. return SUCCESS;
  1996. }
  1997. // Invoke user callback first, to get fresh output data.
  1998. if ( handle->drainCounter == 0 ) {
  1999. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2000. double streamTime = getStreamTime();
  2001. RtAudioStreamStatus status = 0;
  2002. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  2003. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2004. handle->xrun[0] = false;
  2005. }
  2006. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  2007. status |= RTAUDIO_INPUT_OVERFLOW;
  2008. handle->xrun[1] = false;
  2009. }
  2010. handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2011. stream_.bufferSize, streamTime, status, info->userData );
  2012. if ( handle->drainCounter == 2 ) {
  2013. MUTEX_UNLOCK( &stream_.mutex );
  2014. abortStream();
  2015. return SUCCESS;
  2016. }
  2017. else if ( handle->drainCounter == 1 )
  2018. handle->internalDrain = true;
  2019. }
  2020. jack_default_audio_sample_t *jackbuffer;
  2021. unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
  2022. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2023. if ( handle->drainCounter > 0 ) { // write zeros to the output stream
  2024. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2025. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2026. memset( jackbuffer, 0, bufferBytes );
  2027. }
  2028. }
  2029. else if ( stream_.doConvertBuffer[0] ) {
  2030. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2031. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2032. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2033. memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
  2034. }
  2035. }
  2036. else { // no buffer conversion
  2037. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2038. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2039. memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
  2040. }
  2041. }
  2042. if ( handle->drainCounter ) {
  2043. handle->drainCounter++;
  2044. goto unlock;
  2045. }
  2046. }
  2047. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2048. if ( stream_.doConvertBuffer[1] ) {
  2049. for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
  2050. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2051. memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
  2052. }
  2053. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2054. }
  2055. else { // no buffer conversion
  2056. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2057. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2058. memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
  2059. }
  2060. }
  2061. }
  2062. unlock:
  2063. MUTEX_UNLOCK(&stream_.mutex);
  2064. RtApi::tickStreamTime();
  2065. return SUCCESS;
  2066. }
  2067. //******************** End of __UNIX_JACK__ *********************//
  2068. #endif
  2069. #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2070. // The ASIO API is designed around a callback scheme, so this
  2071. // implementation is similar to that used for OS-X CoreAudio and Linux
  2072. // Jack. The primary constraint with ASIO is that it only allows
  2073. // access to a single driver at a time. Thus, it is not possible to
  2074. // have more than one simultaneous RtAudio stream.
  2075. //
  2076. // This implementation also requires a number of external ASIO files
  2077. // and a few global variables. The ASIO callback scheme does not
  2078. // allow for the passing of user data, so we must create a global
  2079. // pointer to our callbackInfo structure.
  2080. //
  2081. // On unix systems, we make use of a pthread condition variable.
  2082. // Since there is no equivalent in Windows, I hacked something based
  2083. // on information found in
  2084. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
  2085. #include "asiosys.h"
  2086. #include "asio.h"
  2087. #include "iasiothiscallresolver.h"
  2088. #include "asiodrivers.h"
  2089. #include <cmath>
  2090. AsioDrivers drivers;
  2091. ASIOCallbacks asioCallbacks;
  2092. ASIODriverInfo driverInfo;
  2093. CallbackInfo *asioCallbackInfo;
  2094. bool asioXRun;
  2095. struct AsioHandle {
  2096. int drainCounter; // Tracks callback counts when draining
  2097. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2098. ASIOBufferInfo *bufferInfos;
  2099. HANDLE condition;
  2100. AsioHandle()
  2101. :drainCounter(0), internalDrain(false), bufferInfos(0) {}
  2102. };
  2103. // Function declarations (definitions at end of section)
  2104. static const char* getAsioErrorString( ASIOError result );
  2105. void sampleRateChanged( ASIOSampleRate sRate );
  2106. long asioMessages( long selector, long value, void* message, double* opt );
  2107. RtApiAsio :: RtApiAsio()
  2108. {
  2109. // ASIO cannot run on a multi-threaded appartment. You can call
  2110. // CoInitialize beforehand, but it must be for appartment threading
  2111. // (in which case, CoInitilialize will return S_FALSE here).
  2112. coInitialized_ = false;
  2113. HRESULT hr = CoInitialize( NULL );
  2114. if ( FAILED(hr) ) {
  2115. errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
  2116. error( RtError::WARNING );
  2117. }
  2118. coInitialized_ = true;
  2119. drivers.removeCurrentDriver();
  2120. driverInfo.asioVersion = 2;
  2121. // See note in DirectSound implementation about GetDesktopWindow().
  2122. driverInfo.sysRef = GetForegroundWindow();
  2123. }
  2124. RtApiAsio :: ~RtApiAsio()
  2125. {
  2126. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2127. if ( coInitialized_ ) CoUninitialize();
  2128. }
  2129. unsigned int RtApiAsio :: getDeviceCount( void )
  2130. {
  2131. return (unsigned int) drivers.asioGetNumDev();
  2132. }
  2133. RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
  2134. {
  2135. RtAudio::DeviceInfo info;
  2136. info.probed = false;
  2137. // Get device ID
  2138. unsigned int nDevices = getDeviceCount();
  2139. if ( nDevices == 0 ) {
  2140. errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
  2141. error( RtError::INVALID_USE );
  2142. }
  2143. if ( device >= nDevices ) {
  2144. errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
  2145. error( RtError::INVALID_USE );
  2146. }
  2147. // If a stream is already open, we cannot probe other devices. Thus, use the saved results.
  2148. if ( stream_.state != STREAM_CLOSED ) {
  2149. if ( device >= devices_.size() ) {
  2150. errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
  2151. error( RtError::WARNING );
  2152. return info;
  2153. }
  2154. return devices_[ device ];
  2155. }
  2156. char driverName[32];
  2157. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2158. if ( result != ASE_OK ) {
  2159. errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2160. errorText_ = errorStream_.str();
  2161. error( RtError::WARNING );
  2162. return info;
  2163. }
  2164. info.name = driverName;
  2165. if ( !drivers.loadDriver( driverName ) ) {
  2166. errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
  2167. errorText_ = errorStream_.str();
  2168. error( RtError::WARNING );
  2169. return info;
  2170. }
  2171. result = ASIOInit( &driverInfo );
  2172. if ( result != ASE_OK ) {
  2173. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2174. errorText_ = errorStream_.str();
  2175. error( RtError::WARNING );
  2176. return info;
  2177. }
  2178. // Determine the device channel information.
  2179. long inputChannels, outputChannels;
  2180. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2181. if ( result != ASE_OK ) {
  2182. drivers.removeCurrentDriver();
  2183. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2184. errorText_ = errorStream_.str();
  2185. error( RtError::WARNING );
  2186. return info;
  2187. }
  2188. info.outputChannels = outputChannels;
  2189. info.inputChannels = inputChannels;
  2190. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  2191. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  2192. // Determine the supported sample rates.
  2193. info.sampleRates.clear();
  2194. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  2195. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  2196. if ( result == ASE_OK )
  2197. info.sampleRates.push_back( SAMPLE_RATES[i] );
  2198. }
  2199. // Determine supported data types ... just check first channel and assume rest are the same.
  2200. ASIOChannelInfo channelInfo;
  2201. channelInfo.channel = 0;
  2202. channelInfo.isInput = true;
  2203. if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
  2204. result = ASIOGetChannelInfo( &channelInfo );
  2205. if ( result != ASE_OK ) {
  2206. drivers.removeCurrentDriver();
  2207. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
  2208. errorText_ = errorStream_.str();
  2209. error( RtError::WARNING );
  2210. return info;
  2211. }
  2212. info.nativeFormats = 0;
  2213. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  2214. info.nativeFormats |= RTAUDIO_SINT16;
  2215. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  2216. info.nativeFormats |= RTAUDIO_SINT32;
  2217. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  2218. info.nativeFormats |= RTAUDIO_FLOAT32;
  2219. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  2220. info.nativeFormats |= RTAUDIO_FLOAT64;
  2221. if ( getDefaultOutputDevice() == device )
  2222. info.isDefaultOutput = true;
  2223. if ( getDefaultInputDevice() == device )
  2224. info.isDefaultInput = true;
  2225. info.probed = true;
  2226. drivers.removeCurrentDriver();
  2227. return info;
  2228. }
  2229. void bufferSwitch( long index, ASIOBool processNow )
  2230. {
  2231. RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
  2232. object->callbackEvent( index );
  2233. }
  2234. void RtApiAsio :: saveDeviceInfo( void )
  2235. {
  2236. devices_.clear();
  2237. unsigned int nDevices = getDeviceCount();
  2238. devices_.resize( nDevices );
  2239. for ( unsigned int i=0; i<nDevices; i++ )
  2240. devices_[i] = getDeviceInfo( i );
  2241. }
  2242. bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  2243. unsigned int firstChannel, unsigned int sampleRate,
  2244. RtAudioFormat format, unsigned int *bufferSize,
  2245. RtAudio::StreamOptions *options )
  2246. {
  2247. // For ASIO, a duplex stream MUST use the same driver.
  2248. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] != device ) {
  2249. errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
  2250. return FAILURE;
  2251. }
  2252. char driverName[32];
  2253. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2254. if ( result != ASE_OK ) {
  2255. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2256. errorText_ = errorStream_.str();
  2257. return FAILURE;
  2258. }
  2259. // The getDeviceInfo() function will not work when a stream is open
  2260. // because ASIO does not allow multiple devices to run at the same
  2261. // time. Thus, we'll probe the system before opening a stream and
  2262. // save the results for use by getDeviceInfo().
  2263. this->saveDeviceInfo();
  2264. // Only load the driver once for duplex stream.
  2265. if ( mode != INPUT || stream_.mode != OUTPUT ) {
  2266. if ( !drivers.loadDriver( driverName ) ) {
  2267. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
  2268. errorText_ = errorStream_.str();
  2269. return FAILURE;
  2270. }
  2271. result = ASIOInit( &driverInfo );
  2272. if ( result != ASE_OK ) {
  2273. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2274. errorText_ = errorStream_.str();
  2275. return FAILURE;
  2276. }
  2277. }
  2278. // Check the device channel count.
  2279. long inputChannels, outputChannels;
  2280. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2281. if ( result != ASE_OK ) {
  2282. drivers.removeCurrentDriver();
  2283. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2284. errorText_ = errorStream_.str();
  2285. return FAILURE;
  2286. }
  2287. if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
  2288. ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
  2289. drivers.removeCurrentDriver();
  2290. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
  2291. errorText_ = errorStream_.str();
  2292. return FAILURE;
  2293. }
  2294. stream_.nDeviceChannels[mode] = channels;
  2295. stream_.nUserChannels[mode] = channels;
  2296. stream_.channelOffset[mode] = firstChannel;
  2297. // Verify the sample rate is supported.
  2298. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  2299. if ( result != ASE_OK ) {
  2300. drivers.removeCurrentDriver();
  2301. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
  2302. errorText_ = errorStream_.str();
  2303. return FAILURE;
  2304. }
  2305. // Get the current sample rate
  2306. ASIOSampleRate currentRate;
  2307. result = ASIOGetSampleRate( &currentRate );
  2308. if ( result != ASE_OK ) {
  2309. drivers.removeCurrentDriver();
  2310. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
  2311. errorText_ = errorStream_.str();
  2312. return FAILURE;
  2313. }
  2314. // Set the sample rate only if necessary
  2315. if ( currentRate != sampleRate ) {
  2316. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  2317. if ( result != ASE_OK ) {
  2318. drivers.removeCurrentDriver();
  2319. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
  2320. errorText_ = errorStream_.str();
  2321. return FAILURE;
  2322. }
  2323. }
  2324. // Determine the driver data type.
  2325. ASIOChannelInfo channelInfo;
  2326. channelInfo.channel = 0;
  2327. if ( mode == OUTPUT ) channelInfo.isInput = false;
  2328. else channelInfo.isInput = true;
  2329. result = ASIOGetChannelInfo( &channelInfo );
  2330. if ( result != ASE_OK ) {
  2331. drivers.removeCurrentDriver();
  2332. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
  2333. errorText_ = errorStream_.str();
  2334. return FAILURE;
  2335. }
  2336. // Assuming WINDOWS host is always little-endian.
  2337. stream_.doByteSwap[mode] = false;
  2338. stream_.userFormat = format;
  2339. stream_.deviceFormat[mode] = 0;
  2340. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  2341. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  2342. if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
  2343. }
  2344. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  2345. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  2346. if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
  2347. }
  2348. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  2349. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2350. if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
  2351. }
  2352. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  2353. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  2354. if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
  2355. }
  2356. if ( stream_.deviceFormat[mode] == 0 ) {
  2357. drivers.removeCurrentDriver();
  2358. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
  2359. errorText_ = errorStream_.str();
  2360. return FAILURE;
  2361. }
  2362. // Set the buffer size. For a duplex stream, this will end up
  2363. // setting the buffer size based on the input constraints, which
  2364. // should be ok.
  2365. long minSize, maxSize, preferSize, granularity;
  2366. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  2367. if ( result != ASE_OK ) {
  2368. drivers.removeCurrentDriver();
  2369. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
  2370. errorText_ = errorStream_.str();
  2371. return FAILURE;
  2372. }
  2373. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2374. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2375. else if ( granularity == -1 ) {
  2376. // Make sure bufferSize is a power of two.
  2377. int log2_of_min_size = 0;
  2378. int log2_of_max_size = 0;
  2379. for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
  2380. if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
  2381. if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
  2382. }
  2383. long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
  2384. int min_delta_num = log2_of_min_size;
  2385. for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
  2386. long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
  2387. if (current_delta < min_delta) {
  2388. min_delta = current_delta;
  2389. min_delta_num = i;
  2390. }
  2391. }
  2392. *bufferSize = ( (unsigned int)1 << min_delta_num );
  2393. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2394. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2395. }
  2396. else if ( granularity != 0 ) {
  2397. // Set to an even multiple of granularity, rounding up.
  2398. *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
  2399. }
  2400. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.bufferSize != *bufferSize ) {
  2401. drivers.removeCurrentDriver();
  2402. errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
  2403. return FAILURE;
  2404. }
  2405. stream_.bufferSize = *bufferSize;
  2406. stream_.nBuffers = 2;
  2407. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2408. else stream_.userInterleaved = true;
  2409. // ASIO always uses non-interleaved buffers.
  2410. stream_.deviceInterleaved[mode] = false;
  2411. // Allocate, if necessary, our AsioHandle structure for the stream.
  2412. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2413. if ( handle == 0 ) {
  2414. try {
  2415. handle = new AsioHandle;
  2416. }
  2417. catch ( std::bad_alloc& ) {
  2418. //if ( handle == NULL ) {
  2419. drivers.removeCurrentDriver();
  2420. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
  2421. return FAILURE;
  2422. }
  2423. handle->bufferInfos = 0;
  2424. // Create a manual-reset event.
  2425. handle->condition = CreateEvent( NULL, // no security
  2426. TRUE, // manual-reset
  2427. FALSE, // non-signaled initially
  2428. NULL ); // unnamed
  2429. stream_.apiHandle = (void *) handle;
  2430. }
  2431. // Create the ASIO internal buffers. Since RtAudio sets up input
  2432. // and output separately, we'll have to dispose of previously
  2433. // created output buffers for a duplex stream.
  2434. long inputLatency, outputLatency;
  2435. if ( mode == INPUT && stream_.mode == OUTPUT ) {
  2436. ASIODisposeBuffers();
  2437. if ( handle->bufferInfos ) free( handle->bufferInfos );
  2438. }
  2439. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  2440. bool buffersAllocated = false;
  2441. unsigned int i, nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2442. handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  2443. if ( handle->bufferInfos == NULL ) {
  2444. errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
  2445. errorText_ = errorStream_.str();
  2446. goto error;
  2447. }
  2448. ASIOBufferInfo *infos;
  2449. infos = handle->bufferInfos;
  2450. for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
  2451. infos->isInput = ASIOFalse;
  2452. infos->channelNum = i + stream_.channelOffset[0];
  2453. infos->buffers[0] = infos->buffers[1] = 0;
  2454. }
  2455. for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
  2456. infos->isInput = ASIOTrue;
  2457. infos->channelNum = i + stream_.channelOffset[1];
  2458. infos->buffers[0] = infos->buffers[1] = 0;
  2459. }
  2460. // Set up the ASIO callback structure and create the ASIO data buffers.
  2461. asioCallbacks.bufferSwitch = &bufferSwitch;
  2462. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  2463. asioCallbacks.asioMessage = &asioMessages;
  2464. asioCallbacks.bufferSwitchTimeInfo = NULL;
  2465. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2466. if ( result != ASE_OK ) {
  2467. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
  2468. errorText_ = errorStream_.str();
  2469. goto error;
  2470. }
  2471. buffersAllocated = true;
  2472. // Set flags for buffer conversion.
  2473. stream_.doConvertBuffer[mode] = false;
  2474. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2475. stream_.doConvertBuffer[mode] = true;
  2476. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2477. stream_.nUserChannels[mode] > 1 )
  2478. stream_.doConvertBuffer[mode] = true;
  2479. // Allocate necessary internal buffers
  2480. unsigned long bufferBytes;
  2481. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2482. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2483. if ( stream_.userBuffer[mode] == NULL ) {
  2484. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
  2485. goto error;
  2486. }
  2487. if ( stream_.doConvertBuffer[mode] ) {
  2488. bool makeBuffer = true;
  2489. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  2490. if ( mode == INPUT ) {
  2491. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  2492. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2493. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  2494. }
  2495. }
  2496. if ( makeBuffer ) {
  2497. bufferBytes *= *bufferSize;
  2498. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2499. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2500. if ( stream_.deviceBuffer == NULL ) {
  2501. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
  2502. goto error;
  2503. }
  2504. }
  2505. }
  2506. stream_.sampleRate = sampleRate;
  2507. stream_.device[mode] = device;
  2508. stream_.state = STREAM_STOPPED;
  2509. asioCallbackInfo = &stream_.callbackInfo;
  2510. stream_.callbackInfo.object = (void *) this;
  2511. if ( stream_.mode == OUTPUT && mode == INPUT )
  2512. // We had already set up an output stream.
  2513. stream_.mode = DUPLEX;
  2514. else
  2515. stream_.mode = mode;
  2516. // Determine device latencies
  2517. result = ASIOGetLatencies( &inputLatency, &outputLatency );
  2518. if ( result != ASE_OK ) {
  2519. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
  2520. errorText_ = errorStream_.str();
  2521. error( RtError::WARNING); // warn but don't fail
  2522. }
  2523. else {
  2524. stream_.latency[0] = outputLatency;
  2525. stream_.latency[1] = inputLatency;
  2526. }
  2527. // Setup the buffer conversion information structure. We don't use
  2528. // buffers to do channel offsets, so we override that parameter
  2529. // here.
  2530. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2531. return SUCCESS;
  2532. error:
  2533. if ( buffersAllocated )
  2534. ASIODisposeBuffers();
  2535. drivers.removeCurrentDriver();
  2536. if ( handle ) {
  2537. CloseHandle( handle->condition );
  2538. if ( handle->bufferInfos )
  2539. free( handle->bufferInfos );
  2540. delete handle;
  2541. stream_.apiHandle = 0;
  2542. }
  2543. for ( int i=0; i<2; i++ ) {
  2544. if ( stream_.userBuffer[i] ) {
  2545. free( stream_.userBuffer[i] );
  2546. stream_.userBuffer[i] = 0;
  2547. }
  2548. }
  2549. if ( stream_.deviceBuffer ) {
  2550. free( stream_.deviceBuffer );
  2551. stream_.deviceBuffer = 0;
  2552. }
  2553. return FAILURE;
  2554. }
  2555. void RtApiAsio :: closeStream()
  2556. {
  2557. if ( stream_.state == STREAM_CLOSED ) {
  2558. errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
  2559. error( RtError::WARNING );
  2560. return;
  2561. }
  2562. if ( stream_.state == STREAM_RUNNING ) {
  2563. stream_.state = STREAM_STOPPED;
  2564. ASIOStop();
  2565. }
  2566. ASIODisposeBuffers();
  2567. drivers.removeCurrentDriver();
  2568. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2569. if ( handle ) {
  2570. CloseHandle( handle->condition );
  2571. if ( handle->bufferInfos )
  2572. free( handle->bufferInfos );
  2573. delete handle;
  2574. stream_.apiHandle = 0;
  2575. }
  2576. for ( int i=0; i<2; i++ ) {
  2577. if ( stream_.userBuffer[i] ) {
  2578. free( stream_.userBuffer[i] );
  2579. stream_.userBuffer[i] = 0;
  2580. }
  2581. }
  2582. if ( stream_.deviceBuffer ) {
  2583. free( stream_.deviceBuffer );
  2584. stream_.deviceBuffer = 0;
  2585. }
  2586. stream_.mode = UNINITIALIZED;
  2587. stream_.state = STREAM_CLOSED;
  2588. }
  2589. void RtApiAsio :: startStream()
  2590. {
  2591. verifyStream();
  2592. if ( stream_.state == STREAM_RUNNING ) {
  2593. errorText_ = "RtApiAsio::startStream(): the stream is already running!";
  2594. error( RtError::WARNING );
  2595. return;
  2596. }
  2597. MUTEX_LOCK( &stream_.mutex );
  2598. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2599. ASIOError result = ASIOStart();
  2600. if ( result != ASE_OK ) {
  2601. errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
  2602. errorText_ = errorStream_.str();
  2603. goto unlock;
  2604. }
  2605. handle->drainCounter = 0;
  2606. handle->internalDrain = false;
  2607. stream_.state = STREAM_RUNNING;
  2608. asioXRun = false;
  2609. unlock:
  2610. MUTEX_UNLOCK( &stream_.mutex );
  2611. if ( result == ASE_OK ) return;
  2612. error( RtError::SYSTEM_ERROR );
  2613. }
  2614. void RtApiAsio :: stopStream()
  2615. {
  2616. verifyStream();
  2617. if ( stream_.state == STREAM_STOPPED ) {
  2618. errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
  2619. error( RtError::WARNING );
  2620. return;
  2621. }
  2622. MUTEX_LOCK( &stream_.mutex );
  2623. if ( stream_.state == STREAM_STOPPED ) {
  2624. MUTEX_UNLOCK( &stream_.mutex );
  2625. return;
  2626. }
  2627. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2628. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2629. if ( handle->drainCounter == 0 ) {
  2630. handle->drainCounter = 1;
  2631. MUTEX_UNLOCK( &stream_.mutex );
  2632. WaitForMultipleObjects( 1, &handle->condition, FALSE, INFINITE ); // block until signaled
  2633. ResetEvent( handle->condition );
  2634. MUTEX_LOCK( &stream_.mutex );
  2635. }
  2636. }
  2637. ASIOError result = ASIOStop();
  2638. if ( result != ASE_OK ) {
  2639. errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
  2640. errorText_ = errorStream_.str();
  2641. }
  2642. stream_.state = STREAM_STOPPED;
  2643. MUTEX_UNLOCK( &stream_.mutex );
  2644. if ( result == ASE_OK ) return;
  2645. error( RtError::SYSTEM_ERROR );
  2646. }
  2647. void RtApiAsio :: abortStream()
  2648. {
  2649. verifyStream();
  2650. if ( stream_.state == STREAM_STOPPED ) {
  2651. errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
  2652. error( RtError::WARNING );
  2653. return;
  2654. }
  2655. // The following lines were commented-out because some behavior was
  2656. // noted where the device buffers need to be zeroed to avoid
  2657. // continuing sound, even when the device buffers are completely
  2658. // disposed. So now, calling abort is the same as calling stop.
  2659. // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2660. // handle->drainCounter = 1;
  2661. stopStream();
  2662. }
  2663. bool RtApiAsio :: callbackEvent( long bufferIndex )
  2664. {
  2665. if ( stream_.state == STREAM_STOPPED ) return SUCCESS;
  2666. if ( stream_.state == STREAM_CLOSED ) {
  2667. errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2668. error( RtError::WARNING );
  2669. return FAILURE;
  2670. }
  2671. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2672. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2673. // Check if we were draining the stream and signal is finished.
  2674. if ( handle->drainCounter > 3 ) {
  2675. if ( handle->internalDrain == false )
  2676. SetEvent( handle->condition );
  2677. else
  2678. stopStream();
  2679. return SUCCESS;
  2680. }
  2681. MUTEX_LOCK( &stream_.mutex );
  2682. // The state might change while waiting on a mutex.
  2683. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  2684. // Invoke user callback to get fresh output data UNLESS we are
  2685. // draining stream.
  2686. if ( handle->drainCounter == 0 ) {
  2687. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2688. double streamTime = getStreamTime();
  2689. RtAudioStreamStatus status = 0;
  2690. if ( stream_.mode != INPUT && asioXRun == true ) {
  2691. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2692. asioXRun = false;
  2693. }
  2694. if ( stream_.mode != OUTPUT && asioXRun == true ) {
  2695. status |= RTAUDIO_INPUT_OVERFLOW;
  2696. asioXRun = false;
  2697. }
  2698. handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2699. stream_.bufferSize, streamTime, status, info->userData );
  2700. if ( handle->drainCounter == 2 ) {
  2701. MUTEX_UNLOCK( &stream_.mutex );
  2702. abortStream();
  2703. return SUCCESS;
  2704. }
  2705. else if ( handle->drainCounter == 1 )
  2706. handle->internalDrain = true;
  2707. }
  2708. unsigned int nChannels, bufferBytes, i, j;
  2709. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2710. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2711. bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
  2712. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2713. for ( i=0, j=0; i<nChannels; i++ ) {
  2714. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2715. memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
  2716. }
  2717. }
  2718. else if ( stream_.doConvertBuffer[0] ) {
  2719. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2720. if ( stream_.doByteSwap[0] )
  2721. byteSwapBuffer( stream_.deviceBuffer,
  2722. stream_.bufferSize * stream_.nDeviceChannels[0],
  2723. stream_.deviceFormat[0] );
  2724. for ( i=0, j=0; i<nChannels; i++ ) {
  2725. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2726. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2727. &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
  2728. }
  2729. }
  2730. else {
  2731. if ( stream_.doByteSwap[0] )
  2732. byteSwapBuffer( stream_.userBuffer[0],
  2733. stream_.bufferSize * stream_.nUserChannels[0],
  2734. stream_.userFormat );
  2735. for ( i=0, j=0; i<nChannels; i++ ) {
  2736. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2737. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2738. &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
  2739. }
  2740. }
  2741. if ( handle->drainCounter ) {
  2742. handle->drainCounter++;
  2743. goto unlock;
  2744. }
  2745. }
  2746. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2747. bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
  2748. if (stream_.doConvertBuffer[1]) {
  2749. // Always interleave ASIO input data.
  2750. for ( i=0, j=0; i<nChannels; i++ ) {
  2751. if ( handle->bufferInfos[i].isInput == ASIOTrue )
  2752. memcpy( &stream_.deviceBuffer[j++*bufferBytes],
  2753. handle->bufferInfos[i].buffers[bufferIndex],
  2754. bufferBytes );
  2755. }
  2756. if ( stream_.doByteSwap[1] )
  2757. byteSwapBuffer( stream_.deviceBuffer,
  2758. stream_.bufferSize * stream_.nDeviceChannels[1],
  2759. stream_.deviceFormat[1] );
  2760. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2761. }
  2762. else {
  2763. for ( i=0, j=0; i<nChannels; i++ ) {
  2764. if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
  2765. memcpy( &stream_.userBuffer[1][bufferBytes*j++],
  2766. handle->bufferInfos[i].buffers[bufferIndex],
  2767. bufferBytes );
  2768. }
  2769. }
  2770. if ( stream_.doByteSwap[1] )
  2771. byteSwapBuffer( stream_.userBuffer[1],
  2772. stream_.bufferSize * stream_.nUserChannels[1],
  2773. stream_.userFormat );
  2774. }
  2775. }
  2776. unlock:
  2777. // The following call was suggested by Malte Clasen. While the API
  2778. // documentation indicates it should not be required, some device
  2779. // drivers apparently do not function correctly without it.
  2780. ASIOOutputReady();
  2781. MUTEX_UNLOCK( &stream_.mutex );
  2782. RtApi::tickStreamTime();
  2783. return SUCCESS;
  2784. }
  2785. void sampleRateChanged( ASIOSampleRate sRate )
  2786. {
  2787. // The ASIO documentation says that this usually only happens during
  2788. // external sync. Audio processing is not stopped by the driver,
  2789. // actual sample rate might not have even changed, maybe only the
  2790. // sample rate status of an AES/EBU or S/PDIF digital input at the
  2791. // audio device.
  2792. RtApi *object = (RtApi *) asioCallbackInfo->object;
  2793. try {
  2794. object->stopStream();
  2795. }
  2796. catch ( RtError &exception ) {
  2797. std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
  2798. return;
  2799. }
  2800. std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
  2801. }
  2802. long asioMessages( long selector, long value, void* message, double* opt )
  2803. {
  2804. long ret = 0;
  2805. switch( selector ) {
  2806. case kAsioSelectorSupported:
  2807. if ( value == kAsioResetRequest
  2808. || value == kAsioEngineVersion
  2809. || value == kAsioResyncRequest
  2810. || value == kAsioLatenciesChanged
  2811. // The following three were added for ASIO 2.0, you don't
  2812. // necessarily have to support them.
  2813. || value == kAsioSupportsTimeInfo
  2814. || value == kAsioSupportsTimeCode
  2815. || value == kAsioSupportsInputMonitor)
  2816. ret = 1L;
  2817. break;
  2818. case kAsioResetRequest:
  2819. // Defer the task and perform the reset of the driver during the
  2820. // next "safe" situation. You cannot reset the driver right now,
  2821. // as this code is called from the driver. Reset the driver is
  2822. // done by completely destruct is. I.e. ASIOStop(),
  2823. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  2824. // driver again.
  2825. std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
  2826. ret = 1L;
  2827. break;
  2828. case kAsioResyncRequest:
  2829. // This informs the application that the driver encountered some
  2830. // non-fatal data loss. It is used for synchronization purposes
  2831. // of different media. Added mainly to work around the Win16Mutex
  2832. // problems in Windows 95/98 with the Windows Multimedia system,
  2833. // which could lose data because the Mutex was held too long by
  2834. // another thread. However a driver can issue it in other
  2835. // situations, too.
  2836. // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
  2837. asioXRun = true;
  2838. ret = 1L;
  2839. break;
  2840. case kAsioLatenciesChanged:
  2841. // This will inform the host application that the drivers were
  2842. // latencies changed. Beware, it this does not mean that the
  2843. // buffer sizes have changed! You might need to update internal
  2844. // delay data.
  2845. std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
  2846. ret = 1L;
  2847. break;
  2848. case kAsioEngineVersion:
  2849. // Return the supported ASIO version of the host application. If
  2850. // a host application does not implement this selector, ASIO 1.0
  2851. // is assumed by the driver.
  2852. ret = 2L;
  2853. break;
  2854. case kAsioSupportsTimeInfo:
  2855. // Informs the driver whether the
  2856. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  2857. // For compatibility with ASIO 1.0 drivers the host application
  2858. // should always support the "old" bufferSwitch method, too.
  2859. ret = 0;
  2860. break;
  2861. case kAsioSupportsTimeCode:
  2862. // Informs the driver whether application is interested in time
  2863. // code info. If an application does not need to know about time
  2864. // code, the driver has less work to do.
  2865. ret = 0;
  2866. break;
  2867. }
  2868. return ret;
  2869. }
  2870. static const char* getAsioErrorString( ASIOError result )
  2871. {
  2872. struct Messages
  2873. {
  2874. ASIOError value;
  2875. const char*message;
  2876. };
  2877. static Messages m[] =
  2878. {
  2879. { ASE_NotPresent, "Hardware input or output is not present or available." },
  2880. { ASE_HWMalfunction, "Hardware is malfunctioning." },
  2881. { ASE_InvalidParameter, "Invalid input parameter." },
  2882. { ASE_InvalidMode, "Invalid mode." },
  2883. { ASE_SPNotAdvancing, "Sample position not advancing." },
  2884. { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
  2885. { ASE_NoMemory, "Not enough memory to complete the request." }
  2886. };
  2887. for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
  2888. if ( m[i].value == result ) return m[i].message;
  2889. return "Unknown error.";
  2890. }
  2891. //******************** End of __WINDOWS_ASIO__ *********************//
  2892. #endif
  2893. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  2894. // Modified by Robin Davies, October 2005
  2895. // - Improvements to DirectX pointer chasing.
  2896. // - Backdoor RtDsStatistics hook provides DirectX performance information.
  2897. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  2898. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  2899. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  2900. #include <dsound.h>
  2901. #include <assert.h>
  2902. #if defined(__MINGW32__)
  2903. // missing from latest mingw winapi
  2904. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  2905. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  2906. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  2907. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  2908. #endif
  2909. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  2910. #ifdef _MSC_VER // if Microsoft Visual C++
  2911. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  2912. #endif
  2913. static inline DWORD dsPointerDifference( DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  2914. {
  2915. if ( laterPointer > earlierPointer )
  2916. return laterPointer - earlierPointer;
  2917. else
  2918. return laterPointer - earlierPointer + bufferSize;
  2919. }
  2920. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  2921. {
  2922. if ( pointer > bufferSize ) pointer -= bufferSize;
  2923. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  2924. if ( pointer < earlierPointer ) pointer += bufferSize;
  2925. return pointer >= earlierPointer && pointer < laterPointer;
  2926. }
  2927. // A structure to hold various information related to the DirectSound
  2928. // API implementation.
  2929. struct DsHandle {
  2930. unsigned int drainCounter; // Tracks callback counts when draining
  2931. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2932. void *id[2];
  2933. void *buffer[2];
  2934. bool xrun[2];
  2935. UINT bufferPointer[2];
  2936. DWORD dsBufferSize[2];
  2937. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  2938. HANDLE condition;
  2939. DsHandle()
  2940. :drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; }
  2941. };
  2942. /*
  2943. RtApiDs::RtDsStatistics RtApiDs::statistics;
  2944. // Provides a backdoor hook to monitor for DirectSound read overruns and write underruns.
  2945. RtApiDs::RtDsStatistics RtApiDs::getDsStatistics()
  2946. {
  2947. RtDsStatistics s = statistics;
  2948. // update the calculated fields.
  2949. if ( s.inputFrameSize != 0 )
  2950. s.latency += s.readDeviceSafeLeadBytes * 1.0 / s.inputFrameSize / s.sampleRate;
  2951. if ( s.outputFrameSize != 0 )
  2952. s.latency += (s.writeDeviceSafeLeadBytes + s.writeDeviceBufferLeadBytes) * 1.0 / s.outputFrameSize / s.sampleRate;
  2953. return s;
  2954. }
  2955. */
  2956. // Declarations for utility functions, callbacks, and structures
  2957. // specific to the DirectSound implementation.
  2958. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  2959. LPCTSTR description,
  2960. LPCTSTR module,
  2961. LPVOID lpContext );
  2962. static char* getErrorString( int code );
  2963. extern "C" unsigned __stdcall callbackHandler( void *ptr );
  2964. struct EnumInfo {
  2965. bool isInput;
  2966. bool getDefault;
  2967. bool findIndex;
  2968. unsigned int counter;
  2969. unsigned int index;
  2970. LPGUID id;
  2971. std::string name;
  2972. EnumInfo()
  2973. : isInput(false), getDefault(false), findIndex(false), counter(0), index(0) {}
  2974. };
  2975. RtApiDs :: RtApiDs()
  2976. {
  2977. // Dsound will run both-threaded. If CoInitialize fails, then just
  2978. // accept whatever the mainline chose for a threading model.
  2979. coInitialized_ = false;
  2980. HRESULT hr = CoInitialize( NULL );
  2981. if ( !FAILED( hr ) ) coInitialized_ = true;
  2982. }
  2983. RtApiDs :: ~RtApiDs()
  2984. {
  2985. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  2986. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2987. }
  2988. unsigned int RtApiDs :: getDefaultInputDevice( void )
  2989. {
  2990. // Count output devices.
  2991. EnumInfo info;
  2992. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
  2993. if ( FAILED( result ) ) {
  2994. errorStream_ << "RtApiDs::getDefaultOutputDevice: error (" << getErrorString( result ) << ") counting output devices!";
  2995. errorText_ = errorStream_.str();
  2996. error( RtError::WARNING );
  2997. return 0;
  2998. }
  2999. // Now enumerate input devices until we find the id = NULL.
  3000. info.isInput = true;
  3001. info.getDefault = true;
  3002. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
  3003. if ( FAILED( result ) ) {
  3004. errorStream_ << "RtApiDs::getDefaultInputDevice: error (" << getErrorString( result ) << ") enumerating input devices!";
  3005. errorText_ = errorStream_.str();
  3006. error( RtError::WARNING );
  3007. return 0;
  3008. }
  3009. if ( info.counter > 0 ) return info.counter - 1;
  3010. return 0;
  3011. }
  3012. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  3013. {
  3014. // Enumerate output devices until we find the id = NULL.
  3015. EnumInfo info;
  3016. info.getDefault = true;
  3017. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
  3018. if ( FAILED( result ) ) {
  3019. errorStream_ << "RtApiDs::getDefaultOutputDevice: error (" << getErrorString( result ) << ") enumerating output devices!";
  3020. errorText_ = errorStream_.str();
  3021. error( RtError::WARNING );
  3022. return 0;
  3023. }
  3024. if ( info.counter > 0 ) return info.counter - 1;
  3025. return 0;
  3026. }
  3027. unsigned int RtApiDs :: getDeviceCount( void )
  3028. {
  3029. // Count DirectSound devices.
  3030. EnumInfo info;
  3031. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
  3032. if ( FAILED( result ) ) {
  3033. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  3034. errorText_ = errorStream_.str();
  3035. error( RtError::WARNING );
  3036. }
  3037. // Count DirectSoundCapture devices.
  3038. info.isInput = true;
  3039. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
  3040. if ( FAILED( result ) ) {
  3041. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  3042. errorText_ = errorStream_.str();
  3043. error( RtError::WARNING );
  3044. }
  3045. return info.counter;
  3046. }
  3047. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  3048. {
  3049. // Because DirectSound always enumerates input and output devices
  3050. // separately (and because we don't attempt to combine devices
  3051. // internally), none of our "devices" will ever be duplex.
  3052. RtAudio::DeviceInfo info;
  3053. info.probed = false;
  3054. // Enumerate through devices to find the id (if it exists). Note
  3055. // that we have to do the output enumeration first, even if this is
  3056. // an input device, in order for the device counter to be correct.
  3057. EnumInfo dsinfo;
  3058. dsinfo.findIndex = true;
  3059. dsinfo.index = device;
  3060. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
  3061. if ( FAILED( result ) ) {
  3062. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") enumerating output devices!";
  3063. errorText_ = errorStream_.str();
  3064. error( RtError::WARNING );
  3065. }
  3066. if ( dsinfo.name.empty() ) goto probeInput;
  3067. LPDIRECTSOUND output;
  3068. DSCAPS outCaps;
  3069. result = DirectSoundCreate( dsinfo.id, &output, NULL );
  3070. if ( FAILED( result ) ) {
  3071. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsinfo.name << ")!";
  3072. errorText_ = errorStream_.str();
  3073. error( RtError::WARNING );
  3074. return info;
  3075. }
  3076. outCaps.dwSize = sizeof( outCaps );
  3077. result = output->GetCaps( &outCaps );
  3078. if ( FAILED( result ) ) {
  3079. output->Release();
  3080. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  3081. errorText_ = errorStream_.str();
  3082. error( RtError::WARNING );
  3083. return info;
  3084. }
  3085. // Get output channel information.
  3086. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  3087. // Get sample rate information.
  3088. info.sampleRates.clear();
  3089. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  3090. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  3091. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate )
  3092. info.sampleRates.push_back( SAMPLE_RATES[k] );
  3093. }
  3094. // Get format information.
  3095. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  3096. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  3097. output->Release();
  3098. if ( getDefaultOutputDevice() == device )
  3099. info.isDefaultOutput = true;
  3100. // Copy name and return.
  3101. info.name = dsinfo.name;
  3102. info.probed = true;
  3103. return info;
  3104. probeInput:
  3105. dsinfo.isInput = true;
  3106. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
  3107. if ( FAILED( result ) ) {
  3108. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") enumerating input devices!";
  3109. errorText_ = errorStream_.str();
  3110. error( RtError::WARNING );
  3111. }
  3112. if ( dsinfo.name.empty() ) return info;
  3113. LPDIRECTSOUNDCAPTURE input;
  3114. result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
  3115. if ( FAILED( result ) ) {
  3116. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsinfo.name << ")!";
  3117. errorText_ = errorStream_.str();
  3118. error( RtError::WARNING );
  3119. return info;
  3120. }
  3121. DSCCAPS inCaps;
  3122. inCaps.dwSize = sizeof( inCaps );
  3123. result = input->GetCaps( &inCaps );
  3124. if ( FAILED( result ) ) {
  3125. input->Release();
  3126. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsinfo.name << ")!";
  3127. errorText_ = errorStream_.str();
  3128. error( RtError::WARNING );
  3129. return info;
  3130. }
  3131. // Get input channel information.
  3132. info.inputChannels = inCaps.dwChannels;
  3133. // Get sample rate and format information.
  3134. if ( inCaps.dwChannels == 2 ) {
  3135. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3136. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3137. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3138. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3139. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3140. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3141. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3142. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3143. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  3144. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.sampleRates.push_back( 11025 );
  3145. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.sampleRates.push_back( 22050 );
  3146. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.sampleRates.push_back( 44100 );
  3147. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.sampleRates.push_back( 96000 );
  3148. }
  3149. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  3150. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.sampleRates.push_back( 11025 );
  3151. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.sampleRates.push_back( 22050 );
  3152. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.sampleRates.push_back( 44100 );
  3153. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.sampleRates.push_back( 44100 );
  3154. }
  3155. }
  3156. else if ( inCaps.dwChannels == 1 ) {
  3157. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3158. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3159. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3160. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  3161. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3162. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3163. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3164. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  3165. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  3166. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.sampleRates.push_back( 11025 );
  3167. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.sampleRates.push_back( 22050 );
  3168. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.sampleRates.push_back( 44100 );
  3169. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.sampleRates.push_back( 96000 );
  3170. }
  3171. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  3172. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.sampleRates.push_back( 11025 );
  3173. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.sampleRates.push_back( 22050 );
  3174. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.sampleRates.push_back( 44100 );
  3175. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.sampleRates.push_back( 96000 );
  3176. }
  3177. }
  3178. else info.inputChannels = 0; // technically, this would be an error
  3179. input->Release();
  3180. if ( info.inputChannels == 0 ) return info;
  3181. if ( getDefaultInputDevice() == device )
  3182. info.isDefaultInput = true;
  3183. // Copy name and return.
  3184. info.name = dsinfo.name;
  3185. info.probed = true;
  3186. return info;
  3187. }
  3188. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3189. unsigned int firstChannel, unsigned int sampleRate,
  3190. RtAudioFormat format, unsigned int *bufferSize,
  3191. RtAudio::StreamOptions *options )
  3192. {
  3193. if ( channels + firstChannel > 2 ) {
  3194. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  3195. return FAILURE;
  3196. }
  3197. // Enumerate through devices to find the id (if it exists). Note
  3198. // that we have to do the output enumeration first, even if this is
  3199. // an input device, in order for the device counter to be correct.
  3200. EnumInfo dsinfo;
  3201. dsinfo.findIndex = true;
  3202. dsinfo.index = device;
  3203. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
  3204. if ( FAILED( result ) ) {
  3205. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") enumerating output devices!";
  3206. errorText_ = errorStream_.str();
  3207. return FAILURE;
  3208. }
  3209. if ( mode == OUTPUT ) {
  3210. if ( dsinfo.name.empty() ) {
  3211. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  3212. errorText_ = errorStream_.str();
  3213. return FAILURE;
  3214. }
  3215. }
  3216. else { // mode == INPUT
  3217. dsinfo.isInput = true;
  3218. HRESULT result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
  3219. if ( FAILED( result ) ) {
  3220. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") enumerating input devices!";
  3221. errorText_ = errorStream_.str();
  3222. return FAILURE;
  3223. }
  3224. if ( dsinfo.name.empty() ) {
  3225. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  3226. errorText_ = errorStream_.str();
  3227. return FAILURE;
  3228. }
  3229. }
  3230. // According to a note in PortAudio, using GetDesktopWindow()
  3231. // instead of GetForegroundWindow() is supposed to avoid problems
  3232. // that occur when the application's window is not the foreground
  3233. // window. Also, if the application window closes before the
  3234. // DirectSound buffer, DirectSound can crash. However, for console
  3235. // applications, no sound was produced when using GetDesktopWindow().
  3236. HWND hWnd = GetForegroundWindow();
  3237. // Check the numberOfBuffers parameter and limit the lowest value to
  3238. // two. This is a judgement call and a value of two is probably too
  3239. // low for capture, but it should work for playback.
  3240. int nBuffers = 0;
  3241. if ( options ) nBuffers = options->numberOfBuffers;
  3242. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  3243. if ( nBuffers < 2 ) nBuffers = 3;
  3244. // Create the wave format structure. The data format setting will
  3245. // be determined later.
  3246. WAVEFORMATEX waveFormat;
  3247. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  3248. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  3249. waveFormat.nChannels = channels + firstChannel;
  3250. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  3251. // Determine the device buffer size. By default, 32k, but we will
  3252. // grow it to make allowances for very large software buffer sizes.
  3253. DWORD dsBufferSize = 0;
  3254. DWORD dsPointerLeadTime = 0;
  3255. long bufferBytes = MINIMUM_DEVICE_BUFFER_SIZE; // sound cards will always *knock wood* support this
  3256. void *ohandle = 0, *bhandle = 0;
  3257. if ( mode == OUTPUT ) {
  3258. LPDIRECTSOUND output;
  3259. result = DirectSoundCreate( dsinfo.id, &output, NULL );
  3260. if ( FAILED( result ) ) {
  3261. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsinfo.name << ")!";
  3262. errorText_ = errorStream_.str();
  3263. return FAILURE;
  3264. }
  3265. DSCAPS outCaps;
  3266. outCaps.dwSize = sizeof( outCaps );
  3267. result = output->GetCaps( &outCaps );
  3268. if ( FAILED( result ) ) {
  3269. output->Release();
  3270. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsinfo.name << ")!";
  3271. errorText_ = errorStream_.str();
  3272. return FAILURE;
  3273. }
  3274. // Check channel information.
  3275. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  3276. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsinfo.name << ") does not support stereo playback.";
  3277. errorText_ = errorStream_.str();
  3278. return FAILURE;
  3279. }
  3280. // Check format information. Use 16-bit format unless not
  3281. // supported or user requests 8-bit.
  3282. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  3283. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  3284. waveFormat.wBitsPerSample = 16;
  3285. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  3286. }
  3287. else {
  3288. waveFormat.wBitsPerSample = 8;
  3289. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  3290. }
  3291. stream_.userFormat = format;
  3292. // Update wave format structure and buffer information.
  3293. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  3294. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  3295. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  3296. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  3297. while ( dsPointerLeadTime * 2U > (DWORD) bufferBytes )
  3298. bufferBytes *= 2;
  3299. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  3300. //result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  3301. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  3302. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  3303. if ( FAILED( result ) ) {
  3304. output->Release();
  3305. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsinfo.name << ")!";
  3306. errorText_ = errorStream_.str();
  3307. return FAILURE;
  3308. }
  3309. // Even though we will write to the secondary buffer, we need to
  3310. // access the primary buffer to set the correct output format
  3311. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  3312. // buffer description.
  3313. DSBUFFERDESC bufferDescription;
  3314. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  3315. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  3316. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  3317. // Obtain the primary buffer
  3318. LPDIRECTSOUNDBUFFER buffer;
  3319. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  3320. if ( FAILED( result ) ) {
  3321. output->Release();
  3322. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsinfo.name << ")!";
  3323. errorText_ = errorStream_.str();
  3324. return FAILURE;
  3325. }
  3326. // Set the primary DS buffer sound format.
  3327. result = buffer->SetFormat( &waveFormat );
  3328. if ( FAILED( result ) ) {
  3329. output->Release();
  3330. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsinfo.name << ")!";
  3331. errorText_ = errorStream_.str();
  3332. return FAILURE;
  3333. }
  3334. // Setup the secondary DS buffer description.
  3335. dsBufferSize = (DWORD) bufferBytes;
  3336. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  3337. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  3338. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  3339. DSBCAPS_GLOBALFOCUS |
  3340. DSBCAPS_GETCURRENTPOSITION2 |
  3341. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  3342. bufferDescription.dwBufferBytes = bufferBytes;
  3343. bufferDescription.lpwfxFormat = &waveFormat;
  3344. // Try to create the secondary DS buffer. If that doesn't work,
  3345. // try to use software mixing. Otherwise, there's a problem.
  3346. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  3347. if ( FAILED( result ) ) {
  3348. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  3349. DSBCAPS_GLOBALFOCUS |
  3350. DSBCAPS_GETCURRENTPOSITION2 |
  3351. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  3352. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  3353. if ( FAILED( result ) ) {
  3354. output->Release();
  3355. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsinfo.name << ")!";
  3356. errorText_ = errorStream_.str();
  3357. return FAILURE;
  3358. }
  3359. }
  3360. // Get the buffer size ... might be different from what we specified.
  3361. DSBCAPS dsbcaps;
  3362. dsbcaps.dwSize = sizeof( DSBCAPS );
  3363. result = buffer->GetCaps( &dsbcaps );
  3364. if ( FAILED( result ) ) {
  3365. output->Release();
  3366. buffer->Release();
  3367. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsinfo.name << ")!";
  3368. errorText_ = errorStream_.str();
  3369. return FAILURE;
  3370. }
  3371. bufferBytes = dsbcaps.dwBufferBytes;
  3372. // Lock the DS buffer
  3373. LPVOID audioPtr;
  3374. DWORD dataLen;
  3375. result = buffer->Lock( 0, bufferBytes, &audioPtr, &dataLen, NULL, NULL, 0 );
  3376. if ( FAILED( result ) ) {
  3377. output->Release();
  3378. buffer->Release();
  3379. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsinfo.name << ")!";
  3380. errorText_ = errorStream_.str();
  3381. return FAILURE;
  3382. }
  3383. // Zero the DS buffer
  3384. ZeroMemory( audioPtr, dataLen );
  3385. // Unlock the DS buffer
  3386. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  3387. if ( FAILED( result ) ) {
  3388. output->Release();
  3389. buffer->Release();
  3390. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsinfo.name << ")!";
  3391. errorText_ = errorStream_.str();
  3392. return FAILURE;
  3393. }
  3394. dsBufferSize = bufferBytes;
  3395. ohandle = (void *) output;
  3396. bhandle = (void *) buffer;
  3397. }
  3398. if ( mode == INPUT ) {
  3399. LPDIRECTSOUNDCAPTURE input;
  3400. result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
  3401. if ( FAILED( result ) ) {
  3402. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsinfo.name << ")!";
  3403. errorText_ = errorStream_.str();
  3404. return FAILURE;
  3405. }
  3406. DSCCAPS inCaps;
  3407. inCaps.dwSize = sizeof( inCaps );
  3408. result = input->GetCaps( &inCaps );
  3409. if ( FAILED( result ) ) {
  3410. input->Release();
  3411. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsinfo.name << ")!";
  3412. errorText_ = errorStream_.str();
  3413. return FAILURE;
  3414. }
  3415. // Check channel information.
  3416. if ( inCaps.dwChannels < channels + firstChannel ) {
  3417. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  3418. return FAILURE;
  3419. }
  3420. // Check format information. Use 16-bit format unless user
  3421. // requests 8-bit.
  3422. DWORD deviceFormats;
  3423. if ( channels + firstChannel == 2 ) {
  3424. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  3425. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  3426. waveFormat.wBitsPerSample = 8;
  3427. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  3428. }
  3429. else { // assume 16-bit is supported
  3430. waveFormat.wBitsPerSample = 16;
  3431. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  3432. }
  3433. }
  3434. else { // channel == 1
  3435. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  3436. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  3437. waveFormat.wBitsPerSample = 8;
  3438. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  3439. }
  3440. else { // assume 16-bit is supported
  3441. waveFormat.wBitsPerSample = 16;
  3442. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  3443. }
  3444. }
  3445. stream_.userFormat = format;
  3446. // Update wave format structure and buffer information.
  3447. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  3448. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  3449. // Setup the secondary DS buffer description.
  3450. dsBufferSize = bufferBytes;
  3451. DSCBUFFERDESC bufferDescription;
  3452. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  3453. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  3454. bufferDescription.dwFlags = 0;
  3455. bufferDescription.dwReserved = 0;
  3456. bufferDescription.dwBufferBytes = bufferBytes;
  3457. bufferDescription.lpwfxFormat = &waveFormat;
  3458. // Create the capture buffer.
  3459. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  3460. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  3461. if ( FAILED( result ) ) {
  3462. input->Release();
  3463. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsinfo.name << ")!";
  3464. errorText_ = errorStream_.str();
  3465. return FAILURE;
  3466. }
  3467. // Lock the capture buffer
  3468. LPVOID audioPtr;
  3469. DWORD dataLen;
  3470. result = buffer->Lock( 0, bufferBytes, &audioPtr, &dataLen, NULL, NULL, 0 );
  3471. if ( FAILED( result ) ) {
  3472. input->Release();
  3473. buffer->Release();
  3474. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsinfo.name << ")!";
  3475. errorText_ = errorStream_.str();
  3476. return FAILURE;
  3477. }
  3478. // Zero the buffer
  3479. ZeroMemory( audioPtr, dataLen );
  3480. // Unlock the buffer
  3481. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  3482. if ( FAILED( result ) ) {
  3483. input->Release();
  3484. buffer->Release();
  3485. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsinfo.name << ")!";
  3486. errorText_ = errorStream_.str();
  3487. return FAILURE;
  3488. }
  3489. dsBufferSize = bufferBytes;
  3490. ohandle = (void *) input;
  3491. bhandle = (void *) buffer;
  3492. }
  3493. // Set various stream parameters
  3494. DsHandle *handle = 0;
  3495. stream_.nDeviceChannels[mode] = channels + firstChannel;
  3496. stream_.nUserChannels[mode] = channels;
  3497. stream_.bufferSize = *bufferSize;
  3498. stream_.channelOffset[mode] = firstChannel;
  3499. stream_.deviceInterleaved[mode] = true;
  3500. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  3501. else stream_.userInterleaved = true;
  3502. // Set flag for buffer conversion
  3503. stream_.doConvertBuffer[mode] = false;
  3504. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  3505. stream_.doConvertBuffer[mode] = true;
  3506. if (stream_.userFormat != stream_.deviceFormat[mode])
  3507. stream_.doConvertBuffer[mode] = true;
  3508. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  3509. stream_.nUserChannels[mode] > 1 )
  3510. stream_.doConvertBuffer[mode] = true;
  3511. // Allocate necessary internal buffers
  3512. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  3513. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  3514. if ( stream_.userBuffer[mode] == NULL ) {
  3515. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  3516. goto error;
  3517. }
  3518. if ( stream_.doConvertBuffer[mode] ) {
  3519. bool makeBuffer = true;
  3520. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  3521. if ( mode == INPUT ) {
  3522. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  3523. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  3524. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  3525. }
  3526. }
  3527. if ( makeBuffer ) {
  3528. bufferBytes *= *bufferSize;
  3529. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  3530. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  3531. if ( stream_.deviceBuffer == NULL ) {
  3532. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  3533. goto error;
  3534. }
  3535. }
  3536. }
  3537. // Allocate our DsHandle structures for the stream.
  3538. if ( stream_.apiHandle == 0 ) {
  3539. try {
  3540. handle = new DsHandle;
  3541. }
  3542. catch ( std::bad_alloc& ) {
  3543. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  3544. goto error;
  3545. }
  3546. // Create a manual-reset event.
  3547. handle->condition = CreateEvent( NULL, // no security
  3548. TRUE, // manual-reset
  3549. FALSE, // non-signaled initially
  3550. NULL ); // unnamed
  3551. stream_.apiHandle = (void *) handle;
  3552. }
  3553. else
  3554. handle = (DsHandle *) stream_.apiHandle;
  3555. handle->id[mode] = ohandle;
  3556. handle->buffer[mode] = bhandle;
  3557. handle->dsBufferSize[mode] = dsBufferSize;
  3558. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  3559. stream_.device[mode] = device;
  3560. stream_.state = STREAM_STOPPED;
  3561. if ( stream_.mode == OUTPUT && mode == INPUT )
  3562. // We had already set up an output stream.
  3563. stream_.mode = DUPLEX;
  3564. else
  3565. stream_.mode = mode;
  3566. stream_.nBuffers = nBuffers;
  3567. stream_.sampleRate = sampleRate;
  3568. // Setup the buffer conversion information structure.
  3569. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  3570. // Setup the callback thread.
  3571. unsigned threadId;
  3572. stream_.callbackInfo.object = (void *) this;
  3573. stream_.callbackInfo.isRunning = true;
  3574. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  3575. &stream_.callbackInfo, 0, &threadId );
  3576. if ( stream_.callbackInfo.thread == 0 ) {
  3577. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  3578. goto error;
  3579. }
  3580. // Boost DS thread priority
  3581. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  3582. return SUCCESS;
  3583. error:
  3584. if ( handle ) {
  3585. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  3586. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  3587. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  3588. if ( buffer ) buffer->Release();
  3589. object->Release();
  3590. }
  3591. if ( handle->buffer[1] ) {
  3592. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  3593. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  3594. if ( buffer ) buffer->Release();
  3595. object->Release();
  3596. }
  3597. CloseHandle( handle->condition );
  3598. delete handle;
  3599. stream_.apiHandle = 0;
  3600. }
  3601. for ( int i=0; i<2; i++ ) {
  3602. if ( stream_.userBuffer[i] ) {
  3603. free( stream_.userBuffer[i] );
  3604. stream_.userBuffer[i] = 0;
  3605. }
  3606. }
  3607. if ( stream_.deviceBuffer ) {
  3608. free( stream_.deviceBuffer );
  3609. stream_.deviceBuffer = 0;
  3610. }
  3611. return FAILURE;
  3612. }
  3613. void RtApiDs :: closeStream()
  3614. {
  3615. if ( stream_.state == STREAM_CLOSED ) {
  3616. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  3617. error( RtError::WARNING );
  3618. return;
  3619. }
  3620. // Stop the callback thread.
  3621. stream_.callbackInfo.isRunning = false;
  3622. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  3623. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  3624. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  3625. if ( handle ) {
  3626. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  3627. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  3628. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  3629. if ( buffer ) {
  3630. buffer->Stop();
  3631. buffer->Release();
  3632. }
  3633. object->Release();
  3634. }
  3635. if ( handle->buffer[1] ) {
  3636. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  3637. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  3638. if ( buffer ) {
  3639. buffer->Stop();
  3640. buffer->Release();
  3641. }
  3642. object->Release();
  3643. }
  3644. CloseHandle( handle->condition );
  3645. delete handle;
  3646. stream_.apiHandle = 0;
  3647. }
  3648. for ( int i=0; i<2; i++ ) {
  3649. if ( stream_.userBuffer[i] ) {
  3650. free( stream_.userBuffer[i] );
  3651. stream_.userBuffer[i] = 0;
  3652. }
  3653. }
  3654. if ( stream_.deviceBuffer ) {
  3655. free( stream_.deviceBuffer );
  3656. stream_.deviceBuffer = 0;
  3657. }
  3658. stream_.mode = UNINITIALIZED;
  3659. stream_.state = STREAM_CLOSED;
  3660. }
  3661. void RtApiDs :: startStream()
  3662. {
  3663. verifyStream();
  3664. if ( stream_.state == STREAM_RUNNING ) {
  3665. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  3666. error( RtError::WARNING );
  3667. return;
  3668. }
  3669. // Increase scheduler frequency on lesser windows (a side-effect of
  3670. // increasing timer accuracy). On greater windows (Win2K or later),
  3671. // this is already in effect.
  3672. MUTEX_LOCK( &stream_.mutex );
  3673. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  3674. timeBeginPeriod( 1 );
  3675. /*
  3676. memset( &statistics, 0, sizeof( statistics ) );
  3677. statistics.sampleRate = stream_.sampleRate;
  3678. statistics.writeDeviceBufferLeadBytes = handle->dsPointerLeadTime[0];
  3679. */
  3680. buffersRolling = false;
  3681. duplexPrerollBytes = 0;
  3682. if ( stream_.mode == DUPLEX ) {
  3683. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  3684. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  3685. }
  3686. HRESULT result = 0;
  3687. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  3688. //statistics.outputFrameSize = formatBytes( stream_.deviceFormat[0] ) * stream_.nDeviceChannels[0];
  3689. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  3690. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  3691. if ( FAILED( result ) ) {
  3692. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  3693. errorText_ = errorStream_.str();
  3694. goto unlock;
  3695. }
  3696. }
  3697. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  3698. //statistics.inputFrameSize = formatBytes( stream_.deviceFormat[1]) * stream_.nDeviceChannels[1];
  3699. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  3700. result = buffer->Start( DSCBSTART_LOOPING );
  3701. if ( FAILED( result ) ) {
  3702. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  3703. errorText_ = errorStream_.str();
  3704. goto unlock;
  3705. }
  3706. }
  3707. handle->drainCounter = 0;
  3708. handle->internalDrain = false;
  3709. stream_.state = STREAM_RUNNING;
  3710. unlock:
  3711. MUTEX_UNLOCK( &stream_.mutex );
  3712. if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );
  3713. }
  3714. void RtApiDs :: stopStream()
  3715. {
  3716. verifyStream();
  3717. if ( stream_.state == STREAM_STOPPED ) {
  3718. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  3719. error( RtError::WARNING );
  3720. return;
  3721. }
  3722. MUTEX_LOCK( &stream_.mutex );
  3723. if ( stream_.state == STREAM_STOPPED ) {
  3724. MUTEX_UNLOCK( &stream_.mutex );
  3725. return;
  3726. }
  3727. HRESULT result = 0;
  3728. LPVOID audioPtr;
  3729. DWORD dataLen;
  3730. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  3731. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  3732. if ( handle->drainCounter == 0 ) {
  3733. handle->drainCounter = 1;
  3734. MUTEX_UNLOCK( &stream_.mutex );
  3735. WaitForMultipleObjects( 1, &handle->condition, FALSE, INFINITE ); // block until signaled
  3736. ResetEvent( handle->condition );
  3737. MUTEX_LOCK( &stream_.mutex );
  3738. }
  3739. // Stop the buffer and clear memory
  3740. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  3741. result = buffer->Stop();
  3742. if ( FAILED( result ) ) {
  3743. errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  3744. errorText_ = errorStream_.str();
  3745. goto unlock;
  3746. }
  3747. // Lock the buffer and clear it so that if we start to play again,
  3748. // we won't have old data playing.
  3749. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  3750. if ( FAILED( result ) ) {
  3751. errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") locking output buffer!";
  3752. errorText_ = errorStream_.str();
  3753. goto unlock;
  3754. }
  3755. // Zero the DS buffer
  3756. ZeroMemory( audioPtr, dataLen );
  3757. // Unlock the DS buffer
  3758. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  3759. if ( FAILED( result ) ) {
  3760. errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  3761. errorText_ = errorStream_.str();
  3762. goto unlock;
  3763. }
  3764. // If we start playing again, we must begin at beginning of buffer.
  3765. handle->bufferPointer[0] = 0;
  3766. }
  3767. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  3768. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  3769. audioPtr = NULL;
  3770. dataLen = 0;
  3771. result = buffer->Stop();
  3772. if ( FAILED( result ) ) {
  3773. errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  3774. errorText_ = errorStream_.str();
  3775. goto unlock;
  3776. }
  3777. // Lock the buffer and clear it so that if we start to play again,
  3778. // we won't have old data playing.
  3779. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  3780. if ( FAILED( result ) ) {
  3781. errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") locking input buffer!";
  3782. errorText_ = errorStream_.str();
  3783. goto unlock;
  3784. }
  3785. // Zero the DS buffer
  3786. ZeroMemory( audioPtr, dataLen );
  3787. // Unlock the DS buffer
  3788. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  3789. if ( FAILED( result ) ) {
  3790. errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  3791. errorText_ = errorStream_.str();
  3792. goto unlock;
  3793. }
  3794. // If we start recording again, we must begin at beginning of buffer.
  3795. handle->bufferPointer[1] = 0;
  3796. }
  3797. unlock:
  3798. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  3799. stream_.state = STREAM_STOPPED;
  3800. MUTEX_UNLOCK( &stream_.mutex );
  3801. if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );
  3802. }
  3803. void RtApiDs :: abortStream()
  3804. {
  3805. verifyStream();
  3806. if ( stream_.state == STREAM_STOPPED ) {
  3807. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  3808. error( RtError::WARNING );
  3809. return;
  3810. }
  3811. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  3812. handle->drainCounter = 1;
  3813. stopStream();
  3814. }
  3815. void RtApiDs :: callbackEvent()
  3816. {
  3817. if ( stream_.state == STREAM_STOPPED ) {
  3818. Sleep(50); // sleep 50 milliseconds
  3819. return;
  3820. }
  3821. if ( stream_.state == STREAM_CLOSED ) {
  3822. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  3823. error( RtError::WARNING );
  3824. return;
  3825. }
  3826. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  3827. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  3828. // Check if we were draining the stream and signal is finished.
  3829. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  3830. if ( handle->internalDrain == false )
  3831. SetEvent( handle->condition );
  3832. else
  3833. stopStream();
  3834. return;
  3835. }
  3836. MUTEX_LOCK( &stream_.mutex );
  3837. // The state might change while waiting on a mutex.
  3838. if ( stream_.state == STREAM_STOPPED ) {
  3839. MUTEX_UNLOCK( &stream_.mutex );
  3840. return SUCCESS;
  3841. }
  3842. // Invoke user callback to get fresh output data UNLESS we are
  3843. // draining stream.
  3844. if ( handle->drainCounter == 0 ) {
  3845. RtAudioCallback callback = (RtAudioCallback) info->callback;
  3846. double streamTime = getStreamTime();
  3847. RtAudioStreamStatus status = 0;
  3848. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  3849. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  3850. handle->xrun[0] = false;
  3851. }
  3852. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  3853. status |= RTAUDIO_INPUT_OVERFLOW;
  3854. handle->xrun[1] = false;
  3855. }
  3856. handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  3857. stream_.bufferSize, streamTime, status, info->userData );
  3858. if ( handle->drainCounter == 2 ) {
  3859. MUTEX_UNLOCK( &stream_.mutex );
  3860. abortStream();
  3861. return;
  3862. }
  3863. else if ( handle->drainCounter == 1 )
  3864. handle->internalDrain = true;
  3865. }
  3866. HRESULT result;
  3867. DWORD currentWritePos, safeWritePos;
  3868. DWORD currentReadPos, safeReadPos;
  3869. DWORD leadPos;
  3870. UINT nextWritePos;
  3871. #ifdef GENERATE_DEBUG_LOG
  3872. DWORD writeTime, readTime;
  3873. #endif
  3874. LPVOID buffer1 = NULL;
  3875. LPVOID buffer2 = NULL;
  3876. DWORD bufferSize1 = 0;
  3877. DWORD bufferSize2 = 0;
  3878. char *buffer;
  3879. long bufferBytes;
  3880. if ( stream_.mode == DUPLEX && !buffersRolling ) {
  3881. assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  3882. // It takes a while for the devices to get rolling. As a result,
  3883. // there's no guarantee that the capture and write device pointers
  3884. // will move in lockstep. Wait here for both devices to start
  3885. // rolling, and then set our buffer pointers accordingly.
  3886. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  3887. // bytes later than the write buffer.
  3888. // Stub: a serious risk of having a pre-emptive scheduling round
  3889. // take place between the two GetCurrentPosition calls... but I'm
  3890. // really not sure how to solve the problem. Temporarily boost to
  3891. // Realtime priority, maybe; but I'm not sure what priority the
  3892. // DirectSound service threads run at. We *should* be roughly
  3893. // within a ms or so of correct.
  3894. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  3895. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  3896. DWORD initialWritePos, initialSafeWritePos;
  3897. DWORD initialReadPos, initialSafeReadPos;
  3898. result = dsWriteBuffer->GetCurrentPosition( &initialWritePos, &initialSafeWritePos );
  3899. if ( FAILED( result ) ) {
  3900. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  3901. errorText_ = errorStream_.str();
  3902. error( RtError::SYSTEM_ERROR );
  3903. }
  3904. result = dsCaptureBuffer->GetCurrentPosition( &initialReadPos, &initialSafeReadPos );
  3905. if ( FAILED( result ) ) {
  3906. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  3907. errorText_ = errorStream_.str();
  3908. error( RtError::SYSTEM_ERROR );
  3909. }
  3910. while ( true ) {
  3911. result = dsWriteBuffer->GetCurrentPosition( &currentWritePos, &safeWritePos );
  3912. if ( FAILED( result ) ) {
  3913. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  3914. errorText_ = errorStream_.str();
  3915. error( RtError::SYSTEM_ERROR );
  3916. }
  3917. result = dsCaptureBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
  3918. if ( FAILED( result ) ) {
  3919. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  3920. errorText_ = errorStream_.str();
  3921. error( RtError::SYSTEM_ERROR );
  3922. }
  3923. if ( safeWritePos != initialSafeWritePos && safeReadPos != initialSafeReadPos ) break;
  3924. Sleep( 1 );
  3925. }
  3926. assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  3927. buffersRolling = true;
  3928. handle->bufferPointer[0] = ( safeWritePos + handle->dsPointerLeadTime[0] );
  3929. handle->bufferPointer[1] = safeReadPos;
  3930. }
  3931. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  3932. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  3933. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  3934. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  3935. bufferBytes *= formatBytes( stream_.userFormat );
  3936. memset( stream_.userBuffer[0], 0, bufferBytes );
  3937. }
  3938. // Setup parameters and do buffer conversion if necessary.
  3939. if ( stream_.doConvertBuffer[0] ) {
  3940. buffer = stream_.deviceBuffer;
  3941. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  3942. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  3943. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  3944. }
  3945. else {
  3946. buffer = stream_.userBuffer[0];
  3947. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  3948. bufferBytes *= formatBytes( stream_.userFormat );
  3949. }
  3950. // No byte swapping necessary in DirectSound implementation.
  3951. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  3952. // unsigned. So, we need to convert our signed 8-bit data here to
  3953. // unsigned.
  3954. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  3955. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  3956. DWORD dsBufferSize = handle->dsBufferSize[0];
  3957. nextWritePos = handle->bufferPointer[0];
  3958. DWORD endWrite;
  3959. while ( true ) {
  3960. // Find out where the read and "safe write" pointers are.
  3961. result = dsBuffer->GetCurrentPosition( &currentWritePos, &safeWritePos );
  3962. if ( FAILED( result ) ) {
  3963. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  3964. errorText_ = errorStream_.str();
  3965. error( RtError::SYSTEM_ERROR );
  3966. }
  3967. leadPos = safeWritePos + handle->dsPointerLeadTime[0];
  3968. if ( leadPos > dsBufferSize ) leadPos -= dsBufferSize;
  3969. if ( leadPos < nextWritePos ) leadPos += dsBufferSize; // unwrap offset
  3970. endWrite = nextWritePos + bufferBytes;
  3971. // Check whether the entire write region is behind the play pointer.
  3972. if ( leadPos >= endWrite ) break;
  3973. // If we are here, then we must wait until the play pointer gets
  3974. // beyond the write region. The approach here is to use the
  3975. // Sleep() function to suspend operation until safePos catches
  3976. // up. Calculate number of milliseconds to wait as:
  3977. // time = distance * (milliseconds/second) * fudgefactor /
  3978. // ((bytes/sample) * (samples/second))
  3979. // A "fudgefactor" less than 1 is used because it was found
  3980. // that sleeping too long was MUCH worse than sleeping for
  3981. // several shorter periods.
  3982. double millis = ( endWrite - leadPos ) * 900.0;
  3983. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  3984. if ( millis < 1.0 ) millis = 1.0;
  3985. if ( millis > 50.0 ) {
  3986. static int nOverruns = 0;
  3987. ++nOverruns;
  3988. }
  3989. Sleep( (DWORD) millis );
  3990. }
  3991. //if ( statistics.writeDeviceSafeLeadBytes < dsPointerDifference( safeWritePos, currentWritePos, handle->dsBufferSize[0] ) ) {
  3992. // statistics.writeDeviceSafeLeadBytes = dsPointerDifference( safeWritePos, currentWritePos, handle->dsBufferSize[0] );
  3993. //}
  3994. if ( dsPointerBetween( nextWritePos, safeWritePos, currentWritePos, dsBufferSize )
  3995. || dsPointerBetween( endWrite, safeWritePos, currentWritePos, dsBufferSize ) ) {
  3996. // We've strayed into the forbidden zone ... resync the read pointer.
  3997. //++statistics.numberOfWriteUnderruns;
  3998. handle->xrun[0] = true;
  3999. nextWritePos = safeWritePos + handle->dsPointerLeadTime[0] - bufferBytes + dsBufferSize;
  4000. while ( nextWritePos >= dsBufferSize ) nextWritePos -= dsBufferSize;
  4001. handle->bufferPointer[0] = nextWritePos;
  4002. endWrite = nextWritePos + bufferBytes;
  4003. }
  4004. // Lock free space in the buffer
  4005. result = dsBuffer->Lock( nextWritePos, bufferBytes, &buffer1,
  4006. &bufferSize1, &buffer2, &bufferSize2, 0 );
  4007. if ( FAILED( result ) ) {
  4008. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  4009. errorText_ = errorStream_.str();
  4010. error( RtError::SYSTEM_ERROR );
  4011. }
  4012. // Copy our buffer into the DS buffer
  4013. CopyMemory( buffer1, buffer, bufferSize1 );
  4014. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  4015. // Update our buffer offset and unlock sound buffer
  4016. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  4017. if ( FAILED( result ) ) {
  4018. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  4019. errorText_ = errorStream_.str();
  4020. error( RtError::SYSTEM_ERROR );
  4021. }
  4022. nextWritePos = ( nextWritePos + bufferSize1 + bufferSize2 ) % dsBufferSize;
  4023. handle->bufferPointer[0] = nextWritePos;
  4024. if ( handle->drainCounter ) {
  4025. handle->drainCounter++;
  4026. goto unlock;
  4027. }
  4028. }
  4029. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  4030. // Setup parameters.
  4031. if ( stream_.doConvertBuffer[1] ) {
  4032. buffer = stream_.deviceBuffer;
  4033. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  4034. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  4035. }
  4036. else {
  4037. buffer = stream_.userBuffer[1];
  4038. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  4039. bufferBytes *= formatBytes( stream_.userFormat );
  4040. }
  4041. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  4042. long nextReadPos = handle->bufferPointer[1];
  4043. DWORD dsBufferSize = handle->dsBufferSize[1];
  4044. // Find out where the write and "safe read" pointers are.
  4045. result = dsBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
  4046. if ( FAILED( result ) ) {
  4047. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  4048. errorText_ = errorStream_.str();
  4049. error( RtError::SYSTEM_ERROR );
  4050. }
  4051. if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
  4052. DWORD endRead = nextReadPos + bufferBytes;
  4053. // Handling depends on whether we are INPUT or DUPLEX.
  4054. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  4055. // then a wait here will drag the write pointers into the forbidden zone.
  4056. //
  4057. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  4058. // it's in a safe position. This causes dropouts, but it seems to be the only
  4059. // practical way to sync up the read and write pointers reliably, given the
  4060. // the very complex relationship between phase and increment of the read and write
  4061. // pointers.
  4062. //
  4063. // In order to minimize audible dropouts in DUPLEX mode, we will
  4064. // provide a pre-roll period of 0.5 seconds in which we return
  4065. // zeros from the read buffer while the pointers sync up.
  4066. if ( stream_.mode == DUPLEX ) {
  4067. if ( safeReadPos < endRead ) {
  4068. if ( duplexPrerollBytes <= 0 ) {
  4069. // Pre-roll time over. Be more agressive.
  4070. int adjustment = endRead-safeReadPos;
  4071. handle->xrun[1] = true;
  4072. //++statistics.numberOfReadOverruns;
  4073. // Two cases:
  4074. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  4075. // and perform fine adjustments later.
  4076. // - small adjustments: back off by twice as much.
  4077. if ( adjustment >= 2*bufferBytes )
  4078. nextReadPos = safeReadPos-2*bufferBytes;
  4079. else
  4080. nextReadPos = safeReadPos-bufferBytes-adjustment;
  4081. //statistics.readDeviceSafeLeadBytes = currentReadPos-nextReadPos;
  4082. //if ( statistics.readDeviceSafeLeadBytes < 0) statistics.readDeviceSafeLeadBytes += dsBufferSize;
  4083. if ( nextReadPos < 0 ) nextReadPos += dsBufferSize;
  4084. }
  4085. else {
  4086. // In pre=roll time. Just do it.
  4087. nextReadPos = safeReadPos-bufferBytes;
  4088. while ( nextReadPos < 0 ) nextReadPos += dsBufferSize;
  4089. }
  4090. endRead = nextReadPos + bufferBytes;
  4091. }
  4092. }
  4093. else { // mode == INPUT
  4094. while ( safeReadPos < endRead ) {
  4095. // See comments for playback.
  4096. double millis = (endRead - safeReadPos) * 900.0;
  4097. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  4098. if ( millis < 1.0 ) millis = 1.0;
  4099. Sleep( (DWORD) millis );
  4100. // Wake up, find out where we are now
  4101. result = dsBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
  4102. if ( FAILED( result ) ) {
  4103. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  4104. errorText_ = errorStream_.str();
  4105. error( RtError::SYSTEM_ERROR );
  4106. }
  4107. if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
  4108. }
  4109. }
  4110. //if (statistics.readDeviceSafeLeadBytes < dsPointerDifference( currentReadPos, nextReadPos, dsBufferSize ) )
  4111. // statistics.readDeviceSafeLeadBytes = dsPointerDifference( currentReadPos, nextReadPos, dsBufferSize );
  4112. // Lock free space in the buffer
  4113. result = dsBuffer->Lock( nextReadPos, bufferBytes, &buffer1,
  4114. &bufferSize1, &buffer2, &bufferSize2, 0 );
  4115. if ( FAILED( result ) ) {
  4116. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  4117. errorText_ = errorStream_.str();
  4118. error( RtError::SYSTEM_ERROR );
  4119. }
  4120. if ( duplexPrerollBytes <= 0 ) {
  4121. // Copy our buffer into the DS buffer
  4122. CopyMemory( buffer, buffer1, bufferSize1 );
  4123. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  4124. }
  4125. else {
  4126. memset( buffer, 0, bufferSize1 );
  4127. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  4128. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  4129. }
  4130. // Update our buffer offset and unlock sound buffer
  4131. nextReadPos = ( nextReadPos + bufferSize1 + bufferSize2 ) % dsBufferSize;
  4132. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  4133. if ( FAILED( result ) ) {
  4134. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  4135. errorText_ = errorStream_.str();
  4136. error( RtError::SYSTEM_ERROR );
  4137. }
  4138. handle->bufferPointer[1] = nextReadPos;
  4139. // No byte swapping necessary in DirectSound implementation.
  4140. // If necessary, convert 8-bit data from unsigned to signed.
  4141. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  4142. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  4143. // Do buffer conversion if necessary.
  4144. if ( stream_.doConvertBuffer[1] )
  4145. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  4146. }
  4147. #ifdef GENERATE_DEBUG_LOG
  4148. if ( currentDebugLogEntry < debugLog.size() )
  4149. {
  4150. TTickRecord &r = debugLog[currentDebugLogEntry++];
  4151. r.currentReadPointer = currentReadPos;
  4152. r.safeReadPointer = safeReadPos;
  4153. r.currentWritePointer = currentWritePos;
  4154. r.safeWritePointer = safeWritePos;
  4155. r.readTime = readTime;
  4156. r.writeTime = writeTime;
  4157. r.nextReadPointer = handles[1].bufferPointer;
  4158. r.nextWritePointer = handles[0].bufferPointer;
  4159. }
  4160. #endif
  4161. unlock:
  4162. MUTEX_UNLOCK( &stream_.mutex );
  4163. RtApi::tickStreamTime();
  4164. }
  4165. // Definitions for utility functions and callbacks
  4166. // specific to the DirectSound implementation.
  4167. extern "C" unsigned __stdcall callbackHandler( void *ptr )
  4168. {
  4169. CallbackInfo *info = (CallbackInfo *) ptr;
  4170. RtApiDs *object = (RtApiDs *) info->object;
  4171. bool* isRunning = &info->isRunning;
  4172. while ( *isRunning == true ) {
  4173. object->callbackEvent();
  4174. }
  4175. _endthreadex( 0 );
  4176. return 0;
  4177. }
  4178. #include "tchar.h"
  4179. std::string convertTChar( LPCTSTR name )
  4180. {
  4181. std::string s;
  4182. #if defined( UNICODE ) || defined( _UNICODE )
  4183. // Yes, this conversion doesn't make sense for two-byte characters
  4184. // but RtAudio is currently written to return an std::string of
  4185. // one-byte chars for the device name.
  4186. for ( unsigned int i=0; i<wcslen( name ); i++ )
  4187. s.push_back( name[i] );
  4188. #else
  4189. s.append( std::string( name ) );
  4190. #endif
  4191. return s;
  4192. }
  4193. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4194. LPCTSTR description,
  4195. LPCTSTR module,
  4196. LPVOID lpContext )
  4197. {
  4198. EnumInfo *info = (EnumInfo *) lpContext;
  4199. HRESULT hr;
  4200. if ( info->isInput == true ) {
  4201. DSCCAPS caps;
  4202. LPDIRECTSOUNDCAPTURE object;
  4203. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  4204. if ( hr != DS_OK ) return TRUE;
  4205. caps.dwSize = sizeof(caps);
  4206. hr = object->GetCaps( &caps );
  4207. if ( hr == DS_OK ) {
  4208. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  4209. info->counter++;
  4210. }
  4211. object->Release();
  4212. }
  4213. else {
  4214. DSCAPS caps;
  4215. LPDIRECTSOUND object;
  4216. hr = DirectSoundCreate( lpguid, &object, NULL );
  4217. if ( hr != DS_OK ) return TRUE;
  4218. caps.dwSize = sizeof(caps);
  4219. hr = object->GetCaps( &caps );
  4220. if ( hr == DS_OK ) {
  4221. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  4222. info->counter++;
  4223. }
  4224. object->Release();
  4225. }
  4226. if ( info->getDefault && lpguid == NULL ) return FALSE;
  4227. if ( info->findIndex && info->counter > info->index ) {
  4228. info->id = lpguid;
  4229. info->name = convertTChar( description );
  4230. return FALSE;
  4231. }
  4232. return TRUE;
  4233. }
  4234. static char* getErrorString( int code )
  4235. {
  4236. switch ( code ) {
  4237. case DSERR_ALLOCATED:
  4238. return "Already allocated";
  4239. case DSERR_CONTROLUNAVAIL:
  4240. return "Control unavailable";
  4241. case DSERR_INVALIDPARAM:
  4242. return "Invalid parameter";
  4243. case DSERR_INVALIDCALL:
  4244. return "Invalid call";
  4245. case DSERR_GENERIC:
  4246. return "Generic error";
  4247. case DSERR_PRIOLEVELNEEDED:
  4248. return "Priority level needed";
  4249. case DSERR_OUTOFMEMORY:
  4250. return "Out of memory";
  4251. case DSERR_BADFORMAT:
  4252. return "The sample rate or the channel format is not supported";
  4253. case DSERR_UNSUPPORTED:
  4254. return "Not supported";
  4255. case DSERR_NODRIVER:
  4256. return "No driver";
  4257. case DSERR_ALREADYINITIALIZED:
  4258. return "Already initialized";
  4259. case DSERR_NOAGGREGATION:
  4260. return "No aggregation";
  4261. case DSERR_BUFFERLOST:
  4262. return "Buffer lost";
  4263. case DSERR_OTHERAPPHASPRIO:
  4264. return "Another application already has priority";
  4265. case DSERR_UNINITIALIZED:
  4266. return "Uninitialized";
  4267. default:
  4268. return "DirectSound unknown error";
  4269. }
  4270. }
  4271. //******************** End of __WINDOWS_DS__ *********************//
  4272. #endif
  4273. #if defined(__LINUX_ALSA__)
  4274. #include <alsa/asoundlib.h>
  4275. #include <unistd.h>
  4276. // A structure to hold various information related to the ALSA API
  4277. // implementation.
  4278. struct AlsaHandle {
  4279. snd_pcm_t *handles[2];
  4280. bool synchronized;
  4281. bool xrun[2];
  4282. pthread_cond_t runnable;
  4283. AlsaHandle()
  4284. :synchronized(false) { xrun[0] = false; xrun[1] = false; }
  4285. };
  4286. extern "C" void *alsaCallbackHandler( void * ptr );
  4287. RtApiAlsa :: RtApiAlsa()
  4288. {
  4289. // Nothing to do here.
  4290. }
  4291. RtApiAlsa :: ~RtApiAlsa()
  4292. {
  4293. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4294. }
  4295. unsigned int RtApiAlsa :: getDeviceCount( void )
  4296. {
  4297. unsigned nDevices = 0;
  4298. int result, subdevice, card;
  4299. char name[64];
  4300. snd_ctl_t *handle;
  4301. // Count cards and devices
  4302. card = -1;
  4303. snd_card_next( &card );
  4304. while ( card >= 0 ) {
  4305. sprintf( name, "hw:%d", card );
  4306. result = snd_ctl_open( &handle, name, 0 );
  4307. if ( result < 0 ) {
  4308. errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  4309. errorText_ = errorStream_.str();
  4310. error( RtError::WARNING );
  4311. goto nextcard;
  4312. }
  4313. subdevice = -1;
  4314. while( 1 ) {
  4315. result = snd_ctl_pcm_next_device( handle, &subdevice );
  4316. if ( result < 0 ) {
  4317. errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  4318. errorText_ = errorStream_.str();
  4319. error( RtError::WARNING );
  4320. break;
  4321. }
  4322. if ( subdevice < 0 )
  4323. break;
  4324. nDevices++;
  4325. }
  4326. nextcard:
  4327. snd_ctl_close( handle );
  4328. snd_card_next( &card );
  4329. }
  4330. return nDevices;
  4331. }
  4332. RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
  4333. {
  4334. RtAudio::DeviceInfo info;
  4335. info.probed = false;
  4336. unsigned nDevices = 0;
  4337. int result, subdevice, card;
  4338. char name[64];
  4339. snd_ctl_t *chandle;
  4340. // Count cards and devices
  4341. card = -1;
  4342. snd_card_next( &card );
  4343. while ( card >= 0 ) {
  4344. sprintf( name, "hw:%d", card );
  4345. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  4346. if ( result < 0 ) {
  4347. errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  4348. errorText_ = errorStream_.str();
  4349. error( RtError::WARNING );
  4350. goto nextcard;
  4351. }
  4352. subdevice = -1;
  4353. while( 1 ) {
  4354. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  4355. if ( result < 0 ) {
  4356. errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  4357. errorText_ = errorStream_.str();
  4358. error( RtError::WARNING );
  4359. break;
  4360. }
  4361. if ( subdevice < 0 ) break;
  4362. if ( nDevices == device ) {
  4363. sprintf( name, "hw:%d,%d", card, subdevice );
  4364. goto foundDevice;
  4365. }
  4366. nDevices++;
  4367. }
  4368. nextcard:
  4369. snd_ctl_close( chandle );
  4370. snd_card_next( &card );
  4371. }
  4372. if ( nDevices == 0 ) {
  4373. errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
  4374. error( RtError::INVALID_USE );
  4375. }
  4376. if ( device >= nDevices ) {
  4377. errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
  4378. error( RtError::INVALID_USE );
  4379. }
  4380. foundDevice:
  4381. // If a stream is already open, we cannot probe the stream devices.
  4382. // Thus, use the saved results.
  4383. if ( stream_.state != STREAM_CLOSED &&
  4384. ( stream_.device[0] == device || stream_.device[1] == device ) ) {
  4385. if ( device >= devices_.size() ) {
  4386. errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
  4387. error( RtError::WARNING );
  4388. return info;
  4389. }
  4390. return devices_[ device ];
  4391. }
  4392. int openMode = SND_PCM_ASYNC;
  4393. snd_pcm_stream_t stream;
  4394. snd_pcm_info_t *pcminfo;
  4395. snd_pcm_info_alloca( &pcminfo );
  4396. snd_pcm_t *phandle;
  4397. snd_pcm_hw_params_t *params;
  4398. snd_pcm_hw_params_alloca( &params );
  4399. // First try for playback
  4400. stream = SND_PCM_STREAM_PLAYBACK;
  4401. snd_pcm_info_set_device( pcminfo, subdevice );
  4402. snd_pcm_info_set_subdevice( pcminfo, 0 );
  4403. snd_pcm_info_set_stream( pcminfo, stream );
  4404. result = snd_ctl_pcm_info( chandle, pcminfo );
  4405. if ( result < 0 ) {
  4406. // Device probably doesn't support playback.
  4407. goto captureProbe;
  4408. }
  4409. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
  4410. if ( result < 0 ) {
  4411. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  4412. errorText_ = errorStream_.str();
  4413. error( RtError::WARNING );
  4414. goto captureProbe;
  4415. }
  4416. // The device is open ... fill the parameter structure.
  4417. result = snd_pcm_hw_params_any( phandle, params );
  4418. if ( result < 0 ) {
  4419. snd_pcm_close( phandle );
  4420. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  4421. errorText_ = errorStream_.str();
  4422. error( RtError::WARNING );
  4423. goto captureProbe;
  4424. }
  4425. // Get output channel information.
  4426. unsigned int value;
  4427. result = snd_pcm_hw_params_get_channels_max( params, &value );
  4428. if ( result < 0 ) {
  4429. snd_pcm_close( phandle );
  4430. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
  4431. errorText_ = errorStream_.str();
  4432. error( RtError::WARNING );
  4433. goto captureProbe;
  4434. }
  4435. info.outputChannels = value;
  4436. snd_pcm_close( phandle );
  4437. captureProbe:
  4438. // Now try for capture
  4439. stream = SND_PCM_STREAM_CAPTURE;
  4440. snd_pcm_info_set_stream( pcminfo, stream );
  4441. result = snd_ctl_pcm_info( chandle, pcminfo );
  4442. snd_ctl_close( chandle );
  4443. if ( result < 0 ) {
  4444. // Device probably doesn't support capture.
  4445. if ( info.outputChannels == 0 ) return info;
  4446. goto probeParameters;
  4447. }
  4448. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  4449. if ( result < 0 ) {
  4450. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  4451. errorText_ = errorStream_.str();
  4452. error( RtError::WARNING );
  4453. if ( info.outputChannels == 0 ) return info;
  4454. goto probeParameters;
  4455. }
  4456. // The device is open ... fill the parameter structure.
  4457. result = snd_pcm_hw_params_any( phandle, params );
  4458. if ( result < 0 ) {
  4459. snd_pcm_close( phandle );
  4460. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  4461. errorText_ = errorStream_.str();
  4462. error( RtError::WARNING );
  4463. if ( info.outputChannels == 0 ) return info;
  4464. goto probeParameters;
  4465. }
  4466. result = snd_pcm_hw_params_get_channels_max( params, &value );
  4467. if ( result < 0 ) {
  4468. snd_pcm_close( phandle );
  4469. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
  4470. errorText_ = errorStream_.str();
  4471. error( RtError::WARNING );
  4472. if ( info.outputChannels == 0 ) return info;
  4473. goto probeParameters;
  4474. }
  4475. info.inputChannels = value;
  4476. snd_pcm_close( phandle );
  4477. // If device opens for both playback and capture, we determine the channels.
  4478. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4479. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4480. // ALSA doesn't provide default devices so we'll use the first available one.
  4481. if ( device == 0 && info.outputChannels > 0 )
  4482. info.isDefaultOutput = true;
  4483. if ( device == 0 && info.inputChannels > 0 )
  4484. info.isDefaultInput = true;
  4485. probeParameters:
  4486. // At this point, we just need to figure out the supported data
  4487. // formats and sample rates. We'll proceed by opening the device in
  4488. // the direction with the maximum number of channels, or playback if
  4489. // they are equal. This might limit our sample rate options, but so
  4490. // be it.
  4491. if ( info.outputChannels >= info.inputChannels )
  4492. stream = SND_PCM_STREAM_PLAYBACK;
  4493. else
  4494. stream = SND_PCM_STREAM_CAPTURE;
  4495. snd_pcm_info_set_stream( pcminfo, stream );
  4496. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  4497. if ( result < 0 ) {
  4498. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  4499. errorText_ = errorStream_.str();
  4500. error( RtError::WARNING );
  4501. return info;
  4502. }
  4503. // The device is open ... fill the parameter structure.
  4504. result = snd_pcm_hw_params_any( phandle, params );
  4505. if ( result < 0 ) {
  4506. snd_pcm_close( phandle );
  4507. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  4508. errorText_ = errorStream_.str();
  4509. error( RtError::WARNING );
  4510. return info;
  4511. }
  4512. // Test our discrete set of sample rate values.
  4513. info.sampleRates.clear();
  4514. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  4515. if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 )
  4516. info.sampleRates.push_back( SAMPLE_RATES[i] );
  4517. }
  4518. if ( info.sampleRates.size() == 0 ) {
  4519. snd_pcm_close( phandle );
  4520. errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
  4521. errorText_ = errorStream_.str();
  4522. error( RtError::WARNING );
  4523. return info;
  4524. }
  4525. // Probe the supported data formats ... we don't care about endian-ness just yet
  4526. snd_pcm_format_t format;
  4527. info.nativeFormats = 0;
  4528. format = SND_PCM_FORMAT_S8;
  4529. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  4530. info.nativeFormats |= RTAUDIO_SINT8;
  4531. format = SND_PCM_FORMAT_S16;
  4532. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  4533. info.nativeFormats |= RTAUDIO_SINT16;
  4534. format = SND_PCM_FORMAT_S24;
  4535. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  4536. info.nativeFormats |= RTAUDIO_SINT24;
  4537. format = SND_PCM_FORMAT_S32;
  4538. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  4539. info.nativeFormats |= RTAUDIO_SINT32;
  4540. format = SND_PCM_FORMAT_FLOAT;
  4541. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  4542. info.nativeFormats |= RTAUDIO_FLOAT32;
  4543. format = SND_PCM_FORMAT_FLOAT64;
  4544. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  4545. info.nativeFormats |= RTAUDIO_FLOAT64;
  4546. // Check that we have at least one supported format
  4547. if ( info.nativeFormats == 0 ) {
  4548. errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
  4549. errorText_ = errorStream_.str();
  4550. error( RtError::WARNING );
  4551. return info;
  4552. }
  4553. // Get the device name
  4554. char *cardname;
  4555. result = snd_card_get_name( card, &cardname );
  4556. if ( result >= 0 )
  4557. sprintf( name, "hw:%s,%d", cardname, subdevice );
  4558. info.name = name;
  4559. // That's all ... close the device and return
  4560. snd_pcm_close( phandle );
  4561. info.probed = true;
  4562. return info;
  4563. }
  4564. void RtApiAlsa :: saveDeviceInfo( void )
  4565. {
  4566. devices_.clear();
  4567. unsigned int nDevices = getDeviceCount();
  4568. devices_.resize( nDevices );
  4569. for ( unsigned int i=0; i<nDevices; i++ )
  4570. devices_[i] = getDeviceInfo( i );
  4571. }
  4572. bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4573. unsigned int firstChannel, unsigned int sampleRate,
  4574. RtAudioFormat format, unsigned int *bufferSize,
  4575. RtAudio::StreamOptions *options )
  4576. {
  4577. #if defined(__RTAUDIO_DEBUG__)
  4578. snd_output_t *out;
  4579. snd_output_stdio_attach(&out, stderr, 0);
  4580. #endif
  4581. // I'm not using the "plug" interface ... too much inconsistent behavior.
  4582. unsigned nDevices = 0;
  4583. int result, subdevice, card;
  4584. char name[64];
  4585. snd_ctl_t *chandle;
  4586. // Count cards and devices
  4587. card = -1;
  4588. snd_card_next( &card );
  4589. while ( card >= 0 ) {
  4590. sprintf( name, "hw:%d", card );
  4591. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  4592. if ( result < 0 ) {
  4593. errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  4594. errorText_ = errorStream_.str();
  4595. return FAILURE;
  4596. }
  4597. subdevice = -1;
  4598. while( 1 ) {
  4599. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  4600. if ( result < 0 ) break;
  4601. if ( subdevice < 0 ) break;
  4602. if ( nDevices == device ) {
  4603. sprintf( name, "hw:%d,%d", card, subdevice );
  4604. snd_ctl_close( chandle );
  4605. goto foundDevice;
  4606. }
  4607. nDevices++;
  4608. }
  4609. snd_ctl_close( chandle );
  4610. snd_card_next( &card );
  4611. }
  4612. if ( nDevices == 0 ) {
  4613. // This should not happen because a check is made before this function is called.
  4614. errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
  4615. return FAILURE;
  4616. }
  4617. if ( device >= nDevices ) {
  4618. // This should not happen because a check is made before this function is called.
  4619. errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
  4620. return FAILURE;
  4621. }
  4622. foundDevice:
  4623. // The getDeviceInfo() function will not work for a device that is
  4624. // already open. Thus, we'll probe the system before opening a
  4625. // stream and save the results for use by getDeviceInfo().
  4626. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
  4627. this->saveDeviceInfo();
  4628. snd_pcm_stream_t stream;
  4629. if ( mode == OUTPUT )
  4630. stream = SND_PCM_STREAM_PLAYBACK;
  4631. else
  4632. stream = SND_PCM_STREAM_CAPTURE;
  4633. snd_pcm_t *phandle;
  4634. int openMode = SND_PCM_ASYNC;
  4635. result = snd_pcm_open( &phandle, name, stream, openMode );
  4636. if ( result < 0 ) {
  4637. if ( mode == OUTPUT )
  4638. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
  4639. else
  4640. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
  4641. errorText_ = errorStream_.str();
  4642. return FAILURE;
  4643. }
  4644. // Fill the parameter structure.
  4645. snd_pcm_hw_params_t *hw_params;
  4646. snd_pcm_hw_params_alloca( &hw_params );
  4647. result = snd_pcm_hw_params_any( phandle, hw_params );
  4648. if ( result < 0 ) {
  4649. snd_pcm_close( phandle );
  4650. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
  4651. errorText_ = errorStream_.str();
  4652. return FAILURE;
  4653. }
  4654. #if defined(__RTAUDIO_DEBUG__)
  4655. fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
  4656. snd_pcm_hw_params_dump( hw_params, out );
  4657. #endif
  4658. // Set access ... check user preference.
  4659. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
  4660. stream_.userInterleaved = false;
  4661. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  4662. if ( result < 0 ) {
  4663. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  4664. stream_.deviceInterleaved[mode] = true;
  4665. }
  4666. else
  4667. stream_.deviceInterleaved[mode] = false;
  4668. }
  4669. else {
  4670. stream_.userInterleaved = true;
  4671. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  4672. if ( result < 0 ) {
  4673. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  4674. stream_.deviceInterleaved[mode] = false;
  4675. }
  4676. else
  4677. stream_.deviceInterleaved[mode] = true;
  4678. }
  4679. if ( result < 0 ) {
  4680. snd_pcm_close( phandle );
  4681. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
  4682. errorText_ = errorStream_.str();
  4683. return FAILURE;
  4684. }
  4685. // Determine how to set the device format.
  4686. stream_.userFormat = format;
  4687. snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
  4688. if ( format == RTAUDIO_SINT8 )
  4689. deviceFormat = SND_PCM_FORMAT_S8;
  4690. else if ( format == RTAUDIO_SINT16 )
  4691. deviceFormat = SND_PCM_FORMAT_S16;
  4692. else if ( format == RTAUDIO_SINT24 )
  4693. deviceFormat = SND_PCM_FORMAT_S24;
  4694. else if ( format == RTAUDIO_SINT32 )
  4695. deviceFormat = SND_PCM_FORMAT_S32;
  4696. else if ( format == RTAUDIO_FLOAT32 )
  4697. deviceFormat = SND_PCM_FORMAT_FLOAT;
  4698. else if ( format == RTAUDIO_FLOAT64 )
  4699. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  4700. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
  4701. stream_.deviceFormat[mode] = format;
  4702. goto setFormat;
  4703. }
  4704. // The user requested format is not natively supported by the device.
  4705. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  4706. if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
  4707. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  4708. goto setFormat;
  4709. }
  4710. deviceFormat = SND_PCM_FORMAT_FLOAT;
  4711. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  4712. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  4713. goto setFormat;
  4714. }
  4715. deviceFormat = SND_PCM_FORMAT_S32;
  4716. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  4717. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  4718. goto setFormat;
  4719. }
  4720. deviceFormat = SND_PCM_FORMAT_S24;
  4721. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  4722. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  4723. goto setFormat;
  4724. }
  4725. deviceFormat = SND_PCM_FORMAT_S16;
  4726. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  4727. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4728. goto setFormat;
  4729. }
  4730. deviceFormat = SND_PCM_FORMAT_S8;
  4731. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  4732. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4733. goto setFormat;
  4734. }
  4735. // If we get here, no supported format was found.
  4736. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
  4737. errorText_ = errorStream_.str();
  4738. return FAILURE;
  4739. setFormat:
  4740. result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
  4741. if ( result < 0 ) {
  4742. snd_pcm_close( phandle );
  4743. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
  4744. errorText_ = errorStream_.str();
  4745. return FAILURE;
  4746. }
  4747. // Determine whether byte-swaping is necessary.
  4748. stream_.doByteSwap[mode] = false;
  4749. if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
  4750. result = snd_pcm_format_cpu_endian( deviceFormat );
  4751. if ( result == 0 )
  4752. stream_.doByteSwap[mode] = true;
  4753. else if (result < 0) {
  4754. snd_pcm_close( phandle );
  4755. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
  4756. errorText_ = errorStream_.str();
  4757. return FAILURE;
  4758. }
  4759. }
  4760. // Set the sample rate.
  4761. result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
  4762. if ( result < 0 ) {
  4763. snd_pcm_close( phandle );
  4764. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
  4765. errorText_ = errorStream_.str();
  4766. return FAILURE;
  4767. }
  4768. // Determine the number of channels for this device. We support a possible
  4769. // minimum device channel number > than the value requested by the user.
  4770. stream_.nUserChannels[mode] = channels;
  4771. unsigned int value;
  4772. result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
  4773. unsigned int deviceChannels = value;
  4774. if ( result < 0 || deviceChannels < channels + firstChannel ) {
  4775. snd_pcm_close( phandle );
  4776. errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
  4777. errorText_ = errorStream_.str();
  4778. return FAILURE;
  4779. }
  4780. result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
  4781. if ( result < 0 ) {
  4782. snd_pcm_close( phandle );
  4783. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
  4784. errorText_ = errorStream_.str();
  4785. return FAILURE;
  4786. }
  4787. deviceChannels = value;
  4788. if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
  4789. stream_.nDeviceChannels[mode] = deviceChannels;
  4790. // Set the device channels.
  4791. result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
  4792. if ( result < 0 ) {
  4793. snd_pcm_close( phandle );
  4794. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
  4795. errorText_ = errorStream_.str();
  4796. return FAILURE;
  4797. }
  4798. // Set the buffer number, which in ALSA is referred to as the "period".
  4799. int totalSize, dir;
  4800. unsigned int periods = 0;
  4801. if ( options ) periods = options->numberOfBuffers;
  4802. totalSize = *bufferSize * periods;
  4803. // Set the buffer (or period) size.
  4804. snd_pcm_uframes_t periodSize = *bufferSize;
  4805. result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
  4806. if ( result < 0 ) {
  4807. snd_pcm_close( phandle );
  4808. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
  4809. errorText_ = errorStream_.str();
  4810. return FAILURE;
  4811. }
  4812. *bufferSize = periodSize;
  4813. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
  4814. else periods = totalSize / *bufferSize;
  4815. // Even though the hardware might allow 1 buffer, it won't work reliably.
  4816. if ( periods < 2 ) periods = 2;
  4817. result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
  4818. if ( result < 0 ) {
  4819. snd_pcm_close( phandle );
  4820. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
  4821. errorText_ = errorStream_.str();
  4822. return FAILURE;
  4823. }
  4824. // If attempting to setup a duplex stream, the bufferSize parameter
  4825. // MUST be the same in both directions!
  4826. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  4827. errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
  4828. errorText_ = errorStream_.str();
  4829. return FAILURE;
  4830. }
  4831. stream_.bufferSize = *bufferSize;
  4832. // Install the hardware configuration
  4833. result = snd_pcm_hw_params( phandle, hw_params );
  4834. if ( result < 0 ) {
  4835. snd_pcm_close( phandle );
  4836. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  4837. errorText_ = errorStream_.str();
  4838. return FAILURE;
  4839. }
  4840. #if defined(__RTAUDIO_DEBUG__)
  4841. fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
  4842. snd_pcm_hw_params_dump( hw_params, out );
  4843. #endif
  4844. // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
  4845. snd_pcm_sw_params_t *sw_params = NULL;
  4846. snd_pcm_sw_params_alloca( &sw_params );
  4847. snd_pcm_sw_params_current( phandle, sw_params );
  4848. snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
  4849. snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
  4850. snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
  4851. // The following two settings were suggested by Theo Veenker
  4852. //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
  4853. //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
  4854. // here are two options for a fix
  4855. //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
  4856. snd_pcm_uframes_t val;
  4857. snd_pcm_sw_params_get_boundary( sw_params, &val );
  4858. snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
  4859. result = snd_pcm_sw_params( phandle, sw_params );
  4860. if ( result < 0 ) {
  4861. snd_pcm_close( phandle );
  4862. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  4863. errorText_ = errorStream_.str();
  4864. return FAILURE;
  4865. }
  4866. #if defined(__RTAUDIO_DEBUG__)
  4867. fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
  4868. snd_pcm_sw_params_dump( sw_params, out );
  4869. #endif
  4870. // Set flags for buffer conversion
  4871. stream_.doConvertBuffer[mode] = false;
  4872. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  4873. stream_.doConvertBuffer[mode] = true;
  4874. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  4875. stream_.doConvertBuffer[mode] = true;
  4876. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4877. stream_.nUserChannels[mode] > 1 )
  4878. stream_.doConvertBuffer[mode] = true;
  4879. // Allocate the ApiHandle if necessary and then save.
  4880. AlsaHandle *apiInfo = 0;
  4881. if ( stream_.apiHandle == 0 ) {
  4882. try {
  4883. apiInfo = (AlsaHandle *) new AlsaHandle;
  4884. }
  4885. catch ( std::bad_alloc& ) {
  4886. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
  4887. goto error;
  4888. }
  4889. if ( pthread_cond_init( &apiInfo->runnable, NULL ) ) {
  4890. errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
  4891. goto error;
  4892. }
  4893. stream_.apiHandle = (void *) apiInfo;
  4894. apiInfo->handles[0] = 0;
  4895. apiInfo->handles[1] = 0;
  4896. }
  4897. else {
  4898. apiInfo = (AlsaHandle *) stream_.apiHandle;
  4899. }
  4900. apiInfo->handles[mode] = phandle;
  4901. // Allocate necessary internal buffers.
  4902. unsigned long bufferBytes;
  4903. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  4904. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  4905. if ( stream_.userBuffer[mode] == NULL ) {
  4906. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
  4907. goto error;
  4908. }
  4909. if ( stream_.doConvertBuffer[mode] ) {
  4910. bool makeBuffer = true;
  4911. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  4912. if ( mode == INPUT ) {
  4913. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  4914. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  4915. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  4916. }
  4917. }
  4918. if ( makeBuffer ) {
  4919. bufferBytes *= *bufferSize;
  4920. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  4921. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  4922. if ( stream_.deviceBuffer == NULL ) {
  4923. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
  4924. goto error;
  4925. }
  4926. }
  4927. }
  4928. stream_.sampleRate = sampleRate;
  4929. stream_.nBuffers = periods;
  4930. stream_.device[mode] = device;
  4931. stream_.state = STREAM_STOPPED;
  4932. // Setup the buffer conversion information structure.
  4933. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  4934. // Setup thread if necessary.
  4935. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  4936. // We had already set up an output stream.
  4937. stream_.mode = DUPLEX;
  4938. // Link the streams if possible.
  4939. apiInfo->synchronized = false;
  4940. if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
  4941. apiInfo->synchronized = true;
  4942. else {
  4943. errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
  4944. error( RtError::WARNING );
  4945. }
  4946. }
  4947. else {
  4948. stream_.mode = mode;
  4949. // Setup callback thread.
  4950. stream_.callbackInfo.object = (void *) this;
  4951. // Set the thread attributes for joinable and realtime scheduling
  4952. // priority (optional). The higher priority will only take affect
  4953. // if the program is run as root or suid. Note, under Linux
  4954. // processes with CAP_SYS_NICE privilege, a user can change
  4955. // scheduling policy and priority (thus need not be root). See
  4956. // POSIX "capabilities".
  4957. pthread_attr_t attr;
  4958. pthread_attr_init( &attr );
  4959. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  4960. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  4961. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  4962. struct sched_param param;
  4963. int priority = options->priority;
  4964. int min = sched_get_priority_min( SCHED_RR );
  4965. int max = sched_get_priority_max( SCHED_RR );
  4966. if ( priority < min ) priority = min;
  4967. else if ( priority > max ) priority = max;
  4968. param.sched_priority = priority;
  4969. pthread_attr_setschedparam( &attr, &param );
  4970. pthread_attr_setschedpolicy( &attr, SCHED_RR );
  4971. }
  4972. else
  4973. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  4974. #else
  4975. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  4976. #endif
  4977. stream_.callbackInfo.isRunning = true;
  4978. result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
  4979. pthread_attr_destroy( &attr );
  4980. if ( result ) {
  4981. stream_.callbackInfo.isRunning = false;
  4982. errorText_ = "RtApiAlsa::error creating callback thread!";
  4983. goto error;
  4984. }
  4985. }
  4986. return SUCCESS;
  4987. error:
  4988. if ( apiInfo ) {
  4989. pthread_cond_destroy( &apiInfo->runnable );
  4990. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  4991. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  4992. delete apiInfo;
  4993. stream_.apiHandle = 0;
  4994. }
  4995. for ( int i=0; i<2; i++ ) {
  4996. if ( stream_.userBuffer[i] ) {
  4997. free( stream_.userBuffer[i] );
  4998. stream_.userBuffer[i] = 0;
  4999. }
  5000. }
  5001. if ( stream_.deviceBuffer ) {
  5002. free( stream_.deviceBuffer );
  5003. stream_.deviceBuffer = 0;
  5004. }
  5005. return FAILURE;
  5006. }
  5007. void RtApiAlsa :: closeStream()
  5008. {
  5009. if ( stream_.state == STREAM_CLOSED ) {
  5010. errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
  5011. error( RtError::WARNING );
  5012. return;
  5013. }
  5014. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  5015. stream_.callbackInfo.isRunning = false;
  5016. MUTEX_LOCK( &stream_.mutex );
  5017. if ( stream_.state == STREAM_STOPPED )
  5018. pthread_cond_signal( &apiInfo->runnable );
  5019. MUTEX_UNLOCK( &stream_.mutex );
  5020. pthread_join( stream_.callbackInfo.thread, NULL );
  5021. if ( stream_.state == STREAM_RUNNING ) {
  5022. stream_.state = STREAM_STOPPED;
  5023. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  5024. snd_pcm_drop( apiInfo->handles[0] );
  5025. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  5026. snd_pcm_drop( apiInfo->handles[1] );
  5027. }
  5028. if ( apiInfo ) {
  5029. pthread_cond_destroy( &apiInfo->runnable );
  5030. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  5031. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  5032. delete apiInfo;
  5033. stream_.apiHandle = 0;
  5034. }
  5035. for ( int i=0; i<2; i++ ) {
  5036. if ( stream_.userBuffer[i] ) {
  5037. free( stream_.userBuffer[i] );
  5038. stream_.userBuffer[i] = 0;
  5039. }
  5040. }
  5041. if ( stream_.deviceBuffer ) {
  5042. free( stream_.deviceBuffer );
  5043. stream_.deviceBuffer = 0;
  5044. }
  5045. stream_.mode = UNINITIALIZED;
  5046. stream_.state = STREAM_CLOSED;
  5047. }
  5048. void RtApiAlsa :: startStream()
  5049. {
  5050. // This method calls snd_pcm_prepare if the device isn't already in that state.
  5051. verifyStream();
  5052. if ( stream_.state == STREAM_RUNNING ) {
  5053. errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
  5054. error( RtError::WARNING );
  5055. return;
  5056. }
  5057. MUTEX_LOCK( &stream_.mutex );
  5058. int result = 0;
  5059. snd_pcm_state_t state;
  5060. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  5061. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  5062. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5063. state = snd_pcm_state( handle[0] );
  5064. if ( state != SND_PCM_STATE_PREPARED ) {
  5065. result = snd_pcm_prepare( handle[0] );
  5066. if ( result < 0 ) {
  5067. errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
  5068. errorText_ = errorStream_.str();
  5069. goto unlock;
  5070. }
  5071. }
  5072. }
  5073. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  5074. state = snd_pcm_state( handle[1] );
  5075. if ( state != SND_PCM_STATE_PREPARED ) {
  5076. result = snd_pcm_prepare( handle[1] );
  5077. if ( result < 0 ) {
  5078. errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
  5079. errorText_ = errorStream_.str();
  5080. goto unlock;
  5081. }
  5082. }
  5083. }
  5084. stream_.state = STREAM_RUNNING;
  5085. unlock:
  5086. MUTEX_UNLOCK( &stream_.mutex );
  5087. pthread_cond_signal( &apiInfo->runnable );
  5088. if ( result >= 0 ) return;
  5089. error( RtError::SYSTEM_ERROR );
  5090. }
  5091. void RtApiAlsa :: stopStream()
  5092. {
  5093. verifyStream();
  5094. if ( stream_.state == STREAM_STOPPED ) {
  5095. errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
  5096. error( RtError::WARNING );
  5097. return;
  5098. }
  5099. MUTEX_LOCK( &stream_.mutex );
  5100. if ( stream_.state == STREAM_STOPPED ) {
  5101. MUTEX_UNLOCK( &stream_.mutex );
  5102. return;
  5103. }
  5104. int result = 0;
  5105. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  5106. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  5107. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5108. if ( apiInfo->synchronized )
  5109. result = snd_pcm_drop( handle[0] );
  5110. else
  5111. result = snd_pcm_drain( handle[0] );
  5112. if ( result < 0 ) {
  5113. errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
  5114. errorText_ = errorStream_.str();
  5115. goto unlock;
  5116. }
  5117. }
  5118. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  5119. result = snd_pcm_drop( handle[1] );
  5120. if ( result < 0 ) {
  5121. errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
  5122. errorText_ = errorStream_.str();
  5123. goto unlock;
  5124. }
  5125. }
  5126. unlock:
  5127. stream_.state = STREAM_STOPPED;
  5128. MUTEX_UNLOCK( &stream_.mutex );
  5129. if ( result >= 0 ) return;
  5130. error( RtError::SYSTEM_ERROR );
  5131. }
  5132. void RtApiAlsa :: abortStream()
  5133. {
  5134. verifyStream();
  5135. if ( stream_.state == STREAM_STOPPED ) {
  5136. errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
  5137. error( RtError::WARNING );
  5138. return;
  5139. }
  5140. MUTEX_LOCK( &stream_.mutex );
  5141. if ( stream_.state == STREAM_STOPPED ) {
  5142. MUTEX_UNLOCK( &stream_.mutex );
  5143. return;
  5144. }
  5145. int result = 0;
  5146. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  5147. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  5148. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5149. result = snd_pcm_drop( handle[0] );
  5150. if ( result < 0 ) {
  5151. errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
  5152. errorText_ = errorStream_.str();
  5153. goto unlock;
  5154. }
  5155. }
  5156. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  5157. result = snd_pcm_drop( handle[1] );
  5158. if ( result < 0 ) {
  5159. errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
  5160. errorText_ = errorStream_.str();
  5161. goto unlock;
  5162. }
  5163. }
  5164. unlock:
  5165. stream_.state = STREAM_STOPPED;
  5166. MUTEX_UNLOCK( &stream_.mutex );
  5167. if ( result >= 0 ) return;
  5168. error( RtError::SYSTEM_ERROR );
  5169. }
  5170. void RtApiAlsa :: callbackEvent()
  5171. {
  5172. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  5173. if ( stream_.state == STREAM_STOPPED ) {
  5174. MUTEX_LOCK( &stream_.mutex );
  5175. pthread_cond_wait( &apiInfo->runnable, &stream_.mutex );
  5176. if ( stream_.state != STREAM_RUNNING ) {
  5177. MUTEX_UNLOCK( &stream_.mutex );
  5178. return;
  5179. }
  5180. MUTEX_UNLOCK( &stream_.mutex );
  5181. }
  5182. if ( stream_.state == STREAM_CLOSED ) {
  5183. errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5184. error( RtError::WARNING );
  5185. return;
  5186. }
  5187. int doStopStream = 0;
  5188. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  5189. double streamTime = getStreamTime();
  5190. RtAudioStreamStatus status = 0;
  5191. if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
  5192. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5193. apiInfo->xrun[0] = false;
  5194. }
  5195. if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
  5196. status |= RTAUDIO_INPUT_OVERFLOW;
  5197. apiInfo->xrun[1] = false;
  5198. }
  5199. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5200. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  5201. if ( doStopStream == 2 ) {
  5202. abortStream();
  5203. return;
  5204. }
  5205. MUTEX_LOCK( &stream_.mutex );
  5206. // The state might change while waiting on a mutex.
  5207. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  5208. int result;
  5209. char *buffer;
  5210. int channels;
  5211. snd_pcm_t **handle;
  5212. snd_pcm_sframes_t frames;
  5213. RtAudioFormat format;
  5214. handle = (snd_pcm_t **) apiInfo->handles;
  5215. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5216. // Setup parameters.
  5217. if ( stream_.doConvertBuffer[1] ) {
  5218. buffer = stream_.deviceBuffer;
  5219. channels = stream_.nDeviceChannels[1];
  5220. format = stream_.deviceFormat[1];
  5221. }
  5222. else {
  5223. buffer = stream_.userBuffer[1];
  5224. channels = stream_.nUserChannels[1];
  5225. format = stream_.userFormat;
  5226. }
  5227. // Read samples from device in interleaved/non-interleaved format.
  5228. if ( stream_.deviceInterleaved[1] )
  5229. result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
  5230. else {
  5231. void *bufs[channels];
  5232. size_t offset = stream_.bufferSize * formatBytes( format );
  5233. for ( int i=0; i<channels; i++ )
  5234. bufs[i] = (void *) (buffer + (i * offset));
  5235. result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
  5236. }
  5237. if ( result < (int) stream_.bufferSize ) {
  5238. // Either an error or overrun occured.
  5239. if ( result == -EPIPE ) {
  5240. snd_pcm_state_t state = snd_pcm_state( handle[1] );
  5241. if ( state == SND_PCM_STATE_XRUN ) {
  5242. apiInfo->xrun[1] = true;
  5243. result = snd_pcm_prepare( handle[1] );
  5244. if ( result < 0 ) {
  5245. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
  5246. errorText_ = errorStream_.str();
  5247. }
  5248. }
  5249. else {
  5250. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  5251. errorText_ = errorStream_.str();
  5252. }
  5253. }
  5254. else {
  5255. errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
  5256. errorText_ = errorStream_.str();
  5257. }
  5258. error( RtError::WARNING );
  5259. goto tryOutput;
  5260. }
  5261. // Do byte swapping if necessary.
  5262. if ( stream_.doByteSwap[1] )
  5263. byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
  5264. // Do buffer conversion if necessary.
  5265. if ( stream_.doConvertBuffer[1] )
  5266. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5267. // Check stream latency
  5268. result = snd_pcm_delay( handle[1], &frames );
  5269. if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
  5270. }
  5271. tryOutput:
  5272. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5273. // Setup parameters and do buffer conversion if necessary.
  5274. if ( stream_.doConvertBuffer[0] ) {
  5275. buffer = stream_.deviceBuffer;
  5276. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5277. channels = stream_.nDeviceChannels[0];
  5278. format = stream_.deviceFormat[0];
  5279. }
  5280. else {
  5281. buffer = stream_.userBuffer[0];
  5282. channels = stream_.nUserChannels[0];
  5283. format = stream_.userFormat;
  5284. }
  5285. // Do byte swapping if necessary.
  5286. if ( stream_.doByteSwap[0] )
  5287. byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
  5288. // Write samples to device in interleaved/non-interleaved format.
  5289. if ( stream_.deviceInterleaved[0] )
  5290. result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
  5291. else {
  5292. void *bufs[channels];
  5293. size_t offset = stream_.bufferSize * formatBytes( format );
  5294. for ( int i=0; i<channels; i++ )
  5295. bufs[i] = (void *) (buffer + (i * offset));
  5296. result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
  5297. }
  5298. if ( result < (int) stream_.bufferSize ) {
  5299. // Either an error or underrun occured.
  5300. if ( result == -EPIPE ) {
  5301. snd_pcm_state_t state = snd_pcm_state( handle[0] );
  5302. if ( state == SND_PCM_STATE_XRUN ) {
  5303. apiInfo->xrun[0] = true;
  5304. result = snd_pcm_prepare( handle[0] );
  5305. if ( result < 0 ) {
  5306. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
  5307. errorText_ = errorStream_.str();
  5308. }
  5309. }
  5310. else {
  5311. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  5312. errorText_ = errorStream_.str();
  5313. }
  5314. }
  5315. else {
  5316. errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
  5317. errorText_ = errorStream_.str();
  5318. }
  5319. error( RtError::WARNING );
  5320. goto unlock;
  5321. }
  5322. // Check stream latency
  5323. result = snd_pcm_delay( handle[0], &frames );
  5324. if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
  5325. }
  5326. unlock:
  5327. MUTEX_UNLOCK( &stream_.mutex );
  5328. RtApi::tickStreamTime();
  5329. if ( doStopStream == 1 ) this->stopStream();
  5330. }
  5331. extern "C" void *alsaCallbackHandler( void *ptr )
  5332. {
  5333. CallbackInfo *info = (CallbackInfo *) ptr;
  5334. RtApiAlsa *object = (RtApiAlsa *) info->object;
  5335. bool *isRunning = &info->isRunning;
  5336. while ( *isRunning == true ) {
  5337. pthread_testcancel();
  5338. object->callbackEvent();
  5339. }
  5340. pthread_exit( NULL );
  5341. }
  5342. //******************** End of __LINUX_ALSA__ *********************//
  5343. #endif
  5344. #if defined(__LINUX_OSS__)
  5345. #include <unistd.h>
  5346. #include <sys/ioctl.h>
  5347. #include <unistd.h>
  5348. #include <fcntl.h>
  5349. #include "soundcard.h"
  5350. #include <errno.h>
  5351. #include <math.h>
  5352. extern "C" void *ossCallbackHandler(void * ptr);
  5353. // A structure to hold various information related to the OSS API
  5354. // implementation.
  5355. struct OssHandle {
  5356. int id[2]; // device ids
  5357. bool xrun[2];
  5358. bool triggered;
  5359. pthread_cond_t runnable;
  5360. OssHandle()
  5361. :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  5362. };
  5363. RtApiOss :: RtApiOss()
  5364. {
  5365. // Nothing to do here.
  5366. }
  5367. RtApiOss :: ~RtApiOss()
  5368. {
  5369. if ( stream_.state != STREAM_CLOSED ) closeStream();
  5370. }
  5371. unsigned int RtApiOss :: getDeviceCount( void )
  5372. {
  5373. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  5374. if ( mixerfd == -1 ) {
  5375. errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
  5376. error( RtError::WARNING );
  5377. return 0;
  5378. }
  5379. oss_sysinfo sysinfo;
  5380. if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
  5381. close( mixerfd );
  5382. errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
  5383. error( RtError::WARNING );
  5384. return 0;
  5385. }
  5386. close( mixerfd );
  5387. return sysinfo.numaudios;
  5388. }
  5389. RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
  5390. {
  5391. RtAudio::DeviceInfo info;
  5392. info.probed = false;
  5393. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  5394. if ( mixerfd == -1 ) {
  5395. errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
  5396. error( RtError::WARNING );
  5397. return info;
  5398. }
  5399. oss_sysinfo sysinfo;
  5400. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  5401. if ( result == -1 ) {
  5402. close( mixerfd );
  5403. errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
  5404. error( RtError::WARNING );
  5405. return info;
  5406. }
  5407. unsigned nDevices = sysinfo.numaudios;
  5408. if ( nDevices == 0 ) {
  5409. close( mixerfd );
  5410. errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
  5411. error( RtError::INVALID_USE );
  5412. }
  5413. if ( device >= nDevices ) {
  5414. close( mixerfd );
  5415. errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
  5416. error( RtError::INVALID_USE );
  5417. }
  5418. oss_audioinfo ainfo;
  5419. ainfo.dev = device;
  5420. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  5421. close( mixerfd );
  5422. if ( result == -1 ) {
  5423. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  5424. errorText_ = errorStream_.str();
  5425. error( RtError::WARNING );
  5426. return info;
  5427. }
  5428. // Probe channels
  5429. if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
  5430. if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
  5431. if ( ainfo.caps & PCM_CAP_DUPLEX ) {
  5432. if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
  5433. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  5434. }
  5435. // Probe data formats ... do for input
  5436. unsigned long mask = ainfo.iformats;
  5437. if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
  5438. info.nativeFormats |= RTAUDIO_SINT16;
  5439. if ( mask & AFMT_S8 )
  5440. info.nativeFormats |= RTAUDIO_SINT8;
  5441. if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
  5442. info.nativeFormats |= RTAUDIO_SINT32;
  5443. if ( mask & AFMT_FLOAT )
  5444. info.nativeFormats |= RTAUDIO_FLOAT32;
  5445. if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
  5446. info.nativeFormats |= RTAUDIO_SINT24;
  5447. // Check that we have at least one supported format
  5448. if ( info.nativeFormats == 0 ) {
  5449. errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
  5450. errorText_ = errorStream_.str();
  5451. error( RtError::WARNING );
  5452. return info;
  5453. }
  5454. // Probe the supported sample rates.
  5455. info.sampleRates.clear();
  5456. if ( ainfo.nrates ) {
  5457. for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
  5458. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  5459. if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
  5460. info.sampleRates.push_back( SAMPLE_RATES[k] );
  5461. break;
  5462. }
  5463. }
  5464. }
  5465. }
  5466. else {
  5467. // Check min and max rate values;
  5468. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  5469. if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] )
  5470. info.sampleRates.push_back( SAMPLE_RATES[k] );
  5471. }
  5472. }
  5473. if ( info.sampleRates.size() == 0 ) {
  5474. errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
  5475. errorText_ = errorStream_.str();
  5476. error( RtError::WARNING );
  5477. }
  5478. else {
  5479. info.probed = true;
  5480. info.name = ainfo.name;
  5481. }
  5482. return info;
  5483. }
  5484. bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  5485. unsigned int firstChannel, unsigned int sampleRate,
  5486. RtAudioFormat format, unsigned int *bufferSize,
  5487. RtAudio::StreamOptions *options )
  5488. {
  5489. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  5490. if ( mixerfd == -1 ) {
  5491. errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
  5492. return FAILURE;
  5493. }
  5494. oss_sysinfo sysinfo;
  5495. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  5496. if ( result == -1 ) {
  5497. close( mixerfd );
  5498. errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
  5499. return FAILURE;
  5500. }
  5501. unsigned nDevices = sysinfo.numaudios;
  5502. if ( nDevices == 0 ) {
  5503. // This should not happen because a check is made before this function is called.
  5504. close( mixerfd );
  5505. errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
  5506. return FAILURE;
  5507. }
  5508. if ( device >= nDevices ) {
  5509. // This should not happen because a check is made before this function is called.
  5510. close( mixerfd );
  5511. errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
  5512. return FAILURE;
  5513. }
  5514. oss_audioinfo ainfo;
  5515. ainfo.dev = device;
  5516. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  5517. close( mixerfd );
  5518. if ( result == -1 ) {
  5519. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  5520. errorText_ = errorStream_.str();
  5521. return FAILURE;
  5522. }
  5523. // Check if device supports input or output
  5524. if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
  5525. ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
  5526. if ( mode == OUTPUT )
  5527. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
  5528. else
  5529. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
  5530. errorText_ = errorStream_.str();
  5531. return FAILURE;
  5532. }
  5533. int flags = 0;
  5534. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  5535. if ( mode == OUTPUT )
  5536. flags |= O_WRONLY;
  5537. else { // mode == INPUT
  5538. if (stream_.mode == OUTPUT && stream_.device[0] == device) {
  5539. // We just set the same device for playback ... close and reopen for duplex (OSS only).
  5540. close( handle->id[0] );
  5541. handle->id[0] = 0;
  5542. if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
  5543. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
  5544. errorText_ = errorStream_.str();
  5545. return FAILURE;
  5546. }
  5547. // Check that the number previously set channels is the same.
  5548. if ( stream_.nUserChannels[0] != channels ) {
  5549. errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
  5550. errorText_ = errorStream_.str();
  5551. return FAILURE;
  5552. }
  5553. flags |= O_RDWR;
  5554. }
  5555. else
  5556. flags |= O_RDONLY;
  5557. }
  5558. // Set exclusive access if specified.
  5559. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
  5560. // Try to open the device.
  5561. int fd;
  5562. fd = open( ainfo.devnode, flags, 0 );
  5563. if ( fd == -1 ) {
  5564. if ( errno == EBUSY )
  5565. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
  5566. else
  5567. errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
  5568. errorText_ = errorStream_.str();
  5569. return FAILURE;
  5570. }
  5571. // For duplex operation, specifically set this mode (this doesn't seem to work).
  5572. /*
  5573. if ( flags | O_RDWR ) {
  5574. result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
  5575. if ( result == -1) {
  5576. errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
  5577. errorText_ = errorStream_.str();
  5578. return FAILURE;
  5579. }
  5580. }
  5581. */
  5582. // Check the device channel support.
  5583. stream_.nUserChannels[mode] = channels;
  5584. if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
  5585. close( fd );
  5586. errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
  5587. errorText_ = errorStream_.str();
  5588. return FAILURE;
  5589. }
  5590. // Set the number of channels.
  5591. int deviceChannels = channels + firstChannel;
  5592. result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
  5593. if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
  5594. close( fd );
  5595. errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
  5596. errorText_ = errorStream_.str();
  5597. return FAILURE;
  5598. }
  5599. stream_.nDeviceChannels[mode] = deviceChannels;
  5600. // Get the data format mask
  5601. int mask;
  5602. result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
  5603. if ( result == -1 ) {
  5604. close( fd );
  5605. errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
  5606. errorText_ = errorStream_.str();
  5607. return FAILURE;
  5608. }
  5609. // Determine how to set the device format.
  5610. stream_.userFormat = format;
  5611. int deviceFormat = -1;
  5612. stream_.doByteSwap[mode] = false;
  5613. if ( format == RTAUDIO_SINT8 ) {
  5614. if ( mask & AFMT_S8 ) {
  5615. deviceFormat = AFMT_S8;
  5616. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5617. }
  5618. }
  5619. else if ( format == RTAUDIO_SINT16 ) {
  5620. if ( mask & AFMT_S16_NE ) {
  5621. deviceFormat = AFMT_S16_NE;
  5622. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5623. }
  5624. else if ( mask & AFMT_S16_OE ) {
  5625. deviceFormat = AFMT_S16_OE;
  5626. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5627. stream_.doByteSwap[mode] = true;
  5628. }
  5629. }
  5630. else if ( format == RTAUDIO_SINT24 ) {
  5631. if ( mask & AFMT_S24_NE ) {
  5632. deviceFormat = AFMT_S24_NE;
  5633. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  5634. }
  5635. else if ( mask & AFMT_S24_OE ) {
  5636. deviceFormat = AFMT_S24_OE;
  5637. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  5638. stream_.doByteSwap[mode] = true;
  5639. }
  5640. }
  5641. else if ( format == RTAUDIO_SINT32 ) {
  5642. if ( mask & AFMT_S32_NE ) {
  5643. deviceFormat = AFMT_S32_NE;
  5644. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  5645. }
  5646. else if ( mask & AFMT_S32_OE ) {
  5647. deviceFormat = AFMT_S32_OE;
  5648. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  5649. stream_.doByteSwap[mode] = true;
  5650. }
  5651. }
  5652. if ( deviceFormat == -1 ) {
  5653. // The user requested format is not natively supported by the device.
  5654. if ( mask & AFMT_S16_NE ) {
  5655. deviceFormat = AFMT_S16_NE;
  5656. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5657. }
  5658. else if ( mask & AFMT_S32_NE ) {
  5659. deviceFormat = AFMT_S32_NE;
  5660. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  5661. }
  5662. else if ( mask & AFMT_S24_NE ) {
  5663. deviceFormat = AFMT_S24_NE;
  5664. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  5665. }
  5666. else if ( mask & AFMT_S16_OE ) {
  5667. deviceFormat = AFMT_S16_OE;
  5668. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5669. stream_.doByteSwap[mode] = true;
  5670. }
  5671. else if ( mask & AFMT_S32_OE ) {
  5672. deviceFormat = AFMT_S32_OE;
  5673. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  5674. stream_.doByteSwap[mode] = true;
  5675. }
  5676. else if ( mask & AFMT_S24_OE ) {
  5677. deviceFormat = AFMT_S24_OE;
  5678. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  5679. stream_.doByteSwap[mode] = true;
  5680. }
  5681. else if ( mask & AFMT_S8) {
  5682. deviceFormat = AFMT_S8;
  5683. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5684. }
  5685. }
  5686. if ( stream_.deviceFormat[mode] == 0 ) {
  5687. // This really shouldn't happen ...
  5688. close( fd );
  5689. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
  5690. errorText_ = errorStream_.str();
  5691. return FAILURE;
  5692. }
  5693. // Set the data format.
  5694. int temp = deviceFormat;
  5695. result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
  5696. if ( result == -1 || deviceFormat != temp ) {
  5697. close( fd );
  5698. errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
  5699. errorText_ = errorStream_.str();
  5700. return FAILURE;
  5701. }
  5702. // Attempt to set the buffer size. According to OSS, the minimum
  5703. // number of buffers is two. The supposed minimum buffer size is 16
  5704. // bytes, so that will be our lower bound. The argument to this
  5705. // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
  5706. // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
  5707. // We'll check the actual value used near the end of the setup
  5708. // procedure.
  5709. int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
  5710. if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
  5711. int buffers = 0;
  5712. if ( options ) buffers = options->numberOfBuffers;
  5713. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
  5714. if ( buffers < 2 ) buffers = 3;
  5715. temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
  5716. result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
  5717. if ( result == -1 ) {
  5718. close( fd );
  5719. errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
  5720. errorText_ = errorStream_.str();
  5721. return FAILURE;
  5722. }
  5723. stream_.nBuffers = buffers;
  5724. // Save buffer size (in sample frames).
  5725. *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
  5726. stream_.bufferSize = *bufferSize;
  5727. // Set the sample rate.
  5728. int srate = sampleRate;
  5729. result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
  5730. if ( result == -1 ) {
  5731. close( fd );
  5732. errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
  5733. errorText_ = errorStream_.str();
  5734. return FAILURE;
  5735. }
  5736. // Verify the sample rate setup worked.
  5737. if ( abs( srate - sampleRate ) > 100 ) {
  5738. close( fd );
  5739. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
  5740. errorText_ = errorStream_.str();
  5741. return FAILURE;
  5742. }
  5743. stream_.sampleRate = sampleRate;
  5744. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
  5745. // We're doing duplex setup here.
  5746. stream_.deviceFormat[0] = stream_.deviceFormat[1];
  5747. stream_.nDeviceChannels[0] = deviceChannels;
  5748. }
  5749. // Set interleaving parameters.
  5750. stream_.userInterleaved = true;
  5751. stream_.deviceInterleaved[mode] = true;
  5752. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  5753. stream_.userInterleaved = false;
  5754. // Set flags for buffer conversion
  5755. stream_.doConvertBuffer[mode] = false;
  5756. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  5757. stream_.doConvertBuffer[mode] = true;
  5758. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  5759. stream_.doConvertBuffer[mode] = true;
  5760. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  5761. stream_.nUserChannels[mode] > 1 )
  5762. stream_.doConvertBuffer[mode] = true;
  5763. // Allocate the stream handles if necessary and then save.
  5764. if ( stream_.apiHandle == 0 ) {
  5765. try {
  5766. handle = new OssHandle;
  5767. }
  5768. catch ( std::bad_alloc& ) {
  5769. errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
  5770. goto error;
  5771. }
  5772. if ( pthread_cond_init( &handle->runnable, NULL ) ) {
  5773. errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
  5774. goto error;
  5775. }
  5776. stream_.apiHandle = (void *) handle;
  5777. }
  5778. else {
  5779. handle = (OssHandle *) stream_.apiHandle;
  5780. }
  5781. handle->id[mode] = fd;
  5782. // Allocate necessary internal buffers.
  5783. unsigned long bufferBytes;
  5784. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  5785. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  5786. if ( stream_.userBuffer[mode] == NULL ) {
  5787. errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
  5788. goto error;
  5789. }
  5790. if ( stream_.doConvertBuffer[mode] ) {
  5791. bool makeBuffer = true;
  5792. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  5793. if ( mode == INPUT ) {
  5794. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  5795. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  5796. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  5797. }
  5798. }
  5799. if ( makeBuffer ) {
  5800. bufferBytes *= *bufferSize;
  5801. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  5802. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  5803. if ( stream_.deviceBuffer == NULL ) {
  5804. errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
  5805. goto error;
  5806. }
  5807. }
  5808. }
  5809. stream_.device[mode] = device;
  5810. stream_.state = STREAM_STOPPED;
  5811. // Setup the buffer conversion information structure.
  5812. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  5813. // Setup thread if necessary.
  5814. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  5815. // We had already set up an output stream.
  5816. stream_.mode = DUPLEX;
  5817. if ( stream_.device[0] == device ) handle->id[0] = fd;
  5818. }
  5819. else {
  5820. stream_.mode = mode;
  5821. // Setup callback thread.
  5822. stream_.callbackInfo.object = (void *) this;
  5823. // Set the thread attributes for joinable and realtime scheduling
  5824. // priority. The higher priority will only take affect if the
  5825. // program is run as root or suid.
  5826. pthread_attr_t attr;
  5827. pthread_attr_init( &attr );
  5828. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  5829. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  5830. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  5831. struct sched_param param;
  5832. int priority = options->priority;
  5833. int min = sched_get_priority_min( SCHED_RR );
  5834. int max = sched_get_priority_max( SCHED_RR );
  5835. if ( priority < min ) priority = min;
  5836. else if ( priority > max ) priority = max;
  5837. param.sched_priority = priority;
  5838. pthread_attr_setschedparam( &attr, &param );
  5839. pthread_attr_setschedpolicy( &attr, SCHED_RR );
  5840. }
  5841. else
  5842. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  5843. #else
  5844. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  5845. #endif
  5846. stream_.callbackInfo.isRunning = true;
  5847. result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
  5848. pthread_attr_destroy( &attr );
  5849. if ( result ) {
  5850. stream_.callbackInfo.isRunning = false;
  5851. errorText_ = "RtApiOss::error creating callback thread!";
  5852. goto error;
  5853. }
  5854. }
  5855. return SUCCESS;
  5856. error:
  5857. if ( handle ) {
  5858. pthread_cond_destroy( &handle->runnable );
  5859. if ( handle->id[0] ) close( handle->id[0] );
  5860. if ( handle->id[1] ) close( handle->id[1] );
  5861. delete handle;
  5862. stream_.apiHandle = 0;
  5863. }
  5864. for ( int i=0; i<2; i++ ) {
  5865. if ( stream_.userBuffer[i] ) {
  5866. free( stream_.userBuffer[i] );
  5867. stream_.userBuffer[i] = 0;
  5868. }
  5869. }
  5870. if ( stream_.deviceBuffer ) {
  5871. free( stream_.deviceBuffer );
  5872. stream_.deviceBuffer = 0;
  5873. }
  5874. return FAILURE;
  5875. }
  5876. void RtApiOss :: closeStream()
  5877. {
  5878. if ( stream_.state == STREAM_CLOSED ) {
  5879. errorText_ = "RtApiOss::closeStream(): no open stream to close!";
  5880. error( RtError::WARNING );
  5881. return;
  5882. }
  5883. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  5884. stream_.callbackInfo.isRunning = false;
  5885. MUTEX_LOCK( &stream_.mutex );
  5886. if ( stream_.state == STREAM_STOPPED )
  5887. pthread_cond_signal( &handle->runnable );
  5888. MUTEX_UNLOCK( &stream_.mutex );
  5889. pthread_join( stream_.callbackInfo.thread, NULL );
  5890. if ( stream_.state == STREAM_RUNNING ) {
  5891. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  5892. ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  5893. else
  5894. ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  5895. stream_.state = STREAM_STOPPED;
  5896. }
  5897. if ( handle ) {
  5898. pthread_cond_destroy( &handle->runnable );
  5899. if ( handle->id[0] ) close( handle->id[0] );
  5900. if ( handle->id[1] ) close( handle->id[1] );
  5901. delete handle;
  5902. stream_.apiHandle = 0;
  5903. }
  5904. for ( int i=0; i<2; i++ ) {
  5905. if ( stream_.userBuffer[i] ) {
  5906. free( stream_.userBuffer[i] );
  5907. stream_.userBuffer[i] = 0;
  5908. }
  5909. }
  5910. if ( stream_.deviceBuffer ) {
  5911. free( stream_.deviceBuffer );
  5912. stream_.deviceBuffer = 0;
  5913. }
  5914. stream_.mode = UNINITIALIZED;
  5915. stream_.state = STREAM_CLOSED;
  5916. }
  5917. void RtApiOss :: startStream()
  5918. {
  5919. verifyStream();
  5920. if ( stream_.state == STREAM_RUNNING ) {
  5921. errorText_ = "RtApiOss::startStream(): the stream is already running!";
  5922. error( RtError::WARNING );
  5923. return;
  5924. }
  5925. MUTEX_LOCK( &stream_.mutex );
  5926. stream_.state = STREAM_RUNNING;
  5927. // No need to do anything else here ... OSS automatically starts
  5928. // when fed samples.
  5929. MUTEX_UNLOCK( &stream_.mutex );
  5930. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  5931. pthread_cond_signal( &handle->runnable );
  5932. }
  5933. void RtApiOss :: stopStream()
  5934. {
  5935. verifyStream();
  5936. if ( stream_.state == STREAM_STOPPED ) {
  5937. errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
  5938. error( RtError::WARNING );
  5939. return;
  5940. }
  5941. MUTEX_LOCK( &stream_.mutex );
  5942. // The state might change while waiting on a mutex.
  5943. if ( stream_.state == STREAM_STOPPED ) {
  5944. MUTEX_UNLOCK( &stream_.mutex );
  5945. return;
  5946. }
  5947. int result = 0;
  5948. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  5949. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5950. // Flush the output with zeros a few times.
  5951. char *buffer;
  5952. int samples;
  5953. RtAudioFormat format;
  5954. if ( stream_.doConvertBuffer[0] ) {
  5955. buffer = stream_.deviceBuffer;
  5956. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  5957. format = stream_.deviceFormat[0];
  5958. }
  5959. else {
  5960. buffer = stream_.userBuffer[0];
  5961. samples = stream_.bufferSize * stream_.nUserChannels[0];
  5962. format = stream_.userFormat;
  5963. }
  5964. memset( buffer, 0, samples * formatBytes(format) );
  5965. for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
  5966. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  5967. if ( result == -1 ) {
  5968. errorText_ = "RtApiOss::stopStream: audio write error.";
  5969. error( RtError::WARNING );
  5970. }
  5971. }
  5972. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  5973. if ( result == -1 ) {
  5974. errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  5975. errorText_ = errorStream_.str();
  5976. goto unlock;
  5977. }
  5978. handle->triggered = false;
  5979. }
  5980. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  5981. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  5982. if ( result == -1 ) {
  5983. errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  5984. errorText_ = errorStream_.str();
  5985. goto unlock;
  5986. }
  5987. }
  5988. unlock:
  5989. stream_.state = STREAM_STOPPED;
  5990. MUTEX_UNLOCK( &stream_.mutex );
  5991. if ( result != -1 ) return;
  5992. error( RtError::SYSTEM_ERROR );
  5993. }
  5994. void RtApiOss :: abortStream()
  5995. {
  5996. verifyStream();
  5997. if ( stream_.state == STREAM_STOPPED ) {
  5998. errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
  5999. error( RtError::WARNING );
  6000. return;
  6001. }
  6002. MUTEX_LOCK( &stream_.mutex );
  6003. // The state might change while waiting on a mutex.
  6004. if ( stream_.state == STREAM_STOPPED ) {
  6005. MUTEX_UNLOCK( &stream_.mutex );
  6006. return;
  6007. }
  6008. int result = 0;
  6009. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  6010. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6011. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  6012. if ( result == -1 ) {
  6013. errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  6014. errorText_ = errorStream_.str();
  6015. goto unlock;
  6016. }
  6017. handle->triggered = false;
  6018. }
  6019. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  6020. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  6021. if ( result == -1 ) {
  6022. errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  6023. errorText_ = errorStream_.str();
  6024. goto unlock;
  6025. }
  6026. }
  6027. unlock:
  6028. stream_.state = STREAM_STOPPED;
  6029. MUTEX_UNLOCK( &stream_.mutex );
  6030. if ( result != -1 ) return;
  6031. error( RtError::SYSTEM_ERROR );
  6032. }
  6033. void RtApiOss :: callbackEvent()
  6034. {
  6035. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  6036. if ( stream_.state == STREAM_STOPPED ) {
  6037. MUTEX_LOCK( &stream_.mutex );
  6038. pthread_cond_wait( &handle->runnable, &stream_.mutex );
  6039. if ( stream_.state != STREAM_RUNNING ) {
  6040. MUTEX_UNLOCK( &stream_.mutex );
  6041. return;
  6042. }
  6043. MUTEX_UNLOCK( &stream_.mutex );
  6044. }
  6045. if ( stream_.state == STREAM_CLOSED ) {
  6046. errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
  6047. error( RtError::WARNING );
  6048. return;
  6049. }
  6050. // Invoke user callback to get fresh output data.
  6051. int doStopStream = 0;
  6052. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  6053. double streamTime = getStreamTime();
  6054. RtAudioStreamStatus status = 0;
  6055. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  6056. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  6057. handle->xrun[0] = false;
  6058. }
  6059. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  6060. status |= RTAUDIO_INPUT_OVERFLOW;
  6061. handle->xrun[1] = false;
  6062. }
  6063. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  6064. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  6065. if ( doStopStream == 2 ) {
  6066. this->abortStream();
  6067. return;
  6068. }
  6069. MUTEX_LOCK( &stream_.mutex );
  6070. // The state might change while waiting on a mutex.
  6071. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  6072. int result;
  6073. char *buffer;
  6074. int samples;
  6075. RtAudioFormat format;
  6076. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6077. // Setup parameters and do buffer conversion if necessary.
  6078. if ( stream_.doConvertBuffer[0] ) {
  6079. buffer = stream_.deviceBuffer;
  6080. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  6081. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  6082. format = stream_.deviceFormat[0];
  6083. }
  6084. else {
  6085. buffer = stream_.userBuffer[0];
  6086. samples = stream_.bufferSize * stream_.nUserChannels[0];
  6087. format = stream_.userFormat;
  6088. }
  6089. // Do byte swapping if necessary.
  6090. if ( stream_.doByteSwap[0] )
  6091. byteSwapBuffer( buffer, samples, format );
  6092. if ( stream_.mode == DUPLEX && handle->triggered == false ) {
  6093. int trig = 0;
  6094. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  6095. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  6096. trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
  6097. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  6098. handle->triggered = true;
  6099. }
  6100. else
  6101. // Write samples to device.
  6102. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  6103. if ( result == -1 ) {
  6104. // We'll assume this is an underrun, though there isn't a
  6105. // specific means for determining that.
  6106. handle->xrun[0] = true;
  6107. errorText_ = "RtApiOss::callbackEvent: audio write error.";
  6108. error( RtError::WARNING );
  6109. // Continue on to input section.
  6110. }
  6111. }
  6112. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  6113. // Setup parameters.
  6114. if ( stream_.doConvertBuffer[1] ) {
  6115. buffer = stream_.deviceBuffer;
  6116. samples = stream_.bufferSize * stream_.nDeviceChannels[1];
  6117. format = stream_.deviceFormat[1];
  6118. }
  6119. else {
  6120. buffer = stream_.userBuffer[1];
  6121. samples = stream_.bufferSize * stream_.nUserChannels[1];
  6122. format = stream_.userFormat;
  6123. }
  6124. // Read samples from device.
  6125. result = read( handle->id[1], buffer, samples * formatBytes(format) );
  6126. if ( result == -1 ) {
  6127. // We'll assume this is an overrun, though there isn't a
  6128. // specific means for determining that.
  6129. handle->xrun[1] = true;
  6130. errorText_ = "RtApiOss::callbackEvent: audio read error.";
  6131. error( RtError::WARNING );
  6132. goto unlock;
  6133. }
  6134. // Do byte swapping if necessary.
  6135. if ( stream_.doByteSwap[1] )
  6136. byteSwapBuffer( buffer, samples, format );
  6137. // Do buffer conversion if necessary.
  6138. if ( stream_.doConvertBuffer[1] )
  6139. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  6140. }
  6141. unlock:
  6142. MUTEX_UNLOCK( &stream_.mutex );
  6143. RtApi::tickStreamTime();
  6144. if ( doStopStream == 1 ) this->stopStream();
  6145. }
  6146. extern "C" void *ossCallbackHandler( void *ptr )
  6147. {
  6148. CallbackInfo *info = (CallbackInfo *) ptr;
  6149. RtApiOss *object = (RtApiOss *) info->object;
  6150. bool *isRunning = &info->isRunning;
  6151. while ( *isRunning == true ) {
  6152. pthread_testcancel();
  6153. object->callbackEvent();
  6154. }
  6155. pthread_exit( NULL );
  6156. }
  6157. //******************** End of __LINUX_OSS__ *********************//
  6158. #endif
  6159. // *************************************************** //
  6160. //
  6161. // Protected common (OS-independent) RtAudio methods.
  6162. //
  6163. // *************************************************** //
  6164. // This method can be modified to control the behavior of error
  6165. // message printing.
  6166. void RtApi :: error( RtError::Type type )
  6167. {
  6168. errorStream_.str(""); // clear the ostringstream
  6169. if ( type == RtError::WARNING && showWarnings_ == true )
  6170. std::cerr << '\n' << errorText_ << "\n\n";
  6171. else
  6172. throw( RtError( errorText_, type ) );
  6173. }
  6174. void RtApi :: verifyStream()
  6175. {
  6176. if ( stream_.state == STREAM_CLOSED ) {
  6177. errorText_ = "RtApi:: a stream is not open!";
  6178. error( RtError::INVALID_USE );
  6179. }
  6180. }
  6181. void RtApi :: clearStreamInfo()
  6182. {
  6183. stream_.mode = UNINITIALIZED;
  6184. stream_.state = STREAM_CLOSED;
  6185. stream_.sampleRate = 0;
  6186. stream_.bufferSize = 0;
  6187. stream_.nBuffers = 0;
  6188. stream_.userFormat = 0;
  6189. stream_.userInterleaved = true;
  6190. stream_.streamTime = 0.0;
  6191. stream_.apiHandle = 0;
  6192. stream_.deviceBuffer = 0;
  6193. stream_.callbackInfo.callback = 0;
  6194. stream_.callbackInfo.userData = 0;
  6195. stream_.callbackInfo.isRunning = false;
  6196. for ( int i=0; i<2; i++ ) {
  6197. stream_.device[i] = 11111;
  6198. stream_.doConvertBuffer[i] = false;
  6199. stream_.deviceInterleaved[i] = true;
  6200. stream_.doByteSwap[i] = false;
  6201. stream_.nUserChannels[i] = 0;
  6202. stream_.nDeviceChannels[i] = 0;
  6203. stream_.channelOffset[i] = 0;
  6204. stream_.deviceFormat[i] = 0;
  6205. stream_.latency[i] = 0;
  6206. stream_.userBuffer[i] = 0;
  6207. stream_.convertInfo[i].channels = 0;
  6208. stream_.convertInfo[i].inJump = 0;
  6209. stream_.convertInfo[i].outJump = 0;
  6210. stream_.convertInfo[i].inFormat = 0;
  6211. stream_.convertInfo[i].outFormat = 0;
  6212. stream_.convertInfo[i].inOffset.clear();
  6213. stream_.convertInfo[i].outOffset.clear();
  6214. }
  6215. }
  6216. unsigned int RtApi :: formatBytes( RtAudioFormat format )
  6217. {
  6218. if ( format == RTAUDIO_SINT16 )
  6219. return 2;
  6220. else if ( format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 ||
  6221. format == RTAUDIO_FLOAT32 )
  6222. return 4;
  6223. else if ( format == RTAUDIO_FLOAT64 )
  6224. return 8;
  6225. else if ( format == RTAUDIO_SINT8 )
  6226. return 1;
  6227. errorText_ = "RtApi::formatBytes: undefined format.";
  6228. error( RtError::WARNING );
  6229. return 0;
  6230. }
  6231. void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
  6232. {
  6233. if ( mode == INPUT ) { // convert device to user buffer
  6234. stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
  6235. stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
  6236. stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
  6237. stream_.convertInfo[mode].outFormat = stream_.userFormat;
  6238. }
  6239. else { // convert user to device buffer
  6240. stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
  6241. stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
  6242. stream_.convertInfo[mode].inFormat = stream_.userFormat;
  6243. stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
  6244. }
  6245. if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
  6246. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
  6247. else
  6248. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
  6249. // Set up the interleave/deinterleave offsets.
  6250. if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
  6251. if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
  6252. ( mode == INPUT && stream_.userInterleaved ) ) {
  6253. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  6254. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  6255. stream_.convertInfo[mode].outOffset.push_back( k );
  6256. stream_.convertInfo[mode].inJump = 1;
  6257. }
  6258. }
  6259. else {
  6260. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  6261. stream_.convertInfo[mode].inOffset.push_back( k );
  6262. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  6263. stream_.convertInfo[mode].outJump = 1;
  6264. }
  6265. }
  6266. }
  6267. else { // no (de)interleaving
  6268. if ( stream_.userInterleaved ) {
  6269. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  6270. stream_.convertInfo[mode].inOffset.push_back( k );
  6271. stream_.convertInfo[mode].outOffset.push_back( k );
  6272. }
  6273. }
  6274. else {
  6275. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  6276. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  6277. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  6278. stream_.convertInfo[mode].inJump = 1;
  6279. stream_.convertInfo[mode].outJump = 1;
  6280. }
  6281. }
  6282. }
  6283. // Add channel offset.
  6284. if ( firstChannel > 0 ) {
  6285. if ( stream_.deviceInterleaved[mode] ) {
  6286. if ( mode == OUTPUT ) {
  6287. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  6288. stream_.convertInfo[mode].outOffset[k] += firstChannel;
  6289. }
  6290. else {
  6291. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  6292. stream_.convertInfo[mode].inOffset[k] += firstChannel;
  6293. }
  6294. }
  6295. else {
  6296. if ( mode == OUTPUT ) {
  6297. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  6298. stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
  6299. }
  6300. else {
  6301. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  6302. stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize );
  6303. }
  6304. }
  6305. }
  6306. }
  6307. void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
  6308. {
  6309. // This function does format conversion, input/output channel compensation, and
  6310. // data interleaving/deinterleaving. 24-bit integers are assumed to occupy
  6311. // the upper three bytes of a 32-bit integer.
  6312. // Clear our device buffer when in/out duplex device channels are different
  6313. if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
  6314. ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
  6315. memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
  6316. int j;
  6317. if (info.outFormat == RTAUDIO_FLOAT64) {
  6318. Float64 scale;
  6319. Float64 *out = (Float64 *)outBuffer;
  6320. if (info.inFormat == RTAUDIO_SINT8) {
  6321. signed char *in = (signed char *)inBuffer;
  6322. scale = 1.0 / 127.5;
  6323. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6324. for (j=0; j<info.channels; j++) {
  6325. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  6326. out[info.outOffset[j]] += 0.5;
  6327. out[info.outOffset[j]] *= scale;
  6328. }
  6329. in += info.inJump;
  6330. out += info.outJump;
  6331. }
  6332. }
  6333. else if (info.inFormat == RTAUDIO_SINT16) {
  6334. Int16 *in = (Int16 *)inBuffer;
  6335. scale = 1.0 / 32767.5;
  6336. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6337. for (j=0; j<info.channels; j++) {
  6338. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  6339. out[info.outOffset[j]] += 0.5;
  6340. out[info.outOffset[j]] *= scale;
  6341. }
  6342. in += info.inJump;
  6343. out += info.outJump;
  6344. }
  6345. }
  6346. else if (info.inFormat == RTAUDIO_SINT24) {
  6347. Int32 *in = (Int32 *)inBuffer;
  6348. scale = 1.0 / 8388607.5;
  6349. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6350. for (j=0; j<info.channels; j++) {
  6351. out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]] & 0x00ffffff);
  6352. out[info.outOffset[j]] += 0.5;
  6353. out[info.outOffset[j]] *= scale;
  6354. }
  6355. in += info.inJump;
  6356. out += info.outJump;
  6357. }
  6358. }
  6359. else if (info.inFormat == RTAUDIO_SINT32) {
  6360. Int32 *in = (Int32 *)inBuffer;
  6361. scale = 1.0 / 2147483647.5;
  6362. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6363. for (j=0; j<info.channels; j++) {
  6364. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  6365. out[info.outOffset[j]] += 0.5;
  6366. out[info.outOffset[j]] *= scale;
  6367. }
  6368. in += info.inJump;
  6369. out += info.outJump;
  6370. }
  6371. }
  6372. else if (info.inFormat == RTAUDIO_FLOAT32) {
  6373. Float32 *in = (Float32 *)inBuffer;
  6374. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6375. for (j=0; j<info.channels; j++) {
  6376. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  6377. }
  6378. in += info.inJump;
  6379. out += info.outJump;
  6380. }
  6381. }
  6382. else if (info.inFormat == RTAUDIO_FLOAT64) {
  6383. // Channel compensation and/or (de)interleaving only.
  6384. Float64 *in = (Float64 *)inBuffer;
  6385. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6386. for (j=0; j<info.channels; j++) {
  6387. out[info.outOffset[j]] = in[info.inOffset[j]];
  6388. }
  6389. in += info.inJump;
  6390. out += info.outJump;
  6391. }
  6392. }
  6393. }
  6394. else if (info.outFormat == RTAUDIO_FLOAT32) {
  6395. Float32 scale;
  6396. Float32 *out = (Float32 *)outBuffer;
  6397. if (info.inFormat == RTAUDIO_SINT8) {
  6398. signed char *in = (signed char *)inBuffer;
  6399. scale = (Float32) ( 1.0 / 127.5 );
  6400. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6401. for (j=0; j<info.channels; j++) {
  6402. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  6403. out[info.outOffset[j]] += 0.5;
  6404. out[info.outOffset[j]] *= scale;
  6405. }
  6406. in += info.inJump;
  6407. out += info.outJump;
  6408. }
  6409. }
  6410. else if (info.inFormat == RTAUDIO_SINT16) {
  6411. Int16 *in = (Int16 *)inBuffer;
  6412. scale = (Float32) ( 1.0 / 32767.5 );
  6413. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6414. for (j=0; j<info.channels; j++) {
  6415. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  6416. out[info.outOffset[j]] += 0.5;
  6417. out[info.outOffset[j]] *= scale;
  6418. }
  6419. in += info.inJump;
  6420. out += info.outJump;
  6421. }
  6422. }
  6423. else if (info.inFormat == RTAUDIO_SINT24) {
  6424. Int32 *in = (Int32 *)inBuffer;
  6425. scale = (Float32) ( 1.0 / 8388607.5 );
  6426. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6427. for (j=0; j<info.channels; j++) {
  6428. out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]] & 0x00ffffff);
  6429. out[info.outOffset[j]] += 0.5;
  6430. out[info.outOffset[j]] *= scale;
  6431. }
  6432. in += info.inJump;
  6433. out += info.outJump;
  6434. }
  6435. }
  6436. else if (info.inFormat == RTAUDIO_SINT32) {
  6437. Int32 *in = (Int32 *)inBuffer;
  6438. scale = (Float32) ( 1.0 / 2147483647.5 );
  6439. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6440. for (j=0; j<info.channels; j++) {
  6441. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  6442. out[info.outOffset[j]] += 0.5;
  6443. out[info.outOffset[j]] *= scale;
  6444. }
  6445. in += info.inJump;
  6446. out += info.outJump;
  6447. }
  6448. }
  6449. else if (info.inFormat == RTAUDIO_FLOAT32) {
  6450. // Channel compensation and/or (de)interleaving only.
  6451. Float32 *in = (Float32 *)inBuffer;
  6452. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6453. for (j=0; j<info.channels; j++) {
  6454. out[info.outOffset[j]] = in[info.inOffset[j]];
  6455. }
  6456. in += info.inJump;
  6457. out += info.outJump;
  6458. }
  6459. }
  6460. else if (info.inFormat == RTAUDIO_FLOAT64) {
  6461. Float64 *in = (Float64 *)inBuffer;
  6462. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6463. for (j=0; j<info.channels; j++) {
  6464. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  6465. }
  6466. in += info.inJump;
  6467. out += info.outJump;
  6468. }
  6469. }
  6470. }
  6471. else if (info.outFormat == RTAUDIO_SINT32) {
  6472. Int32 *out = (Int32 *)outBuffer;
  6473. if (info.inFormat == RTAUDIO_SINT8) {
  6474. signed char *in = (signed char *)inBuffer;
  6475. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6476. for (j=0; j<info.channels; j++) {
  6477. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  6478. out[info.outOffset[j]] <<= 24;
  6479. }
  6480. in += info.inJump;
  6481. out += info.outJump;
  6482. }
  6483. }
  6484. else if (info.inFormat == RTAUDIO_SINT16) {
  6485. Int16 *in = (Int16 *)inBuffer;
  6486. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6487. for (j=0; j<info.channels; j++) {
  6488. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  6489. out[info.outOffset[j]] <<= 16;
  6490. }
  6491. in += info.inJump;
  6492. out += info.outJump;
  6493. }
  6494. }
  6495. else if (info.inFormat == RTAUDIO_SINT24) {
  6496. Int32 *in = (Int32 *)inBuffer;
  6497. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6498. for (j=0; j<info.channels; j++) {
  6499. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  6500. out[info.outOffset[j]] <<= 8;
  6501. }
  6502. in += info.inJump;
  6503. out += info.outJump;
  6504. }
  6505. }
  6506. else if (info.inFormat == RTAUDIO_SINT32) {
  6507. // Channel compensation and/or (de)interleaving only.
  6508. Int32 *in = (Int32 *)inBuffer;
  6509. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6510. for (j=0; j<info.channels; j++) {
  6511. out[info.outOffset[j]] = in[info.inOffset[j]];
  6512. }
  6513. in += info.inJump;
  6514. out += info.outJump;
  6515. }
  6516. }
  6517. else if (info.inFormat == RTAUDIO_FLOAT32) {
  6518. Float32 *in = (Float32 *)inBuffer;
  6519. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6520. for (j=0; j<info.channels; j++) {
  6521. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  6522. }
  6523. in += info.inJump;
  6524. out += info.outJump;
  6525. }
  6526. }
  6527. else if (info.inFormat == RTAUDIO_FLOAT64) {
  6528. Float64 *in = (Float64 *)inBuffer;
  6529. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6530. for (j=0; j<info.channels; j++) {
  6531. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  6532. }
  6533. in += info.inJump;
  6534. out += info.outJump;
  6535. }
  6536. }
  6537. }
  6538. else if (info.outFormat == RTAUDIO_SINT24) {
  6539. Int32 *out = (Int32 *)outBuffer;
  6540. if (info.inFormat == RTAUDIO_SINT8) {
  6541. signed char *in = (signed char *)inBuffer;
  6542. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6543. for (j=0; j<info.channels; j++) {
  6544. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  6545. out[info.outOffset[j]] <<= 16;
  6546. }
  6547. in += info.inJump;
  6548. out += info.outJump;
  6549. }
  6550. }
  6551. else if (info.inFormat == RTAUDIO_SINT16) {
  6552. Int16 *in = (Int16 *)inBuffer;
  6553. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6554. for (j=0; j<info.channels; j++) {
  6555. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  6556. out[info.outOffset[j]] <<= 8;
  6557. }
  6558. in += info.inJump;
  6559. out += info.outJump;
  6560. }
  6561. }
  6562. else if (info.inFormat == RTAUDIO_SINT24) {
  6563. // Channel compensation and/or (de)interleaving only.
  6564. Int32 *in = (Int32 *)inBuffer;
  6565. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6566. for (j=0; j<info.channels; j++) {
  6567. out[info.outOffset[j]] = in[info.inOffset[j]];
  6568. }
  6569. in += info.inJump;
  6570. out += info.outJump;
  6571. }
  6572. }
  6573. else if (info.inFormat == RTAUDIO_SINT32) {
  6574. Int32 *in = (Int32 *)inBuffer;
  6575. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6576. for (j=0; j<info.channels; j++) {
  6577. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  6578. out[info.outOffset[j]] >>= 8;
  6579. }
  6580. in += info.inJump;
  6581. out += info.outJump;
  6582. }
  6583. }
  6584. else if (info.inFormat == RTAUDIO_FLOAT32) {
  6585. Float32 *in = (Float32 *)inBuffer;
  6586. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6587. for (j=0; j<info.channels; j++) {
  6588. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  6589. }
  6590. in += info.inJump;
  6591. out += info.outJump;
  6592. }
  6593. }
  6594. else if (info.inFormat == RTAUDIO_FLOAT64) {
  6595. Float64 *in = (Float64 *)inBuffer;
  6596. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6597. for (j=0; j<info.channels; j++) {
  6598. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  6599. }
  6600. in += info.inJump;
  6601. out += info.outJump;
  6602. }
  6603. }
  6604. }
  6605. else if (info.outFormat == RTAUDIO_SINT16) {
  6606. Int16 *out = (Int16 *)outBuffer;
  6607. if (info.inFormat == RTAUDIO_SINT8) {
  6608. signed char *in = (signed char *)inBuffer;
  6609. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6610. for (j=0; j<info.channels; j++) {
  6611. out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
  6612. out[info.outOffset[j]] <<= 8;
  6613. }
  6614. in += info.inJump;
  6615. out += info.outJump;
  6616. }
  6617. }
  6618. else if (info.inFormat == RTAUDIO_SINT16) {
  6619. // Channel compensation and/or (de)interleaving only.
  6620. Int16 *in = (Int16 *)inBuffer;
  6621. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6622. for (j=0; j<info.channels; j++) {
  6623. out[info.outOffset[j]] = in[info.inOffset[j]];
  6624. }
  6625. in += info.inJump;
  6626. out += info.outJump;
  6627. }
  6628. }
  6629. else if (info.inFormat == RTAUDIO_SINT24) {
  6630. Int32 *in = (Int32 *)inBuffer;
  6631. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6632. for (j=0; j<info.channels; j++) {
  6633. out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 8) & 0x0000ffff);
  6634. }
  6635. in += info.inJump;
  6636. out += info.outJump;
  6637. }
  6638. }
  6639. else if (info.inFormat == RTAUDIO_SINT32) {
  6640. Int32 *in = (Int32 *)inBuffer;
  6641. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6642. for (j=0; j<info.channels; j++) {
  6643. out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
  6644. }
  6645. in += info.inJump;
  6646. out += info.outJump;
  6647. }
  6648. }
  6649. else if (info.inFormat == RTAUDIO_FLOAT32) {
  6650. Float32 *in = (Float32 *)inBuffer;
  6651. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6652. for (j=0; j<info.channels; j++) {
  6653. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  6654. }
  6655. in += info.inJump;
  6656. out += info.outJump;
  6657. }
  6658. }
  6659. else if (info.inFormat == RTAUDIO_FLOAT64) {
  6660. Float64 *in = (Float64 *)inBuffer;
  6661. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6662. for (j=0; j<info.channels; j++) {
  6663. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  6664. }
  6665. in += info.inJump;
  6666. out += info.outJump;
  6667. }
  6668. }
  6669. }
  6670. else if (info.outFormat == RTAUDIO_SINT8) {
  6671. signed char *out = (signed char *)outBuffer;
  6672. if (info.inFormat == RTAUDIO_SINT8) {
  6673. // Channel compensation and/or (de)interleaving only.
  6674. signed char *in = (signed char *)inBuffer;
  6675. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6676. for (j=0; j<info.channels; j++) {
  6677. out[info.outOffset[j]] = in[info.inOffset[j]];
  6678. }
  6679. in += info.inJump;
  6680. out += info.outJump;
  6681. }
  6682. }
  6683. if (info.inFormat == RTAUDIO_SINT16) {
  6684. Int16 *in = (Int16 *)inBuffer;
  6685. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6686. for (j=0; j<info.channels; j++) {
  6687. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
  6688. }
  6689. in += info.inJump;
  6690. out += info.outJump;
  6691. }
  6692. }
  6693. else if (info.inFormat == RTAUDIO_SINT24) {
  6694. Int32 *in = (Int32 *)inBuffer;
  6695. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6696. for (j=0; j<info.channels; j++) {
  6697. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 16) & 0x000000ff);
  6698. }
  6699. in += info.inJump;
  6700. out += info.outJump;
  6701. }
  6702. }
  6703. else if (info.inFormat == RTAUDIO_SINT32) {
  6704. Int32 *in = (Int32 *)inBuffer;
  6705. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6706. for (j=0; j<info.channels; j++) {
  6707. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
  6708. }
  6709. in += info.inJump;
  6710. out += info.outJump;
  6711. }
  6712. }
  6713. else if (info.inFormat == RTAUDIO_FLOAT32) {
  6714. Float32 *in = (Float32 *)inBuffer;
  6715. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6716. for (j=0; j<info.channels; j++) {
  6717. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  6718. }
  6719. in += info.inJump;
  6720. out += info.outJump;
  6721. }
  6722. }
  6723. else if (info.inFormat == RTAUDIO_FLOAT64) {
  6724. Float64 *in = (Float64 *)inBuffer;
  6725. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  6726. for (j=0; j<info.channels; j++) {
  6727. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  6728. }
  6729. in += info.inJump;
  6730. out += info.outJump;
  6731. }
  6732. }
  6733. }
  6734. }
  6735. //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
  6736. //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
  6737. //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
  6738. void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
  6739. {
  6740. register char val;
  6741. register char *ptr;
  6742. ptr = buffer;
  6743. if ( format == RTAUDIO_SINT16 ) {
  6744. for ( unsigned int i=0; i<samples; i++ ) {
  6745. // Swap 1st and 2nd bytes.
  6746. val = *(ptr);
  6747. *(ptr) = *(ptr+1);
  6748. *(ptr+1) = val;
  6749. // Increment 2 bytes.
  6750. ptr += 2;
  6751. }
  6752. }
  6753. else if ( format == RTAUDIO_SINT24 ||
  6754. format == RTAUDIO_SINT32 ||
  6755. format == RTAUDIO_FLOAT32 ) {
  6756. for ( unsigned int i=0; i<samples; i++ ) {
  6757. // Swap 1st and 4th bytes.
  6758. val = *(ptr);
  6759. *(ptr) = *(ptr+3);
  6760. *(ptr+3) = val;
  6761. // Swap 2nd and 3rd bytes.
  6762. ptr += 1;
  6763. val = *(ptr);
  6764. *(ptr) = *(ptr+1);
  6765. *(ptr+1) = val;
  6766. // Increment 3 more bytes.
  6767. ptr += 3;
  6768. }
  6769. }
  6770. else if ( format == RTAUDIO_FLOAT64 ) {
  6771. for ( unsigned int i=0; i<samples; i++ ) {
  6772. // Swap 1st and 8th bytes
  6773. val = *(ptr);
  6774. *(ptr) = *(ptr+7);
  6775. *(ptr+7) = val;
  6776. // Swap 2nd and 7th bytes
  6777. ptr += 1;
  6778. val = *(ptr);
  6779. *(ptr) = *(ptr+5);
  6780. *(ptr+5) = val;
  6781. // Swap 3rd and 6th bytes
  6782. ptr += 1;
  6783. val = *(ptr);
  6784. *(ptr) = *(ptr+3);
  6785. *(ptr+3) = val;
  6786. // Swap 4th and 5th bytes
  6787. ptr += 1;
  6788. val = *(ptr);
  6789. *(ptr) = *(ptr+1);
  6790. *(ptr+1) = val;
  6791. // Increment 5 more bytes.
  6792. ptr += 5;
  6793. }
  6794. }
  6795. }
  6796. // Indentation settings for Vim and Emacs
  6797. //
  6798. // Local Variables:
  6799. // c-basic-offset: 2
  6800. // indent-tabs-mode: nil
  6801. // End:
  6802. //
  6803. // vim: et sts=2 sw=2