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.

7988 lines
281KB

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