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.

7892 lines
268KB

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