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.

10124 lines
356KB

  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, ASIO and WASAPI) 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-2014 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.1.1pre
  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__) || defined(__WINDOWS_WASAPI__)
  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(__LINUX_PULSE__) || 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. std::string RtAudio :: getVersion( void ) throw()
  66. {
  67. return RTAUDIO_VERSION;
  68. }
  69. void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis ) throw()
  70. {
  71. apis.clear();
  72. // The order here will control the order of RtAudio's API search in
  73. // the constructor.
  74. #if defined(__UNIX_JACK__)
  75. apis.push_back( UNIX_JACK );
  76. #endif
  77. #if defined(__LINUX_ALSA__)
  78. apis.push_back( LINUX_ALSA );
  79. #endif
  80. #if defined(__LINUX_PULSE__)
  81. apis.push_back( LINUX_PULSE );
  82. #endif
  83. #if defined(__LINUX_OSS__)
  84. apis.push_back( LINUX_OSS );
  85. #endif
  86. #if defined(__WINDOWS_ASIO__)
  87. apis.push_back( WINDOWS_ASIO );
  88. #endif
  89. #if defined(__WINDOWS_WASAPI__)
  90. apis.push_back( WINDOWS_WASAPI );
  91. #endif
  92. #if defined(__WINDOWS_DS__)
  93. apis.push_back( WINDOWS_DS );
  94. #endif
  95. #if defined(__MACOSX_CORE__)
  96. apis.push_back( MACOSX_CORE );
  97. #endif
  98. #if defined(__RTAUDIO_DUMMY__)
  99. apis.push_back( RTAUDIO_DUMMY );
  100. #endif
  101. }
  102. void RtAudio :: openRtApi( RtAudio::Api api )
  103. {
  104. if ( rtapi_ )
  105. delete rtapi_;
  106. rtapi_ = 0;
  107. #if defined(__UNIX_JACK__)
  108. if ( api == UNIX_JACK )
  109. rtapi_ = new RtApiJack();
  110. #endif
  111. #if defined(__LINUX_ALSA__)
  112. if ( api == LINUX_ALSA )
  113. rtapi_ = new RtApiAlsa();
  114. #endif
  115. #if defined(__LINUX_PULSE__)
  116. if ( api == LINUX_PULSE )
  117. rtapi_ = new RtApiPulse();
  118. #endif
  119. #if defined(__LINUX_OSS__)
  120. if ( api == LINUX_OSS )
  121. rtapi_ = new RtApiOss();
  122. #endif
  123. #if defined(__WINDOWS_ASIO__)
  124. if ( api == WINDOWS_ASIO )
  125. rtapi_ = new RtApiAsio();
  126. #endif
  127. #if defined(__WINDOWS_WASAPI__)
  128. if ( api == WINDOWS_WASAPI )
  129. rtapi_ = new RtApiWasapi();
  130. #endif
  131. #if defined(__WINDOWS_DS__)
  132. if ( api == WINDOWS_DS )
  133. rtapi_ = new RtApiDs();
  134. #endif
  135. #if defined(__MACOSX_CORE__)
  136. if ( api == MACOSX_CORE )
  137. rtapi_ = new RtApiCore();
  138. #endif
  139. #if defined(__RTAUDIO_DUMMY__)
  140. if ( api == RTAUDIO_DUMMY )
  141. rtapi_ = new RtApiDummy();
  142. #endif
  143. }
  144. RtAudio :: RtAudio( RtAudio::Api api )
  145. {
  146. rtapi_ = 0;
  147. if ( api != UNSPECIFIED ) {
  148. // Attempt to open the specified API.
  149. openRtApi( api );
  150. if ( rtapi_ ) return;
  151. // No compiled support for specified API value. Issue a debug
  152. // warning and continue as if no API was specified.
  153. std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;
  154. }
  155. // Iterate through the compiled APIs and return as soon as we find
  156. // one with at least one device or we reach the end of the list.
  157. std::vector< RtAudio::Api > apis;
  158. getCompiledApi( apis );
  159. for ( unsigned int i=0; i<apis.size(); i++ ) {
  160. openRtApi( apis[i] );
  161. if ( rtapi_->getDeviceCount() ) break;
  162. }
  163. if ( rtapi_ ) return;
  164. // It should not be possible to get here because the preprocessor
  165. // definition __RTAUDIO_DUMMY__ is automatically defined if no
  166. // API-specific definitions are passed to the compiler. But just in
  167. // case something weird happens, we'll thow an error.
  168. std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";
  169. throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );
  170. }
  171. RtAudio :: ~RtAudio() throw()
  172. {
  173. if ( rtapi_ )
  174. delete rtapi_;
  175. }
  176. void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
  177. RtAudio::StreamParameters *inputParameters,
  178. RtAudioFormat format, unsigned int sampleRate,
  179. unsigned int *bufferFrames,
  180. RtAudioCallback callback, void *userData,
  181. RtAudio::StreamOptions *options,
  182. RtAudioErrorCallback errorCallback )
  183. {
  184. return rtapi_->openStream( outputParameters, inputParameters, format,
  185. sampleRate, bufferFrames, callback,
  186. userData, options, errorCallback );
  187. }
  188. // *************************************************** //
  189. //
  190. // Public RtApi definitions (see end of file for
  191. // private or protected utility functions).
  192. //
  193. // *************************************************** //
  194. RtApi :: RtApi()
  195. {
  196. stream_.state = STREAM_CLOSED;
  197. stream_.mode = UNINITIALIZED;
  198. stream_.apiHandle = 0;
  199. stream_.userBuffer[0] = 0;
  200. stream_.userBuffer[1] = 0;
  201. MUTEX_INITIALIZE( &stream_.mutex );
  202. showWarnings_ = true;
  203. firstErrorOccurred_ = false;
  204. }
  205. RtApi :: ~RtApi()
  206. {
  207. MUTEX_DESTROY( &stream_.mutex );
  208. }
  209. void RtApi :: openStream( RtAudio::StreamParameters *oParams,
  210. RtAudio::StreamParameters *iParams,
  211. RtAudioFormat format, unsigned int sampleRate,
  212. unsigned int *bufferFrames,
  213. RtAudioCallback callback, void *userData,
  214. RtAudio::StreamOptions *options,
  215. RtAudioErrorCallback errorCallback )
  216. {
  217. if ( stream_.state != STREAM_CLOSED ) {
  218. errorText_ = "RtApi::openStream: a stream is already open!";
  219. error( RtAudioError::INVALID_USE );
  220. return;
  221. }
  222. // Clear stream information potentially left from a previously open stream.
  223. clearStreamInfo();
  224. if ( oParams && oParams->nChannels < 1 ) {
  225. errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
  226. error( RtAudioError::INVALID_USE );
  227. return;
  228. }
  229. if ( iParams && iParams->nChannels < 1 ) {
  230. errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
  231. error( RtAudioError::INVALID_USE );
  232. return;
  233. }
  234. if ( oParams == NULL && iParams == NULL ) {
  235. errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
  236. error( RtAudioError::INVALID_USE );
  237. return;
  238. }
  239. if ( formatBytes(format) == 0 ) {
  240. errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
  241. error( RtAudioError::INVALID_USE );
  242. return;
  243. }
  244. unsigned int nDevices = getDeviceCount();
  245. unsigned int oChannels = 0;
  246. if ( oParams ) {
  247. oChannels = oParams->nChannels;
  248. if ( oParams->deviceId >= nDevices ) {
  249. errorText_ = "RtApi::openStream: output device parameter value is invalid.";
  250. error( RtAudioError::INVALID_USE );
  251. return;
  252. }
  253. }
  254. unsigned int iChannels = 0;
  255. if ( iParams ) {
  256. iChannels = iParams->nChannels;
  257. if ( iParams->deviceId >= nDevices ) {
  258. errorText_ = "RtApi::openStream: input device parameter value is invalid.";
  259. error( RtAudioError::INVALID_USE );
  260. return;
  261. }
  262. }
  263. bool result;
  264. if ( oChannels > 0 ) {
  265. result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
  266. sampleRate, format, bufferFrames, options );
  267. if ( result == false ) {
  268. error( RtAudioError::SYSTEM_ERROR );
  269. return;
  270. }
  271. }
  272. if ( iChannels > 0 ) {
  273. result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
  274. sampleRate, format, bufferFrames, options );
  275. if ( result == false ) {
  276. if ( oChannels > 0 ) closeStream();
  277. error( RtAudioError::SYSTEM_ERROR );
  278. return;
  279. }
  280. }
  281. stream_.callbackInfo.callback = (void *) callback;
  282. stream_.callbackInfo.userData = userData;
  283. stream_.callbackInfo.errorCallback = (void *) errorCallback;
  284. if ( options ) options->numberOfBuffers = stream_.nBuffers;
  285. stream_.state = STREAM_STOPPED;
  286. }
  287. unsigned int RtApi :: getDefaultInputDevice( void )
  288. {
  289. // Should be implemented in subclasses if possible.
  290. return 0;
  291. }
  292. unsigned int RtApi :: getDefaultOutputDevice( void )
  293. {
  294. // Should be implemented in subclasses if possible.
  295. return 0;
  296. }
  297. void RtApi :: closeStream( void )
  298. {
  299. // MUST be implemented in subclasses!
  300. return;
  301. }
  302. bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
  303. unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
  304. RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
  305. RtAudio::StreamOptions * /*options*/ )
  306. {
  307. // MUST be implemented in subclasses!
  308. return FAILURE;
  309. }
  310. void RtApi :: tickStreamTime( void )
  311. {
  312. // Subclasses that do not provide their own implementation of
  313. // getStreamTime should call this function once per buffer I/O to
  314. // provide basic stream time support.
  315. stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
  316. #if defined( HAVE_GETTIMEOFDAY )
  317. gettimeofday( &stream_.lastTickTimestamp, NULL );
  318. #endif
  319. }
  320. long RtApi :: getStreamLatency( void )
  321. {
  322. verifyStream();
  323. long totalLatency = 0;
  324. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  325. totalLatency = stream_.latency[0];
  326. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  327. totalLatency += stream_.latency[1];
  328. return totalLatency;
  329. }
  330. double RtApi :: getStreamTime( void )
  331. {
  332. verifyStream();
  333. #if defined( HAVE_GETTIMEOFDAY )
  334. // Return a very accurate estimate of the stream time by
  335. // adding in the elapsed time since the last tick.
  336. struct timeval then;
  337. struct timeval now;
  338. if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
  339. return stream_.streamTime;
  340. gettimeofday( &now, NULL );
  341. then = stream_.lastTickTimestamp;
  342. return stream_.streamTime +
  343. ((now.tv_sec + 0.000001 * now.tv_usec) -
  344. (then.tv_sec + 0.000001 * then.tv_usec));
  345. #else
  346. return stream_.streamTime;
  347. #endif
  348. }
  349. unsigned int RtApi :: getStreamSampleRate( void )
  350. {
  351. verifyStream();
  352. return stream_.sampleRate;
  353. }
  354. // *************************************************** //
  355. //
  356. // OS/API-specific methods.
  357. //
  358. // *************************************************** //
  359. #if defined(__MACOSX_CORE__)
  360. // The OS X CoreAudio API is designed to use a separate callback
  361. // procedure for each of its audio devices. A single RtAudio duplex
  362. // stream using two different devices is supported here, though it
  363. // cannot be guaranteed to always behave correctly because we cannot
  364. // synchronize these two callbacks.
  365. //
  366. // A property listener is installed for over/underrun information.
  367. // However, no functionality is currently provided to allow property
  368. // listeners to trigger user handlers because it is unclear what could
  369. // be done if a critical stream parameter (buffer size, sample rate,
  370. // device disconnect) notification arrived. The listeners entail
  371. // quite a bit of extra code and most likely, a user program wouldn't
  372. // be prepared for the result anyway. However, we do provide a flag
  373. // to the client callback function to inform of an over/underrun.
  374. // A structure to hold various information related to the CoreAudio API
  375. // implementation.
  376. struct CoreHandle {
  377. AudioDeviceID id[2]; // device ids
  378. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  379. AudioDeviceIOProcID procId[2];
  380. #endif
  381. UInt32 iStream[2]; // device stream index (or first if using multiple)
  382. UInt32 nStreams[2]; // number of streams to use
  383. bool xrun[2];
  384. char *deviceBuffer;
  385. pthread_cond_t condition;
  386. int drainCounter; // Tracks callback counts when draining
  387. bool internalDrain; // Indicates if stop is initiated from callback or not.
  388. CoreHandle()
  389. :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  390. };
  391. RtApiCore:: RtApiCore()
  392. {
  393. #if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )
  394. // This is a largely undocumented but absolutely necessary
  395. // requirement starting with OS-X 10.6. If not called, queries and
  396. // updates to various audio device properties are not handled
  397. // correctly.
  398. CFRunLoopRef theRunLoop = NULL;
  399. AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,
  400. kAudioObjectPropertyScopeGlobal,
  401. kAudioObjectPropertyElementMaster };
  402. OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  403. if ( result != noErr ) {
  404. errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
  405. error( RtAudioError::WARNING );
  406. }
  407. #endif
  408. }
  409. RtApiCore :: ~RtApiCore()
  410. {
  411. // The subclass destructor gets called before the base class
  412. // destructor, so close an existing stream before deallocating
  413. // apiDeviceId memory.
  414. if ( stream_.state != STREAM_CLOSED ) closeStream();
  415. }
  416. unsigned int RtApiCore :: getDeviceCount( void )
  417. {
  418. // Find out how many audio devices there are, if any.
  419. UInt32 dataSize;
  420. AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  421. OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );
  422. if ( result != noErr ) {
  423. errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
  424. error( RtAudioError::WARNING );
  425. return 0;
  426. }
  427. return dataSize / sizeof( AudioDeviceID );
  428. }
  429. unsigned int RtApiCore :: getDefaultInputDevice( void )
  430. {
  431. unsigned int nDevices = getDeviceCount();
  432. if ( nDevices <= 1 ) return 0;
  433. AudioDeviceID id;
  434. UInt32 dataSize = sizeof( AudioDeviceID );
  435. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  436. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  437. if ( result != noErr ) {
  438. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
  439. error( RtAudioError::WARNING );
  440. return 0;
  441. }
  442. dataSize *= nDevices;
  443. AudioDeviceID deviceList[ nDevices ];
  444. property.mSelector = kAudioHardwarePropertyDevices;
  445. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  446. if ( result != noErr ) {
  447. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
  448. error( RtAudioError::WARNING );
  449. return 0;
  450. }
  451. for ( unsigned int i=0; i<nDevices; i++ )
  452. if ( id == deviceList[i] ) return i;
  453. errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
  454. error( RtAudioError::WARNING );
  455. return 0;
  456. }
  457. unsigned int RtApiCore :: getDefaultOutputDevice( void )
  458. {
  459. unsigned int nDevices = getDeviceCount();
  460. if ( nDevices <= 1 ) return 0;
  461. AudioDeviceID id;
  462. UInt32 dataSize = sizeof( AudioDeviceID );
  463. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  464. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  465. if ( result != noErr ) {
  466. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
  467. error( RtAudioError::WARNING );
  468. return 0;
  469. }
  470. dataSize = sizeof( AudioDeviceID ) * nDevices;
  471. AudioDeviceID deviceList[ nDevices ];
  472. property.mSelector = kAudioHardwarePropertyDevices;
  473. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  474. if ( result != noErr ) {
  475. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
  476. error( RtAudioError::WARNING );
  477. return 0;
  478. }
  479. for ( unsigned int i=0; i<nDevices; i++ )
  480. if ( id == deviceList[i] ) return i;
  481. errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
  482. error( RtAudioError::WARNING );
  483. return 0;
  484. }
  485. RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
  486. {
  487. RtAudio::DeviceInfo info;
  488. info.probed = false;
  489. // Get device ID
  490. unsigned int nDevices = getDeviceCount();
  491. if ( nDevices == 0 ) {
  492. errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
  493. error( RtAudioError::INVALID_USE );
  494. return info;
  495. }
  496. if ( device >= nDevices ) {
  497. errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
  498. error( RtAudioError::INVALID_USE );
  499. return info;
  500. }
  501. AudioDeviceID deviceList[ nDevices ];
  502. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  503. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  504. kAudioObjectPropertyScopeGlobal,
  505. kAudioObjectPropertyElementMaster };
  506. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  507. 0, NULL, &dataSize, (void *) &deviceList );
  508. if ( result != noErr ) {
  509. errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
  510. error( RtAudioError::WARNING );
  511. return info;
  512. }
  513. AudioDeviceID id = deviceList[ device ];
  514. // Get the device name.
  515. info.name.erase();
  516. CFStringRef cfname;
  517. dataSize = sizeof( CFStringRef );
  518. property.mSelector = kAudioObjectPropertyManufacturer;
  519. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  520. if ( result != noErr ) {
  521. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
  522. errorText_ = errorStream_.str();
  523. error( RtAudioError::WARNING );
  524. return info;
  525. }
  526. //const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  527. int length = CFStringGetLength(cfname);
  528. char *mname = (char *)malloc(length * 3 + 1);
  529. #if defined( UNICODE ) || defined( _UNICODE )
  530. CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
  531. #else
  532. CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
  533. #endif
  534. info.name.append( (const char *)mname, strlen(mname) );
  535. info.name.append( ": " );
  536. CFRelease( cfname );
  537. free(mname);
  538. property.mSelector = kAudioObjectPropertyName;
  539. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  540. if ( result != noErr ) {
  541. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
  542. errorText_ = errorStream_.str();
  543. error( RtAudioError::WARNING );
  544. return info;
  545. }
  546. //const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  547. length = CFStringGetLength(cfname);
  548. char *name = (char *)malloc(length * 3 + 1);
  549. #if defined( UNICODE ) || defined( _UNICODE )
  550. CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
  551. #else
  552. CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
  553. #endif
  554. info.name.append( (const char *)name, strlen(name) );
  555. CFRelease( cfname );
  556. free(name);
  557. // Get the output stream "configuration".
  558. AudioBufferList *bufferList = nil;
  559. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  560. property.mScope = kAudioDevicePropertyScopeOutput;
  561. // property.mElement = kAudioObjectPropertyElementWildcard;
  562. dataSize = 0;
  563. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  564. if ( result != noErr || dataSize == 0 ) {
  565. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";
  566. errorText_ = errorStream_.str();
  567. error( RtAudioError::WARNING );
  568. return info;
  569. }
  570. // Allocate the AudioBufferList.
  571. bufferList = (AudioBufferList *) malloc( dataSize );
  572. if ( bufferList == NULL ) {
  573. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
  574. error( RtAudioError::WARNING );
  575. return info;
  576. }
  577. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  578. if ( result != noErr || dataSize == 0 ) {
  579. free( bufferList );
  580. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";
  581. errorText_ = errorStream_.str();
  582. error( RtAudioError::WARNING );
  583. return info;
  584. }
  585. // Get output channel information.
  586. unsigned int i, nStreams = bufferList->mNumberBuffers;
  587. for ( i=0; i<nStreams; i++ )
  588. info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
  589. free( bufferList );
  590. // Get the input stream "configuration".
  591. property.mScope = kAudioDevicePropertyScopeInput;
  592. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  593. if ( result != noErr || dataSize == 0 ) {
  594. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";
  595. errorText_ = errorStream_.str();
  596. error( RtAudioError::WARNING );
  597. return info;
  598. }
  599. // Allocate the AudioBufferList.
  600. bufferList = (AudioBufferList *) malloc( dataSize );
  601. if ( bufferList == NULL ) {
  602. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
  603. error( RtAudioError::WARNING );
  604. return info;
  605. }
  606. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  607. if (result != noErr || dataSize == 0) {
  608. free( bufferList );
  609. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";
  610. errorText_ = errorStream_.str();
  611. error( RtAudioError::WARNING );
  612. return info;
  613. }
  614. // Get input channel information.
  615. nStreams = bufferList->mNumberBuffers;
  616. for ( i=0; i<nStreams; i++ )
  617. info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
  618. free( bufferList );
  619. // If device opens for both playback and capture, we determine the channels.
  620. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  621. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  622. // Probe the device sample rates.
  623. bool isInput = false;
  624. if ( info.outputChannels == 0 ) isInput = true;
  625. // Determine the supported sample rates.
  626. property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  627. if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;
  628. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  629. if ( result != kAudioHardwareNoError || dataSize == 0 ) {
  630. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
  631. errorText_ = errorStream_.str();
  632. error( RtAudioError::WARNING );
  633. return info;
  634. }
  635. UInt32 nRanges = dataSize / sizeof( AudioValueRange );
  636. AudioValueRange rangeList[ nRanges ];
  637. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );
  638. if ( result != kAudioHardwareNoError ) {
  639. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
  640. errorText_ = errorStream_.str();
  641. error( RtAudioError::WARNING );
  642. return info;
  643. }
  644. // The sample rate reporting mechanism is a bit of a mystery. It
  645. // seems that it can either return individual rates or a range of
  646. // rates. I assume that if the min / max range values are the same,
  647. // then that represents a single supported rate and if the min / max
  648. // range values are different, the device supports an arbitrary
  649. // range of values (though there might be multiple ranges, so we'll
  650. // use the most conservative range).
  651. Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
  652. bool haveValueRange = false;
  653. info.sampleRates.clear();
  654. for ( UInt32 i=0; i<nRanges; i++ ) {
  655. if ( rangeList[i].mMinimum == rangeList[i].mMaximum )
  656. info.sampleRates.push_back( (unsigned int) rangeList[i].mMinimum );
  657. else {
  658. haveValueRange = true;
  659. if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;
  660. if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;
  661. }
  662. }
  663. if ( haveValueRange ) {
  664. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  665. if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate )
  666. info.sampleRates.push_back( SAMPLE_RATES[k] );
  667. }
  668. }
  669. // Sort and remove any redundant values
  670. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  671. info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );
  672. if ( info.sampleRates.size() == 0 ) {
  673. errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
  674. errorText_ = errorStream_.str();
  675. error( RtAudioError::WARNING );
  676. return info;
  677. }
  678. // CoreAudio always uses 32-bit floating point data for PCM streams.
  679. // Thus, any other "physical" formats supported by the device are of
  680. // no interest to the client.
  681. info.nativeFormats = RTAUDIO_FLOAT32;
  682. if ( info.outputChannels > 0 )
  683. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  684. if ( info.inputChannels > 0 )
  685. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  686. info.probed = true;
  687. return info;
  688. }
  689. static OSStatus callbackHandler( AudioDeviceID inDevice,
  690. const AudioTimeStamp* /*inNow*/,
  691. const AudioBufferList* inInputData,
  692. const AudioTimeStamp* /*inInputTime*/,
  693. AudioBufferList* outOutputData,
  694. const AudioTimeStamp* /*inOutputTime*/,
  695. void* infoPointer )
  696. {
  697. CallbackInfo *info = (CallbackInfo *) infoPointer;
  698. RtApiCore *object = (RtApiCore *) info->object;
  699. if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
  700. return kAudioHardwareUnspecifiedError;
  701. else
  702. return kAudioHardwareNoError;
  703. }
  704. static OSStatus xrunListener( AudioObjectID /*inDevice*/,
  705. UInt32 nAddresses,
  706. const AudioObjectPropertyAddress properties[],
  707. void* handlePointer )
  708. {
  709. CoreHandle *handle = (CoreHandle *) handlePointer;
  710. for ( UInt32 i=0; i<nAddresses; i++ ) {
  711. if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {
  712. if ( properties[i].mScope == kAudioDevicePropertyScopeInput )
  713. handle->xrun[1] = true;
  714. else
  715. handle->xrun[0] = true;
  716. }
  717. }
  718. return kAudioHardwareNoError;
  719. }
  720. static OSStatus rateListener( AudioObjectID inDevice,
  721. UInt32 /*nAddresses*/,
  722. const AudioObjectPropertyAddress /*properties*/[],
  723. void* ratePointer )
  724. {
  725. Float64 *rate = (Float64 *) ratePointer;
  726. UInt32 dataSize = sizeof( Float64 );
  727. AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,
  728. kAudioObjectPropertyScopeGlobal,
  729. kAudioObjectPropertyElementMaster };
  730. AudioObjectGetPropertyData( inDevice, &property, 0, NULL, &dataSize, rate );
  731. return kAudioHardwareNoError;
  732. }
  733. bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  734. unsigned int firstChannel, unsigned int sampleRate,
  735. RtAudioFormat format, unsigned int *bufferSize,
  736. RtAudio::StreamOptions *options )
  737. {
  738. // Get device ID
  739. unsigned int nDevices = getDeviceCount();
  740. if ( nDevices == 0 ) {
  741. // This should not happen because a check is made before this function is called.
  742. errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
  743. return FAILURE;
  744. }
  745. if ( device >= nDevices ) {
  746. // This should not happen because a check is made before this function is called.
  747. errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
  748. return FAILURE;
  749. }
  750. AudioDeviceID deviceList[ nDevices ];
  751. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  752. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  753. kAudioObjectPropertyScopeGlobal,
  754. kAudioObjectPropertyElementMaster };
  755. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  756. 0, NULL, &dataSize, (void *) &deviceList );
  757. if ( result != noErr ) {
  758. errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
  759. return FAILURE;
  760. }
  761. AudioDeviceID id = deviceList[ device ];
  762. // Setup for stream mode.
  763. bool isInput = false;
  764. if ( mode == INPUT ) {
  765. isInput = true;
  766. property.mScope = kAudioDevicePropertyScopeInput;
  767. }
  768. else
  769. property.mScope = kAudioDevicePropertyScopeOutput;
  770. // Get the stream "configuration".
  771. AudioBufferList *bufferList = nil;
  772. dataSize = 0;
  773. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  774. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  775. if ( result != noErr || dataSize == 0 ) {
  776. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";
  777. errorText_ = errorStream_.str();
  778. return FAILURE;
  779. }
  780. // Allocate the AudioBufferList.
  781. bufferList = (AudioBufferList *) malloc( dataSize );
  782. if ( bufferList == NULL ) {
  783. errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
  784. return FAILURE;
  785. }
  786. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  787. if (result != noErr || dataSize == 0) {
  788. free( bufferList );
  789. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";
  790. errorText_ = errorStream_.str();
  791. return FAILURE;
  792. }
  793. // Search for one or more streams that contain the desired number of
  794. // channels. CoreAudio devices can have an arbitrary number of
  795. // streams and each stream can have an arbitrary number of channels.
  796. // For each stream, a single buffer of interleaved samples is
  797. // provided. RtAudio prefers the use of one stream of interleaved
  798. // data or multiple consecutive single-channel streams. However, we
  799. // now support multiple consecutive multi-channel streams of
  800. // interleaved data as well.
  801. UInt32 iStream, offsetCounter = firstChannel;
  802. UInt32 nStreams = bufferList->mNumberBuffers;
  803. bool monoMode = false;
  804. bool foundStream = false;
  805. // First check that the device supports the requested number of
  806. // channels.
  807. UInt32 deviceChannels = 0;
  808. for ( iStream=0; iStream<nStreams; iStream++ )
  809. deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
  810. if ( deviceChannels < ( channels + firstChannel ) ) {
  811. free( bufferList );
  812. errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";
  813. errorText_ = errorStream_.str();
  814. return FAILURE;
  815. }
  816. // Look for a single stream meeting our needs.
  817. UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;
  818. for ( iStream=0; iStream<nStreams; iStream++ ) {
  819. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  820. if ( streamChannels >= channels + offsetCounter ) {
  821. firstStream = iStream;
  822. channelOffset = offsetCounter;
  823. foundStream = true;
  824. break;
  825. }
  826. if ( streamChannels > offsetCounter ) break;
  827. offsetCounter -= streamChannels;
  828. }
  829. // If we didn't find a single stream above, then we should be able
  830. // to meet the channel specification with multiple streams.
  831. if ( foundStream == false ) {
  832. monoMode = true;
  833. offsetCounter = firstChannel;
  834. for ( iStream=0; iStream<nStreams; iStream++ ) {
  835. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  836. if ( streamChannels > offsetCounter ) break;
  837. offsetCounter -= streamChannels;
  838. }
  839. firstStream = iStream;
  840. channelOffset = offsetCounter;
  841. Int32 channelCounter = channels + offsetCounter - streamChannels;
  842. if ( streamChannels > 1 ) monoMode = false;
  843. while ( channelCounter > 0 ) {
  844. streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
  845. if ( streamChannels > 1 ) monoMode = false;
  846. channelCounter -= streamChannels;
  847. streamCount++;
  848. }
  849. }
  850. free( bufferList );
  851. // Determine the buffer size.
  852. AudioValueRange bufferRange;
  853. dataSize = sizeof( AudioValueRange );
  854. property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  855. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange );
  856. if ( result != noErr ) {
  857. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ").";
  858. errorText_ = errorStream_.str();
  859. return FAILURE;
  860. }
  861. if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  862. else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMaximum;
  863. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  864. // Set the buffer size. For multiple streams, I'm assuming we only
  865. // need to make this setting for the master channel.
  866. UInt32 theSize = (UInt32) *bufferSize;
  867. dataSize = sizeof( UInt32 );
  868. property.mSelector = kAudioDevicePropertyBufferFrameSize;
  869. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize );
  870. if ( result != noErr ) {
  871. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ").";
  872. errorText_ = errorStream_.str();
  873. return FAILURE;
  874. }
  875. // If attempting to setup a duplex stream, the bufferSize parameter
  876. // MUST be the same in both directions!
  877. *bufferSize = theSize;
  878. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  879. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";
  880. errorText_ = errorStream_.str();
  881. return FAILURE;
  882. }
  883. stream_.bufferSize = *bufferSize;
  884. stream_.nBuffers = 1;
  885. // Try to set "hog" mode ... it's not clear to me this is working.
  886. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) {
  887. pid_t hog_pid;
  888. dataSize = sizeof( hog_pid );
  889. property.mSelector = kAudioDevicePropertyHogMode;
  890. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid );
  891. if ( result != noErr ) {
  892. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!";
  893. errorText_ = errorStream_.str();
  894. return FAILURE;
  895. }
  896. if ( hog_pid != getpid() ) {
  897. hog_pid = getpid();
  898. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid );
  899. if ( result != noErr ) {
  900. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";
  901. errorText_ = errorStream_.str();
  902. return FAILURE;
  903. }
  904. }
  905. }
  906. // Check and if necessary, change the sample rate for the device.
  907. Float64 nominalRate;
  908. dataSize = sizeof( Float64 );
  909. property.mSelector = kAudioDevicePropertyNominalSampleRate;
  910. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );
  911. if ( result != noErr ) {
  912. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";
  913. errorText_ = errorStream_.str();
  914. return FAILURE;
  915. }
  916. // Only change the sample rate if off by more than 1 Hz.
  917. if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) {
  918. // Set a property listener for the sample rate change
  919. Float64 reportedRate = 0.0;
  920. AudioObjectPropertyAddress tmp = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  921. result = AudioObjectAddPropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  922. if ( result != noErr ) {
  923. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate property listener for device (" << device << ").";
  924. errorText_ = errorStream_.str();
  925. return FAILURE;
  926. }
  927. nominalRate = (Float64) sampleRate;
  928. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );
  929. if ( result != noErr ) {
  930. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  931. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ").";
  932. errorText_ = errorStream_.str();
  933. return FAILURE;
  934. }
  935. // Now wait until the reported nominal rate is what we just set.
  936. UInt32 microCounter = 0;
  937. while ( reportedRate != nominalRate ) {
  938. microCounter += 5000;
  939. if ( microCounter > 5000000 ) break;
  940. usleep( 5000 );
  941. }
  942. // Remove the property listener.
  943. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  944. if ( microCounter > 5000000 ) {
  945. errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ").";
  946. errorText_ = errorStream_.str();
  947. return FAILURE;
  948. }
  949. }
  950. // Now set the stream format for all streams. Also, check the
  951. // physical format of the device and change that if necessary.
  952. AudioStreamBasicDescription description;
  953. dataSize = sizeof( AudioStreamBasicDescription );
  954. property.mSelector = kAudioStreamPropertyVirtualFormat;
  955. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  956. if ( result != noErr ) {
  957. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ").";
  958. errorText_ = errorStream_.str();
  959. return FAILURE;
  960. }
  961. // Set the sample rate and data format id. However, only make the
  962. // change if the sample rate is not within 1.0 of the desired
  963. // rate and the format is not linear pcm.
  964. bool updateFormat = false;
  965. if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) {
  966. description.mSampleRate = (Float64) sampleRate;
  967. updateFormat = true;
  968. }
  969. if ( description.mFormatID != kAudioFormatLinearPCM ) {
  970. description.mFormatID = kAudioFormatLinearPCM;
  971. updateFormat = true;
  972. }
  973. if ( updateFormat ) {
  974. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description );
  975. if ( result != noErr ) {
  976. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ").";
  977. errorText_ = errorStream_.str();
  978. return FAILURE;
  979. }
  980. }
  981. // Now check the physical format.
  982. property.mSelector = kAudioStreamPropertyPhysicalFormat;
  983. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  984. if ( result != noErr ) {
  985. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ").";
  986. errorText_ = errorStream_.str();
  987. return FAILURE;
  988. }
  989. //std::cout << "Current physical stream format:" << std::endl;
  990. //std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl;
  991. //std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  992. //std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl;
  993. //std::cout << " sample rate = " << description.mSampleRate << std::endl;
  994. if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) {
  995. description.mFormatID = kAudioFormatLinearPCM;
  996. //description.mSampleRate = (Float64) sampleRate;
  997. AudioStreamBasicDescription testDescription = description;
  998. UInt32 formatFlags;
  999. // We'll try higher bit rates first and then work our way down.
  1000. std::vector< std::pair<UInt32, UInt32> > physicalFormats;
  1001. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;
  1002. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1003. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1004. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1005. physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) ); // 24-bit packed
  1006. formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh );
  1007. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low
  1008. formatFlags |= kAudioFormatFlagIsAlignedHigh;
  1009. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high
  1010. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1011. physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) );
  1012. physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) );
  1013. bool setPhysicalFormat = false;
  1014. for( unsigned int i=0; i<physicalFormats.size(); i++ ) {
  1015. testDescription = description;
  1016. testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first;
  1017. testDescription.mFormatFlags = physicalFormats[i].second;
  1018. if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) )
  1019. testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame;
  1020. else
  1021. testDescription.mBytesPerFrame = testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame;
  1022. testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;
  1023. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription );
  1024. if ( result == noErr ) {
  1025. setPhysicalFormat = true;
  1026. //std::cout << "Updated physical stream format:" << std::endl;
  1027. //std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;
  1028. //std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1029. //std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;
  1030. //std::cout << " sample rate = " << testDescription.mSampleRate << std::endl;
  1031. break;
  1032. }
  1033. }
  1034. if ( !setPhysicalFormat ) {
  1035. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ").";
  1036. errorText_ = errorStream_.str();
  1037. return FAILURE;
  1038. }
  1039. } // done setting virtual/physical formats.
  1040. // Get the stream / device latency.
  1041. UInt32 latency;
  1042. dataSize = sizeof( UInt32 );
  1043. property.mSelector = kAudioDevicePropertyLatency;
  1044. if ( AudioObjectHasProperty( id, &property ) == true ) {
  1045. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency );
  1046. if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;
  1047. else {
  1048. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";
  1049. errorText_ = errorStream_.str();
  1050. error( RtAudioError::WARNING );
  1051. }
  1052. }
  1053. // Byte-swapping: According to AudioHardware.h, the stream data will
  1054. // always be presented in native-endian format, so we should never
  1055. // need to byte swap.
  1056. stream_.doByteSwap[mode] = false;
  1057. // From the CoreAudio documentation, PCM data must be supplied as
  1058. // 32-bit floats.
  1059. stream_.userFormat = format;
  1060. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1061. if ( streamCount == 1 )
  1062. stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
  1063. else // multiple streams
  1064. stream_.nDeviceChannels[mode] = channels;
  1065. stream_.nUserChannels[mode] = channels;
  1066. stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
  1067. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1068. else stream_.userInterleaved = true;
  1069. stream_.deviceInterleaved[mode] = true;
  1070. if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;
  1071. // Set flags for buffer conversion.
  1072. stream_.doConvertBuffer[mode] = false;
  1073. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1074. stream_.doConvertBuffer[mode] = true;
  1075. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  1076. stream_.doConvertBuffer[mode] = true;
  1077. if ( streamCount == 1 ) {
  1078. if ( stream_.nUserChannels[mode] > 1 &&
  1079. stream_.userInterleaved != stream_.deviceInterleaved[mode] )
  1080. stream_.doConvertBuffer[mode] = true;
  1081. }
  1082. else if ( monoMode && stream_.userInterleaved )
  1083. stream_.doConvertBuffer[mode] = true;
  1084. // Allocate our CoreHandle structure for the stream.
  1085. CoreHandle *handle = 0;
  1086. if ( stream_.apiHandle == 0 ) {
  1087. try {
  1088. handle = new CoreHandle;
  1089. }
  1090. catch ( std::bad_alloc& ) {
  1091. errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
  1092. goto error;
  1093. }
  1094. if ( pthread_cond_init( &handle->condition, NULL ) ) {
  1095. errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
  1096. goto error;
  1097. }
  1098. stream_.apiHandle = (void *) handle;
  1099. }
  1100. else
  1101. handle = (CoreHandle *) stream_.apiHandle;
  1102. handle->iStream[mode] = firstStream;
  1103. handle->nStreams[mode] = streamCount;
  1104. handle->id[mode] = id;
  1105. // Allocate necessary internal buffers.
  1106. unsigned long bufferBytes;
  1107. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  1108. // stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1109. stream_.userBuffer[mode] = (char *) malloc( bufferBytes * sizeof(char) );
  1110. memset( stream_.userBuffer[mode], 0, bufferBytes * sizeof(char) );
  1111. if ( stream_.userBuffer[mode] == NULL ) {
  1112. errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
  1113. goto error;
  1114. }
  1115. // If possible, we will make use of the CoreAudio stream buffers as
  1116. // "device buffers". However, we can't do this if using multiple
  1117. // streams.
  1118. if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {
  1119. bool makeBuffer = true;
  1120. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  1121. if ( mode == INPUT ) {
  1122. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1123. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1124. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  1125. }
  1126. }
  1127. if ( makeBuffer ) {
  1128. bufferBytes *= *bufferSize;
  1129. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1130. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1131. if ( stream_.deviceBuffer == NULL ) {
  1132. errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
  1133. goto error;
  1134. }
  1135. }
  1136. }
  1137. stream_.sampleRate = sampleRate;
  1138. stream_.device[mode] = device;
  1139. stream_.state = STREAM_STOPPED;
  1140. stream_.callbackInfo.object = (void *) this;
  1141. // Setup the buffer conversion information structure.
  1142. if ( stream_.doConvertBuffer[mode] ) {
  1143. if ( streamCount > 1 ) setConvertInfo( mode, 0 );
  1144. else setConvertInfo( mode, channelOffset );
  1145. }
  1146. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device )
  1147. // Only one callback procedure per device.
  1148. stream_.mode = DUPLEX;
  1149. else {
  1150. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1151. result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );
  1152. #else
  1153. // deprecated in favor of AudioDeviceCreateIOProcID()
  1154. result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
  1155. #endif
  1156. if ( result != noErr ) {
  1157. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";
  1158. errorText_ = errorStream_.str();
  1159. goto error;
  1160. }
  1161. if ( stream_.mode == OUTPUT && mode == INPUT )
  1162. stream_.mode = DUPLEX;
  1163. else
  1164. stream_.mode = mode;
  1165. }
  1166. // Setup the device property listener for over/underload.
  1167. property.mSelector = kAudioDeviceProcessorOverload;
  1168. property.mScope = kAudioObjectPropertyScopeGlobal;
  1169. result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );
  1170. return SUCCESS;
  1171. error:
  1172. if ( handle ) {
  1173. pthread_cond_destroy( &handle->condition );
  1174. delete handle;
  1175. stream_.apiHandle = 0;
  1176. }
  1177. for ( int i=0; i<2; i++ ) {
  1178. if ( stream_.userBuffer[i] ) {
  1179. free( stream_.userBuffer[i] );
  1180. stream_.userBuffer[i] = 0;
  1181. }
  1182. }
  1183. if ( stream_.deviceBuffer ) {
  1184. free( stream_.deviceBuffer );
  1185. stream_.deviceBuffer = 0;
  1186. }
  1187. stream_.state = STREAM_CLOSED;
  1188. return FAILURE;
  1189. }
  1190. void RtApiCore :: closeStream( void )
  1191. {
  1192. if ( stream_.state == STREAM_CLOSED ) {
  1193. errorText_ = "RtApiCore::closeStream(): no open stream to close!";
  1194. error( RtAudioError::WARNING );
  1195. return;
  1196. }
  1197. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1198. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1199. if ( stream_.state == STREAM_RUNNING )
  1200. AudioDeviceStop( handle->id[0], callbackHandler );
  1201. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1202. AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );
  1203. #else
  1204. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1205. AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );
  1206. #endif
  1207. }
  1208. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1209. if ( stream_.state == STREAM_RUNNING )
  1210. AudioDeviceStop( handle->id[1], callbackHandler );
  1211. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1212. AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );
  1213. #else
  1214. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1215. AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );
  1216. #endif
  1217. }
  1218. for ( int i=0; i<2; i++ ) {
  1219. if ( stream_.userBuffer[i] ) {
  1220. free( stream_.userBuffer[i] );
  1221. stream_.userBuffer[i] = 0;
  1222. }
  1223. }
  1224. if ( stream_.deviceBuffer ) {
  1225. free( stream_.deviceBuffer );
  1226. stream_.deviceBuffer = 0;
  1227. }
  1228. // Destroy pthread condition variable.
  1229. pthread_cond_destroy( &handle->condition );
  1230. delete handle;
  1231. stream_.apiHandle = 0;
  1232. stream_.mode = UNINITIALIZED;
  1233. stream_.state = STREAM_CLOSED;
  1234. }
  1235. void RtApiCore :: startStream( void )
  1236. {
  1237. verifyStream();
  1238. if ( stream_.state == STREAM_RUNNING ) {
  1239. errorText_ = "RtApiCore::startStream(): the stream is already running!";
  1240. error( RtAudioError::WARNING );
  1241. return;
  1242. }
  1243. OSStatus result = noErr;
  1244. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1245. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1246. result = AudioDeviceStart( handle->id[0], callbackHandler );
  1247. if ( result != noErr ) {
  1248. errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ").";
  1249. errorText_ = errorStream_.str();
  1250. goto unlock;
  1251. }
  1252. }
  1253. if ( stream_.mode == INPUT ||
  1254. ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1255. result = AudioDeviceStart( handle->id[1], callbackHandler );
  1256. if ( result != noErr ) {
  1257. errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";
  1258. errorText_ = errorStream_.str();
  1259. goto unlock;
  1260. }
  1261. }
  1262. handle->drainCounter = 0;
  1263. handle->internalDrain = false;
  1264. stream_.state = STREAM_RUNNING;
  1265. unlock:
  1266. if ( result == noErr ) return;
  1267. error( RtAudioError::SYSTEM_ERROR );
  1268. }
  1269. void RtApiCore :: stopStream( void )
  1270. {
  1271. verifyStream();
  1272. if ( stream_.state == STREAM_STOPPED ) {
  1273. errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
  1274. error( RtAudioError::WARNING );
  1275. return;
  1276. }
  1277. OSStatus result = noErr;
  1278. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1279. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1280. if ( handle->drainCounter == 0 ) {
  1281. handle->drainCounter = 2;
  1282. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  1283. }
  1284. result = AudioDeviceStop( handle->id[0], callbackHandler );
  1285. if ( result != noErr ) {
  1286. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";
  1287. errorText_ = errorStream_.str();
  1288. goto unlock;
  1289. }
  1290. }
  1291. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1292. result = AudioDeviceStop( handle->id[1], callbackHandler );
  1293. if ( result != noErr ) {
  1294. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";
  1295. errorText_ = errorStream_.str();
  1296. goto unlock;
  1297. }
  1298. }
  1299. stream_.state = STREAM_STOPPED;
  1300. unlock:
  1301. if ( result == noErr ) return;
  1302. error( RtAudioError::SYSTEM_ERROR );
  1303. }
  1304. void RtApiCore :: abortStream( void )
  1305. {
  1306. verifyStream();
  1307. if ( stream_.state == STREAM_STOPPED ) {
  1308. errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
  1309. error( RtAudioError::WARNING );
  1310. return;
  1311. }
  1312. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1313. handle->drainCounter = 2;
  1314. stopStream();
  1315. }
  1316. // This function will be called by a spawned thread when the user
  1317. // callback function signals that the stream should be stopped or
  1318. // aborted. It is better to handle it this way because the
  1319. // callbackEvent() function probably should return before the AudioDeviceStop()
  1320. // function is called.
  1321. static void *coreStopStream( void *ptr )
  1322. {
  1323. CallbackInfo *info = (CallbackInfo *) ptr;
  1324. RtApiCore *object = (RtApiCore *) info->object;
  1325. object->stopStream();
  1326. pthread_exit( NULL );
  1327. }
  1328. bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
  1329. const AudioBufferList *inBufferList,
  1330. const AudioBufferList *outBufferList )
  1331. {
  1332. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  1333. if ( stream_.state == STREAM_CLOSED ) {
  1334. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  1335. error( RtAudioError::WARNING );
  1336. return FAILURE;
  1337. }
  1338. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  1339. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1340. // Check if we were draining the stream and signal is finished.
  1341. if ( handle->drainCounter > 3 ) {
  1342. ThreadHandle threadId;
  1343. stream_.state = STREAM_STOPPING;
  1344. if ( handle->internalDrain == true )
  1345. pthread_create( &threadId, NULL, coreStopStream, info );
  1346. else // external call to stopStream()
  1347. pthread_cond_signal( &handle->condition );
  1348. return SUCCESS;
  1349. }
  1350. AudioDeviceID outputDevice = handle->id[0];
  1351. // Invoke user callback to get fresh output data UNLESS we are
  1352. // draining stream or duplex mode AND the input/output devices are
  1353. // different AND this function is called for the input device.
  1354. if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {
  1355. RtAudioCallback callback = (RtAudioCallback) info->callback;
  1356. double streamTime = getStreamTime();
  1357. RtAudioStreamStatus status = 0;
  1358. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  1359. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  1360. handle->xrun[0] = false;
  1361. }
  1362. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  1363. status |= RTAUDIO_INPUT_OVERFLOW;
  1364. handle->xrun[1] = false;
  1365. }
  1366. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  1367. stream_.bufferSize, streamTime, status, info->userData );
  1368. if ( cbReturnValue == 2 ) {
  1369. stream_.state = STREAM_STOPPING;
  1370. handle->drainCounter = 2;
  1371. abortStream();
  1372. return SUCCESS;
  1373. }
  1374. else if ( cbReturnValue == 1 ) {
  1375. handle->drainCounter = 1;
  1376. handle->internalDrain = true;
  1377. }
  1378. }
  1379. if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {
  1380. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  1381. if ( handle->nStreams[0] == 1 ) {
  1382. memset( outBufferList->mBuffers[handle->iStream[0]].mData,
  1383. 0,
  1384. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1385. }
  1386. else { // fill multiple streams with zeros
  1387. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1388. memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1389. 0,
  1390. outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );
  1391. }
  1392. }
  1393. }
  1394. else if ( handle->nStreams[0] == 1 ) {
  1395. if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer
  1396. convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,
  1397. stream_.userBuffer[0], stream_.convertInfo[0] );
  1398. }
  1399. else { // copy from user buffer
  1400. memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,
  1401. stream_.userBuffer[0],
  1402. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1403. }
  1404. }
  1405. else { // fill multiple streams
  1406. Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];
  1407. if ( stream_.doConvertBuffer[0] ) {
  1408. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  1409. inBuffer = (Float32 *) stream_.deviceBuffer;
  1410. }
  1411. if ( stream_.deviceInterleaved[0] == false ) { // mono mode
  1412. UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
  1413. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1414. memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1415. (void *)&inBuffer[i*stream_.bufferSize], bufferBytes );
  1416. }
  1417. }
  1418. else { // fill multiple multi-channel streams with interleaved data
  1419. UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
  1420. Float32 *out, *in;
  1421. bool inInterleaved = ( stream_.userInterleaved ) ? true : false;
  1422. UInt32 inChannels = stream_.nUserChannels[0];
  1423. if ( stream_.doConvertBuffer[0] ) {
  1424. inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1425. inChannels = stream_.nDeviceChannels[0];
  1426. }
  1427. if ( inInterleaved ) inOffset = 1;
  1428. else inOffset = stream_.bufferSize;
  1429. channelsLeft = inChannels;
  1430. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1431. in = inBuffer;
  1432. out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;
  1433. streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;
  1434. outJump = 0;
  1435. // Account for possible channel offset in first stream
  1436. if ( i == 0 && stream_.channelOffset[0] > 0 ) {
  1437. streamChannels -= stream_.channelOffset[0];
  1438. outJump = stream_.channelOffset[0];
  1439. out += outJump;
  1440. }
  1441. // Account for possible unfilled channels at end of the last stream
  1442. if ( streamChannels > channelsLeft ) {
  1443. outJump = streamChannels - channelsLeft;
  1444. streamChannels = channelsLeft;
  1445. }
  1446. // Determine input buffer offsets and skips
  1447. if ( inInterleaved ) {
  1448. inJump = inChannels;
  1449. in += inChannels - channelsLeft;
  1450. }
  1451. else {
  1452. inJump = 1;
  1453. in += (inChannels - channelsLeft) * inOffset;
  1454. }
  1455. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1456. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1457. *out++ = in[j*inOffset];
  1458. }
  1459. out += outJump;
  1460. in += inJump;
  1461. }
  1462. channelsLeft -= streamChannels;
  1463. }
  1464. }
  1465. }
  1466. if ( handle->drainCounter ) {
  1467. handle->drainCounter++;
  1468. goto unlock;
  1469. }
  1470. }
  1471. AudioDeviceID inputDevice;
  1472. inputDevice = handle->id[1];
  1473. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {
  1474. if ( handle->nStreams[1] == 1 ) {
  1475. if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer
  1476. convertBuffer( stream_.userBuffer[1],
  1477. (char *) inBufferList->mBuffers[handle->iStream[1]].mData,
  1478. stream_.convertInfo[1] );
  1479. }
  1480. else { // copy to user buffer
  1481. memcpy( stream_.userBuffer[1],
  1482. inBufferList->mBuffers[handle->iStream[1]].mData,
  1483. inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );
  1484. }
  1485. }
  1486. else { // read from multiple streams
  1487. Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];
  1488. if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;
  1489. if ( stream_.deviceInterleaved[1] == false ) { // mono mode
  1490. UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
  1491. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1492. memcpy( (void *)&outBuffer[i*stream_.bufferSize],
  1493. inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );
  1494. }
  1495. }
  1496. else { // read from multiple multi-channel streams
  1497. UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
  1498. Float32 *out, *in;
  1499. bool outInterleaved = ( stream_.userInterleaved ) ? true : false;
  1500. UInt32 outChannels = stream_.nUserChannels[1];
  1501. if ( stream_.doConvertBuffer[1] ) {
  1502. outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1503. outChannels = stream_.nDeviceChannels[1];
  1504. }
  1505. if ( outInterleaved ) outOffset = 1;
  1506. else outOffset = stream_.bufferSize;
  1507. channelsLeft = outChannels;
  1508. for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {
  1509. out = outBuffer;
  1510. in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;
  1511. streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;
  1512. inJump = 0;
  1513. // Account for possible channel offset in first stream
  1514. if ( i == 0 && stream_.channelOffset[1] > 0 ) {
  1515. streamChannels -= stream_.channelOffset[1];
  1516. inJump = stream_.channelOffset[1];
  1517. in += inJump;
  1518. }
  1519. // Account for possible unread channels at end of the last stream
  1520. if ( streamChannels > channelsLeft ) {
  1521. inJump = streamChannels - channelsLeft;
  1522. streamChannels = channelsLeft;
  1523. }
  1524. // Determine output buffer offsets and skips
  1525. if ( outInterleaved ) {
  1526. outJump = outChannels;
  1527. out += outChannels - channelsLeft;
  1528. }
  1529. else {
  1530. outJump = 1;
  1531. out += (outChannels - channelsLeft) * outOffset;
  1532. }
  1533. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1534. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1535. out[j*outOffset] = *in++;
  1536. }
  1537. out += outJump;
  1538. in += inJump;
  1539. }
  1540. channelsLeft -= streamChannels;
  1541. }
  1542. }
  1543. if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer
  1544. convertBuffer( stream_.userBuffer[1],
  1545. stream_.deviceBuffer,
  1546. stream_.convertInfo[1] );
  1547. }
  1548. }
  1549. }
  1550. unlock:
  1551. //MUTEX_UNLOCK( &stream_.mutex );
  1552. RtApi::tickStreamTime();
  1553. return SUCCESS;
  1554. }
  1555. const char* RtApiCore :: getErrorCode( OSStatus code )
  1556. {
  1557. switch( code ) {
  1558. case kAudioHardwareNotRunningError:
  1559. return "kAudioHardwareNotRunningError";
  1560. case kAudioHardwareUnspecifiedError:
  1561. return "kAudioHardwareUnspecifiedError";
  1562. case kAudioHardwareUnknownPropertyError:
  1563. return "kAudioHardwareUnknownPropertyError";
  1564. case kAudioHardwareBadPropertySizeError:
  1565. return "kAudioHardwareBadPropertySizeError";
  1566. case kAudioHardwareIllegalOperationError:
  1567. return "kAudioHardwareIllegalOperationError";
  1568. case kAudioHardwareBadObjectError:
  1569. return "kAudioHardwareBadObjectError";
  1570. case kAudioHardwareBadDeviceError:
  1571. return "kAudioHardwareBadDeviceError";
  1572. case kAudioHardwareBadStreamError:
  1573. return "kAudioHardwareBadStreamError";
  1574. case kAudioHardwareUnsupportedOperationError:
  1575. return "kAudioHardwareUnsupportedOperationError";
  1576. case kAudioDeviceUnsupportedFormatError:
  1577. return "kAudioDeviceUnsupportedFormatError";
  1578. case kAudioDevicePermissionsError:
  1579. return "kAudioDevicePermissionsError";
  1580. default:
  1581. return "CoreAudio unknown error";
  1582. }
  1583. }
  1584. //******************** End of __MACOSX_CORE__ *********************//
  1585. #endif
  1586. #if defined(__UNIX_JACK__)
  1587. // JACK is a low-latency audio server, originally written for the
  1588. // GNU/Linux operating system and now also ported to OS-X. It can
  1589. // connect a number of different applications to an audio device, as
  1590. // well as allowing them to share audio between themselves.
  1591. //
  1592. // When using JACK with RtAudio, "devices" refer to JACK clients that
  1593. // have ports connected to the server. The JACK server is typically
  1594. // started in a terminal as follows:
  1595. //
  1596. // .jackd -d alsa -d hw:0
  1597. //
  1598. // or through an interface program such as qjackctl. Many of the
  1599. // parameters normally set for a stream are fixed by the JACK server
  1600. // and can be specified when the JACK server is started. In
  1601. // particular,
  1602. //
  1603. // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
  1604. //
  1605. // specifies a sample rate of 44100 Hz, a buffer size of 512 sample
  1606. // frames, and number of buffers = 4. Once the server is running, it
  1607. // is not possible to override these values. If the values are not
  1608. // specified in the command-line, the JACK server uses default values.
  1609. //
  1610. // The JACK server does not have to be running when an instance of
  1611. // RtApiJack is created, though the function getDeviceCount() will
  1612. // report 0 devices found until JACK has been started. When no
  1613. // devices are available (i.e., the JACK server is not running), a
  1614. // stream cannot be opened.
  1615. #include <jack/jack.h>
  1616. #include <unistd.h>
  1617. #include <cstdio>
  1618. // A structure to hold various information related to the Jack API
  1619. // implementation.
  1620. struct JackHandle {
  1621. jack_client_t *client;
  1622. jack_port_t **ports[2];
  1623. std::string deviceName[2];
  1624. bool xrun[2];
  1625. pthread_cond_t condition;
  1626. int drainCounter; // Tracks callback counts when draining
  1627. bool internalDrain; // Indicates if stop is initiated from callback or not.
  1628. JackHandle()
  1629. :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
  1630. };
  1631. static void jackSilentError( const char * ) {};
  1632. RtApiJack :: RtApiJack()
  1633. {
  1634. // Nothing to do here.
  1635. #if !defined(__RTAUDIO_DEBUG__)
  1636. // Turn off Jack's internal error reporting.
  1637. jack_set_error_function( &jackSilentError );
  1638. #endif
  1639. }
  1640. RtApiJack :: ~RtApiJack()
  1641. {
  1642. if ( stream_.state != STREAM_CLOSED ) closeStream();
  1643. }
  1644. unsigned int RtApiJack :: getDeviceCount( void )
  1645. {
  1646. // See if we can become a jack client.
  1647. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1648. jack_status_t *status = NULL;
  1649. jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );
  1650. if ( client == 0 ) return 0;
  1651. const char **ports;
  1652. std::string port, previousPort;
  1653. unsigned int nChannels = 0, nDevices = 0;
  1654. ports = jack_get_ports( client, NULL, NULL, 0 );
  1655. if ( ports ) {
  1656. // Parse the port names up to the first colon (:).
  1657. size_t iColon = 0;
  1658. do {
  1659. port = (char *) ports[ nChannels ];
  1660. iColon = port.find(":");
  1661. if ( iColon != std::string::npos ) {
  1662. port = port.substr( 0, iColon + 1 );
  1663. if ( port != previousPort ) {
  1664. nDevices++;
  1665. previousPort = port;
  1666. }
  1667. }
  1668. } while ( ports[++nChannels] );
  1669. free( ports );
  1670. }
  1671. jack_client_close( client );
  1672. return nDevices;
  1673. }
  1674. RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
  1675. {
  1676. RtAudio::DeviceInfo info;
  1677. info.probed = false;
  1678. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption
  1679. jack_status_t *status = NULL;
  1680. jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );
  1681. if ( client == 0 ) {
  1682. errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
  1683. error( RtAudioError::WARNING );
  1684. return info;
  1685. }
  1686. const char **ports;
  1687. std::string port, previousPort;
  1688. unsigned int nPorts = 0, nDevices = 0;
  1689. ports = jack_get_ports( client, NULL, NULL, 0 );
  1690. if ( ports ) {
  1691. // Parse the port names up to the first colon (:).
  1692. size_t iColon = 0;
  1693. do {
  1694. port = (char *) ports[ nPorts ];
  1695. iColon = port.find(":");
  1696. if ( iColon != std::string::npos ) {
  1697. port = port.substr( 0, iColon );
  1698. if ( port != previousPort ) {
  1699. if ( nDevices == device ) info.name = port;
  1700. nDevices++;
  1701. previousPort = port;
  1702. }
  1703. }
  1704. } while ( ports[++nPorts] );
  1705. free( ports );
  1706. }
  1707. if ( device >= nDevices ) {
  1708. jack_client_close( client );
  1709. errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
  1710. error( RtAudioError::INVALID_USE );
  1711. return info;
  1712. }
  1713. // Get the current jack server sample rate.
  1714. info.sampleRates.clear();
  1715. info.sampleRates.push_back( jack_get_sample_rate( client ) );
  1716. // Count the available ports containing the client name as device
  1717. // channels. Jack "input ports" equal RtAudio output channels.
  1718. unsigned int nChannels = 0;
  1719. ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsInput );
  1720. if ( ports ) {
  1721. while ( ports[ nChannels ] ) nChannels++;
  1722. free( ports );
  1723. info.outputChannels = nChannels;
  1724. }
  1725. // Jack "output ports" equal RtAudio input channels.
  1726. nChannels = 0;
  1727. ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsOutput );
  1728. if ( ports ) {
  1729. while ( ports[ nChannels ] ) nChannels++;
  1730. free( ports );
  1731. info.inputChannels = nChannels;
  1732. }
  1733. if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
  1734. jack_client_close(client);
  1735. errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
  1736. error( RtAudioError::WARNING );
  1737. return info;
  1738. }
  1739. // If device opens for both playback and capture, we determine the channels.
  1740. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  1741. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  1742. // Jack always uses 32-bit floats.
  1743. info.nativeFormats = RTAUDIO_FLOAT32;
  1744. // Jack doesn't provide default devices so we'll use the first available one.
  1745. if ( device == 0 && info.outputChannels > 0 )
  1746. info.isDefaultOutput = true;
  1747. if ( device == 0 && info.inputChannels > 0 )
  1748. info.isDefaultInput = true;
  1749. jack_client_close(client);
  1750. info.probed = true;
  1751. return info;
  1752. }
  1753. static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
  1754. {
  1755. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1756. RtApiJack *object = (RtApiJack *) info->object;
  1757. if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
  1758. return 0;
  1759. }
  1760. // This function will be called by a spawned thread when the Jack
  1761. // server signals that it is shutting down. It is necessary to handle
  1762. // it this way because the jackShutdown() function must return before
  1763. // the jack_deactivate() function (in closeStream()) will return.
  1764. static void *jackCloseStream( void *ptr )
  1765. {
  1766. CallbackInfo *info = (CallbackInfo *) ptr;
  1767. RtApiJack *object = (RtApiJack *) info->object;
  1768. object->closeStream();
  1769. pthread_exit( NULL );
  1770. }
  1771. static void jackShutdown( void *infoPointer )
  1772. {
  1773. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1774. RtApiJack *object = (RtApiJack *) info->object;
  1775. // Check current stream state. If stopped, then we'll assume this
  1776. // was called as a result of a call to RtApiJack::stopStream (the
  1777. // deactivation of a client handle causes this function to be called).
  1778. // If not, we'll assume the Jack server is shutting down or some
  1779. // other problem occurred and we should close the stream.
  1780. if ( object->isStreamRunning() == false ) return;
  1781. ThreadHandle threadId;
  1782. pthread_create( &threadId, NULL, jackCloseStream, info );
  1783. std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
  1784. }
  1785. static int jackXrun( void *infoPointer )
  1786. {
  1787. JackHandle *handle = (JackHandle *) infoPointer;
  1788. if ( handle->ports[0] ) handle->xrun[0] = true;
  1789. if ( handle->ports[1] ) handle->xrun[1] = true;
  1790. return 0;
  1791. }
  1792. bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  1793. unsigned int firstChannel, unsigned int sampleRate,
  1794. RtAudioFormat format, unsigned int *bufferSize,
  1795. RtAudio::StreamOptions *options )
  1796. {
  1797. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1798. // Look for jack server and try to become a client (only do once per stream).
  1799. jack_client_t *client = 0;
  1800. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
  1801. jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1802. jack_status_t *status = NULL;
  1803. if ( options && !options->streamName.empty() )
  1804. client = jack_client_open( options->streamName.c_str(), jackoptions, status );
  1805. else
  1806. client = jack_client_open( "RtApiJack", jackoptions, status );
  1807. if ( client == 0 ) {
  1808. errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
  1809. error( RtAudioError::WARNING );
  1810. return FAILURE;
  1811. }
  1812. }
  1813. else {
  1814. // The handle must have been created on an earlier pass.
  1815. client = handle->client;
  1816. }
  1817. const char **ports;
  1818. std::string port, previousPort, deviceName;
  1819. unsigned int nPorts = 0, nDevices = 0;
  1820. ports = jack_get_ports( client, NULL, NULL, 0 );
  1821. if ( ports ) {
  1822. // Parse the port names up to the first colon (:).
  1823. size_t iColon = 0;
  1824. do {
  1825. port = (char *) ports[ nPorts ];
  1826. iColon = port.find(":");
  1827. if ( iColon != std::string::npos ) {
  1828. port = port.substr( 0, iColon );
  1829. if ( port != previousPort ) {
  1830. if ( nDevices == device ) deviceName = port;
  1831. nDevices++;
  1832. previousPort = port;
  1833. }
  1834. }
  1835. } while ( ports[++nPorts] );
  1836. free( ports );
  1837. }
  1838. if ( device >= nDevices ) {
  1839. errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
  1840. return FAILURE;
  1841. }
  1842. // Count the available ports containing the client name as device
  1843. // channels. Jack "input ports" equal RtAudio output channels.
  1844. unsigned int nChannels = 0;
  1845. unsigned long flag = JackPortIsInput;
  1846. if ( mode == INPUT ) flag = JackPortIsOutput;
  1847. ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
  1848. if ( ports ) {
  1849. while ( ports[ nChannels ] ) nChannels++;
  1850. free( ports );
  1851. }
  1852. // Compare the jack ports for specified client to the requested number of channels.
  1853. if ( nChannels < (channels + firstChannel) ) {
  1854. errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
  1855. errorText_ = errorStream_.str();
  1856. return FAILURE;
  1857. }
  1858. // Check the jack server sample rate.
  1859. unsigned int jackRate = jack_get_sample_rate( client );
  1860. if ( sampleRate != jackRate ) {
  1861. jack_client_close( client );
  1862. errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
  1863. errorText_ = errorStream_.str();
  1864. return FAILURE;
  1865. }
  1866. stream_.sampleRate = jackRate;
  1867. // Get the latency of the JACK port.
  1868. ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
  1869. if ( ports[ firstChannel ] ) {
  1870. // Added by Ge Wang
  1871. jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
  1872. // the range (usually the min and max are equal)
  1873. jack_latency_range_t latrange; latrange.min = latrange.max = 0;
  1874. // get the latency range
  1875. jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );
  1876. // be optimistic, use the min!
  1877. stream_.latency[mode] = latrange.min;
  1878. //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
  1879. }
  1880. free( ports );
  1881. // The jack server always uses 32-bit floating-point data.
  1882. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1883. stream_.userFormat = format;
  1884. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1885. else stream_.userInterleaved = true;
  1886. // Jack always uses non-interleaved buffers.
  1887. stream_.deviceInterleaved[mode] = false;
  1888. // Jack always provides host byte-ordered data.
  1889. stream_.doByteSwap[mode] = false;
  1890. // Get the buffer size. The buffer size and number of buffers
  1891. // (periods) is set when the jack server is started.
  1892. stream_.bufferSize = (int) jack_get_buffer_size( client );
  1893. *bufferSize = stream_.bufferSize;
  1894. stream_.nDeviceChannels[mode] = channels;
  1895. stream_.nUserChannels[mode] = channels;
  1896. // Set flags for buffer conversion.
  1897. stream_.doConvertBuffer[mode] = false;
  1898. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1899. stream_.doConvertBuffer[mode] = true;
  1900. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  1901. stream_.nUserChannels[mode] > 1 )
  1902. stream_.doConvertBuffer[mode] = true;
  1903. // Allocate our JackHandle structure for the stream.
  1904. if ( handle == 0 ) {
  1905. try {
  1906. handle = new JackHandle;
  1907. }
  1908. catch ( std::bad_alloc& ) {
  1909. errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
  1910. goto error;
  1911. }
  1912. if ( pthread_cond_init(&handle->condition, NULL) ) {
  1913. errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
  1914. goto error;
  1915. }
  1916. stream_.apiHandle = (void *) handle;
  1917. handle->client = client;
  1918. }
  1919. handle->deviceName[mode] = deviceName;
  1920. // Allocate necessary internal buffers.
  1921. unsigned long bufferBytes;
  1922. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  1923. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1924. if ( stream_.userBuffer[mode] == NULL ) {
  1925. errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
  1926. goto error;
  1927. }
  1928. if ( stream_.doConvertBuffer[mode] ) {
  1929. bool makeBuffer = true;
  1930. if ( mode == OUTPUT )
  1931. bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1932. else { // mode == INPUT
  1933. bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
  1934. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1935. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
  1936. if ( bufferBytes < bytesOut ) makeBuffer = false;
  1937. }
  1938. }
  1939. if ( makeBuffer ) {
  1940. bufferBytes *= *bufferSize;
  1941. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1942. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1943. if ( stream_.deviceBuffer == NULL ) {
  1944. errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
  1945. goto error;
  1946. }
  1947. }
  1948. }
  1949. // Allocate memory for the Jack ports (channels) identifiers.
  1950. handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
  1951. if ( handle->ports[mode] == NULL ) {
  1952. errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
  1953. goto error;
  1954. }
  1955. stream_.device[mode] = device;
  1956. stream_.channelOffset[mode] = firstChannel;
  1957. stream_.state = STREAM_STOPPED;
  1958. stream_.callbackInfo.object = (void *) this;
  1959. if ( stream_.mode == OUTPUT && mode == INPUT )
  1960. // We had already set up the stream for output.
  1961. stream_.mode = DUPLEX;
  1962. else {
  1963. stream_.mode = mode;
  1964. jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
  1965. jack_set_xrun_callback( handle->client, jackXrun, (void *) &handle );
  1966. jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
  1967. }
  1968. // Register our ports.
  1969. char label[64];
  1970. if ( mode == OUTPUT ) {
  1971. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1972. snprintf( label, 64, "outport %d", i );
  1973. handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
  1974. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
  1975. }
  1976. }
  1977. else {
  1978. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1979. snprintf( label, 64, "inport %d", i );
  1980. handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
  1981. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
  1982. }
  1983. }
  1984. // Setup the buffer conversion information structure. We don't use
  1985. // buffers to do channel offsets, so we override that parameter
  1986. // here.
  1987. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  1988. return SUCCESS;
  1989. error:
  1990. if ( handle ) {
  1991. pthread_cond_destroy( &handle->condition );
  1992. jack_client_close( handle->client );
  1993. if ( handle->ports[0] ) free( handle->ports[0] );
  1994. if ( handle->ports[1] ) free( handle->ports[1] );
  1995. delete handle;
  1996. stream_.apiHandle = 0;
  1997. }
  1998. for ( int i=0; i<2; i++ ) {
  1999. if ( stream_.userBuffer[i] ) {
  2000. free( stream_.userBuffer[i] );
  2001. stream_.userBuffer[i] = 0;
  2002. }
  2003. }
  2004. if ( stream_.deviceBuffer ) {
  2005. free( stream_.deviceBuffer );
  2006. stream_.deviceBuffer = 0;
  2007. }
  2008. return FAILURE;
  2009. }
  2010. void RtApiJack :: closeStream( void )
  2011. {
  2012. if ( stream_.state == STREAM_CLOSED ) {
  2013. errorText_ = "RtApiJack::closeStream(): no open stream to close!";
  2014. error( RtAudioError::WARNING );
  2015. return;
  2016. }
  2017. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2018. if ( handle ) {
  2019. if ( stream_.state == STREAM_RUNNING )
  2020. jack_deactivate( handle->client );
  2021. jack_client_close( handle->client );
  2022. }
  2023. if ( handle ) {
  2024. if ( handle->ports[0] ) free( handle->ports[0] );
  2025. if ( handle->ports[1] ) free( handle->ports[1] );
  2026. pthread_cond_destroy( &handle->condition );
  2027. delete handle;
  2028. stream_.apiHandle = 0;
  2029. }
  2030. for ( int i=0; i<2; i++ ) {
  2031. if ( stream_.userBuffer[i] ) {
  2032. free( stream_.userBuffer[i] );
  2033. stream_.userBuffer[i] = 0;
  2034. }
  2035. }
  2036. if ( stream_.deviceBuffer ) {
  2037. free( stream_.deviceBuffer );
  2038. stream_.deviceBuffer = 0;
  2039. }
  2040. stream_.mode = UNINITIALIZED;
  2041. stream_.state = STREAM_CLOSED;
  2042. }
  2043. void RtApiJack :: startStream( void )
  2044. {
  2045. verifyStream();
  2046. if ( stream_.state == STREAM_RUNNING ) {
  2047. errorText_ = "RtApiJack::startStream(): the stream is already running!";
  2048. error( RtAudioError::WARNING );
  2049. return;
  2050. }
  2051. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2052. int result = jack_activate( handle->client );
  2053. if ( result ) {
  2054. errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
  2055. goto unlock;
  2056. }
  2057. const char **ports;
  2058. // Get the list of available ports.
  2059. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2060. result = 1;
  2061. ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), NULL, JackPortIsInput);
  2062. if ( ports == NULL) {
  2063. errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
  2064. goto unlock;
  2065. }
  2066. // Now make the port connections. Since RtAudio wasn't designed to
  2067. // allow the user to select particular channels of a device, we'll
  2068. // just open the first "nChannels" ports with offset.
  2069. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2070. result = 1;
  2071. if ( ports[ stream_.channelOffset[0] + i ] )
  2072. result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
  2073. if ( result ) {
  2074. free( ports );
  2075. errorText_ = "RtApiJack::startStream(): error connecting output ports!";
  2076. goto unlock;
  2077. }
  2078. }
  2079. free(ports);
  2080. }
  2081. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2082. result = 1;
  2083. ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), NULL, JackPortIsOutput );
  2084. if ( ports == NULL) {
  2085. errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
  2086. goto unlock;
  2087. }
  2088. // Now make the port connections. See note above.
  2089. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2090. result = 1;
  2091. if ( ports[ stream_.channelOffset[1] + i ] )
  2092. result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
  2093. if ( result ) {
  2094. free( ports );
  2095. errorText_ = "RtApiJack::startStream(): error connecting input ports!";
  2096. goto unlock;
  2097. }
  2098. }
  2099. free(ports);
  2100. }
  2101. handle->drainCounter = 0;
  2102. handle->internalDrain = false;
  2103. stream_.state = STREAM_RUNNING;
  2104. unlock:
  2105. if ( result == 0 ) return;
  2106. error( RtAudioError::SYSTEM_ERROR );
  2107. }
  2108. void RtApiJack :: stopStream( void )
  2109. {
  2110. verifyStream();
  2111. if ( stream_.state == STREAM_STOPPED ) {
  2112. errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
  2113. error( RtAudioError::WARNING );
  2114. return;
  2115. }
  2116. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2117. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2118. if ( handle->drainCounter == 0 ) {
  2119. handle->drainCounter = 2;
  2120. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  2121. }
  2122. }
  2123. jack_deactivate( handle->client );
  2124. stream_.state = STREAM_STOPPED;
  2125. }
  2126. void RtApiJack :: abortStream( void )
  2127. {
  2128. verifyStream();
  2129. if ( stream_.state == STREAM_STOPPED ) {
  2130. errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
  2131. error( RtAudioError::WARNING );
  2132. return;
  2133. }
  2134. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2135. handle->drainCounter = 2;
  2136. stopStream();
  2137. }
  2138. // This function will be called by a spawned thread when the user
  2139. // callback function signals that the stream should be stopped or
  2140. // aborted. It is necessary to handle it this way because the
  2141. // callbackEvent() function must return before the jack_deactivate()
  2142. // function will return.
  2143. static void *jackStopStream( void *ptr )
  2144. {
  2145. CallbackInfo *info = (CallbackInfo *) ptr;
  2146. RtApiJack *object = (RtApiJack *) info->object;
  2147. object->stopStream();
  2148. pthread_exit( NULL );
  2149. }
  2150. bool RtApiJack :: callbackEvent( unsigned long nframes )
  2151. {
  2152. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2153. if ( stream_.state == STREAM_CLOSED ) {
  2154. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2155. error( RtAudioError::WARNING );
  2156. return FAILURE;
  2157. }
  2158. if ( stream_.bufferSize != nframes ) {
  2159. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
  2160. error( RtAudioError::WARNING );
  2161. return FAILURE;
  2162. }
  2163. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2164. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2165. // Check if we were draining the stream and signal is finished.
  2166. if ( handle->drainCounter > 3 ) {
  2167. ThreadHandle threadId;
  2168. stream_.state = STREAM_STOPPING;
  2169. if ( handle->internalDrain == true )
  2170. pthread_create( &threadId, NULL, jackStopStream, info );
  2171. else
  2172. pthread_cond_signal( &handle->condition );
  2173. return SUCCESS;
  2174. }
  2175. // Invoke user callback first, to get fresh output data.
  2176. if ( handle->drainCounter == 0 ) {
  2177. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2178. double streamTime = getStreamTime();
  2179. RtAudioStreamStatus status = 0;
  2180. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  2181. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2182. handle->xrun[0] = false;
  2183. }
  2184. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  2185. status |= RTAUDIO_INPUT_OVERFLOW;
  2186. handle->xrun[1] = false;
  2187. }
  2188. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2189. stream_.bufferSize, streamTime, status, info->userData );
  2190. if ( cbReturnValue == 2 ) {
  2191. stream_.state = STREAM_STOPPING;
  2192. handle->drainCounter = 2;
  2193. ThreadHandle id;
  2194. pthread_create( &id, NULL, jackStopStream, info );
  2195. return SUCCESS;
  2196. }
  2197. else if ( cbReturnValue == 1 ) {
  2198. handle->drainCounter = 1;
  2199. handle->internalDrain = true;
  2200. }
  2201. }
  2202. jack_default_audio_sample_t *jackbuffer;
  2203. unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
  2204. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2205. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2206. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2207. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2208. memset( jackbuffer, 0, bufferBytes );
  2209. }
  2210. }
  2211. else if ( stream_.doConvertBuffer[0] ) {
  2212. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2213. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2214. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2215. memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
  2216. }
  2217. }
  2218. else { // no buffer conversion
  2219. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2220. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2221. memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
  2222. }
  2223. }
  2224. if ( handle->drainCounter ) {
  2225. handle->drainCounter++;
  2226. goto unlock;
  2227. }
  2228. }
  2229. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2230. if ( stream_.doConvertBuffer[1] ) {
  2231. for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
  2232. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2233. memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
  2234. }
  2235. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2236. }
  2237. else { // no buffer conversion
  2238. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2239. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2240. memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
  2241. }
  2242. }
  2243. }
  2244. unlock:
  2245. RtApi::tickStreamTime();
  2246. return SUCCESS;
  2247. }
  2248. //******************** End of __UNIX_JACK__ *********************//
  2249. #endif
  2250. #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2251. // The ASIO API is designed around a callback scheme, so this
  2252. // implementation is similar to that used for OS-X CoreAudio and Linux
  2253. // Jack. The primary constraint with ASIO is that it only allows
  2254. // access to a single driver at a time. Thus, it is not possible to
  2255. // have more than one simultaneous RtAudio stream.
  2256. //
  2257. // This implementation also requires a number of external ASIO files
  2258. // and a few global variables. The ASIO callback scheme does not
  2259. // allow for the passing of user data, so we must create a global
  2260. // pointer to our callbackInfo structure.
  2261. //
  2262. // On unix systems, we make use of a pthread condition variable.
  2263. // Since there is no equivalent in Windows, I hacked something based
  2264. // on information found in
  2265. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
  2266. #include "asiosys.h"
  2267. #include "asio.h"
  2268. #include "iasiothiscallresolver.h"
  2269. #include "asiodrivers.h"
  2270. #include <cmath>
  2271. static AsioDrivers drivers;
  2272. static ASIOCallbacks asioCallbacks;
  2273. static ASIODriverInfo driverInfo;
  2274. static CallbackInfo *asioCallbackInfo;
  2275. static bool asioXRun;
  2276. struct AsioHandle {
  2277. int drainCounter; // Tracks callback counts when draining
  2278. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2279. ASIOBufferInfo *bufferInfos;
  2280. HANDLE condition;
  2281. AsioHandle()
  2282. :drainCounter(0), internalDrain(false), bufferInfos(0) {}
  2283. };
  2284. // Function declarations (definitions at end of section)
  2285. static const char* getAsioErrorString( ASIOError result );
  2286. static void sampleRateChanged( ASIOSampleRate sRate );
  2287. static long asioMessages( long selector, long value, void* message, double* opt );
  2288. RtApiAsio :: RtApiAsio()
  2289. {
  2290. // ASIO cannot run on a multi-threaded appartment. You can call
  2291. // CoInitialize beforehand, but it must be for appartment threading
  2292. // (in which case, CoInitilialize will return S_FALSE here).
  2293. coInitialized_ = false;
  2294. HRESULT hr = CoInitialize( NULL );
  2295. if ( FAILED(hr) ) {
  2296. errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
  2297. error( RtAudioError::WARNING );
  2298. }
  2299. coInitialized_ = true;
  2300. drivers.removeCurrentDriver();
  2301. driverInfo.asioVersion = 2;
  2302. // See note in DirectSound implementation about GetDesktopWindow().
  2303. driverInfo.sysRef = GetForegroundWindow();
  2304. }
  2305. RtApiAsio :: ~RtApiAsio()
  2306. {
  2307. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2308. if ( coInitialized_ ) CoUninitialize();
  2309. }
  2310. unsigned int RtApiAsio :: getDeviceCount( void )
  2311. {
  2312. return (unsigned int) drivers.asioGetNumDev();
  2313. }
  2314. RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
  2315. {
  2316. RtAudio::DeviceInfo info;
  2317. info.probed = false;
  2318. // Get device ID
  2319. unsigned int nDevices = getDeviceCount();
  2320. if ( nDevices == 0 ) {
  2321. errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
  2322. error( RtAudioError::INVALID_USE );
  2323. return info;
  2324. }
  2325. if ( device >= nDevices ) {
  2326. errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
  2327. error( RtAudioError::INVALID_USE );
  2328. return info;
  2329. }
  2330. // If a stream is already open, we cannot probe other devices. Thus, use the saved results.
  2331. if ( stream_.state != STREAM_CLOSED ) {
  2332. if ( device >= devices_.size() ) {
  2333. errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
  2334. error( RtAudioError::WARNING );
  2335. return info;
  2336. }
  2337. return devices_[ device ];
  2338. }
  2339. char driverName[32];
  2340. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2341. if ( result != ASE_OK ) {
  2342. errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2343. errorText_ = errorStream_.str();
  2344. error( RtAudioError::WARNING );
  2345. return info;
  2346. }
  2347. info.name = driverName;
  2348. if ( !drivers.loadDriver( driverName ) ) {
  2349. errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
  2350. errorText_ = errorStream_.str();
  2351. error( RtAudioError::WARNING );
  2352. return info;
  2353. }
  2354. result = ASIOInit( &driverInfo );
  2355. if ( result != ASE_OK ) {
  2356. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2357. errorText_ = errorStream_.str();
  2358. error( RtAudioError::WARNING );
  2359. return info;
  2360. }
  2361. // Determine the device channel information.
  2362. long inputChannels, outputChannels;
  2363. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2364. if ( result != ASE_OK ) {
  2365. drivers.removeCurrentDriver();
  2366. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2367. errorText_ = errorStream_.str();
  2368. error( RtAudioError::WARNING );
  2369. return info;
  2370. }
  2371. info.outputChannels = outputChannels;
  2372. info.inputChannels = inputChannels;
  2373. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  2374. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  2375. // Determine the supported sample rates.
  2376. info.sampleRates.clear();
  2377. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  2378. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  2379. if ( result == ASE_OK )
  2380. info.sampleRates.push_back( SAMPLE_RATES[i] );
  2381. }
  2382. // Determine supported data types ... just check first channel and assume rest are the same.
  2383. ASIOChannelInfo channelInfo;
  2384. channelInfo.channel = 0;
  2385. channelInfo.isInput = true;
  2386. if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
  2387. result = ASIOGetChannelInfo( &channelInfo );
  2388. if ( result != ASE_OK ) {
  2389. drivers.removeCurrentDriver();
  2390. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
  2391. errorText_ = errorStream_.str();
  2392. error( RtAudioError::WARNING );
  2393. return info;
  2394. }
  2395. info.nativeFormats = 0;
  2396. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  2397. info.nativeFormats |= RTAUDIO_SINT16;
  2398. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  2399. info.nativeFormats |= RTAUDIO_SINT32;
  2400. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  2401. info.nativeFormats |= RTAUDIO_FLOAT32;
  2402. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  2403. info.nativeFormats |= RTAUDIO_FLOAT64;
  2404. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )
  2405. info.nativeFormats |= RTAUDIO_SINT24;
  2406. if ( info.outputChannels > 0 )
  2407. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  2408. if ( info.inputChannels > 0 )
  2409. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  2410. info.probed = true;
  2411. drivers.removeCurrentDriver();
  2412. return info;
  2413. }
  2414. static void bufferSwitch( long index, ASIOBool /*processNow*/ )
  2415. {
  2416. RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
  2417. object->callbackEvent( index );
  2418. }
  2419. void RtApiAsio :: saveDeviceInfo( void )
  2420. {
  2421. devices_.clear();
  2422. unsigned int nDevices = getDeviceCount();
  2423. devices_.resize( nDevices );
  2424. for ( unsigned int i=0; i<nDevices; i++ )
  2425. devices_[i] = getDeviceInfo( i );
  2426. }
  2427. bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  2428. unsigned int firstChannel, unsigned int sampleRate,
  2429. RtAudioFormat format, unsigned int *bufferSize,
  2430. RtAudio::StreamOptions *options )
  2431. {
  2432. // For ASIO, a duplex stream MUST use the same driver.
  2433. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] != device ) {
  2434. errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
  2435. return FAILURE;
  2436. }
  2437. char driverName[32];
  2438. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2439. if ( result != ASE_OK ) {
  2440. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2441. errorText_ = errorStream_.str();
  2442. return FAILURE;
  2443. }
  2444. // Only load the driver once for duplex stream.
  2445. if ( mode != INPUT || stream_.mode != OUTPUT ) {
  2446. // The getDeviceInfo() function will not work when a stream is open
  2447. // because ASIO does not allow multiple devices to run at the same
  2448. // time. Thus, we'll probe the system before opening a stream and
  2449. // save the results for use by getDeviceInfo().
  2450. this->saveDeviceInfo();
  2451. if ( !drivers.loadDriver( driverName ) ) {
  2452. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
  2453. errorText_ = errorStream_.str();
  2454. return FAILURE;
  2455. }
  2456. result = ASIOInit( &driverInfo );
  2457. if ( result != ASE_OK ) {
  2458. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2459. errorText_ = errorStream_.str();
  2460. return FAILURE;
  2461. }
  2462. }
  2463. // Check the device channel count.
  2464. long inputChannels, outputChannels;
  2465. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2466. if ( result != ASE_OK ) {
  2467. drivers.removeCurrentDriver();
  2468. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2469. errorText_ = errorStream_.str();
  2470. return FAILURE;
  2471. }
  2472. if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
  2473. ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
  2474. drivers.removeCurrentDriver();
  2475. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
  2476. errorText_ = errorStream_.str();
  2477. return FAILURE;
  2478. }
  2479. stream_.nDeviceChannels[mode] = channels;
  2480. stream_.nUserChannels[mode] = channels;
  2481. stream_.channelOffset[mode] = firstChannel;
  2482. // Verify the sample rate is supported.
  2483. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  2484. if ( result != ASE_OK ) {
  2485. drivers.removeCurrentDriver();
  2486. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
  2487. errorText_ = errorStream_.str();
  2488. return FAILURE;
  2489. }
  2490. // Get the current sample rate
  2491. ASIOSampleRate currentRate;
  2492. result = ASIOGetSampleRate( &currentRate );
  2493. if ( result != ASE_OK ) {
  2494. drivers.removeCurrentDriver();
  2495. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
  2496. errorText_ = errorStream_.str();
  2497. return FAILURE;
  2498. }
  2499. // Set the sample rate only if necessary
  2500. if ( currentRate != sampleRate ) {
  2501. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  2502. if ( result != ASE_OK ) {
  2503. drivers.removeCurrentDriver();
  2504. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
  2505. errorText_ = errorStream_.str();
  2506. return FAILURE;
  2507. }
  2508. }
  2509. // Determine the driver data type.
  2510. ASIOChannelInfo channelInfo;
  2511. channelInfo.channel = 0;
  2512. if ( mode == OUTPUT ) channelInfo.isInput = false;
  2513. else channelInfo.isInput = true;
  2514. result = ASIOGetChannelInfo( &channelInfo );
  2515. if ( result != ASE_OK ) {
  2516. drivers.removeCurrentDriver();
  2517. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
  2518. errorText_ = errorStream_.str();
  2519. return FAILURE;
  2520. }
  2521. // Assuming WINDOWS host is always little-endian.
  2522. stream_.doByteSwap[mode] = false;
  2523. stream_.userFormat = format;
  2524. stream_.deviceFormat[mode] = 0;
  2525. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  2526. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  2527. if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
  2528. }
  2529. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  2530. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  2531. if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
  2532. }
  2533. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  2534. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2535. if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
  2536. }
  2537. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  2538. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  2539. if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
  2540. }
  2541. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {
  2542. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  2543. if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;
  2544. }
  2545. if ( stream_.deviceFormat[mode] == 0 ) {
  2546. drivers.removeCurrentDriver();
  2547. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
  2548. errorText_ = errorStream_.str();
  2549. return FAILURE;
  2550. }
  2551. // Set the buffer size. For a duplex stream, this will end up
  2552. // setting the buffer size based on the input constraints, which
  2553. // should be ok.
  2554. long minSize, maxSize, preferSize, granularity;
  2555. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  2556. if ( result != ASE_OK ) {
  2557. drivers.removeCurrentDriver();
  2558. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
  2559. errorText_ = errorStream_.str();
  2560. return FAILURE;
  2561. }
  2562. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2563. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2564. else if ( granularity == -1 ) {
  2565. // Make sure bufferSize is a power of two.
  2566. int log2_of_min_size = 0;
  2567. int log2_of_max_size = 0;
  2568. for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
  2569. if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
  2570. if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
  2571. }
  2572. long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
  2573. int min_delta_num = log2_of_min_size;
  2574. for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
  2575. long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
  2576. if (current_delta < min_delta) {
  2577. min_delta = current_delta;
  2578. min_delta_num = i;
  2579. }
  2580. }
  2581. *bufferSize = ( (unsigned int)1 << min_delta_num );
  2582. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2583. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2584. }
  2585. else if ( granularity != 0 ) {
  2586. // Set to an even multiple of granularity, rounding up.
  2587. *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
  2588. }
  2589. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.bufferSize != *bufferSize ) {
  2590. drivers.removeCurrentDriver();
  2591. errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
  2592. return FAILURE;
  2593. }
  2594. stream_.bufferSize = *bufferSize;
  2595. stream_.nBuffers = 2;
  2596. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2597. else stream_.userInterleaved = true;
  2598. // ASIO always uses non-interleaved buffers.
  2599. stream_.deviceInterleaved[mode] = false;
  2600. // Allocate, if necessary, our AsioHandle structure for the stream.
  2601. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2602. if ( handle == 0 ) {
  2603. try {
  2604. handle = new AsioHandle;
  2605. }
  2606. catch ( std::bad_alloc& ) {
  2607. //if ( handle == NULL ) {
  2608. drivers.removeCurrentDriver();
  2609. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
  2610. return FAILURE;
  2611. }
  2612. handle->bufferInfos = 0;
  2613. // Create a manual-reset event.
  2614. handle->condition = CreateEvent( NULL, // no security
  2615. TRUE, // manual-reset
  2616. FALSE, // non-signaled initially
  2617. NULL ); // unnamed
  2618. stream_.apiHandle = (void *) handle;
  2619. }
  2620. // Create the ASIO internal buffers. Since RtAudio sets up input
  2621. // and output separately, we'll have to dispose of previously
  2622. // created output buffers for a duplex stream.
  2623. long inputLatency, outputLatency;
  2624. if ( mode == INPUT && stream_.mode == OUTPUT ) {
  2625. ASIODisposeBuffers();
  2626. if ( handle->bufferInfos ) free( handle->bufferInfos );
  2627. }
  2628. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  2629. bool buffersAllocated = false;
  2630. unsigned int i, nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2631. handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  2632. if ( handle->bufferInfos == NULL ) {
  2633. errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
  2634. errorText_ = errorStream_.str();
  2635. goto error;
  2636. }
  2637. ASIOBufferInfo *infos;
  2638. infos = handle->bufferInfos;
  2639. for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
  2640. infos->isInput = ASIOFalse;
  2641. infos->channelNum = i + stream_.channelOffset[0];
  2642. infos->buffers[0] = infos->buffers[1] = 0;
  2643. }
  2644. for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
  2645. infos->isInput = ASIOTrue;
  2646. infos->channelNum = i + stream_.channelOffset[1];
  2647. infos->buffers[0] = infos->buffers[1] = 0;
  2648. }
  2649. // Set up the ASIO callback structure and create the ASIO data buffers.
  2650. asioCallbacks.bufferSwitch = &bufferSwitch;
  2651. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  2652. asioCallbacks.asioMessage = &asioMessages;
  2653. asioCallbacks.bufferSwitchTimeInfo = NULL;
  2654. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2655. if ( result != ASE_OK ) {
  2656. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
  2657. errorText_ = errorStream_.str();
  2658. goto error;
  2659. }
  2660. buffersAllocated = true;
  2661. // Set flags for buffer conversion.
  2662. stream_.doConvertBuffer[mode] = false;
  2663. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2664. stream_.doConvertBuffer[mode] = true;
  2665. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2666. stream_.nUserChannels[mode] > 1 )
  2667. stream_.doConvertBuffer[mode] = true;
  2668. // Allocate necessary internal buffers
  2669. unsigned long bufferBytes;
  2670. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2671. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2672. if ( stream_.userBuffer[mode] == NULL ) {
  2673. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
  2674. goto error;
  2675. }
  2676. if ( stream_.doConvertBuffer[mode] ) {
  2677. bool makeBuffer = true;
  2678. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  2679. if ( mode == INPUT ) {
  2680. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  2681. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2682. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  2683. }
  2684. }
  2685. if ( makeBuffer ) {
  2686. bufferBytes *= *bufferSize;
  2687. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2688. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2689. if ( stream_.deviceBuffer == NULL ) {
  2690. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
  2691. goto error;
  2692. }
  2693. }
  2694. }
  2695. stream_.sampleRate = sampleRate;
  2696. stream_.device[mode] = device;
  2697. stream_.state = STREAM_STOPPED;
  2698. asioCallbackInfo = &stream_.callbackInfo;
  2699. stream_.callbackInfo.object = (void *) this;
  2700. if ( stream_.mode == OUTPUT && mode == INPUT )
  2701. // We had already set up an output stream.
  2702. stream_.mode = DUPLEX;
  2703. else
  2704. stream_.mode = mode;
  2705. // Determine device latencies
  2706. result = ASIOGetLatencies( &inputLatency, &outputLatency );
  2707. if ( result != ASE_OK ) {
  2708. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
  2709. errorText_ = errorStream_.str();
  2710. error( RtAudioError::WARNING); // warn but don't fail
  2711. }
  2712. else {
  2713. stream_.latency[0] = outputLatency;
  2714. stream_.latency[1] = inputLatency;
  2715. }
  2716. // Setup the buffer conversion information structure. We don't use
  2717. // buffers to do channel offsets, so we override that parameter
  2718. // here.
  2719. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2720. return SUCCESS;
  2721. error:
  2722. if ( buffersAllocated )
  2723. ASIODisposeBuffers();
  2724. drivers.removeCurrentDriver();
  2725. if ( handle ) {
  2726. CloseHandle( handle->condition );
  2727. if ( handle->bufferInfos )
  2728. free( handle->bufferInfos );
  2729. delete handle;
  2730. stream_.apiHandle = 0;
  2731. }
  2732. for ( int i=0; i<2; i++ ) {
  2733. if ( stream_.userBuffer[i] ) {
  2734. free( stream_.userBuffer[i] );
  2735. stream_.userBuffer[i] = 0;
  2736. }
  2737. }
  2738. if ( stream_.deviceBuffer ) {
  2739. free( stream_.deviceBuffer );
  2740. stream_.deviceBuffer = 0;
  2741. }
  2742. return FAILURE;
  2743. }
  2744. void RtApiAsio :: closeStream()
  2745. {
  2746. if ( stream_.state == STREAM_CLOSED ) {
  2747. errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
  2748. error( RtAudioError::WARNING );
  2749. return;
  2750. }
  2751. if ( stream_.state == STREAM_RUNNING ) {
  2752. stream_.state = STREAM_STOPPED;
  2753. ASIOStop();
  2754. }
  2755. ASIODisposeBuffers();
  2756. drivers.removeCurrentDriver();
  2757. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2758. if ( handle ) {
  2759. CloseHandle( handle->condition );
  2760. if ( handle->bufferInfos )
  2761. free( handle->bufferInfos );
  2762. delete handle;
  2763. stream_.apiHandle = 0;
  2764. }
  2765. for ( int i=0; i<2; i++ ) {
  2766. if ( stream_.userBuffer[i] ) {
  2767. free( stream_.userBuffer[i] );
  2768. stream_.userBuffer[i] = 0;
  2769. }
  2770. }
  2771. if ( stream_.deviceBuffer ) {
  2772. free( stream_.deviceBuffer );
  2773. stream_.deviceBuffer = 0;
  2774. }
  2775. stream_.mode = UNINITIALIZED;
  2776. stream_.state = STREAM_CLOSED;
  2777. }
  2778. bool stopThreadCalled = false;
  2779. void RtApiAsio :: startStream()
  2780. {
  2781. verifyStream();
  2782. if ( stream_.state == STREAM_RUNNING ) {
  2783. errorText_ = "RtApiAsio::startStream(): the stream is already running!";
  2784. error( RtAudioError::WARNING );
  2785. return;
  2786. }
  2787. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2788. ASIOError result = ASIOStart();
  2789. if ( result != ASE_OK ) {
  2790. errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
  2791. errorText_ = errorStream_.str();
  2792. goto unlock;
  2793. }
  2794. handle->drainCounter = 0;
  2795. handle->internalDrain = false;
  2796. ResetEvent( handle->condition );
  2797. stream_.state = STREAM_RUNNING;
  2798. asioXRun = false;
  2799. unlock:
  2800. stopThreadCalled = false;
  2801. if ( result == ASE_OK ) return;
  2802. error( RtAudioError::SYSTEM_ERROR );
  2803. }
  2804. void RtApiAsio :: stopStream()
  2805. {
  2806. verifyStream();
  2807. if ( stream_.state == STREAM_STOPPED ) {
  2808. errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
  2809. error( RtAudioError::WARNING );
  2810. return;
  2811. }
  2812. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2813. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2814. if ( handle->drainCounter == 0 ) {
  2815. handle->drainCounter = 2;
  2816. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  2817. }
  2818. }
  2819. stream_.state = STREAM_STOPPED;
  2820. ASIOError result = ASIOStop();
  2821. if ( result != ASE_OK ) {
  2822. errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
  2823. errorText_ = errorStream_.str();
  2824. }
  2825. if ( result == ASE_OK ) return;
  2826. error( RtAudioError::SYSTEM_ERROR );
  2827. }
  2828. void RtApiAsio :: abortStream()
  2829. {
  2830. verifyStream();
  2831. if ( stream_.state == STREAM_STOPPED ) {
  2832. errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
  2833. error( RtAudioError::WARNING );
  2834. return;
  2835. }
  2836. // The following lines were commented-out because some behavior was
  2837. // noted where the device buffers need to be zeroed to avoid
  2838. // continuing sound, even when the device buffers are completely
  2839. // disposed. So now, calling abort is the same as calling stop.
  2840. // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2841. // handle->drainCounter = 2;
  2842. stopStream();
  2843. }
  2844. // This function will be called by a spawned thread when the user
  2845. // callback function signals that the stream should be stopped or
  2846. // aborted. It is necessary to handle it this way because the
  2847. // callbackEvent() function must return before the ASIOStop()
  2848. // function will return.
  2849. static unsigned __stdcall asioStopStream( void *ptr )
  2850. {
  2851. CallbackInfo *info = (CallbackInfo *) ptr;
  2852. RtApiAsio *object = (RtApiAsio *) info->object;
  2853. object->stopStream();
  2854. _endthreadex( 0 );
  2855. return 0;
  2856. }
  2857. bool RtApiAsio :: callbackEvent( long bufferIndex )
  2858. {
  2859. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2860. if ( stream_.state == STREAM_CLOSED ) {
  2861. errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2862. error( RtAudioError::WARNING );
  2863. return FAILURE;
  2864. }
  2865. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2866. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2867. // Check if we were draining the stream and signal if finished.
  2868. if ( handle->drainCounter > 3 ) {
  2869. stream_.state = STREAM_STOPPING;
  2870. if ( handle->internalDrain == false )
  2871. SetEvent( handle->condition );
  2872. else { // spawn a thread to stop the stream
  2873. unsigned threadId;
  2874. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  2875. &stream_.callbackInfo, 0, &threadId );
  2876. }
  2877. return SUCCESS;
  2878. }
  2879. // Invoke user callback to get fresh output data UNLESS we are
  2880. // draining stream.
  2881. if ( handle->drainCounter == 0 ) {
  2882. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2883. double streamTime = getStreamTime();
  2884. RtAudioStreamStatus status = 0;
  2885. if ( stream_.mode != INPUT && asioXRun == true ) {
  2886. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2887. asioXRun = false;
  2888. }
  2889. if ( stream_.mode != OUTPUT && asioXRun == true ) {
  2890. status |= RTAUDIO_INPUT_OVERFLOW;
  2891. asioXRun = false;
  2892. }
  2893. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2894. stream_.bufferSize, streamTime, status, info->userData );
  2895. if ( cbReturnValue == 2 ) {
  2896. stream_.state = STREAM_STOPPING;
  2897. handle->drainCounter = 2;
  2898. unsigned threadId;
  2899. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  2900. &stream_.callbackInfo, 0, &threadId );
  2901. return SUCCESS;
  2902. }
  2903. else if ( cbReturnValue == 1 ) {
  2904. handle->drainCounter = 1;
  2905. handle->internalDrain = true;
  2906. }
  2907. }
  2908. unsigned int nChannels, bufferBytes, i, j;
  2909. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2910. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2911. bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
  2912. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2913. for ( i=0, j=0; i<nChannels; i++ ) {
  2914. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2915. memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
  2916. }
  2917. }
  2918. else if ( stream_.doConvertBuffer[0] ) {
  2919. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2920. if ( stream_.doByteSwap[0] )
  2921. byteSwapBuffer( stream_.deviceBuffer,
  2922. stream_.bufferSize * stream_.nDeviceChannels[0],
  2923. stream_.deviceFormat[0] );
  2924. for ( i=0, j=0; i<nChannels; i++ ) {
  2925. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2926. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2927. &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
  2928. }
  2929. }
  2930. else {
  2931. if ( stream_.doByteSwap[0] )
  2932. byteSwapBuffer( stream_.userBuffer[0],
  2933. stream_.bufferSize * stream_.nUserChannels[0],
  2934. stream_.userFormat );
  2935. for ( i=0, j=0; i<nChannels; i++ ) {
  2936. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  2937. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  2938. &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
  2939. }
  2940. }
  2941. if ( handle->drainCounter ) {
  2942. handle->drainCounter++;
  2943. goto unlock;
  2944. }
  2945. }
  2946. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2947. bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
  2948. if (stream_.doConvertBuffer[1]) {
  2949. // Always interleave ASIO input data.
  2950. for ( i=0, j=0; i<nChannels; i++ ) {
  2951. if ( handle->bufferInfos[i].isInput == ASIOTrue )
  2952. memcpy( &stream_.deviceBuffer[j++*bufferBytes],
  2953. handle->bufferInfos[i].buffers[bufferIndex],
  2954. bufferBytes );
  2955. }
  2956. if ( stream_.doByteSwap[1] )
  2957. byteSwapBuffer( stream_.deviceBuffer,
  2958. stream_.bufferSize * stream_.nDeviceChannels[1],
  2959. stream_.deviceFormat[1] );
  2960. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2961. }
  2962. else {
  2963. for ( i=0, j=0; i<nChannels; i++ ) {
  2964. if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
  2965. memcpy( &stream_.userBuffer[1][bufferBytes*j++],
  2966. handle->bufferInfos[i].buffers[bufferIndex],
  2967. bufferBytes );
  2968. }
  2969. }
  2970. if ( stream_.doByteSwap[1] )
  2971. byteSwapBuffer( stream_.userBuffer[1],
  2972. stream_.bufferSize * stream_.nUserChannels[1],
  2973. stream_.userFormat );
  2974. }
  2975. }
  2976. unlock:
  2977. // The following call was suggested by Malte Clasen. While the API
  2978. // documentation indicates it should not be required, some device
  2979. // drivers apparently do not function correctly without it.
  2980. ASIOOutputReady();
  2981. RtApi::tickStreamTime();
  2982. return SUCCESS;
  2983. }
  2984. static void sampleRateChanged( ASIOSampleRate sRate )
  2985. {
  2986. // The ASIO documentation says that this usually only happens during
  2987. // external sync. Audio processing is not stopped by the driver,
  2988. // actual sample rate might not have even changed, maybe only the
  2989. // sample rate status of an AES/EBU or S/PDIF digital input at the
  2990. // audio device.
  2991. RtApi *object = (RtApi *) asioCallbackInfo->object;
  2992. try {
  2993. object->stopStream();
  2994. }
  2995. catch ( RtAudioError &exception ) {
  2996. std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
  2997. return;
  2998. }
  2999. std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
  3000. }
  3001. static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )
  3002. {
  3003. long ret = 0;
  3004. switch( selector ) {
  3005. case kAsioSelectorSupported:
  3006. if ( value == kAsioResetRequest
  3007. || value == kAsioEngineVersion
  3008. || value == kAsioResyncRequest
  3009. || value == kAsioLatenciesChanged
  3010. // The following three were added for ASIO 2.0, you don't
  3011. // necessarily have to support them.
  3012. || value == kAsioSupportsTimeInfo
  3013. || value == kAsioSupportsTimeCode
  3014. || value == kAsioSupportsInputMonitor)
  3015. ret = 1L;
  3016. break;
  3017. case kAsioResetRequest:
  3018. // Defer the task and perform the reset of the driver during the
  3019. // next "safe" situation. You cannot reset the driver right now,
  3020. // as this code is called from the driver. Reset the driver is
  3021. // done by completely destruct is. I.e. ASIOStop(),
  3022. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  3023. // driver again.
  3024. std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
  3025. ret = 1L;
  3026. break;
  3027. case kAsioResyncRequest:
  3028. // This informs the application that the driver encountered some
  3029. // non-fatal data loss. It is used for synchronization purposes
  3030. // of different media. Added mainly to work around the Win16Mutex
  3031. // problems in Windows 95/98 with the Windows Multimedia system,
  3032. // which could lose data because the Mutex was held too long by
  3033. // another thread. However a driver can issue it in other
  3034. // situations, too.
  3035. // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
  3036. asioXRun = true;
  3037. ret = 1L;
  3038. break;
  3039. case kAsioLatenciesChanged:
  3040. // This will inform the host application that the drivers were
  3041. // latencies changed. Beware, it this does not mean that the
  3042. // buffer sizes have changed! You might need to update internal
  3043. // delay data.
  3044. std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
  3045. ret = 1L;
  3046. break;
  3047. case kAsioEngineVersion:
  3048. // Return the supported ASIO version of the host application. If
  3049. // a host application does not implement this selector, ASIO 1.0
  3050. // is assumed by the driver.
  3051. ret = 2L;
  3052. break;
  3053. case kAsioSupportsTimeInfo:
  3054. // Informs the driver whether the
  3055. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  3056. // For compatibility with ASIO 1.0 drivers the host application
  3057. // should always support the "old" bufferSwitch method, too.
  3058. ret = 0;
  3059. break;
  3060. case kAsioSupportsTimeCode:
  3061. // Informs the driver whether application is interested in time
  3062. // code info. If an application does not need to know about time
  3063. // code, the driver has less work to do.
  3064. ret = 0;
  3065. break;
  3066. }
  3067. return ret;
  3068. }
  3069. static const char* getAsioErrorString( ASIOError result )
  3070. {
  3071. struct Messages
  3072. {
  3073. ASIOError value;
  3074. const char*message;
  3075. };
  3076. static const Messages m[] =
  3077. {
  3078. { ASE_NotPresent, "Hardware input or output is not present or available." },
  3079. { ASE_HWMalfunction, "Hardware is malfunctioning." },
  3080. { ASE_InvalidParameter, "Invalid input parameter." },
  3081. { ASE_InvalidMode, "Invalid mode." },
  3082. { ASE_SPNotAdvancing, "Sample position not advancing." },
  3083. { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
  3084. { ASE_NoMemory, "Not enough memory to complete the request." }
  3085. };
  3086. for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
  3087. if ( m[i].value == result ) return m[i].message;
  3088. return "Unknown error.";
  3089. }
  3090. //******************** End of __WINDOWS_ASIO__ *********************//
  3091. #endif
  3092. #if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
  3093. #ifndef INITGUID
  3094. #define INITGUID
  3095. #endif
  3096. #include <audioclient.h>
  3097. #include <avrt.h>
  3098. #include <mmdeviceapi.h>
  3099. #include <functiondiscoverykeys_devpkey.h>
  3100. //=============================================================================
  3101. #define SAFE_RELEASE( objectPtr )\
  3102. if ( objectPtr )\
  3103. {\
  3104. objectPtr->Release();\
  3105. objectPtr = NULL;\
  3106. }
  3107. typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );
  3108. //-----------------------------------------------------------------------------
  3109. // WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
  3110. // Therefore we must perform all necessary conversions to user buffers in order to satisfy these
  3111. // requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
  3112. // provide intermediate storage for read / write synchronization.
  3113. class WasapiBuffer
  3114. {
  3115. public:
  3116. WasapiBuffer()
  3117. : buffer_( NULL ),
  3118. bufferSize_( 0 ),
  3119. inIndex_( 0 ),
  3120. outIndex_( 0 ) {}
  3121. ~WasapiBuffer() {
  3122. delete buffer_;
  3123. }
  3124. // sets the length of the internal ring buffer
  3125. void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {
  3126. delete buffer_;
  3127. buffer_ = ( char* ) calloc( bufferSize, formatBytes );
  3128. bufferSize_ = bufferSize;
  3129. inIndex_ = 0;
  3130. outIndex_ = 0;
  3131. }
  3132. // attempt to push a buffer into the ring buffer at the current "in" index
  3133. bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3134. {
  3135. if ( !buffer || // incoming buffer is NULL
  3136. bufferSize == 0 || // incoming buffer has no data
  3137. bufferSize > bufferSize_ ) // incoming buffer too large
  3138. {
  3139. return false;
  3140. }
  3141. unsigned int relOutIndex = outIndex_;
  3142. unsigned int inIndexEnd = inIndex_ + bufferSize;
  3143. if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {
  3144. relOutIndex += bufferSize_;
  3145. }
  3146. // "in" index can end on the "out" index but cannot begin at it
  3147. if ( inIndex_ <= relOutIndex && inIndexEnd > relOutIndex ) {
  3148. return false; // not enough space between "in" index and "out" index
  3149. }
  3150. // copy buffer from external to internal
  3151. int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
  3152. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3153. int fromInSize = bufferSize - fromZeroSize;
  3154. switch( format )
  3155. {
  3156. case RTAUDIO_SINT8:
  3157. memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );
  3158. memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );
  3159. break;
  3160. case RTAUDIO_SINT16:
  3161. memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );
  3162. memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );
  3163. break;
  3164. case RTAUDIO_SINT24:
  3165. memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );
  3166. memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );
  3167. break;
  3168. case RTAUDIO_SINT32:
  3169. memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );
  3170. memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );
  3171. break;
  3172. case RTAUDIO_FLOAT32:
  3173. memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );
  3174. memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );
  3175. break;
  3176. case RTAUDIO_FLOAT64:
  3177. memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );
  3178. memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );
  3179. break;
  3180. }
  3181. // update "in" index
  3182. inIndex_ += bufferSize;
  3183. inIndex_ %= bufferSize_;
  3184. return true;
  3185. }
  3186. // attempt to pull a buffer from the ring buffer from the current "out" index
  3187. bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3188. {
  3189. if ( !buffer || // incoming buffer is NULL
  3190. bufferSize == 0 || // incoming buffer has no data
  3191. bufferSize > bufferSize_ ) // incoming buffer too large
  3192. {
  3193. return false;
  3194. }
  3195. unsigned int relInIndex = inIndex_;
  3196. unsigned int outIndexEnd = outIndex_ + bufferSize;
  3197. if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {
  3198. relInIndex += bufferSize_;
  3199. }
  3200. // "out" index can begin at and end on the "in" index
  3201. if ( outIndex_ < relInIndex && outIndexEnd > relInIndex ) {
  3202. return false; // not enough space between "out" index and "in" index
  3203. }
  3204. // copy buffer from internal to external
  3205. int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
  3206. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3207. int fromOutSize = bufferSize - fromZeroSize;
  3208. switch( format )
  3209. {
  3210. case RTAUDIO_SINT8:
  3211. memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );
  3212. memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );
  3213. break;
  3214. case RTAUDIO_SINT16:
  3215. memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );
  3216. memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );
  3217. break;
  3218. case RTAUDIO_SINT24:
  3219. memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );
  3220. memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );
  3221. break;
  3222. case RTAUDIO_SINT32:
  3223. memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );
  3224. memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );
  3225. break;
  3226. case RTAUDIO_FLOAT32:
  3227. memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );
  3228. memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );
  3229. break;
  3230. case RTAUDIO_FLOAT64:
  3231. memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );
  3232. memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );
  3233. break;
  3234. }
  3235. // update "out" index
  3236. outIndex_ += bufferSize;
  3237. outIndex_ %= bufferSize_;
  3238. return true;
  3239. }
  3240. private:
  3241. char* buffer_;
  3242. unsigned int bufferSize_;
  3243. unsigned int inIndex_;
  3244. unsigned int outIndex_;
  3245. };
  3246. //-----------------------------------------------------------------------------
  3247. // In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate and
  3248. // channel counts between HW and the user. The convertBufferWasapi function is used to perform
  3249. // these conversions between HwIn->UserIn and UserOut->HwOut during the stream callback loop.
  3250. // This sample rate converter favors speed over quality, and works best with conversions between
  3251. // one rate and its multiple. RtApiWasapi will not populate a device's sample rate list with rates
  3252. // that may cause artifacts via this conversion.
  3253. void convertBufferWasapi( char* outBuffer,
  3254. const char* inBuffer,
  3255. const unsigned int& inChannelCount,
  3256. const unsigned int& outChannelCount,
  3257. const unsigned int& inSampleRate,
  3258. const unsigned int& outSampleRate,
  3259. const unsigned int& inSampleCount,
  3260. unsigned int& outSampleCount,
  3261. const RtAudioFormat& format )
  3262. {
  3263. // calculate the new outSampleCount and relative sampleStep
  3264. float sampleRatio = ( float ) outSampleRate / inSampleRate;
  3265. float sampleStep = 1.0f / sampleRatio;
  3266. float inSampleFraction = 0.0f;
  3267. unsigned int commonChannelCount = std::min( inChannelCount, outChannelCount );
  3268. outSampleCount = ( unsigned int ) ( inSampleCount * sampleRatio );
  3269. // frame-by-frame, copy each relative input sample into it's corresponding output sample
  3270. for ( unsigned int outSample = 0; outSample < outSampleCount; outSample++ )
  3271. {
  3272. unsigned int inSample = ( unsigned int ) inSampleFraction;
  3273. switch ( format )
  3274. {
  3275. case RTAUDIO_SINT8:
  3276. memcpy( &( ( char* ) outBuffer )[ outSample * outChannelCount ], &( ( char* ) inBuffer )[ inSample * inChannelCount ], commonChannelCount * sizeof( char ) );
  3277. break;
  3278. case RTAUDIO_SINT16:
  3279. memcpy( &( ( short* ) outBuffer )[ outSample * outChannelCount ], &( ( short* ) inBuffer )[ inSample * inChannelCount ], commonChannelCount * sizeof( short ) );
  3280. break;
  3281. case RTAUDIO_SINT24:
  3282. memcpy( &( ( S24* ) outBuffer )[ outSample * outChannelCount ], &( ( S24* ) inBuffer )[ inSample * inChannelCount ], commonChannelCount * sizeof( S24 ) );
  3283. break;
  3284. case RTAUDIO_SINT32:
  3285. memcpy( &( ( int* ) outBuffer )[ outSample * outChannelCount ], &( ( int* ) inBuffer )[ inSample * inChannelCount ], commonChannelCount * sizeof( int ) );
  3286. break;
  3287. case RTAUDIO_FLOAT32:
  3288. memcpy( &( ( float* ) outBuffer )[ outSample * outChannelCount ], &( ( float* ) inBuffer )[ inSample * inChannelCount ], commonChannelCount * sizeof( float ) );
  3289. break;
  3290. case RTAUDIO_FLOAT64:
  3291. memcpy( &( ( double* ) outBuffer )[ outSample * outChannelCount ], &( ( double* ) inBuffer )[ inSample * inChannelCount ], commonChannelCount * sizeof( double ) );
  3292. break;
  3293. }
  3294. // jump to next in sample
  3295. inSampleFraction += sampleStep;
  3296. }
  3297. }
  3298. //-----------------------------------------------------------------------------
  3299. // A structure to hold various information related to the WASAPI implementation.
  3300. struct WasapiHandle
  3301. {
  3302. IAudioClient* captureAudioClient;
  3303. IAudioClient* renderAudioClient;
  3304. IAudioCaptureClient* captureClient;
  3305. IAudioRenderClient* renderClient;
  3306. HANDLE captureEvent;
  3307. HANDLE renderEvent;
  3308. WasapiHandle()
  3309. : captureAudioClient( NULL ),
  3310. renderAudioClient( NULL ),
  3311. captureClient( NULL ),
  3312. renderClient( NULL ),
  3313. captureEvent( NULL ),
  3314. renderEvent( NULL ) {}
  3315. };
  3316. //=============================================================================
  3317. RtApiWasapi::RtApiWasapi()
  3318. : coInitialized_( false ), deviceEnumerator_( NULL )
  3319. {
  3320. // WASAPI can run either apartment or multi-threaded
  3321. HRESULT hr = CoInitialize( NULL );
  3322. if ( !FAILED( hr ) )
  3323. coInitialized_ = true;
  3324. // Instantiate device enumerator
  3325. hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
  3326. CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
  3327. ( void** ) &deviceEnumerator_ );
  3328. if ( FAILED( hr ) ) {
  3329. errorText_ = "RtApiWasapi::RtApiWasapi: Unable to instantiate device enumerator";
  3330. error( RtAudioError::DRIVER_ERROR );
  3331. }
  3332. }
  3333. //-----------------------------------------------------------------------------
  3334. RtApiWasapi::~RtApiWasapi()
  3335. {
  3336. // if this object previously called CoInitialize()
  3337. if ( coInitialized_ ) {
  3338. CoUninitialize();
  3339. }
  3340. if ( stream_.state != STREAM_CLOSED ) {
  3341. closeStream();
  3342. }
  3343. SAFE_RELEASE( deviceEnumerator_ );
  3344. }
  3345. //=============================================================================
  3346. unsigned int RtApiWasapi::getDeviceCount( void )
  3347. {
  3348. unsigned int captureDeviceCount = 0;
  3349. unsigned int renderDeviceCount = 0;
  3350. IMMDeviceCollection* captureDevices = NULL;
  3351. IMMDeviceCollection* renderDevices = NULL;
  3352. // Count capture devices
  3353. errorText_.clear();
  3354. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3355. if ( FAILED( hr ) ) {
  3356. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
  3357. goto Exit;
  3358. }
  3359. hr = captureDevices->GetCount( &captureDeviceCount );
  3360. if ( FAILED( hr ) ) {
  3361. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
  3362. goto Exit;
  3363. }
  3364. // Count render devices
  3365. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3366. if ( FAILED( hr ) ) {
  3367. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
  3368. goto Exit;
  3369. }
  3370. hr = renderDevices->GetCount( &renderDeviceCount );
  3371. if ( FAILED( hr ) ) {
  3372. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
  3373. goto Exit;
  3374. }
  3375. Exit:
  3376. // release all references
  3377. SAFE_RELEASE( captureDevices );
  3378. SAFE_RELEASE( renderDevices );
  3379. if ( errorText_.empty() )
  3380. return captureDeviceCount + renderDeviceCount;
  3381. error( RtAudioError::DRIVER_ERROR );
  3382. return 0;
  3383. }
  3384. //-----------------------------------------------------------------------------
  3385. RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
  3386. {
  3387. RtAudio::DeviceInfo info;
  3388. unsigned int captureDeviceCount = 0;
  3389. unsigned int renderDeviceCount = 0;
  3390. std::wstring deviceName;
  3391. std::string defaultDeviceName;
  3392. bool isCaptureDevice = false;
  3393. PROPVARIANT deviceNameProp;
  3394. PROPVARIANT defaultDeviceNameProp;
  3395. IMMDeviceCollection* captureDevices = NULL;
  3396. IMMDeviceCollection* renderDevices = NULL;
  3397. IMMDevice* devicePtr = NULL;
  3398. IMMDevice* defaultDevicePtr = NULL;
  3399. IAudioClient* audioClient = NULL;
  3400. IPropertyStore* devicePropStore = NULL;
  3401. IPropertyStore* defaultDevicePropStore = NULL;
  3402. WAVEFORMATEX* deviceFormat = NULL;
  3403. WAVEFORMATEX* closestMatchFormat = NULL;
  3404. // probed
  3405. info.probed = false;
  3406. // Count capture devices
  3407. errorText_.clear();
  3408. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3409. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3410. if ( FAILED( hr ) ) {
  3411. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
  3412. goto Exit;
  3413. }
  3414. hr = captureDevices->GetCount( &captureDeviceCount );
  3415. if ( FAILED( hr ) ) {
  3416. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
  3417. goto Exit;
  3418. }
  3419. // Count render devices
  3420. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3421. if ( FAILED( hr ) ) {
  3422. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
  3423. goto Exit;
  3424. }
  3425. hr = renderDevices->GetCount( &renderDeviceCount );
  3426. if ( FAILED( hr ) ) {
  3427. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
  3428. goto Exit;
  3429. }
  3430. // validate device index
  3431. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3432. errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
  3433. errorType = RtAudioError::INVALID_USE;
  3434. goto Exit;
  3435. }
  3436. // determine whether index falls within capture or render devices
  3437. if ( device >= renderDeviceCount ) {
  3438. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3439. if ( FAILED( hr ) ) {
  3440. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
  3441. goto Exit;
  3442. }
  3443. isCaptureDevice = true;
  3444. }
  3445. else {
  3446. hr = renderDevices->Item( device, &devicePtr );
  3447. if ( FAILED( hr ) ) {
  3448. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
  3449. goto Exit;
  3450. }
  3451. isCaptureDevice = false;
  3452. }
  3453. // get default device name
  3454. if ( isCaptureDevice ) {
  3455. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );
  3456. if ( FAILED( hr ) ) {
  3457. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
  3458. goto Exit;
  3459. }
  3460. }
  3461. else {
  3462. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );
  3463. if ( FAILED( hr ) ) {
  3464. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
  3465. goto Exit;
  3466. }
  3467. }
  3468. hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );
  3469. if ( FAILED( hr ) ) {
  3470. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
  3471. goto Exit;
  3472. }
  3473. PropVariantInit( &defaultDeviceNameProp );
  3474. hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );
  3475. if ( FAILED( hr ) ) {
  3476. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
  3477. goto Exit;
  3478. }
  3479. deviceName = defaultDeviceNameProp.pwszVal;
  3480. defaultDeviceName = std::string( deviceName.begin(), deviceName.end() );
  3481. // name
  3482. hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
  3483. if ( FAILED( hr ) ) {
  3484. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
  3485. goto Exit;
  3486. }
  3487. PropVariantInit( &deviceNameProp );
  3488. hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
  3489. if ( FAILED( hr ) ) {
  3490. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
  3491. goto Exit;
  3492. }
  3493. deviceName = deviceNameProp.pwszVal;
  3494. info.name = std::string( deviceName.begin(), deviceName.end() );
  3495. // is default
  3496. if ( isCaptureDevice ) {
  3497. info.isDefaultInput = info.name == defaultDeviceName;
  3498. info.isDefaultOutput = false;
  3499. }
  3500. else {
  3501. info.isDefaultInput = false;
  3502. info.isDefaultOutput = info.name == defaultDeviceName;
  3503. }
  3504. // channel count
  3505. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
  3506. if ( FAILED( hr ) ) {
  3507. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
  3508. goto Exit;
  3509. }
  3510. hr = audioClient->GetMixFormat( &deviceFormat );
  3511. if ( FAILED( hr ) ) {
  3512. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
  3513. goto Exit;
  3514. }
  3515. if ( isCaptureDevice ) {
  3516. info.inputChannels = deviceFormat->nChannels;
  3517. info.outputChannels = 0;
  3518. info.duplexChannels = 0;
  3519. }
  3520. else {
  3521. info.inputChannels = 0;
  3522. info.outputChannels = deviceFormat->nChannels;
  3523. info.duplexChannels = 0;
  3524. }
  3525. // sample rates
  3526. info.sampleRates.clear();
  3527. // allow support for sample rates that are multiples of the base rate
  3528. for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {
  3529. if ( SAMPLE_RATES[i] < deviceFormat->nSamplesPerSec ) {
  3530. if ( deviceFormat->nSamplesPerSec % SAMPLE_RATES[i] == 0 ) {
  3531. info.sampleRates.push_back( SAMPLE_RATES[i] );
  3532. }
  3533. }
  3534. else {
  3535. if ( SAMPLE_RATES[i] % deviceFormat->nSamplesPerSec == 0 ) {
  3536. info.sampleRates.push_back( SAMPLE_RATES[i] );
  3537. }
  3538. }
  3539. }
  3540. // native format
  3541. info.nativeFormats = 0;
  3542. if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
  3543. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3544. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
  3545. {
  3546. if ( deviceFormat->wBitsPerSample == 32 ) {
  3547. info.nativeFormats |= RTAUDIO_FLOAT32;
  3548. }
  3549. else if ( deviceFormat->wBitsPerSample == 64 ) {
  3550. info.nativeFormats |= RTAUDIO_FLOAT64;
  3551. }
  3552. }
  3553. else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
  3554. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3555. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
  3556. {
  3557. if ( deviceFormat->wBitsPerSample == 8 ) {
  3558. info.nativeFormats |= RTAUDIO_SINT8;
  3559. }
  3560. else if ( deviceFormat->wBitsPerSample == 16 ) {
  3561. info.nativeFormats |= RTAUDIO_SINT16;
  3562. }
  3563. else if ( deviceFormat->wBitsPerSample == 24 ) {
  3564. info.nativeFormats |= RTAUDIO_SINT24;
  3565. }
  3566. else if ( deviceFormat->wBitsPerSample == 32 ) {
  3567. info.nativeFormats |= RTAUDIO_SINT32;
  3568. }
  3569. }
  3570. // probed
  3571. info.probed = true;
  3572. Exit:
  3573. // release all references
  3574. PropVariantClear( &deviceNameProp );
  3575. PropVariantClear( &defaultDeviceNameProp );
  3576. SAFE_RELEASE( captureDevices );
  3577. SAFE_RELEASE( renderDevices );
  3578. SAFE_RELEASE( devicePtr );
  3579. SAFE_RELEASE( defaultDevicePtr );
  3580. SAFE_RELEASE( audioClient );
  3581. SAFE_RELEASE( devicePropStore );
  3582. SAFE_RELEASE( defaultDevicePropStore );
  3583. CoTaskMemFree( deviceFormat );
  3584. CoTaskMemFree( closestMatchFormat );
  3585. if ( !errorText_.empty() )
  3586. error( errorType );
  3587. return info;
  3588. }
  3589. //-----------------------------------------------------------------------------
  3590. unsigned int RtApiWasapi::getDefaultOutputDevice( void )
  3591. {
  3592. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3593. if ( getDeviceInfo( i ).isDefaultOutput ) {
  3594. return i;
  3595. }
  3596. }
  3597. return 0;
  3598. }
  3599. //-----------------------------------------------------------------------------
  3600. unsigned int RtApiWasapi::getDefaultInputDevice( void )
  3601. {
  3602. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3603. if ( getDeviceInfo( i ).isDefaultInput ) {
  3604. return i;
  3605. }
  3606. }
  3607. return 0;
  3608. }
  3609. //-----------------------------------------------------------------------------
  3610. void RtApiWasapi::closeStream( void )
  3611. {
  3612. if ( stream_.state == STREAM_CLOSED ) {
  3613. errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
  3614. error( RtAudioError::WARNING );
  3615. return;
  3616. }
  3617. if ( stream_.state != STREAM_STOPPED )
  3618. stopStream();
  3619. // clean up stream memory
  3620. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
  3621. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
  3622. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )
  3623. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )
  3624. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
  3625. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
  3626. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
  3627. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
  3628. delete ( WasapiHandle* ) stream_.apiHandle;
  3629. stream_.apiHandle = NULL;
  3630. for ( int i = 0; i < 2; i++ ) {
  3631. if ( stream_.userBuffer[i] ) {
  3632. free( stream_.userBuffer[i] );
  3633. stream_.userBuffer[i] = 0;
  3634. }
  3635. }
  3636. if ( stream_.deviceBuffer ) {
  3637. free( stream_.deviceBuffer );
  3638. stream_.deviceBuffer = 0;
  3639. }
  3640. // update stream state
  3641. stream_.state = STREAM_CLOSED;
  3642. }
  3643. //-----------------------------------------------------------------------------
  3644. void RtApiWasapi::startStream( void )
  3645. {
  3646. verifyStream();
  3647. if ( stream_.state == STREAM_RUNNING ) {
  3648. errorText_ = "RtApiWasapi::startStream: The stream is already running.";
  3649. error( RtAudioError::WARNING );
  3650. return;
  3651. }
  3652. // update stream state
  3653. stream_.state = STREAM_RUNNING;
  3654. // create WASAPI stream thread
  3655. stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
  3656. if ( !stream_.callbackInfo.thread ) {
  3657. errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
  3658. error( RtAudioError::THREAD_ERROR );
  3659. }
  3660. else {
  3661. SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
  3662. ResumeThread( ( void* ) stream_.callbackInfo.thread );
  3663. }
  3664. }
  3665. //-----------------------------------------------------------------------------
  3666. void RtApiWasapi::stopStream( void )
  3667. {
  3668. verifyStream();
  3669. if ( stream_.state == STREAM_STOPPED ) {
  3670. errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
  3671. error( RtAudioError::WARNING );
  3672. return;
  3673. }
  3674. // inform stream thread by setting stream state to STREAM_STOPPING
  3675. stream_.state = STREAM_STOPPING;
  3676. // wait until stream thread is stopped
  3677. while( stream_.state != STREAM_STOPPED ) {
  3678. Sleep( 1 );
  3679. }
  3680. // Wait for the last buffer to play before stopping.
  3681. Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );
  3682. // stop capture client if applicable
  3683. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3684. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3685. if ( FAILED( hr ) ) {
  3686. errorText_ = "RtApiWasapi::stopStream: Unable to stop capture stream.";
  3687. error( RtAudioError::DRIVER_ERROR );
  3688. return;
  3689. }
  3690. }
  3691. // stop render client if applicable
  3692. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3693. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3694. if ( FAILED( hr ) ) {
  3695. errorText_ = "RtApiWasapi::stopStream: Unable to stop render stream.";
  3696. error( RtAudioError::DRIVER_ERROR );
  3697. return;
  3698. }
  3699. }
  3700. // close thread handle
  3701. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3702. errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
  3703. error( RtAudioError::THREAD_ERROR );
  3704. return;
  3705. }
  3706. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3707. }
  3708. //-----------------------------------------------------------------------------
  3709. void RtApiWasapi::abortStream( void )
  3710. {
  3711. verifyStream();
  3712. if ( stream_.state == STREAM_STOPPED ) {
  3713. errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
  3714. error( RtAudioError::WARNING );
  3715. return;
  3716. }
  3717. // inform stream thread by setting stream state to STREAM_STOPPING
  3718. stream_.state = STREAM_STOPPING;
  3719. // wait until stream thread is stopped
  3720. while ( stream_.state != STREAM_STOPPED ) {
  3721. Sleep( 1 );
  3722. }
  3723. // stop capture client if applicable
  3724. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3725. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3726. if ( FAILED( hr ) ) {
  3727. errorText_ = "RtApiWasapi::abortStream: Unable to stop capture stream.";
  3728. error( RtAudioError::DRIVER_ERROR );
  3729. return;
  3730. }
  3731. }
  3732. // stop render client if applicable
  3733. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3734. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3735. if ( FAILED( hr ) ) {
  3736. errorText_ = "RtApiWasapi::abortStream: Unable to stop render stream.";
  3737. error( RtAudioError::DRIVER_ERROR );
  3738. return;
  3739. }
  3740. }
  3741. // close thread handle
  3742. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3743. errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
  3744. error( RtAudioError::THREAD_ERROR );
  3745. return;
  3746. }
  3747. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3748. }
  3749. //-----------------------------------------------------------------------------
  3750. bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3751. unsigned int firstChannel, unsigned int sampleRate,
  3752. RtAudioFormat format, unsigned int* bufferSize,
  3753. RtAudio::StreamOptions* options )
  3754. {
  3755. bool methodResult = FAILURE;
  3756. unsigned int captureDeviceCount = 0;
  3757. unsigned int renderDeviceCount = 0;
  3758. IMMDeviceCollection* captureDevices = NULL;
  3759. IMMDeviceCollection* renderDevices = NULL;
  3760. IMMDevice* devicePtr = NULL;
  3761. WAVEFORMATEX* deviceFormat = NULL;
  3762. unsigned int bufferBytes;
  3763. stream_.state = STREAM_STOPPED;
  3764. // create API Handle if not already created
  3765. if ( !stream_.apiHandle )
  3766. stream_.apiHandle = ( void* ) new WasapiHandle();
  3767. // Count capture devices
  3768. errorText_.clear();
  3769. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3770. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3771. if ( FAILED( hr ) ) {
  3772. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
  3773. goto Exit;
  3774. }
  3775. hr = captureDevices->GetCount( &captureDeviceCount );
  3776. if ( FAILED( hr ) ) {
  3777. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
  3778. goto Exit;
  3779. }
  3780. // Count render devices
  3781. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3782. if ( FAILED( hr ) ) {
  3783. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
  3784. goto Exit;
  3785. }
  3786. hr = renderDevices->GetCount( &renderDeviceCount );
  3787. if ( FAILED( hr ) ) {
  3788. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
  3789. goto Exit;
  3790. }
  3791. // validate device index
  3792. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3793. errorType = RtAudioError::INVALID_USE;
  3794. errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
  3795. goto Exit;
  3796. }
  3797. // determine whether index falls within capture or render devices
  3798. if ( device >= renderDeviceCount ) {
  3799. if ( mode != INPUT ) {
  3800. errorType = RtAudioError::INVALID_USE;
  3801. errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
  3802. goto Exit;
  3803. }
  3804. // retrieve captureAudioClient from devicePtr
  3805. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  3806. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3807. if ( FAILED( hr ) ) {
  3808. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
  3809. goto Exit;
  3810. }
  3811. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3812. NULL, ( void** ) &captureAudioClient );
  3813. if ( FAILED( hr ) ) {
  3814. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3815. goto Exit;
  3816. }
  3817. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  3818. if ( FAILED( hr ) ) {
  3819. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3820. goto Exit;
  3821. }
  3822. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  3823. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  3824. }
  3825. else {
  3826. if ( mode != OUTPUT ) {
  3827. errorType = RtAudioError::INVALID_USE;
  3828. errorText_ = "RtApiWasapi::probeDeviceOpen: Render device selected as input device.";
  3829. goto Exit;
  3830. }
  3831. // retrieve renderAudioClient from devicePtr
  3832. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  3833. hr = renderDevices->Item( device, &devicePtr );
  3834. if ( FAILED( hr ) ) {
  3835. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  3836. goto Exit;
  3837. }
  3838. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3839. NULL, ( void** ) &renderAudioClient );
  3840. if ( FAILED( hr ) ) {
  3841. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3842. goto Exit;
  3843. }
  3844. hr = renderAudioClient->GetMixFormat( &deviceFormat );
  3845. if ( FAILED( hr ) ) {
  3846. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3847. goto Exit;
  3848. }
  3849. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  3850. renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  3851. }
  3852. // fill stream data
  3853. if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
  3854. ( stream_.mode == INPUT && mode == OUTPUT ) ) {
  3855. stream_.mode = DUPLEX;
  3856. }
  3857. else {
  3858. stream_.mode = mode;
  3859. }
  3860. stream_.device[mode] = device;
  3861. stream_.doByteSwap[mode] = false;
  3862. stream_.sampleRate = sampleRate;
  3863. stream_.bufferSize = *bufferSize;
  3864. stream_.nBuffers = 1;
  3865. stream_.nUserChannels[mode] = channels;
  3866. stream_.channelOffset[mode] = firstChannel;
  3867. stream_.userFormat = format;
  3868. stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats;
  3869. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  3870. stream_.userInterleaved = false;
  3871. else
  3872. stream_.userInterleaved = true;
  3873. stream_.deviceInterleaved[mode] = true;
  3874. // Set flags for buffer conversion.
  3875. stream_.doConvertBuffer[mode] = false;
  3876. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  3877. stream_.doConvertBuffer[mode] = true;
  3878. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  3879. stream_.nUserChannels[mode] > 1 )
  3880. stream_.doConvertBuffer[mode] = true;
  3881. if ( stream_.doConvertBuffer[mode] )
  3882. setConvertInfo( mode, 0 );
  3883. // Allocate necessary internal buffers
  3884. bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
  3885. stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
  3886. if ( !stream_.userBuffer[mode] ) {
  3887. errorType = RtAudioError::MEMORY_ERROR;
  3888. errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
  3889. goto Exit;
  3890. }
  3891. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
  3892. stream_.callbackInfo.priority = 15;
  3893. else
  3894. stream_.callbackInfo.priority = 0;
  3895. ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
  3896. ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
  3897. methodResult = SUCCESS;
  3898. Exit:
  3899. //clean up
  3900. SAFE_RELEASE( captureDevices );
  3901. SAFE_RELEASE( renderDevices );
  3902. SAFE_RELEASE( devicePtr );
  3903. CoTaskMemFree( deviceFormat );
  3904. // if method failed, close the stream
  3905. if ( methodResult == FAILURE )
  3906. closeStream();
  3907. if ( !errorText_.empty() )
  3908. error( errorType );
  3909. return methodResult;
  3910. }
  3911. //=============================================================================
  3912. DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
  3913. {
  3914. if ( wasapiPtr )
  3915. ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
  3916. return 0;
  3917. }
  3918. DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
  3919. {
  3920. if ( wasapiPtr )
  3921. ( ( RtApiWasapi* ) wasapiPtr )->stopStream();
  3922. return 0;
  3923. }
  3924. DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
  3925. {
  3926. if ( wasapiPtr )
  3927. ( ( RtApiWasapi* ) wasapiPtr )->abortStream();
  3928. return 0;
  3929. }
  3930. //-----------------------------------------------------------------------------
  3931. void RtApiWasapi::wasapiThread()
  3932. {
  3933. // as this is a new thread, we must CoInitialize it
  3934. CoInitialize( NULL );
  3935. HRESULT hr;
  3936. IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  3937. IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  3938. IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
  3939. IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
  3940. HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
  3941. HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
  3942. WAVEFORMATEX* captureFormat = NULL;
  3943. WAVEFORMATEX* renderFormat = NULL;
  3944. float captureSrRatio = 0.0f;
  3945. float renderSrRatio = 0.0f;
  3946. WasapiBuffer captureBuffer;
  3947. WasapiBuffer renderBuffer;
  3948. // declare local stream variables
  3949. RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
  3950. BYTE* streamBuffer = NULL;
  3951. unsigned long captureFlags = 0;
  3952. unsigned int bufferFrameCount = 0;
  3953. unsigned int numFramesPadding = 0;
  3954. unsigned int convBufferSize = 0;
  3955. bool callbackPushed = false;
  3956. bool callbackPulled = false;
  3957. bool callbackStopped = false;
  3958. int callbackResult = 0;
  3959. // convBuffer is used to store converted buffers between WASAPI and the user
  3960. char* convBuffer = NULL;
  3961. unsigned int deviceBufferSize = 0;
  3962. errorText_.clear();
  3963. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3964. // Attempt to assign "Pro Audio" characteristic to thread
  3965. HMODULE AvrtDll = LoadLibrary( "AVRT.dll" );
  3966. if ( AvrtDll ) {
  3967. DWORD taskIndex = 0;
  3968. TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = ( TAvSetMmThreadCharacteristicsPtr ) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
  3969. AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
  3970. FreeLibrary( AvrtDll );
  3971. }
  3972. // start capture stream if applicable
  3973. if ( captureAudioClient ) {
  3974. hr = captureAudioClient->GetMixFormat( &captureFormat );
  3975. if ( FAILED( hr ) ) {
  3976. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  3977. goto Exit;
  3978. }
  3979. captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );
  3980. // initialize capture stream according to desire buffer size
  3981. float desiredBufferSize = stream_.bufferSize * captureSrRatio;
  3982. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / captureFormat->nSamplesPerSec );
  3983. if ( !captureClient ) {
  3984. hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  3985. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  3986. desiredBufferPeriod,
  3987. desiredBufferPeriod,
  3988. captureFormat,
  3989. NULL );
  3990. if ( FAILED( hr ) ) {
  3991. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
  3992. goto Exit;
  3993. }
  3994. hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
  3995. ( void** ) &captureClient );
  3996. if ( FAILED( hr ) ) {
  3997. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
  3998. goto Exit;
  3999. }
  4000. // configure captureEvent to trigger on every available capture buffer
  4001. captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4002. if ( !captureEvent ) {
  4003. errorType = RtAudioError::SYSTEM_ERROR;
  4004. errorText_ = "RtApiWasapi::wasapiThread: Unable to create capture event.";
  4005. goto Exit;
  4006. }
  4007. hr = captureAudioClient->SetEventHandle( captureEvent );
  4008. if ( FAILED( hr ) ) {
  4009. errorText_ = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
  4010. goto Exit;
  4011. }
  4012. ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
  4013. ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
  4014. }
  4015. unsigned int inBufferSize = 0;
  4016. hr = captureAudioClient->GetBufferSize( &inBufferSize );
  4017. if ( FAILED( hr ) ) {
  4018. errorText_ = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
  4019. goto Exit;
  4020. }
  4021. // scale outBufferSize according to stream->user sample rate ratio
  4022. unsigned int outBufferSize = ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];
  4023. inBufferSize *= stream_.nDeviceChannels[INPUT];
  4024. // set captureBuffer size
  4025. captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
  4026. // reset the capture stream
  4027. hr = captureAudioClient->Reset();
  4028. if ( FAILED( hr ) ) {
  4029. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
  4030. goto Exit;
  4031. }
  4032. // start the capture stream
  4033. hr = captureAudioClient->Start();
  4034. if ( FAILED( hr ) ) {
  4035. errorText_ = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
  4036. goto Exit;
  4037. }
  4038. }
  4039. // start render stream if applicable
  4040. if ( renderAudioClient ) {
  4041. hr = renderAudioClient->GetMixFormat( &renderFormat );
  4042. if ( FAILED( hr ) ) {
  4043. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4044. goto Exit;
  4045. }
  4046. renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );
  4047. // initialize render stream according to desire buffer size
  4048. float desiredBufferSize = stream_.bufferSize * renderSrRatio;
  4049. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / renderFormat->nSamplesPerSec );
  4050. if ( !renderClient ) {
  4051. hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4052. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4053. desiredBufferPeriod,
  4054. desiredBufferPeriod,
  4055. renderFormat,
  4056. NULL );
  4057. if ( FAILED( hr ) ) {
  4058. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
  4059. goto Exit;
  4060. }
  4061. hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
  4062. ( void** ) &renderClient );
  4063. if ( FAILED( hr ) ) {
  4064. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
  4065. goto Exit;
  4066. }
  4067. // configure renderEvent to trigger on every available render buffer
  4068. renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4069. if ( !renderEvent ) {
  4070. errorType = RtAudioError::SYSTEM_ERROR;
  4071. errorText_ = "RtApiWasapi::wasapiThread: Unable to create render event.";
  4072. goto Exit;
  4073. }
  4074. hr = renderAudioClient->SetEventHandle( renderEvent );
  4075. if ( FAILED( hr ) ) {
  4076. errorText_ = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
  4077. goto Exit;
  4078. }
  4079. ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
  4080. ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
  4081. }
  4082. unsigned int outBufferSize = 0;
  4083. hr = renderAudioClient->GetBufferSize( &outBufferSize );
  4084. if ( FAILED( hr ) ) {
  4085. errorText_ = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
  4086. goto Exit;
  4087. }
  4088. // scale inBufferSize according to user->stream sample rate ratio
  4089. unsigned int inBufferSize = ( unsigned int ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];
  4090. outBufferSize *= stream_.nDeviceChannels[OUTPUT];
  4091. // set renderBuffer size
  4092. renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4093. // reset the render stream
  4094. hr = renderAudioClient->Reset();
  4095. if ( FAILED( hr ) ) {
  4096. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
  4097. goto Exit;
  4098. }
  4099. // start the render stream
  4100. hr = renderAudioClient->Start();
  4101. if ( FAILED( hr ) ) {
  4102. errorText_ = "RtApiWasapi::wasapiThread: Unable to start render stream.";
  4103. goto Exit;
  4104. }
  4105. }
  4106. if ( stream_.mode == INPUT ) {
  4107. deviceBufferSize = ( size_t ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4108. }
  4109. else if ( stream_.mode == OUTPUT ) {
  4110. deviceBufferSize = ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4111. }
  4112. else if ( stream_.mode == DUPLEX ) {
  4113. deviceBufferSize = std::max( ( size_t ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4114. ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4115. }
  4116. convBuffer = ( char* ) malloc( deviceBufferSize );
  4117. stream_.deviceBuffer = ( char* ) malloc( deviceBufferSize );
  4118. if ( !convBuffer || !stream_.deviceBuffer ) {
  4119. errorType = RtAudioError::MEMORY_ERROR;
  4120. errorText_ = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
  4121. goto Exit;
  4122. }
  4123. // stream process loop
  4124. while ( stream_.state != STREAM_STOPPING ) {
  4125. if ( !callbackPulled ) {
  4126. // Callback Input
  4127. // ==============
  4128. // 1. Pull callback buffer from inputBuffer
  4129. // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count
  4130. // Convert callback buffer to user format
  4131. if ( captureAudioClient ) {
  4132. // Pull callback buffer from inputBuffer
  4133. callbackPulled = captureBuffer.pullBuffer( convBuffer,
  4134. ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT],
  4135. stream_.deviceFormat[INPUT] );
  4136. if ( callbackPulled ) {
  4137. // Convert callback buffer to user sample rate and channel count
  4138. convertBufferWasapi( stream_.deviceBuffer,
  4139. convBuffer,
  4140. stream_.nDeviceChannels[INPUT],
  4141. stream_.nUserChannels[INPUT],
  4142. captureFormat->nSamplesPerSec,
  4143. stream_.sampleRate,
  4144. ( unsigned int ) ( stream_.bufferSize * captureSrRatio ),
  4145. convBufferSize,
  4146. stream_.deviceFormat[INPUT] );
  4147. if ( stream_.doConvertBuffer[INPUT] ) {
  4148. // Convert callback buffer to user format
  4149. convertBuffer( stream_.userBuffer[INPUT],
  4150. stream_.deviceBuffer,
  4151. stream_.convertInfo[INPUT] );
  4152. }
  4153. else {
  4154. // no conversion, simple copy deviceBuffer to userBuffer
  4155. memcpy( stream_.userBuffer[INPUT],
  4156. stream_.deviceBuffer,
  4157. stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
  4158. }
  4159. }
  4160. }
  4161. else {
  4162. // if there is no capture stream, set callbackPulled flag
  4163. callbackPulled = true;
  4164. }
  4165. // Execute Callback
  4166. // ================
  4167. // 1. Execute user callback method
  4168. // 2. Handle return value from callback
  4169. // if callback has not requested the stream to stop
  4170. if ( callbackPulled && !callbackStopped ) {
  4171. // Execute user callback method
  4172. callbackResult = callback( stream_.userBuffer[OUTPUT],
  4173. stream_.userBuffer[INPUT],
  4174. stream_.bufferSize,
  4175. getStreamTime(),
  4176. captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
  4177. stream_.callbackInfo.userData );
  4178. // Handle return value from callback
  4179. if ( callbackResult == 1 ) {
  4180. // instantiate a thread to stop this thread
  4181. HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
  4182. if ( !threadHandle ) {
  4183. errorType = RtAudioError::THREAD_ERROR;
  4184. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
  4185. goto Exit;
  4186. }
  4187. else if ( !CloseHandle( threadHandle ) ) {
  4188. errorType = RtAudioError::THREAD_ERROR;
  4189. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
  4190. goto Exit;
  4191. }
  4192. callbackStopped = true;
  4193. }
  4194. else if ( callbackResult == 2 ) {
  4195. // instantiate a thread to stop this thread
  4196. HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
  4197. if ( !threadHandle ) {
  4198. errorType = RtAudioError::THREAD_ERROR;
  4199. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
  4200. goto Exit;
  4201. }
  4202. else if ( !CloseHandle( threadHandle ) ) {
  4203. errorType = RtAudioError::THREAD_ERROR;
  4204. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
  4205. goto Exit;
  4206. }
  4207. callbackStopped = true;
  4208. }
  4209. }
  4210. }
  4211. // Callback Output
  4212. // ===============
  4213. // 1. Convert callback buffer to stream format
  4214. // 2. Convert callback buffer to stream sample rate and channel count
  4215. // 3. Push callback buffer into outputBuffer
  4216. if ( renderAudioClient && callbackPulled ) {
  4217. if ( stream_.doConvertBuffer[OUTPUT] ) {
  4218. // Convert callback buffer to stream format
  4219. convertBuffer( stream_.deviceBuffer,
  4220. stream_.userBuffer[OUTPUT],
  4221. stream_.convertInfo[OUTPUT] );
  4222. // Convert callback buffer to stream sample rate and channel count
  4223. convertBufferWasapi( convBuffer,
  4224. stream_.deviceBuffer,
  4225. stream_.nUserChannels[OUTPUT],
  4226. stream_.nDeviceChannels[OUTPUT],
  4227. stream_.sampleRate,
  4228. renderFormat->nSamplesPerSec,
  4229. stream_.bufferSize,
  4230. convBufferSize,
  4231. stream_.deviceFormat[OUTPUT] );
  4232. }
  4233. else {
  4234. // Convert callback buffer to stream sample rate and channel count
  4235. convertBufferWasapi( convBuffer,
  4236. stream_.userBuffer[OUTPUT],
  4237. stream_.nUserChannels[OUTPUT],
  4238. stream_.nDeviceChannels[OUTPUT],
  4239. stream_.sampleRate,
  4240. renderFormat->nSamplesPerSec,
  4241. stream_.bufferSize,
  4242. convBufferSize,
  4243. stream_.deviceFormat[OUTPUT] );
  4244. }
  4245. // Push callback buffer into outputBuffer
  4246. callbackPushed = renderBuffer.pushBuffer( convBuffer,
  4247. convBufferSize * stream_.nDeviceChannels[OUTPUT],
  4248. stream_.deviceFormat[OUTPUT] );
  4249. }
  4250. // Stream Capture
  4251. // ==============
  4252. // 1. Get capture buffer from stream
  4253. // 2. Push capture buffer into inputBuffer
  4254. // 3. If 2. was successful: Release capture buffer
  4255. if ( captureAudioClient ) {
  4256. // if the callback input buffer was not pulled from captureBuffer, wait for next capture event
  4257. if ( !callbackPulled ) {
  4258. WaitForSingleObject( captureEvent, INFINITE );
  4259. }
  4260. // Get capture buffer from stream
  4261. hr = captureClient->GetBuffer( &streamBuffer,
  4262. &bufferFrameCount,
  4263. &captureFlags, NULL, NULL );
  4264. if ( FAILED( hr ) ) {
  4265. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
  4266. goto Exit;
  4267. }
  4268. if ( bufferFrameCount != 0 ) {
  4269. // Push capture buffer into inputBuffer
  4270. if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
  4271. bufferFrameCount * stream_.nDeviceChannels[INPUT],
  4272. stream_.deviceFormat[INPUT] ) )
  4273. {
  4274. // Release capture buffer
  4275. hr = captureClient->ReleaseBuffer( bufferFrameCount );
  4276. if ( FAILED( hr ) ) {
  4277. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4278. goto Exit;
  4279. }
  4280. }
  4281. else
  4282. {
  4283. // Inform WASAPI that capture was unsuccessful
  4284. hr = captureClient->ReleaseBuffer( 0 );
  4285. if ( FAILED( hr ) ) {
  4286. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4287. goto Exit;
  4288. }
  4289. }
  4290. }
  4291. else
  4292. {
  4293. // Inform WASAPI that capture was unsuccessful
  4294. hr = captureClient->ReleaseBuffer( 0 );
  4295. if ( FAILED( hr ) ) {
  4296. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4297. goto Exit;
  4298. }
  4299. }
  4300. }
  4301. // Stream Render
  4302. // =============
  4303. // 1. Get render buffer from stream
  4304. // 2. Pull next buffer from outputBuffer
  4305. // 3. If 2. was successful: Fill render buffer with next buffer
  4306. // Release render buffer
  4307. if ( renderAudioClient ) {
  4308. // if the callback output buffer was not pushed to renderBuffer, wait for next render event
  4309. if ( callbackPulled && !callbackPushed ) {
  4310. WaitForSingleObject( renderEvent, INFINITE );
  4311. }
  4312. // Get render buffer from stream
  4313. hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
  4314. if ( FAILED( hr ) ) {
  4315. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
  4316. goto Exit;
  4317. }
  4318. hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
  4319. if ( FAILED( hr ) ) {
  4320. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
  4321. goto Exit;
  4322. }
  4323. bufferFrameCount -= numFramesPadding;
  4324. if ( bufferFrameCount != 0 ) {
  4325. hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
  4326. if ( FAILED( hr ) ) {
  4327. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
  4328. goto Exit;
  4329. }
  4330. // Pull next buffer from outputBuffer
  4331. // Fill render buffer with next buffer
  4332. if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
  4333. bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
  4334. stream_.deviceFormat[OUTPUT] ) )
  4335. {
  4336. // Release render buffer
  4337. hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
  4338. if ( FAILED( hr ) ) {
  4339. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4340. goto Exit;
  4341. }
  4342. }
  4343. else
  4344. {
  4345. // Inform WASAPI that render was unsuccessful
  4346. hr = renderClient->ReleaseBuffer( 0, 0 );
  4347. if ( FAILED( hr ) ) {
  4348. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4349. goto Exit;
  4350. }
  4351. }
  4352. }
  4353. else
  4354. {
  4355. // Inform WASAPI that render was unsuccessful
  4356. hr = renderClient->ReleaseBuffer( 0, 0 );
  4357. if ( FAILED( hr ) ) {
  4358. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4359. goto Exit;
  4360. }
  4361. }
  4362. }
  4363. // if the callback buffer was pushed renderBuffer reset callbackPulled flag
  4364. if ( callbackPushed ) {
  4365. callbackPulled = false;
  4366. }
  4367. // tick stream time
  4368. RtApi::tickStreamTime();
  4369. }
  4370. Exit:
  4371. // clean up
  4372. CoTaskMemFree( captureFormat );
  4373. CoTaskMemFree( renderFormat );
  4374. //delete convBuffer;
  4375. free ( convBuffer );
  4376. CoUninitialize();
  4377. // update stream state
  4378. stream_.state = STREAM_STOPPED;
  4379. if ( errorText_.empty() )
  4380. return;
  4381. else
  4382. error( errorType );
  4383. }
  4384. //******************** End of __WINDOWS_WASAPI__ *********************//
  4385. #endif
  4386. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  4387. // Modified by Robin Davies, October 2005
  4388. // - Improvements to DirectX pointer chasing.
  4389. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  4390. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  4391. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  4392. // Changed device query structure for RtAudio 4.0.7, January 2010
  4393. #include <dsound.h>
  4394. #include <assert.h>
  4395. #include <algorithm>
  4396. #if defined(__MINGW32__)
  4397. // missing from latest mingw winapi
  4398. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  4399. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  4400. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  4401. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  4402. #endif
  4403. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  4404. #ifdef _MSC_VER // if Microsoft Visual C++
  4405. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  4406. #endif
  4407. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  4408. {
  4409. if ( pointer > bufferSize ) pointer -= bufferSize;
  4410. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  4411. if ( pointer < earlierPointer ) pointer += bufferSize;
  4412. return pointer >= earlierPointer && pointer < laterPointer;
  4413. }
  4414. // A structure to hold various information related to the DirectSound
  4415. // API implementation.
  4416. struct DsHandle {
  4417. unsigned int drainCounter; // Tracks callback counts when draining
  4418. bool internalDrain; // Indicates if stop is initiated from callback or not.
  4419. void *id[2];
  4420. void *buffer[2];
  4421. bool xrun[2];
  4422. UINT bufferPointer[2];
  4423. DWORD dsBufferSize[2];
  4424. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  4425. HANDLE condition;
  4426. DsHandle()
  4427. :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; }
  4428. };
  4429. // Declarations for utility functions, callbacks, and structures
  4430. // specific to the DirectSound implementation.
  4431. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4432. LPCTSTR description,
  4433. LPCTSTR module,
  4434. LPVOID lpContext );
  4435. static const char* getErrorString( int code );
  4436. static unsigned __stdcall callbackHandler( void *ptr );
  4437. struct DsDevice {
  4438. LPGUID id[2];
  4439. bool validId[2];
  4440. bool found;
  4441. std::string name;
  4442. DsDevice()
  4443. : found(false) { validId[0] = false; validId[1] = false; }
  4444. };
  4445. struct DsProbeData {
  4446. bool isInput;
  4447. std::vector<struct DsDevice>* dsDevices;
  4448. };
  4449. RtApiDs :: RtApiDs()
  4450. {
  4451. // Dsound will run both-threaded. If CoInitialize fails, then just
  4452. // accept whatever the mainline chose for a threading model.
  4453. coInitialized_ = false;
  4454. HRESULT hr = CoInitialize( NULL );
  4455. if ( !FAILED( hr ) ) coInitialized_ = true;
  4456. }
  4457. RtApiDs :: ~RtApiDs()
  4458. {
  4459. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  4460. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4461. }
  4462. // The DirectSound default output is always the first device.
  4463. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  4464. {
  4465. return 0;
  4466. }
  4467. // The DirectSound default input is always the first input device,
  4468. // which is the first capture device enumerated.
  4469. unsigned int RtApiDs :: getDefaultInputDevice( void )
  4470. {
  4471. return 0;
  4472. }
  4473. unsigned int RtApiDs :: getDeviceCount( void )
  4474. {
  4475. // Set query flag for previously found devices to false, so that we
  4476. // can check for any devices that have disappeared.
  4477. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4478. dsDevices[i].found = false;
  4479. // Query DirectSound devices.
  4480. struct DsProbeData probeInfo;
  4481. probeInfo.isInput = false;
  4482. probeInfo.dsDevices = &dsDevices;
  4483. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4484. if ( FAILED( result ) ) {
  4485. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  4486. errorText_ = errorStream_.str();
  4487. error( RtAudioError::WARNING );
  4488. }
  4489. // Query DirectSoundCapture devices.
  4490. probeInfo.isInput = true;
  4491. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4492. if ( FAILED( result ) ) {
  4493. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  4494. errorText_ = errorStream_.str();
  4495. error( RtAudioError::WARNING );
  4496. }
  4497. // Clean out any devices that may have disappeared.
  4498. std::vector< int > indices;
  4499. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4500. if ( dsDevices[i].found == false ) indices.push_back( i );
  4501. //unsigned int nErased = 0;
  4502. for ( unsigned int i=0; i<indices.size(); i++ )
  4503. dsDevices.erase( dsDevices.begin()+indices[i] );
  4504. //dsDevices.erase( dsDevices.begin()-nErased++ );
  4505. return static_cast<unsigned int>(dsDevices.size());
  4506. }
  4507. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  4508. {
  4509. RtAudio::DeviceInfo info;
  4510. info.probed = false;
  4511. if ( dsDevices.size() == 0 ) {
  4512. // Force a query of all devices
  4513. getDeviceCount();
  4514. if ( dsDevices.size() == 0 ) {
  4515. errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
  4516. error( RtAudioError::INVALID_USE );
  4517. return info;
  4518. }
  4519. }
  4520. if ( device >= dsDevices.size() ) {
  4521. errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
  4522. error( RtAudioError::INVALID_USE );
  4523. return info;
  4524. }
  4525. HRESULT result;
  4526. if ( dsDevices[ device ].validId[0] == false ) goto probeInput;
  4527. LPDIRECTSOUND output;
  4528. DSCAPS outCaps;
  4529. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4530. if ( FAILED( result ) ) {
  4531. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4532. errorText_ = errorStream_.str();
  4533. error( RtAudioError::WARNING );
  4534. goto probeInput;
  4535. }
  4536. outCaps.dwSize = sizeof( outCaps );
  4537. result = output->GetCaps( &outCaps );
  4538. if ( FAILED( result ) ) {
  4539. output->Release();
  4540. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  4541. errorText_ = errorStream_.str();
  4542. error( RtAudioError::WARNING );
  4543. goto probeInput;
  4544. }
  4545. // Get output channel information.
  4546. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  4547. // Get sample rate information.
  4548. info.sampleRates.clear();
  4549. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  4550. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  4551. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate )
  4552. info.sampleRates.push_back( SAMPLE_RATES[k] );
  4553. }
  4554. // Get format information.
  4555. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  4556. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  4557. output->Release();
  4558. if ( getDefaultOutputDevice() == device )
  4559. info.isDefaultOutput = true;
  4560. if ( dsDevices[ device ].validId[1] == false ) {
  4561. info.name = dsDevices[ device ].name;
  4562. info.probed = true;
  4563. return info;
  4564. }
  4565. probeInput:
  4566. LPDIRECTSOUNDCAPTURE input;
  4567. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4568. if ( FAILED( result ) ) {
  4569. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4570. errorText_ = errorStream_.str();
  4571. error( RtAudioError::WARNING );
  4572. return info;
  4573. }
  4574. DSCCAPS inCaps;
  4575. inCaps.dwSize = sizeof( inCaps );
  4576. result = input->GetCaps( &inCaps );
  4577. if ( FAILED( result ) ) {
  4578. input->Release();
  4579. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";
  4580. errorText_ = errorStream_.str();
  4581. error( RtAudioError::WARNING );
  4582. return info;
  4583. }
  4584. // Get input channel information.
  4585. info.inputChannels = inCaps.dwChannels;
  4586. // Get sample rate and format information.
  4587. std::vector<unsigned int> rates;
  4588. if ( inCaps.dwChannels >= 2 ) {
  4589. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4590. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4591. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4592. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4593. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4594. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4595. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4596. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4597. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4598. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
  4599. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
  4600. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
  4601. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
  4602. }
  4603. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4604. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
  4605. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
  4606. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
  4607. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
  4608. }
  4609. }
  4610. else if ( inCaps.dwChannels == 1 ) {
  4611. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4612. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4613. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4614. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4615. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4616. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4617. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4618. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4619. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4620. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
  4621. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
  4622. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
  4623. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
  4624. }
  4625. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4626. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
  4627. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
  4628. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
  4629. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
  4630. }
  4631. }
  4632. else info.inputChannels = 0; // technically, this would be an error
  4633. input->Release();
  4634. if ( info.inputChannels == 0 ) return info;
  4635. // Copy the supported rates to the info structure but avoid duplication.
  4636. bool found;
  4637. for ( unsigned int i=0; i<rates.size(); i++ ) {
  4638. found = false;
  4639. for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
  4640. if ( rates[i] == info.sampleRates[j] ) {
  4641. found = true;
  4642. break;
  4643. }
  4644. }
  4645. if ( found == false ) info.sampleRates.push_back( rates[i] );
  4646. }
  4647. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  4648. // If device opens for both playback and capture, we determine the channels.
  4649. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4650. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4651. if ( device == 0 ) info.isDefaultInput = true;
  4652. // Copy name and return.
  4653. info.name = dsDevices[ device ].name;
  4654. info.probed = true;
  4655. return info;
  4656. }
  4657. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4658. unsigned int firstChannel, unsigned int sampleRate,
  4659. RtAudioFormat format, unsigned int *bufferSize,
  4660. RtAudio::StreamOptions *options )
  4661. {
  4662. if ( channels + firstChannel > 2 ) {
  4663. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  4664. return FAILURE;
  4665. }
  4666. size_t nDevices = dsDevices.size();
  4667. if ( nDevices == 0 ) {
  4668. // This should not happen because a check is made before this function is called.
  4669. errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
  4670. return FAILURE;
  4671. }
  4672. if ( device >= nDevices ) {
  4673. // This should not happen because a check is made before this function is called.
  4674. errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
  4675. return FAILURE;
  4676. }
  4677. if ( mode == OUTPUT ) {
  4678. if ( dsDevices[ device ].validId[0] == false ) {
  4679. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  4680. errorText_ = errorStream_.str();
  4681. return FAILURE;
  4682. }
  4683. }
  4684. else { // mode == INPUT
  4685. if ( dsDevices[ device ].validId[1] == false ) {
  4686. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  4687. errorText_ = errorStream_.str();
  4688. return FAILURE;
  4689. }
  4690. }
  4691. // According to a note in PortAudio, using GetDesktopWindow()
  4692. // instead of GetForegroundWindow() is supposed to avoid problems
  4693. // that occur when the application's window is not the foreground
  4694. // window. Also, if the application window closes before the
  4695. // DirectSound buffer, DirectSound can crash. In the past, I had
  4696. // problems when using GetDesktopWindow() but it seems fine now
  4697. // (January 2010). I'll leave it commented here.
  4698. // HWND hWnd = GetForegroundWindow();
  4699. HWND hWnd = GetDesktopWindow();
  4700. // Check the numberOfBuffers parameter and limit the lowest value to
  4701. // two. This is a judgement call and a value of two is probably too
  4702. // low for capture, but it should work for playback.
  4703. int nBuffers = 0;
  4704. if ( options ) nBuffers = options->numberOfBuffers;
  4705. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  4706. if ( nBuffers < 2 ) nBuffers = 3;
  4707. // Check the lower range of the user-specified buffer size and set
  4708. // (arbitrarily) to a lower bound of 32.
  4709. if ( *bufferSize < 32 ) *bufferSize = 32;
  4710. // Create the wave format structure. The data format setting will
  4711. // be determined later.
  4712. WAVEFORMATEX waveFormat;
  4713. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  4714. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  4715. waveFormat.nChannels = channels + firstChannel;
  4716. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  4717. // Determine the device buffer size. By default, we'll use the value
  4718. // defined above (32K), but we will grow it to make allowances for
  4719. // very large software buffer sizes.
  4720. DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
  4721. DWORD dsPointerLeadTime = 0;
  4722. void *ohandle = 0, *bhandle = 0;
  4723. HRESULT result;
  4724. if ( mode == OUTPUT ) {
  4725. LPDIRECTSOUND output;
  4726. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4727. if ( FAILED( result ) ) {
  4728. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4729. errorText_ = errorStream_.str();
  4730. return FAILURE;
  4731. }
  4732. DSCAPS outCaps;
  4733. outCaps.dwSize = sizeof( outCaps );
  4734. result = output->GetCaps( &outCaps );
  4735. if ( FAILED( result ) ) {
  4736. output->Release();
  4737. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";
  4738. errorText_ = errorStream_.str();
  4739. return FAILURE;
  4740. }
  4741. // Check channel information.
  4742. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  4743. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";
  4744. errorText_ = errorStream_.str();
  4745. return FAILURE;
  4746. }
  4747. // Check format information. Use 16-bit format unless not
  4748. // supported or user requests 8-bit.
  4749. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  4750. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  4751. waveFormat.wBitsPerSample = 16;
  4752. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4753. }
  4754. else {
  4755. waveFormat.wBitsPerSample = 8;
  4756. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4757. }
  4758. stream_.userFormat = format;
  4759. // Update wave format structure and buffer information.
  4760. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  4761. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  4762. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  4763. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  4764. while ( dsPointerLeadTime * 2U > dsBufferSize )
  4765. dsBufferSize *= 2;
  4766. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  4767. // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  4768. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  4769. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  4770. if ( FAILED( result ) ) {
  4771. output->Release();
  4772. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";
  4773. errorText_ = errorStream_.str();
  4774. return FAILURE;
  4775. }
  4776. // Even though we will write to the secondary buffer, we need to
  4777. // access the primary buffer to set the correct output format
  4778. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  4779. // buffer description.
  4780. DSBUFFERDESC bufferDescription;
  4781. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4782. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4783. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  4784. // Obtain the primary buffer
  4785. LPDIRECTSOUNDBUFFER buffer;
  4786. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4787. if ( FAILED( result ) ) {
  4788. output->Release();
  4789. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";
  4790. errorText_ = errorStream_.str();
  4791. return FAILURE;
  4792. }
  4793. // Set the primary DS buffer sound format.
  4794. result = buffer->SetFormat( &waveFormat );
  4795. if ( FAILED( result ) ) {
  4796. output->Release();
  4797. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";
  4798. errorText_ = errorStream_.str();
  4799. return FAILURE;
  4800. }
  4801. // Setup the secondary DS buffer description.
  4802. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4803. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4804. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4805. DSBCAPS_GLOBALFOCUS |
  4806. DSBCAPS_GETCURRENTPOSITION2 |
  4807. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  4808. bufferDescription.dwBufferBytes = dsBufferSize;
  4809. bufferDescription.lpwfxFormat = &waveFormat;
  4810. // Try to create the secondary DS buffer. If that doesn't work,
  4811. // try to use software mixing. Otherwise, there's a problem.
  4812. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4813. if ( FAILED( result ) ) {
  4814. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4815. DSBCAPS_GLOBALFOCUS |
  4816. DSBCAPS_GETCURRENTPOSITION2 |
  4817. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  4818. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4819. if ( FAILED( result ) ) {
  4820. output->Release();
  4821. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";
  4822. errorText_ = errorStream_.str();
  4823. return FAILURE;
  4824. }
  4825. }
  4826. // Get the buffer size ... might be different from what we specified.
  4827. DSBCAPS dsbcaps;
  4828. dsbcaps.dwSize = sizeof( DSBCAPS );
  4829. result = buffer->GetCaps( &dsbcaps );
  4830. if ( FAILED( result ) ) {
  4831. output->Release();
  4832. buffer->Release();
  4833. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  4834. errorText_ = errorStream_.str();
  4835. return FAILURE;
  4836. }
  4837. dsBufferSize = dsbcaps.dwBufferBytes;
  4838. // Lock the DS buffer
  4839. LPVOID audioPtr;
  4840. DWORD dataLen;
  4841. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  4842. if ( FAILED( result ) ) {
  4843. output->Release();
  4844. buffer->Release();
  4845. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";
  4846. errorText_ = errorStream_.str();
  4847. return FAILURE;
  4848. }
  4849. // Zero the DS buffer
  4850. ZeroMemory( audioPtr, dataLen );
  4851. // Unlock the DS buffer
  4852. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  4853. if ( FAILED( result ) ) {
  4854. output->Release();
  4855. buffer->Release();
  4856. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";
  4857. errorText_ = errorStream_.str();
  4858. return FAILURE;
  4859. }
  4860. ohandle = (void *) output;
  4861. bhandle = (void *) buffer;
  4862. }
  4863. if ( mode == INPUT ) {
  4864. LPDIRECTSOUNDCAPTURE input;
  4865. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4866. if ( FAILED( result ) ) {
  4867. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4868. errorText_ = errorStream_.str();
  4869. return FAILURE;
  4870. }
  4871. DSCCAPS inCaps;
  4872. inCaps.dwSize = sizeof( inCaps );
  4873. result = input->GetCaps( &inCaps );
  4874. if ( FAILED( result ) ) {
  4875. input->Release();
  4876. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";
  4877. errorText_ = errorStream_.str();
  4878. return FAILURE;
  4879. }
  4880. // Check channel information.
  4881. if ( inCaps.dwChannels < channels + firstChannel ) {
  4882. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  4883. return FAILURE;
  4884. }
  4885. // Check format information. Use 16-bit format unless user
  4886. // requests 8-bit.
  4887. DWORD deviceFormats;
  4888. if ( channels + firstChannel == 2 ) {
  4889. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  4890. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  4891. waveFormat.wBitsPerSample = 8;
  4892. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4893. }
  4894. else { // assume 16-bit is supported
  4895. waveFormat.wBitsPerSample = 16;
  4896. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4897. }
  4898. }
  4899. else { // channel == 1
  4900. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  4901. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  4902. waveFormat.wBitsPerSample = 8;
  4903. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4904. }
  4905. else { // assume 16-bit is supported
  4906. waveFormat.wBitsPerSample = 16;
  4907. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4908. }
  4909. }
  4910. stream_.userFormat = format;
  4911. // Update wave format structure and buffer information.
  4912. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  4913. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  4914. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  4915. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  4916. while ( dsPointerLeadTime * 2U > dsBufferSize )
  4917. dsBufferSize *= 2;
  4918. // Setup the secondary DS buffer description.
  4919. DSCBUFFERDESC bufferDescription;
  4920. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  4921. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  4922. bufferDescription.dwFlags = 0;
  4923. bufferDescription.dwReserved = 0;
  4924. bufferDescription.dwBufferBytes = dsBufferSize;
  4925. bufferDescription.lpwfxFormat = &waveFormat;
  4926. // Create the capture buffer.
  4927. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  4928. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  4929. if ( FAILED( result ) ) {
  4930. input->Release();
  4931. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";
  4932. errorText_ = errorStream_.str();
  4933. return FAILURE;
  4934. }
  4935. // Get the buffer size ... might be different from what we specified.
  4936. DSCBCAPS dscbcaps;
  4937. dscbcaps.dwSize = sizeof( DSCBCAPS );
  4938. result = buffer->GetCaps( &dscbcaps );
  4939. if ( FAILED( result ) ) {
  4940. input->Release();
  4941. buffer->Release();
  4942. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  4943. errorText_ = errorStream_.str();
  4944. return FAILURE;
  4945. }
  4946. dsBufferSize = dscbcaps.dwBufferBytes;
  4947. // NOTE: We could have a problem here if this is a duplex stream
  4948. // and the play and capture hardware buffer sizes are different
  4949. // (I'm actually not sure if that is a problem or not).
  4950. // Currently, we are not verifying that.
  4951. // Lock the capture buffer
  4952. LPVOID audioPtr;
  4953. DWORD dataLen;
  4954. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  4955. if ( FAILED( result ) ) {
  4956. input->Release();
  4957. buffer->Release();
  4958. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";
  4959. errorText_ = errorStream_.str();
  4960. return FAILURE;
  4961. }
  4962. // Zero the buffer
  4963. ZeroMemory( audioPtr, dataLen );
  4964. // Unlock the buffer
  4965. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  4966. if ( FAILED( result ) ) {
  4967. input->Release();
  4968. buffer->Release();
  4969. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";
  4970. errorText_ = errorStream_.str();
  4971. return FAILURE;
  4972. }
  4973. ohandle = (void *) input;
  4974. bhandle = (void *) buffer;
  4975. }
  4976. // Set various stream parameters
  4977. DsHandle *handle = 0;
  4978. stream_.nDeviceChannels[mode] = channels + firstChannel;
  4979. stream_.nUserChannels[mode] = channels;
  4980. stream_.bufferSize = *bufferSize;
  4981. stream_.channelOffset[mode] = firstChannel;
  4982. stream_.deviceInterleaved[mode] = true;
  4983. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  4984. else stream_.userInterleaved = true;
  4985. // Set flag for buffer conversion
  4986. stream_.doConvertBuffer[mode] = false;
  4987. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  4988. stream_.doConvertBuffer[mode] = true;
  4989. if (stream_.userFormat != stream_.deviceFormat[mode])
  4990. stream_.doConvertBuffer[mode] = true;
  4991. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4992. stream_.nUserChannels[mode] > 1 )
  4993. stream_.doConvertBuffer[mode] = true;
  4994. // Allocate necessary internal buffers
  4995. long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  4996. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  4997. if ( stream_.userBuffer[mode] == NULL ) {
  4998. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  4999. goto error;
  5000. }
  5001. if ( stream_.doConvertBuffer[mode] ) {
  5002. bool makeBuffer = true;
  5003. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  5004. if ( mode == INPUT ) {
  5005. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  5006. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  5007. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  5008. }
  5009. }
  5010. if ( makeBuffer ) {
  5011. bufferBytes *= *bufferSize;
  5012. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  5013. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  5014. if ( stream_.deviceBuffer == NULL ) {
  5015. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  5016. goto error;
  5017. }
  5018. }
  5019. }
  5020. // Allocate our DsHandle structures for the stream.
  5021. if ( stream_.apiHandle == 0 ) {
  5022. try {
  5023. handle = new DsHandle;
  5024. }
  5025. catch ( std::bad_alloc& ) {
  5026. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  5027. goto error;
  5028. }
  5029. // Create a manual-reset event.
  5030. handle->condition = CreateEvent( NULL, // no security
  5031. TRUE, // manual-reset
  5032. FALSE, // non-signaled initially
  5033. NULL ); // unnamed
  5034. stream_.apiHandle = (void *) handle;
  5035. }
  5036. else
  5037. handle = (DsHandle *) stream_.apiHandle;
  5038. handle->id[mode] = ohandle;
  5039. handle->buffer[mode] = bhandle;
  5040. handle->dsBufferSize[mode] = dsBufferSize;
  5041. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  5042. stream_.device[mode] = device;
  5043. stream_.state = STREAM_STOPPED;
  5044. if ( stream_.mode == OUTPUT && mode == INPUT )
  5045. // We had already set up an output stream.
  5046. stream_.mode = DUPLEX;
  5047. else
  5048. stream_.mode = mode;
  5049. stream_.nBuffers = nBuffers;
  5050. stream_.sampleRate = sampleRate;
  5051. // Setup the buffer conversion information structure.
  5052. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  5053. // Setup the callback thread.
  5054. if ( stream_.callbackInfo.isRunning == false ) {
  5055. unsigned threadId;
  5056. stream_.callbackInfo.isRunning = true;
  5057. stream_.callbackInfo.object = (void *) this;
  5058. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  5059. &stream_.callbackInfo, 0, &threadId );
  5060. if ( stream_.callbackInfo.thread == 0 ) {
  5061. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  5062. goto error;
  5063. }
  5064. // Boost DS thread priority
  5065. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  5066. }
  5067. return SUCCESS;
  5068. error:
  5069. if ( handle ) {
  5070. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5071. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5072. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5073. if ( buffer ) buffer->Release();
  5074. object->Release();
  5075. }
  5076. if ( handle->buffer[1] ) {
  5077. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5078. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5079. if ( buffer ) buffer->Release();
  5080. object->Release();
  5081. }
  5082. CloseHandle( handle->condition );
  5083. delete handle;
  5084. stream_.apiHandle = 0;
  5085. }
  5086. for ( int i=0; i<2; i++ ) {
  5087. if ( stream_.userBuffer[i] ) {
  5088. free( stream_.userBuffer[i] );
  5089. stream_.userBuffer[i] = 0;
  5090. }
  5091. }
  5092. if ( stream_.deviceBuffer ) {
  5093. free( stream_.deviceBuffer );
  5094. stream_.deviceBuffer = 0;
  5095. }
  5096. stream_.state = STREAM_CLOSED;
  5097. return FAILURE;
  5098. }
  5099. void RtApiDs :: closeStream()
  5100. {
  5101. if ( stream_.state == STREAM_CLOSED ) {
  5102. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  5103. error( RtAudioError::WARNING );
  5104. return;
  5105. }
  5106. // Stop the callback thread.
  5107. stream_.callbackInfo.isRunning = false;
  5108. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  5109. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  5110. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5111. if ( handle ) {
  5112. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5113. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5114. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5115. if ( buffer ) {
  5116. buffer->Stop();
  5117. buffer->Release();
  5118. }
  5119. object->Release();
  5120. }
  5121. if ( handle->buffer[1] ) {
  5122. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5123. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5124. if ( buffer ) {
  5125. buffer->Stop();
  5126. buffer->Release();
  5127. }
  5128. object->Release();
  5129. }
  5130. CloseHandle( handle->condition );
  5131. delete handle;
  5132. stream_.apiHandle = 0;
  5133. }
  5134. for ( int i=0; i<2; i++ ) {
  5135. if ( stream_.userBuffer[i] ) {
  5136. free( stream_.userBuffer[i] );
  5137. stream_.userBuffer[i] = 0;
  5138. }
  5139. }
  5140. if ( stream_.deviceBuffer ) {
  5141. free( stream_.deviceBuffer );
  5142. stream_.deviceBuffer = 0;
  5143. }
  5144. stream_.mode = UNINITIALIZED;
  5145. stream_.state = STREAM_CLOSED;
  5146. }
  5147. void RtApiDs :: startStream()
  5148. {
  5149. verifyStream();
  5150. if ( stream_.state == STREAM_RUNNING ) {
  5151. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  5152. error( RtAudioError::WARNING );
  5153. return;
  5154. }
  5155. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5156. // Increase scheduler frequency on lesser windows (a side-effect of
  5157. // increasing timer accuracy). On greater windows (Win2K or later),
  5158. // this is already in effect.
  5159. timeBeginPeriod( 1 );
  5160. buffersRolling = false;
  5161. duplexPrerollBytes = 0;
  5162. if ( stream_.mode == DUPLEX ) {
  5163. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  5164. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  5165. }
  5166. HRESULT result = 0;
  5167. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5168. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5169. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  5170. if ( FAILED( result ) ) {
  5171. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  5172. errorText_ = errorStream_.str();
  5173. goto unlock;
  5174. }
  5175. }
  5176. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5177. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5178. result = buffer->Start( DSCBSTART_LOOPING );
  5179. if ( FAILED( result ) ) {
  5180. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  5181. errorText_ = errorStream_.str();
  5182. goto unlock;
  5183. }
  5184. }
  5185. handle->drainCounter = 0;
  5186. handle->internalDrain = false;
  5187. ResetEvent( handle->condition );
  5188. stream_.state = STREAM_RUNNING;
  5189. unlock:
  5190. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5191. }
  5192. void RtApiDs :: stopStream()
  5193. {
  5194. verifyStream();
  5195. if ( stream_.state == STREAM_STOPPED ) {
  5196. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  5197. error( RtAudioError::WARNING );
  5198. return;
  5199. }
  5200. HRESULT result = 0;
  5201. LPVOID audioPtr;
  5202. DWORD dataLen;
  5203. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5204. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5205. if ( handle->drainCounter == 0 ) {
  5206. handle->drainCounter = 2;
  5207. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  5208. }
  5209. stream_.state = STREAM_STOPPED;
  5210. // Stop the buffer and clear memory
  5211. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5212. result = buffer->Stop();
  5213. if ( FAILED( result ) ) {
  5214. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  5215. errorText_ = errorStream_.str();
  5216. goto unlock;
  5217. }
  5218. // Lock the buffer and clear it so that if we start to play again,
  5219. // we won't have old data playing.
  5220. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  5221. if ( FAILED( result ) ) {
  5222. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
  5223. errorText_ = errorStream_.str();
  5224. goto unlock;
  5225. }
  5226. // Zero the DS buffer
  5227. ZeroMemory( audioPtr, dataLen );
  5228. // Unlock the DS buffer
  5229. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5230. if ( FAILED( result ) ) {
  5231. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  5232. errorText_ = errorStream_.str();
  5233. goto unlock;
  5234. }
  5235. // If we start playing again, we must begin at beginning of buffer.
  5236. handle->bufferPointer[0] = 0;
  5237. }
  5238. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5239. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5240. audioPtr = NULL;
  5241. dataLen = 0;
  5242. stream_.state = STREAM_STOPPED;
  5243. result = buffer->Stop();
  5244. if ( FAILED( result ) ) {
  5245. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  5246. errorText_ = errorStream_.str();
  5247. goto unlock;
  5248. }
  5249. // Lock the buffer and clear it so that if we start to play again,
  5250. // we won't have old data playing.
  5251. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  5252. if ( FAILED( result ) ) {
  5253. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
  5254. errorText_ = errorStream_.str();
  5255. goto unlock;
  5256. }
  5257. // Zero the DS buffer
  5258. ZeroMemory( audioPtr, dataLen );
  5259. // Unlock the DS buffer
  5260. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5261. if ( FAILED( result ) ) {
  5262. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  5263. errorText_ = errorStream_.str();
  5264. goto unlock;
  5265. }
  5266. // If we start recording again, we must begin at beginning of buffer.
  5267. handle->bufferPointer[1] = 0;
  5268. }
  5269. unlock:
  5270. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  5271. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5272. }
  5273. void RtApiDs :: abortStream()
  5274. {
  5275. verifyStream();
  5276. if ( stream_.state == STREAM_STOPPED ) {
  5277. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  5278. error( RtAudioError::WARNING );
  5279. return;
  5280. }
  5281. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5282. handle->drainCounter = 2;
  5283. stopStream();
  5284. }
  5285. void RtApiDs :: callbackEvent()
  5286. {
  5287. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
  5288. Sleep( 50 ); // sleep 50 milliseconds
  5289. return;
  5290. }
  5291. if ( stream_.state == STREAM_CLOSED ) {
  5292. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5293. error( RtAudioError::WARNING );
  5294. return;
  5295. }
  5296. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  5297. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5298. // Check if we were draining the stream and signal is finished.
  5299. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  5300. stream_.state = STREAM_STOPPING;
  5301. if ( handle->internalDrain == false )
  5302. SetEvent( handle->condition );
  5303. else
  5304. stopStream();
  5305. return;
  5306. }
  5307. // Invoke user callback to get fresh output data UNLESS we are
  5308. // draining stream.
  5309. if ( handle->drainCounter == 0 ) {
  5310. RtAudioCallback callback = (RtAudioCallback) info->callback;
  5311. double streamTime = getStreamTime();
  5312. RtAudioStreamStatus status = 0;
  5313. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  5314. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5315. handle->xrun[0] = false;
  5316. }
  5317. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  5318. status |= RTAUDIO_INPUT_OVERFLOW;
  5319. handle->xrun[1] = false;
  5320. }
  5321. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5322. stream_.bufferSize, streamTime, status, info->userData );
  5323. if ( cbReturnValue == 2 ) {
  5324. stream_.state = STREAM_STOPPING;
  5325. handle->drainCounter = 2;
  5326. abortStream();
  5327. return;
  5328. }
  5329. else if ( cbReturnValue == 1 ) {
  5330. handle->drainCounter = 1;
  5331. handle->internalDrain = true;
  5332. }
  5333. }
  5334. HRESULT result;
  5335. DWORD currentWritePointer, safeWritePointer;
  5336. DWORD currentReadPointer, safeReadPointer;
  5337. UINT nextWritePointer;
  5338. LPVOID buffer1 = NULL;
  5339. LPVOID buffer2 = NULL;
  5340. DWORD bufferSize1 = 0;
  5341. DWORD bufferSize2 = 0;
  5342. char *buffer;
  5343. long bufferBytes;
  5344. if ( buffersRolling == false ) {
  5345. if ( stream_.mode == DUPLEX ) {
  5346. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5347. // It takes a while for the devices to get rolling. As a result,
  5348. // there's no guarantee that the capture and write device pointers
  5349. // will move in lockstep. Wait here for both devices to start
  5350. // rolling, and then set our buffer pointers accordingly.
  5351. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  5352. // bytes later than the write buffer.
  5353. // Stub: a serious risk of having a pre-emptive scheduling round
  5354. // take place between the two GetCurrentPosition calls... but I'm
  5355. // really not sure how to solve the problem. Temporarily boost to
  5356. // Realtime priority, maybe; but I'm not sure what priority the
  5357. // DirectSound service threads run at. We *should* be roughly
  5358. // within a ms or so of correct.
  5359. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5360. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5361. DWORD startSafeWritePointer, startSafeReadPointer;
  5362. result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
  5363. if ( FAILED( result ) ) {
  5364. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5365. errorText_ = errorStream_.str();
  5366. error( RtAudioError::SYSTEM_ERROR );
  5367. return;
  5368. }
  5369. result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
  5370. if ( FAILED( result ) ) {
  5371. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5372. errorText_ = errorStream_.str();
  5373. error( RtAudioError::SYSTEM_ERROR );
  5374. return;
  5375. }
  5376. while ( true ) {
  5377. result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
  5378. if ( FAILED( result ) ) {
  5379. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5380. errorText_ = errorStream_.str();
  5381. error( RtAudioError::SYSTEM_ERROR );
  5382. return;
  5383. }
  5384. result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
  5385. if ( FAILED( result ) ) {
  5386. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5387. errorText_ = errorStream_.str();
  5388. error( RtAudioError::SYSTEM_ERROR );
  5389. return;
  5390. }
  5391. if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
  5392. Sleep( 1 );
  5393. }
  5394. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5395. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5396. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5397. handle->bufferPointer[1] = safeReadPointer;
  5398. }
  5399. else if ( stream_.mode == OUTPUT ) {
  5400. // Set the proper nextWritePosition after initial startup.
  5401. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5402. result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5403. if ( FAILED( result ) ) {
  5404. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5405. errorText_ = errorStream_.str();
  5406. error( RtAudioError::SYSTEM_ERROR );
  5407. return;
  5408. }
  5409. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5410. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5411. }
  5412. buffersRolling = true;
  5413. }
  5414. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5415. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5416. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  5417. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5418. bufferBytes *= formatBytes( stream_.userFormat );
  5419. memset( stream_.userBuffer[0], 0, bufferBytes );
  5420. }
  5421. // Setup parameters and do buffer conversion if necessary.
  5422. if ( stream_.doConvertBuffer[0] ) {
  5423. buffer = stream_.deviceBuffer;
  5424. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5425. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  5426. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  5427. }
  5428. else {
  5429. buffer = stream_.userBuffer[0];
  5430. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5431. bufferBytes *= formatBytes( stream_.userFormat );
  5432. }
  5433. // No byte swapping necessary in DirectSound implementation.
  5434. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  5435. // unsigned. So, we need to convert our signed 8-bit data here to
  5436. // unsigned.
  5437. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  5438. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  5439. DWORD dsBufferSize = handle->dsBufferSize[0];
  5440. nextWritePointer = handle->bufferPointer[0];
  5441. DWORD endWrite, leadPointer;
  5442. while ( true ) {
  5443. // Find out where the read and "safe write" pointers are.
  5444. result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5445. if ( FAILED( result ) ) {
  5446. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5447. errorText_ = errorStream_.str();
  5448. error( RtAudioError::SYSTEM_ERROR );
  5449. return;
  5450. }
  5451. // We will copy our output buffer into the region between
  5452. // safeWritePointer and leadPointer. If leadPointer is not
  5453. // beyond the next endWrite position, wait until it is.
  5454. leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
  5455. //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
  5456. if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
  5457. if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
  5458. endWrite = nextWritePointer + bufferBytes;
  5459. // Check whether the entire write region is behind the play pointer.
  5460. if ( leadPointer >= endWrite ) break;
  5461. // If we are here, then we must wait until the leadPointer advances
  5462. // beyond the end of our next write region. We use the
  5463. // Sleep() function to suspend operation until that happens.
  5464. double millis = ( endWrite - leadPointer ) * 1000.0;
  5465. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  5466. if ( millis < 1.0 ) millis = 1.0;
  5467. Sleep( (DWORD) millis );
  5468. }
  5469. if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
  5470. || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
  5471. // We've strayed into the forbidden zone ... resync the read pointer.
  5472. handle->xrun[0] = true;
  5473. nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
  5474. if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
  5475. handle->bufferPointer[0] = nextWritePointer;
  5476. endWrite = nextWritePointer + bufferBytes;
  5477. }
  5478. // Lock free space in the buffer
  5479. result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
  5480. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5481. if ( FAILED( result ) ) {
  5482. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  5483. errorText_ = errorStream_.str();
  5484. error( RtAudioError::SYSTEM_ERROR );
  5485. return;
  5486. }
  5487. // Copy our buffer into the DS buffer
  5488. CopyMemory( buffer1, buffer, bufferSize1 );
  5489. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  5490. // Update our buffer offset and unlock sound buffer
  5491. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5492. if ( FAILED( result ) ) {
  5493. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  5494. errorText_ = errorStream_.str();
  5495. error( RtAudioError::SYSTEM_ERROR );
  5496. return;
  5497. }
  5498. nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5499. handle->bufferPointer[0] = nextWritePointer;
  5500. if ( handle->drainCounter ) {
  5501. handle->drainCounter++;
  5502. goto unlock;
  5503. }
  5504. }
  5505. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5506. // Setup parameters.
  5507. if ( stream_.doConvertBuffer[1] ) {
  5508. buffer = stream_.deviceBuffer;
  5509. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  5510. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  5511. }
  5512. else {
  5513. buffer = stream_.userBuffer[1];
  5514. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  5515. bufferBytes *= formatBytes( stream_.userFormat );
  5516. }
  5517. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5518. long nextReadPointer = handle->bufferPointer[1];
  5519. DWORD dsBufferSize = handle->dsBufferSize[1];
  5520. // Find out where the write and "safe read" pointers are.
  5521. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5522. if ( FAILED( result ) ) {
  5523. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5524. errorText_ = errorStream_.str();
  5525. error( RtAudioError::SYSTEM_ERROR );
  5526. return;
  5527. }
  5528. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5529. DWORD endRead = nextReadPointer + bufferBytes;
  5530. // Handling depends on whether we are INPUT or DUPLEX.
  5531. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  5532. // then a wait here will drag the write pointers into the forbidden zone.
  5533. //
  5534. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  5535. // it's in a safe position. This causes dropouts, but it seems to be the only
  5536. // practical way to sync up the read and write pointers reliably, given the
  5537. // the very complex relationship between phase and increment of the read and write
  5538. // pointers.
  5539. //
  5540. // In order to minimize audible dropouts in DUPLEX mode, we will
  5541. // provide a pre-roll period of 0.5 seconds in which we return
  5542. // zeros from the read buffer while the pointers sync up.
  5543. if ( stream_.mode == DUPLEX ) {
  5544. if ( safeReadPointer < endRead ) {
  5545. if ( duplexPrerollBytes <= 0 ) {
  5546. // Pre-roll time over. Be more agressive.
  5547. int adjustment = endRead-safeReadPointer;
  5548. handle->xrun[1] = true;
  5549. // Two cases:
  5550. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  5551. // and perform fine adjustments later.
  5552. // - small adjustments: back off by twice as much.
  5553. if ( adjustment >= 2*bufferBytes )
  5554. nextReadPointer = safeReadPointer-2*bufferBytes;
  5555. else
  5556. nextReadPointer = safeReadPointer-bufferBytes-adjustment;
  5557. if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5558. }
  5559. else {
  5560. // In pre=roll time. Just do it.
  5561. nextReadPointer = safeReadPointer - bufferBytes;
  5562. while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5563. }
  5564. endRead = nextReadPointer + bufferBytes;
  5565. }
  5566. }
  5567. else { // mode == INPUT
  5568. while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
  5569. // See comments for playback.
  5570. double millis = (endRead - safeReadPointer) * 1000.0;
  5571. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  5572. if ( millis < 1.0 ) millis = 1.0;
  5573. Sleep( (DWORD) millis );
  5574. // Wake up and find out where we are now.
  5575. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5576. if ( FAILED( result ) ) {
  5577. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5578. errorText_ = errorStream_.str();
  5579. error( RtAudioError::SYSTEM_ERROR );
  5580. return;
  5581. }
  5582. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5583. }
  5584. }
  5585. // Lock free space in the buffer
  5586. result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
  5587. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5588. if ( FAILED( result ) ) {
  5589. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  5590. errorText_ = errorStream_.str();
  5591. error( RtAudioError::SYSTEM_ERROR );
  5592. return;
  5593. }
  5594. if ( duplexPrerollBytes <= 0 ) {
  5595. // Copy our buffer into the DS buffer
  5596. CopyMemory( buffer, buffer1, bufferSize1 );
  5597. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  5598. }
  5599. else {
  5600. memset( buffer, 0, bufferSize1 );
  5601. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  5602. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  5603. }
  5604. // Update our buffer offset and unlock sound buffer
  5605. nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5606. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5607. if ( FAILED( result ) ) {
  5608. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  5609. errorText_ = errorStream_.str();
  5610. error( RtAudioError::SYSTEM_ERROR );
  5611. return;
  5612. }
  5613. handle->bufferPointer[1] = nextReadPointer;
  5614. // No byte swapping necessary in DirectSound implementation.
  5615. // If necessary, convert 8-bit data from unsigned to signed.
  5616. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  5617. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  5618. // Do buffer conversion if necessary.
  5619. if ( stream_.doConvertBuffer[1] )
  5620. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5621. }
  5622. unlock:
  5623. RtApi::tickStreamTime();
  5624. }
  5625. // Definitions for utility functions and callbacks
  5626. // specific to the DirectSound implementation.
  5627. static unsigned __stdcall callbackHandler( void *ptr )
  5628. {
  5629. CallbackInfo *info = (CallbackInfo *) ptr;
  5630. RtApiDs *object = (RtApiDs *) info->object;
  5631. bool* isRunning = &info->isRunning;
  5632. while ( *isRunning == true ) {
  5633. object->callbackEvent();
  5634. }
  5635. _endthreadex( 0 );
  5636. return 0;
  5637. }
  5638. #include "tchar.h"
  5639. static std::string convertTChar( LPCTSTR name )
  5640. {
  5641. #if defined( UNICODE ) || defined( _UNICODE )
  5642. int length = WideCharToMultiByte(CP_UTF8, 0, name, -1, NULL, 0, NULL, NULL);
  5643. std::string s( length-1, '\0' );
  5644. WideCharToMultiByte(CP_UTF8, 0, name, -1, &s[0], length, NULL, NULL);
  5645. #else
  5646. std::string s( name );
  5647. #endif
  5648. return s;
  5649. }
  5650. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  5651. LPCTSTR description,
  5652. LPCTSTR /*module*/,
  5653. LPVOID lpContext )
  5654. {
  5655. struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
  5656. std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
  5657. HRESULT hr;
  5658. bool validDevice = false;
  5659. if ( probeInfo.isInput == true ) {
  5660. DSCCAPS caps;
  5661. LPDIRECTSOUNDCAPTURE object;
  5662. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  5663. if ( hr != DS_OK ) return TRUE;
  5664. caps.dwSize = sizeof(caps);
  5665. hr = object->GetCaps( &caps );
  5666. if ( hr == DS_OK ) {
  5667. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  5668. validDevice = true;
  5669. }
  5670. object->Release();
  5671. }
  5672. else {
  5673. DSCAPS caps;
  5674. LPDIRECTSOUND object;
  5675. hr = DirectSoundCreate( lpguid, &object, NULL );
  5676. if ( hr != DS_OK ) return TRUE;
  5677. caps.dwSize = sizeof(caps);
  5678. hr = object->GetCaps( &caps );
  5679. if ( hr == DS_OK ) {
  5680. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  5681. validDevice = true;
  5682. }
  5683. object->Release();
  5684. }
  5685. // If good device, then save its name and guid.
  5686. std::string name = convertTChar( description );
  5687. //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
  5688. if ( lpguid == NULL )
  5689. name = "Default Device";
  5690. if ( validDevice ) {
  5691. for ( unsigned int i=0; i<dsDevices.size(); i++ ) {
  5692. if ( dsDevices[i].name == name ) {
  5693. dsDevices[i].found = true;
  5694. if ( probeInfo.isInput ) {
  5695. dsDevices[i].id[1] = lpguid;
  5696. dsDevices[i].validId[1] = true;
  5697. }
  5698. else {
  5699. dsDevices[i].id[0] = lpguid;
  5700. dsDevices[i].validId[0] = true;
  5701. }
  5702. return TRUE;
  5703. }
  5704. }
  5705. DsDevice device;
  5706. device.name = name;
  5707. device.found = true;
  5708. if ( probeInfo.isInput ) {
  5709. device.id[1] = lpguid;
  5710. device.validId[1] = true;
  5711. }
  5712. else {
  5713. device.id[0] = lpguid;
  5714. device.validId[0] = true;
  5715. }
  5716. dsDevices.push_back( device );
  5717. }
  5718. return TRUE;
  5719. }
  5720. static const char* getErrorString( int code )
  5721. {
  5722. switch ( code ) {
  5723. case DSERR_ALLOCATED:
  5724. return "Already allocated";
  5725. case DSERR_CONTROLUNAVAIL:
  5726. return "Control unavailable";
  5727. case DSERR_INVALIDPARAM:
  5728. return "Invalid parameter";
  5729. case DSERR_INVALIDCALL:
  5730. return "Invalid call";
  5731. case DSERR_GENERIC:
  5732. return "Generic error";
  5733. case DSERR_PRIOLEVELNEEDED:
  5734. return "Priority level needed";
  5735. case DSERR_OUTOFMEMORY:
  5736. return "Out of memory";
  5737. case DSERR_BADFORMAT:
  5738. return "The sample rate or the channel format is not supported";
  5739. case DSERR_UNSUPPORTED:
  5740. return "Not supported";
  5741. case DSERR_NODRIVER:
  5742. return "No driver";
  5743. case DSERR_ALREADYINITIALIZED:
  5744. return "Already initialized";
  5745. case DSERR_NOAGGREGATION:
  5746. return "No aggregation";
  5747. case DSERR_BUFFERLOST:
  5748. return "Buffer lost";
  5749. case DSERR_OTHERAPPHASPRIO:
  5750. return "Another application already has priority";
  5751. case DSERR_UNINITIALIZED:
  5752. return "Uninitialized";
  5753. default:
  5754. return "DirectSound unknown error";
  5755. }
  5756. }
  5757. //******************** End of __WINDOWS_DS__ *********************//
  5758. #endif
  5759. #if defined(__LINUX_ALSA__)
  5760. #include <alsa/asoundlib.h>
  5761. #include <unistd.h>
  5762. // A structure to hold various information related to the ALSA API
  5763. // implementation.
  5764. struct AlsaHandle {
  5765. snd_pcm_t *handles[2];
  5766. bool synchronized;
  5767. bool xrun[2];
  5768. pthread_cond_t runnable_cv;
  5769. bool runnable;
  5770. AlsaHandle()
  5771. :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
  5772. };
  5773. static void *alsaCallbackHandler( void * ptr );
  5774. RtApiAlsa :: RtApiAlsa()
  5775. {
  5776. // Nothing to do here.
  5777. }
  5778. RtApiAlsa :: ~RtApiAlsa()
  5779. {
  5780. if ( stream_.state != STREAM_CLOSED ) closeStream();
  5781. }
  5782. unsigned int RtApiAlsa :: getDeviceCount( void )
  5783. {
  5784. unsigned nDevices = 0;
  5785. int result, subdevice, card;
  5786. char name[64];
  5787. snd_ctl_t *handle;
  5788. // Count cards and devices
  5789. card = -1;
  5790. snd_card_next( &card );
  5791. while ( card >= 0 ) {
  5792. sprintf( name, "hw:%d", card );
  5793. result = snd_ctl_open( &handle, name, 0 );
  5794. if ( result < 0 ) {
  5795. errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  5796. errorText_ = errorStream_.str();
  5797. error( RtAudioError::WARNING );
  5798. goto nextcard;
  5799. }
  5800. subdevice = -1;
  5801. while( 1 ) {
  5802. result = snd_ctl_pcm_next_device( handle, &subdevice );
  5803. if ( result < 0 ) {
  5804. errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  5805. errorText_ = errorStream_.str();
  5806. error( RtAudioError::WARNING );
  5807. break;
  5808. }
  5809. if ( subdevice < 0 )
  5810. break;
  5811. nDevices++;
  5812. }
  5813. nextcard:
  5814. snd_ctl_close( handle );
  5815. snd_card_next( &card );
  5816. }
  5817. result = snd_ctl_open( &handle, "default", 0 );
  5818. if (result == 0) {
  5819. nDevices++;
  5820. snd_ctl_close( handle );
  5821. }
  5822. return nDevices;
  5823. }
  5824. RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
  5825. {
  5826. RtAudio::DeviceInfo info;
  5827. info.probed = false;
  5828. unsigned nDevices = 0;
  5829. int result, subdevice, card;
  5830. char name[64];
  5831. snd_ctl_t *chandle;
  5832. // Count cards and devices
  5833. card = -1;
  5834. snd_card_next( &card );
  5835. while ( card >= 0 ) {
  5836. sprintf( name, "hw:%d", card );
  5837. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  5838. if ( result < 0 ) {
  5839. errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  5840. errorText_ = errorStream_.str();
  5841. error( RtAudioError::WARNING );
  5842. goto nextcard;
  5843. }
  5844. subdevice = -1;
  5845. while( 1 ) {
  5846. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  5847. if ( result < 0 ) {
  5848. errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  5849. errorText_ = errorStream_.str();
  5850. error( RtAudioError::WARNING );
  5851. break;
  5852. }
  5853. if ( subdevice < 0 ) break;
  5854. if ( nDevices == device ) {
  5855. sprintf( name, "hw:%d,%d", card, subdevice );
  5856. goto foundDevice;
  5857. }
  5858. nDevices++;
  5859. }
  5860. nextcard:
  5861. snd_ctl_close( chandle );
  5862. snd_card_next( &card );
  5863. }
  5864. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  5865. if ( result == 0 ) {
  5866. if ( nDevices == device ) {
  5867. strcpy( name, "default" );
  5868. goto foundDevice;
  5869. }
  5870. nDevices++;
  5871. }
  5872. if ( nDevices == 0 ) {
  5873. errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
  5874. error( RtAudioError::INVALID_USE );
  5875. return info;
  5876. }
  5877. if ( device >= nDevices ) {
  5878. errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
  5879. error( RtAudioError::INVALID_USE );
  5880. return info;
  5881. }
  5882. foundDevice:
  5883. // If a stream is already open, we cannot probe the stream devices.
  5884. // Thus, use the saved results.
  5885. if ( stream_.state != STREAM_CLOSED &&
  5886. ( stream_.device[0] == device || stream_.device[1] == device ) ) {
  5887. snd_ctl_close( chandle );
  5888. if ( device >= devices_.size() ) {
  5889. errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
  5890. error( RtAudioError::WARNING );
  5891. return info;
  5892. }
  5893. return devices_[ device ];
  5894. }
  5895. int openMode = SND_PCM_ASYNC;
  5896. snd_pcm_stream_t stream;
  5897. snd_pcm_info_t *pcminfo;
  5898. snd_pcm_info_alloca( &pcminfo );
  5899. snd_pcm_t *phandle;
  5900. snd_pcm_hw_params_t *params;
  5901. snd_pcm_hw_params_alloca( &params );
  5902. // First try for playback unless default device (which has subdev -1)
  5903. stream = SND_PCM_STREAM_PLAYBACK;
  5904. snd_pcm_info_set_stream( pcminfo, stream );
  5905. if ( subdevice != -1 ) {
  5906. snd_pcm_info_set_device( pcminfo, subdevice );
  5907. snd_pcm_info_set_subdevice( pcminfo, 0 );
  5908. result = snd_ctl_pcm_info( chandle, pcminfo );
  5909. if ( result < 0 ) {
  5910. // Device probably doesn't support playback.
  5911. goto captureProbe;
  5912. }
  5913. }
  5914. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
  5915. if ( result < 0 ) {
  5916. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  5917. errorText_ = errorStream_.str();
  5918. error( RtAudioError::WARNING );
  5919. goto captureProbe;
  5920. }
  5921. // The device is open ... fill the parameter structure.
  5922. result = snd_pcm_hw_params_any( phandle, params );
  5923. if ( result < 0 ) {
  5924. snd_pcm_close( phandle );
  5925. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  5926. errorText_ = errorStream_.str();
  5927. error( RtAudioError::WARNING );
  5928. goto captureProbe;
  5929. }
  5930. // Get output channel information.
  5931. unsigned int value;
  5932. result = snd_pcm_hw_params_get_channels_max( params, &value );
  5933. if ( result < 0 ) {
  5934. snd_pcm_close( phandle );
  5935. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
  5936. errorText_ = errorStream_.str();
  5937. error( RtAudioError::WARNING );
  5938. goto captureProbe;
  5939. }
  5940. info.outputChannels = value;
  5941. snd_pcm_close( phandle );
  5942. captureProbe:
  5943. stream = SND_PCM_STREAM_CAPTURE;
  5944. snd_pcm_info_set_stream( pcminfo, stream );
  5945. // Now try for capture unless default device (with subdev = -1)
  5946. if ( subdevice != -1 ) {
  5947. result = snd_ctl_pcm_info( chandle, pcminfo );
  5948. snd_ctl_close( chandle );
  5949. if ( result < 0 ) {
  5950. // Device probably doesn't support capture.
  5951. if ( info.outputChannels == 0 ) return info;
  5952. goto probeParameters;
  5953. }
  5954. }
  5955. else
  5956. snd_ctl_close( chandle );
  5957. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  5958. if ( result < 0 ) {
  5959. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  5960. errorText_ = errorStream_.str();
  5961. error( RtAudioError::WARNING );
  5962. if ( info.outputChannels == 0 ) return info;
  5963. goto probeParameters;
  5964. }
  5965. // The device is open ... fill the parameter structure.
  5966. result = snd_pcm_hw_params_any( phandle, params );
  5967. if ( result < 0 ) {
  5968. snd_pcm_close( phandle );
  5969. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  5970. errorText_ = errorStream_.str();
  5971. error( RtAudioError::WARNING );
  5972. if ( info.outputChannels == 0 ) return info;
  5973. goto probeParameters;
  5974. }
  5975. result = snd_pcm_hw_params_get_channels_max( params, &value );
  5976. if ( result < 0 ) {
  5977. snd_pcm_close( phandle );
  5978. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
  5979. errorText_ = errorStream_.str();
  5980. error( RtAudioError::WARNING );
  5981. if ( info.outputChannels == 0 ) return info;
  5982. goto probeParameters;
  5983. }
  5984. info.inputChannels = value;
  5985. snd_pcm_close( phandle );
  5986. // If device opens for both playback and capture, we determine the channels.
  5987. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  5988. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  5989. // ALSA doesn't provide default devices so we'll use the first available one.
  5990. if ( device == 0 && info.outputChannels > 0 )
  5991. info.isDefaultOutput = true;
  5992. if ( device == 0 && info.inputChannels > 0 )
  5993. info.isDefaultInput = true;
  5994. probeParameters:
  5995. // At this point, we just need to figure out the supported data
  5996. // formats and sample rates. We'll proceed by opening the device in
  5997. // the direction with the maximum number of channels, or playback if
  5998. // they are equal. This might limit our sample rate options, but so
  5999. // be it.
  6000. if ( info.outputChannels >= info.inputChannels )
  6001. stream = SND_PCM_STREAM_PLAYBACK;
  6002. else
  6003. stream = SND_PCM_STREAM_CAPTURE;
  6004. snd_pcm_info_set_stream( pcminfo, stream );
  6005. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  6006. if ( result < 0 ) {
  6007. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6008. errorText_ = errorStream_.str();
  6009. error( RtAudioError::WARNING );
  6010. return info;
  6011. }
  6012. // The device is open ... fill the parameter structure.
  6013. result = snd_pcm_hw_params_any( phandle, params );
  6014. if ( result < 0 ) {
  6015. snd_pcm_close( phandle );
  6016. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6017. errorText_ = errorStream_.str();
  6018. error( RtAudioError::WARNING );
  6019. return info;
  6020. }
  6021. // Test our discrete set of sample rate values.
  6022. info.sampleRates.clear();
  6023. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  6024. if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 )
  6025. info.sampleRates.push_back( SAMPLE_RATES[i] );
  6026. }
  6027. if ( info.sampleRates.size() == 0 ) {
  6028. snd_pcm_close( phandle );
  6029. errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
  6030. errorText_ = errorStream_.str();
  6031. error( RtAudioError::WARNING );
  6032. return info;
  6033. }
  6034. // Probe the supported data formats ... we don't care about endian-ness just yet
  6035. snd_pcm_format_t format;
  6036. info.nativeFormats = 0;
  6037. format = SND_PCM_FORMAT_S8;
  6038. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6039. info.nativeFormats |= RTAUDIO_SINT8;
  6040. format = SND_PCM_FORMAT_S16;
  6041. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6042. info.nativeFormats |= RTAUDIO_SINT16;
  6043. format = SND_PCM_FORMAT_S24;
  6044. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6045. info.nativeFormats |= RTAUDIO_SINT24;
  6046. format = SND_PCM_FORMAT_S32;
  6047. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6048. info.nativeFormats |= RTAUDIO_SINT32;
  6049. format = SND_PCM_FORMAT_FLOAT;
  6050. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6051. info.nativeFormats |= RTAUDIO_FLOAT32;
  6052. format = SND_PCM_FORMAT_FLOAT64;
  6053. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6054. info.nativeFormats |= RTAUDIO_FLOAT64;
  6055. // Check that we have at least one supported format
  6056. if ( info.nativeFormats == 0 ) {
  6057. snd_pcm_close( phandle );
  6058. errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
  6059. errorText_ = errorStream_.str();
  6060. error( RtAudioError::WARNING );
  6061. return info;
  6062. }
  6063. // Get the device name
  6064. char *cardname;
  6065. result = snd_card_get_name( card, &cardname );
  6066. if ( result >= 0 ) {
  6067. sprintf( name, "hw:%s,%d", cardname, subdevice );
  6068. free( cardname );
  6069. }
  6070. info.name = name;
  6071. // That's all ... close the device and return
  6072. snd_pcm_close( phandle );
  6073. info.probed = true;
  6074. return info;
  6075. }
  6076. void RtApiAlsa :: saveDeviceInfo( void )
  6077. {
  6078. devices_.clear();
  6079. unsigned int nDevices = getDeviceCount();
  6080. devices_.resize( nDevices );
  6081. for ( unsigned int i=0; i<nDevices; i++ )
  6082. devices_[i] = getDeviceInfo( i );
  6083. }
  6084. bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  6085. unsigned int firstChannel, unsigned int sampleRate,
  6086. RtAudioFormat format, unsigned int *bufferSize,
  6087. RtAudio::StreamOptions *options )
  6088. {
  6089. #if defined(__RTAUDIO_DEBUG__)
  6090. snd_output_t *out;
  6091. snd_output_stdio_attach(&out, stderr, 0);
  6092. #endif
  6093. // I'm not using the "plug" interface ... too much inconsistent behavior.
  6094. unsigned nDevices = 0;
  6095. int result, subdevice, card;
  6096. char name[64];
  6097. snd_ctl_t *chandle;
  6098. if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )
  6099. snprintf(name, sizeof(name), "%s", "default");
  6100. else {
  6101. // Count cards and devices
  6102. card = -1;
  6103. snd_card_next( &card );
  6104. while ( card >= 0 ) {
  6105. sprintf( name, "hw:%d", card );
  6106. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  6107. if ( result < 0 ) {
  6108. errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6109. errorText_ = errorStream_.str();
  6110. return FAILURE;
  6111. }
  6112. subdevice = -1;
  6113. while( 1 ) {
  6114. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  6115. if ( result < 0 ) break;
  6116. if ( subdevice < 0 ) break;
  6117. if ( nDevices == device ) {
  6118. sprintf( name, "hw:%d,%d", card, subdevice );
  6119. snd_ctl_close( chandle );
  6120. goto foundDevice;
  6121. }
  6122. nDevices++;
  6123. }
  6124. snd_ctl_close( chandle );
  6125. snd_card_next( &card );
  6126. }
  6127. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6128. if ( result == 0 ) {
  6129. if ( nDevices == device ) {
  6130. strcpy( name, "default" );
  6131. goto foundDevice;
  6132. }
  6133. nDevices++;
  6134. }
  6135. if ( nDevices == 0 ) {
  6136. // This should not happen because a check is made before this function is called.
  6137. errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
  6138. return FAILURE;
  6139. }
  6140. if ( device >= nDevices ) {
  6141. // This should not happen because a check is made before this function is called.
  6142. errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
  6143. return FAILURE;
  6144. }
  6145. }
  6146. foundDevice:
  6147. // The getDeviceInfo() function will not work for a device that is
  6148. // already open. Thus, we'll probe the system before opening a
  6149. // stream and save the results for use by getDeviceInfo().
  6150. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
  6151. this->saveDeviceInfo();
  6152. snd_pcm_stream_t stream;
  6153. if ( mode == OUTPUT )
  6154. stream = SND_PCM_STREAM_PLAYBACK;
  6155. else
  6156. stream = SND_PCM_STREAM_CAPTURE;
  6157. snd_pcm_t *phandle;
  6158. int openMode = SND_PCM_ASYNC;
  6159. result = snd_pcm_open( &phandle, name, stream, openMode );
  6160. if ( result < 0 ) {
  6161. if ( mode == OUTPUT )
  6162. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
  6163. else
  6164. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
  6165. errorText_ = errorStream_.str();
  6166. return FAILURE;
  6167. }
  6168. // Fill the parameter structure.
  6169. snd_pcm_hw_params_t *hw_params;
  6170. snd_pcm_hw_params_alloca( &hw_params );
  6171. result = snd_pcm_hw_params_any( phandle, hw_params );
  6172. if ( result < 0 ) {
  6173. snd_pcm_close( phandle );
  6174. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
  6175. errorText_ = errorStream_.str();
  6176. return FAILURE;
  6177. }
  6178. #if defined(__RTAUDIO_DEBUG__)
  6179. fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
  6180. snd_pcm_hw_params_dump( hw_params, out );
  6181. #endif
  6182. // Set access ... check user preference.
  6183. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
  6184. stream_.userInterleaved = false;
  6185. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6186. if ( result < 0 ) {
  6187. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6188. stream_.deviceInterleaved[mode] = true;
  6189. }
  6190. else
  6191. stream_.deviceInterleaved[mode] = false;
  6192. }
  6193. else {
  6194. stream_.userInterleaved = true;
  6195. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6196. if ( result < 0 ) {
  6197. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6198. stream_.deviceInterleaved[mode] = false;
  6199. }
  6200. else
  6201. stream_.deviceInterleaved[mode] = true;
  6202. }
  6203. if ( result < 0 ) {
  6204. snd_pcm_close( phandle );
  6205. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
  6206. errorText_ = errorStream_.str();
  6207. return FAILURE;
  6208. }
  6209. // Determine how to set the device format.
  6210. stream_.userFormat = format;
  6211. snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
  6212. if ( format == RTAUDIO_SINT8 )
  6213. deviceFormat = SND_PCM_FORMAT_S8;
  6214. else if ( format == RTAUDIO_SINT16 )
  6215. deviceFormat = SND_PCM_FORMAT_S16;
  6216. else if ( format == RTAUDIO_SINT24 )
  6217. deviceFormat = SND_PCM_FORMAT_S24;
  6218. else if ( format == RTAUDIO_SINT32 )
  6219. deviceFormat = SND_PCM_FORMAT_S32;
  6220. else if ( format == RTAUDIO_FLOAT32 )
  6221. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6222. else if ( format == RTAUDIO_FLOAT64 )
  6223. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6224. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
  6225. stream_.deviceFormat[mode] = format;
  6226. goto setFormat;
  6227. }
  6228. // The user requested format is not natively supported by the device.
  6229. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6230. if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
  6231. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  6232. goto setFormat;
  6233. }
  6234. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6235. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6236. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  6237. goto setFormat;
  6238. }
  6239. deviceFormat = SND_PCM_FORMAT_S32;
  6240. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6241. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  6242. goto setFormat;
  6243. }
  6244. deviceFormat = SND_PCM_FORMAT_S24;
  6245. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6246. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  6247. goto setFormat;
  6248. }
  6249. deviceFormat = SND_PCM_FORMAT_S16;
  6250. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6251. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  6252. goto setFormat;
  6253. }
  6254. deviceFormat = SND_PCM_FORMAT_S8;
  6255. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6256. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  6257. goto setFormat;
  6258. }
  6259. // If we get here, no supported format was found.
  6260. snd_pcm_close( phandle );
  6261. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
  6262. errorText_ = errorStream_.str();
  6263. return FAILURE;
  6264. setFormat:
  6265. result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
  6266. if ( result < 0 ) {
  6267. snd_pcm_close( phandle );
  6268. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
  6269. errorText_ = errorStream_.str();
  6270. return FAILURE;
  6271. }
  6272. // Determine whether byte-swaping is necessary.
  6273. stream_.doByteSwap[mode] = false;
  6274. if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
  6275. result = snd_pcm_format_cpu_endian( deviceFormat );
  6276. if ( result == 0 )
  6277. stream_.doByteSwap[mode] = true;
  6278. else if (result < 0) {
  6279. snd_pcm_close( phandle );
  6280. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
  6281. errorText_ = errorStream_.str();
  6282. return FAILURE;
  6283. }
  6284. }
  6285. // Set the sample rate.
  6286. result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
  6287. if ( result < 0 ) {
  6288. snd_pcm_close( phandle );
  6289. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
  6290. errorText_ = errorStream_.str();
  6291. return FAILURE;
  6292. }
  6293. // Determine the number of channels for this device. We support a possible
  6294. // minimum device channel number > than the value requested by the user.
  6295. stream_.nUserChannels[mode] = channels;
  6296. unsigned int value;
  6297. result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
  6298. unsigned int deviceChannels = value;
  6299. if ( result < 0 || deviceChannels < channels + firstChannel ) {
  6300. snd_pcm_close( phandle );
  6301. errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
  6302. errorText_ = errorStream_.str();
  6303. return FAILURE;
  6304. }
  6305. result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
  6306. if ( result < 0 ) {
  6307. snd_pcm_close( phandle );
  6308. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6309. errorText_ = errorStream_.str();
  6310. return FAILURE;
  6311. }
  6312. deviceChannels = value;
  6313. if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
  6314. stream_.nDeviceChannels[mode] = deviceChannels;
  6315. // Set the device channels.
  6316. result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
  6317. if ( result < 0 ) {
  6318. snd_pcm_close( phandle );
  6319. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6320. errorText_ = errorStream_.str();
  6321. return FAILURE;
  6322. }
  6323. // Set the buffer (or period) size.
  6324. int dir = 0;
  6325. snd_pcm_uframes_t periodSize = *bufferSize;
  6326. result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
  6327. if ( result < 0 ) {
  6328. snd_pcm_close( phandle );
  6329. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
  6330. errorText_ = errorStream_.str();
  6331. return FAILURE;
  6332. }
  6333. *bufferSize = periodSize;
  6334. // Set the buffer number, which in ALSA is referred to as the "period".
  6335. unsigned int periods = 0;
  6336. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
  6337. if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;
  6338. if ( periods < 2 ) periods = 4; // a fairly safe default value
  6339. result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
  6340. if ( result < 0 ) {
  6341. snd_pcm_close( phandle );
  6342. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
  6343. errorText_ = errorStream_.str();
  6344. return FAILURE;
  6345. }
  6346. // If attempting to setup a duplex stream, the bufferSize parameter
  6347. // MUST be the same in both directions!
  6348. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  6349. snd_pcm_close( phandle );
  6350. errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
  6351. errorText_ = errorStream_.str();
  6352. return FAILURE;
  6353. }
  6354. stream_.bufferSize = *bufferSize;
  6355. // Install the hardware configuration
  6356. result = snd_pcm_hw_params( phandle, hw_params );
  6357. if ( result < 0 ) {
  6358. snd_pcm_close( phandle );
  6359. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6360. errorText_ = errorStream_.str();
  6361. return FAILURE;
  6362. }
  6363. #if defined(__RTAUDIO_DEBUG__)
  6364. fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
  6365. snd_pcm_hw_params_dump( hw_params, out );
  6366. #endif
  6367. // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
  6368. snd_pcm_sw_params_t *sw_params = NULL;
  6369. snd_pcm_sw_params_alloca( &sw_params );
  6370. snd_pcm_sw_params_current( phandle, sw_params );
  6371. snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
  6372. snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
  6373. snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
  6374. // The following two settings were suggested by Theo Veenker
  6375. //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
  6376. //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
  6377. // here are two options for a fix
  6378. //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
  6379. snd_pcm_uframes_t val;
  6380. snd_pcm_sw_params_get_boundary( sw_params, &val );
  6381. snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
  6382. result = snd_pcm_sw_params( phandle, sw_params );
  6383. if ( result < 0 ) {
  6384. snd_pcm_close( phandle );
  6385. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6386. errorText_ = errorStream_.str();
  6387. return FAILURE;
  6388. }
  6389. #if defined(__RTAUDIO_DEBUG__)
  6390. fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
  6391. snd_pcm_sw_params_dump( sw_params, out );
  6392. #endif
  6393. // Set flags for buffer conversion
  6394. stream_.doConvertBuffer[mode] = false;
  6395. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  6396. stream_.doConvertBuffer[mode] = true;
  6397. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  6398. stream_.doConvertBuffer[mode] = true;
  6399. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  6400. stream_.nUserChannels[mode] > 1 )
  6401. stream_.doConvertBuffer[mode] = true;
  6402. // Allocate the ApiHandle if necessary and then save.
  6403. AlsaHandle *apiInfo = 0;
  6404. if ( stream_.apiHandle == 0 ) {
  6405. try {
  6406. apiInfo = (AlsaHandle *) new AlsaHandle;
  6407. }
  6408. catch ( std::bad_alloc& ) {
  6409. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
  6410. goto error;
  6411. }
  6412. if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {
  6413. errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
  6414. goto error;
  6415. }
  6416. stream_.apiHandle = (void *) apiInfo;
  6417. apiInfo->handles[0] = 0;
  6418. apiInfo->handles[1] = 0;
  6419. }
  6420. else {
  6421. apiInfo = (AlsaHandle *) stream_.apiHandle;
  6422. }
  6423. apiInfo->handles[mode] = phandle;
  6424. phandle = 0;
  6425. // Allocate necessary internal buffers.
  6426. unsigned long bufferBytes;
  6427. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  6428. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  6429. if ( stream_.userBuffer[mode] == NULL ) {
  6430. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
  6431. goto error;
  6432. }
  6433. if ( stream_.doConvertBuffer[mode] ) {
  6434. bool makeBuffer = true;
  6435. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  6436. if ( mode == INPUT ) {
  6437. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  6438. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  6439. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  6440. }
  6441. }
  6442. if ( makeBuffer ) {
  6443. bufferBytes *= *bufferSize;
  6444. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  6445. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  6446. if ( stream_.deviceBuffer == NULL ) {
  6447. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
  6448. goto error;
  6449. }
  6450. }
  6451. }
  6452. stream_.sampleRate = sampleRate;
  6453. stream_.nBuffers = periods;
  6454. stream_.device[mode] = device;
  6455. stream_.state = STREAM_STOPPED;
  6456. // Setup the buffer conversion information structure.
  6457. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  6458. // Setup thread if necessary.
  6459. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  6460. // We had already set up an output stream.
  6461. stream_.mode = DUPLEX;
  6462. // Link the streams if possible.
  6463. apiInfo->synchronized = false;
  6464. if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
  6465. apiInfo->synchronized = true;
  6466. else {
  6467. errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
  6468. error( RtAudioError::WARNING );
  6469. }
  6470. }
  6471. else {
  6472. stream_.mode = mode;
  6473. // Setup callback thread.
  6474. stream_.callbackInfo.object = (void *) this;
  6475. // Set the thread attributes for joinable and realtime scheduling
  6476. // priority (optional). The higher priority will only take affect
  6477. // if the program is run as root or suid. Note, under Linux
  6478. // processes with CAP_SYS_NICE privilege, a user can change
  6479. // scheduling policy and priority (thus need not be root). See
  6480. // POSIX "capabilities".
  6481. pthread_attr_t attr;
  6482. pthread_attr_init( &attr );
  6483. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  6484. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  6485. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  6486. // We previously attempted to increase the audio callback priority
  6487. // to SCHED_RR here via the attributes. However, while no errors
  6488. // were reported in doing so, it did not work. So, now this is
  6489. // done in the alsaCallbackHandler function.
  6490. stream_.callbackInfo.doRealtime = true;
  6491. int priority = options->priority;
  6492. int min = sched_get_priority_min( SCHED_RR );
  6493. int max = sched_get_priority_max( SCHED_RR );
  6494. if ( priority < min ) priority = min;
  6495. else if ( priority > max ) priority = max;
  6496. stream_.callbackInfo.priority = priority;
  6497. }
  6498. #endif
  6499. stream_.callbackInfo.isRunning = true;
  6500. result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
  6501. pthread_attr_destroy( &attr );
  6502. if ( result ) {
  6503. stream_.callbackInfo.isRunning = false;
  6504. errorText_ = "RtApiAlsa::error creating callback thread!";
  6505. goto error;
  6506. }
  6507. }
  6508. return SUCCESS;
  6509. error:
  6510. if ( apiInfo ) {
  6511. pthread_cond_destroy( &apiInfo->runnable_cv );
  6512. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6513. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6514. delete apiInfo;
  6515. stream_.apiHandle = 0;
  6516. }
  6517. if ( phandle) snd_pcm_close( phandle );
  6518. for ( int i=0; i<2; i++ ) {
  6519. if ( stream_.userBuffer[i] ) {
  6520. free( stream_.userBuffer[i] );
  6521. stream_.userBuffer[i] = 0;
  6522. }
  6523. }
  6524. if ( stream_.deviceBuffer ) {
  6525. free( stream_.deviceBuffer );
  6526. stream_.deviceBuffer = 0;
  6527. }
  6528. stream_.state = STREAM_CLOSED;
  6529. return FAILURE;
  6530. }
  6531. void RtApiAlsa :: closeStream()
  6532. {
  6533. if ( stream_.state == STREAM_CLOSED ) {
  6534. errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
  6535. error( RtAudioError::WARNING );
  6536. return;
  6537. }
  6538. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6539. stream_.callbackInfo.isRunning = false;
  6540. MUTEX_LOCK( &stream_.mutex );
  6541. if ( stream_.state == STREAM_STOPPED ) {
  6542. apiInfo->runnable = true;
  6543. pthread_cond_signal( &apiInfo->runnable_cv );
  6544. }
  6545. MUTEX_UNLOCK( &stream_.mutex );
  6546. pthread_join( stream_.callbackInfo.thread, NULL );
  6547. if ( stream_.state == STREAM_RUNNING ) {
  6548. stream_.state = STREAM_STOPPED;
  6549. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  6550. snd_pcm_drop( apiInfo->handles[0] );
  6551. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  6552. snd_pcm_drop( apiInfo->handles[1] );
  6553. }
  6554. if ( apiInfo ) {
  6555. pthread_cond_destroy( &apiInfo->runnable_cv );
  6556. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6557. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6558. delete apiInfo;
  6559. stream_.apiHandle = 0;
  6560. }
  6561. for ( int i=0; i<2; i++ ) {
  6562. if ( stream_.userBuffer[i] ) {
  6563. free( stream_.userBuffer[i] );
  6564. stream_.userBuffer[i] = 0;
  6565. }
  6566. }
  6567. if ( stream_.deviceBuffer ) {
  6568. free( stream_.deviceBuffer );
  6569. stream_.deviceBuffer = 0;
  6570. }
  6571. stream_.mode = UNINITIALIZED;
  6572. stream_.state = STREAM_CLOSED;
  6573. }
  6574. void RtApiAlsa :: startStream()
  6575. {
  6576. // This method calls snd_pcm_prepare if the device isn't already in that state.
  6577. verifyStream();
  6578. if ( stream_.state == STREAM_RUNNING ) {
  6579. errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
  6580. error( RtAudioError::WARNING );
  6581. return;
  6582. }
  6583. MUTEX_LOCK( &stream_.mutex );
  6584. int result = 0;
  6585. snd_pcm_state_t state;
  6586. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6587. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6588. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6589. state = snd_pcm_state( handle[0] );
  6590. if ( state != SND_PCM_STATE_PREPARED ) {
  6591. result = snd_pcm_prepare( handle[0] );
  6592. if ( result < 0 ) {
  6593. errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
  6594. errorText_ = errorStream_.str();
  6595. goto unlock;
  6596. }
  6597. }
  6598. }
  6599. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6600. result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open
  6601. state = snd_pcm_state( handle[1] );
  6602. if ( state != SND_PCM_STATE_PREPARED ) {
  6603. result = snd_pcm_prepare( handle[1] );
  6604. if ( result < 0 ) {
  6605. errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
  6606. errorText_ = errorStream_.str();
  6607. goto unlock;
  6608. }
  6609. }
  6610. }
  6611. stream_.state = STREAM_RUNNING;
  6612. unlock:
  6613. apiInfo->runnable = true;
  6614. pthread_cond_signal( &apiInfo->runnable_cv );
  6615. MUTEX_UNLOCK( &stream_.mutex );
  6616. if ( result >= 0 ) return;
  6617. error( RtAudioError::SYSTEM_ERROR );
  6618. }
  6619. void RtApiAlsa :: stopStream()
  6620. {
  6621. verifyStream();
  6622. if ( stream_.state == STREAM_STOPPED ) {
  6623. errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
  6624. error( RtAudioError::WARNING );
  6625. return;
  6626. }
  6627. stream_.state = STREAM_STOPPED;
  6628. MUTEX_LOCK( &stream_.mutex );
  6629. int result = 0;
  6630. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6631. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6632. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6633. if ( apiInfo->synchronized )
  6634. result = snd_pcm_drop( handle[0] );
  6635. else
  6636. result = snd_pcm_drain( handle[0] );
  6637. if ( result < 0 ) {
  6638. errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
  6639. errorText_ = errorStream_.str();
  6640. goto unlock;
  6641. }
  6642. }
  6643. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6644. result = snd_pcm_drop( handle[1] );
  6645. if ( result < 0 ) {
  6646. errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
  6647. errorText_ = errorStream_.str();
  6648. goto unlock;
  6649. }
  6650. }
  6651. unlock:
  6652. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6653. MUTEX_UNLOCK( &stream_.mutex );
  6654. if ( result >= 0 ) return;
  6655. error( RtAudioError::SYSTEM_ERROR );
  6656. }
  6657. void RtApiAlsa :: abortStream()
  6658. {
  6659. verifyStream();
  6660. if ( stream_.state == STREAM_STOPPED ) {
  6661. errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
  6662. error( RtAudioError::WARNING );
  6663. return;
  6664. }
  6665. stream_.state = STREAM_STOPPED;
  6666. MUTEX_LOCK( &stream_.mutex );
  6667. int result = 0;
  6668. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6669. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6670. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6671. result = snd_pcm_drop( handle[0] );
  6672. if ( result < 0 ) {
  6673. errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
  6674. errorText_ = errorStream_.str();
  6675. goto unlock;
  6676. }
  6677. }
  6678. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6679. result = snd_pcm_drop( handle[1] );
  6680. if ( result < 0 ) {
  6681. errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
  6682. errorText_ = errorStream_.str();
  6683. goto unlock;
  6684. }
  6685. }
  6686. unlock:
  6687. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6688. MUTEX_UNLOCK( &stream_.mutex );
  6689. if ( result >= 0 ) return;
  6690. error( RtAudioError::SYSTEM_ERROR );
  6691. }
  6692. void RtApiAlsa :: callbackEvent()
  6693. {
  6694. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6695. if ( stream_.state == STREAM_STOPPED ) {
  6696. MUTEX_LOCK( &stream_.mutex );
  6697. while ( !apiInfo->runnable )
  6698. pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );
  6699. if ( stream_.state != STREAM_RUNNING ) {
  6700. MUTEX_UNLOCK( &stream_.mutex );
  6701. return;
  6702. }
  6703. MUTEX_UNLOCK( &stream_.mutex );
  6704. }
  6705. if ( stream_.state == STREAM_CLOSED ) {
  6706. errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
  6707. error( RtAudioError::WARNING );
  6708. return;
  6709. }
  6710. int doStopStream = 0;
  6711. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  6712. double streamTime = getStreamTime();
  6713. RtAudioStreamStatus status = 0;
  6714. if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
  6715. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  6716. apiInfo->xrun[0] = false;
  6717. }
  6718. if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
  6719. status |= RTAUDIO_INPUT_OVERFLOW;
  6720. apiInfo->xrun[1] = false;
  6721. }
  6722. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  6723. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  6724. if ( doStopStream == 2 ) {
  6725. abortStream();
  6726. return;
  6727. }
  6728. MUTEX_LOCK( &stream_.mutex );
  6729. // The state might change while waiting on a mutex.
  6730. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  6731. int result;
  6732. char *buffer;
  6733. int channels;
  6734. snd_pcm_t **handle;
  6735. snd_pcm_sframes_t frames;
  6736. RtAudioFormat format;
  6737. handle = (snd_pcm_t **) apiInfo->handles;
  6738. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  6739. // Setup parameters.
  6740. if ( stream_.doConvertBuffer[1] ) {
  6741. buffer = stream_.deviceBuffer;
  6742. channels = stream_.nDeviceChannels[1];
  6743. format = stream_.deviceFormat[1];
  6744. }
  6745. else {
  6746. buffer = stream_.userBuffer[1];
  6747. channels = stream_.nUserChannels[1];
  6748. format = stream_.userFormat;
  6749. }
  6750. // Read samples from device in interleaved/non-interleaved format.
  6751. if ( stream_.deviceInterleaved[1] )
  6752. result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
  6753. else {
  6754. void *bufs[channels];
  6755. size_t offset = stream_.bufferSize * formatBytes( format );
  6756. for ( int i=0; i<channels; i++ )
  6757. bufs[i] = (void *) (buffer + (i * offset));
  6758. result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
  6759. }
  6760. if ( result < (int) stream_.bufferSize ) {
  6761. // Either an error or overrun occured.
  6762. if ( result == -EPIPE ) {
  6763. snd_pcm_state_t state = snd_pcm_state( handle[1] );
  6764. if ( state == SND_PCM_STATE_XRUN ) {
  6765. apiInfo->xrun[1] = true;
  6766. result = snd_pcm_prepare( handle[1] );
  6767. if ( result < 0 ) {
  6768. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
  6769. errorText_ = errorStream_.str();
  6770. }
  6771. }
  6772. else {
  6773. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  6774. errorText_ = errorStream_.str();
  6775. }
  6776. }
  6777. else {
  6778. errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
  6779. errorText_ = errorStream_.str();
  6780. }
  6781. error( RtAudioError::WARNING );
  6782. goto tryOutput;
  6783. }
  6784. // Do byte swapping if necessary.
  6785. if ( stream_.doByteSwap[1] )
  6786. byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
  6787. // Do buffer conversion if necessary.
  6788. if ( stream_.doConvertBuffer[1] )
  6789. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  6790. // Check stream latency
  6791. result = snd_pcm_delay( handle[1], &frames );
  6792. if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
  6793. }
  6794. tryOutput:
  6795. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6796. // Setup parameters and do buffer conversion if necessary.
  6797. if ( stream_.doConvertBuffer[0] ) {
  6798. buffer = stream_.deviceBuffer;
  6799. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  6800. channels = stream_.nDeviceChannels[0];
  6801. format = stream_.deviceFormat[0];
  6802. }
  6803. else {
  6804. buffer = stream_.userBuffer[0];
  6805. channels = stream_.nUserChannels[0];
  6806. format = stream_.userFormat;
  6807. }
  6808. // Do byte swapping if necessary.
  6809. if ( stream_.doByteSwap[0] )
  6810. byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
  6811. // Write samples to device in interleaved/non-interleaved format.
  6812. if ( stream_.deviceInterleaved[0] )
  6813. result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
  6814. else {
  6815. void *bufs[channels];
  6816. size_t offset = stream_.bufferSize * formatBytes( format );
  6817. for ( int i=0; i<channels; i++ )
  6818. bufs[i] = (void *) (buffer + (i * offset));
  6819. result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
  6820. }
  6821. if ( result < (int) stream_.bufferSize ) {
  6822. // Either an error or underrun occured.
  6823. if ( result == -EPIPE ) {
  6824. snd_pcm_state_t state = snd_pcm_state( handle[0] );
  6825. if ( state == SND_PCM_STATE_XRUN ) {
  6826. apiInfo->xrun[0] = true;
  6827. result = snd_pcm_prepare( handle[0] );
  6828. if ( result < 0 ) {
  6829. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
  6830. errorText_ = errorStream_.str();
  6831. }
  6832. }
  6833. else {
  6834. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  6835. errorText_ = errorStream_.str();
  6836. }
  6837. }
  6838. else {
  6839. errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
  6840. errorText_ = errorStream_.str();
  6841. }
  6842. error( RtAudioError::WARNING );
  6843. goto unlock;
  6844. }
  6845. // Check stream latency
  6846. result = snd_pcm_delay( handle[0], &frames );
  6847. if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
  6848. }
  6849. unlock:
  6850. MUTEX_UNLOCK( &stream_.mutex );
  6851. RtApi::tickStreamTime();
  6852. if ( doStopStream == 1 ) this->stopStream();
  6853. }
  6854. static void *alsaCallbackHandler( void *ptr )
  6855. {
  6856. CallbackInfo *info = (CallbackInfo *) ptr;
  6857. RtApiAlsa *object = (RtApiAlsa *) info->object;
  6858. bool *isRunning = &info->isRunning;
  6859. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  6860. if ( &info->doRealtime ) {
  6861. pthread_t tID = pthread_self(); // ID of this thread
  6862. sched_param prio = { info->priority }; // scheduling priority of thread
  6863. pthread_setschedparam( tID, SCHED_RR, &prio );
  6864. }
  6865. #endif
  6866. while ( *isRunning == true ) {
  6867. pthread_testcancel();
  6868. object->callbackEvent();
  6869. }
  6870. pthread_exit( NULL );
  6871. }
  6872. //******************** End of __LINUX_ALSA__ *********************//
  6873. #endif
  6874. #if defined(__LINUX_PULSE__)
  6875. // Code written by Peter Meerwald, pmeerw@pmeerw.net
  6876. // and Tristan Matthews.
  6877. #include <pulse/error.h>
  6878. #include <pulse/simple.h>
  6879. #include <cstdio>
  6880. static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,
  6881. 44100, 48000, 96000, 0};
  6882. struct rtaudio_pa_format_mapping_t {
  6883. RtAudioFormat rtaudio_format;
  6884. pa_sample_format_t pa_format;
  6885. };
  6886. static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {
  6887. {RTAUDIO_SINT16, PA_SAMPLE_S16LE},
  6888. {RTAUDIO_SINT32, PA_SAMPLE_S32LE},
  6889. {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},
  6890. {0, PA_SAMPLE_INVALID}};
  6891. struct PulseAudioHandle {
  6892. pa_simple *s_play;
  6893. pa_simple *s_rec;
  6894. pthread_t thread;
  6895. pthread_cond_t runnable_cv;
  6896. bool runnable;
  6897. PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }
  6898. };
  6899. RtApiPulse::~RtApiPulse()
  6900. {
  6901. if ( stream_.state != STREAM_CLOSED )
  6902. closeStream();
  6903. }
  6904. unsigned int RtApiPulse::getDeviceCount( void )
  6905. {
  6906. return 1;
  6907. }
  6908. RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )
  6909. {
  6910. RtAudio::DeviceInfo info;
  6911. info.probed = true;
  6912. info.name = "PulseAudio";
  6913. info.outputChannels = 2;
  6914. info.inputChannels = 2;
  6915. info.duplexChannels = 2;
  6916. info.isDefaultOutput = true;
  6917. info.isDefaultInput = true;
  6918. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )
  6919. info.sampleRates.push_back( *sr );
  6920. info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;
  6921. return info;
  6922. }
  6923. static void *pulseaudio_callback( void * user )
  6924. {
  6925. CallbackInfo *cbi = static_cast<CallbackInfo *>( user );
  6926. RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );
  6927. volatile bool *isRunning = &cbi->isRunning;
  6928. while ( *isRunning ) {
  6929. pthread_testcancel();
  6930. context->callbackEvent();
  6931. }
  6932. pthread_exit( NULL );
  6933. }
  6934. void RtApiPulse::closeStream( void )
  6935. {
  6936. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  6937. stream_.callbackInfo.isRunning = false;
  6938. if ( pah ) {
  6939. MUTEX_LOCK( &stream_.mutex );
  6940. if ( stream_.state == STREAM_STOPPED ) {
  6941. pah->runnable = true;
  6942. pthread_cond_signal( &pah->runnable_cv );
  6943. }
  6944. MUTEX_UNLOCK( &stream_.mutex );
  6945. pthread_join( pah->thread, 0 );
  6946. if ( pah->s_play ) {
  6947. pa_simple_flush( pah->s_play, NULL );
  6948. pa_simple_free( pah->s_play );
  6949. }
  6950. if ( pah->s_rec )
  6951. pa_simple_free( pah->s_rec );
  6952. pthread_cond_destroy( &pah->runnable_cv );
  6953. delete pah;
  6954. stream_.apiHandle = 0;
  6955. }
  6956. if ( stream_.userBuffer[0] ) {
  6957. free( stream_.userBuffer[0] );
  6958. stream_.userBuffer[0] = 0;
  6959. }
  6960. if ( stream_.userBuffer[1] ) {
  6961. free( stream_.userBuffer[1] );
  6962. stream_.userBuffer[1] = 0;
  6963. }
  6964. stream_.state = STREAM_CLOSED;
  6965. stream_.mode = UNINITIALIZED;
  6966. }
  6967. void RtApiPulse::callbackEvent( void )
  6968. {
  6969. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  6970. if ( stream_.state == STREAM_STOPPED ) {
  6971. MUTEX_LOCK( &stream_.mutex );
  6972. while ( !pah->runnable )
  6973. pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );
  6974. if ( stream_.state != STREAM_RUNNING ) {
  6975. MUTEX_UNLOCK( &stream_.mutex );
  6976. return;
  6977. }
  6978. MUTEX_UNLOCK( &stream_.mutex );
  6979. }
  6980. if ( stream_.state == STREAM_CLOSED ) {
  6981. errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "
  6982. "this shouldn't happen!";
  6983. error( RtAudioError::WARNING );
  6984. return;
  6985. }
  6986. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  6987. double streamTime = getStreamTime();
  6988. RtAudioStreamStatus status = 0;
  6989. int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],
  6990. stream_.bufferSize, streamTime, status,
  6991. stream_.callbackInfo.userData );
  6992. if ( doStopStream == 2 ) {
  6993. abortStream();
  6994. return;
  6995. }
  6996. MUTEX_LOCK( &stream_.mutex );
  6997. void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];
  6998. void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];
  6999. if ( stream_.state != STREAM_RUNNING )
  7000. goto unlock;
  7001. int pa_error;
  7002. size_t bytes;
  7003. if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7004. if ( stream_.doConvertBuffer[OUTPUT] ) {
  7005. convertBuffer( stream_.deviceBuffer,
  7006. stream_.userBuffer[OUTPUT],
  7007. stream_.convertInfo[OUTPUT] );
  7008. bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *
  7009. formatBytes( stream_.deviceFormat[OUTPUT] );
  7010. } else
  7011. bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *
  7012. formatBytes( stream_.userFormat );
  7013. if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {
  7014. errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<
  7015. pa_strerror( pa_error ) << ".";
  7016. errorText_ = errorStream_.str();
  7017. error( RtAudioError::WARNING );
  7018. }
  7019. }
  7020. if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {
  7021. if ( stream_.doConvertBuffer[INPUT] )
  7022. bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *
  7023. formatBytes( stream_.deviceFormat[INPUT] );
  7024. else
  7025. bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *
  7026. formatBytes( stream_.userFormat );
  7027. if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {
  7028. errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<
  7029. pa_strerror( pa_error ) << ".";
  7030. errorText_ = errorStream_.str();
  7031. error( RtAudioError::WARNING );
  7032. }
  7033. if ( stream_.doConvertBuffer[INPUT] ) {
  7034. convertBuffer( stream_.userBuffer[INPUT],
  7035. stream_.deviceBuffer,
  7036. stream_.convertInfo[INPUT] );
  7037. }
  7038. }
  7039. unlock:
  7040. MUTEX_UNLOCK( &stream_.mutex );
  7041. RtApi::tickStreamTime();
  7042. if ( doStopStream == 1 )
  7043. stopStream();
  7044. }
  7045. void RtApiPulse::startStream( void )
  7046. {
  7047. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7048. if ( stream_.state == STREAM_CLOSED ) {
  7049. errorText_ = "RtApiPulse::startStream(): the stream is not open!";
  7050. error( RtAudioError::INVALID_USE );
  7051. return;
  7052. }
  7053. if ( stream_.state == STREAM_RUNNING ) {
  7054. errorText_ = "RtApiPulse::startStream(): the stream is already running!";
  7055. error( RtAudioError::WARNING );
  7056. return;
  7057. }
  7058. MUTEX_LOCK( &stream_.mutex );
  7059. stream_.state = STREAM_RUNNING;
  7060. pah->runnable = true;
  7061. pthread_cond_signal( &pah->runnable_cv );
  7062. MUTEX_UNLOCK( &stream_.mutex );
  7063. }
  7064. void RtApiPulse::stopStream( void )
  7065. {
  7066. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7067. if ( stream_.state == STREAM_CLOSED ) {
  7068. errorText_ = "RtApiPulse::stopStream(): the stream is not open!";
  7069. error( RtAudioError::INVALID_USE );
  7070. return;
  7071. }
  7072. if ( stream_.state == STREAM_STOPPED ) {
  7073. errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";
  7074. error( RtAudioError::WARNING );
  7075. return;
  7076. }
  7077. stream_.state = STREAM_STOPPED;
  7078. MUTEX_LOCK( &stream_.mutex );
  7079. if ( pah && pah->s_play ) {
  7080. int pa_error;
  7081. if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {
  7082. errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<
  7083. pa_strerror( pa_error ) << ".";
  7084. errorText_ = errorStream_.str();
  7085. MUTEX_UNLOCK( &stream_.mutex );
  7086. error( RtAudioError::SYSTEM_ERROR );
  7087. return;
  7088. }
  7089. }
  7090. stream_.state = STREAM_STOPPED;
  7091. MUTEX_UNLOCK( &stream_.mutex );
  7092. }
  7093. void RtApiPulse::abortStream( void )
  7094. {
  7095. PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );
  7096. if ( stream_.state == STREAM_CLOSED ) {
  7097. errorText_ = "RtApiPulse::abortStream(): the stream is not open!";
  7098. error( RtAudioError::INVALID_USE );
  7099. return;
  7100. }
  7101. if ( stream_.state == STREAM_STOPPED ) {
  7102. errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";
  7103. error( RtAudioError::WARNING );
  7104. return;
  7105. }
  7106. stream_.state = STREAM_STOPPED;
  7107. MUTEX_LOCK( &stream_.mutex );
  7108. if ( pah && pah->s_play ) {
  7109. int pa_error;
  7110. if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {
  7111. errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<
  7112. pa_strerror( pa_error ) << ".";
  7113. errorText_ = errorStream_.str();
  7114. MUTEX_UNLOCK( &stream_.mutex );
  7115. error( RtAudioError::SYSTEM_ERROR );
  7116. return;
  7117. }
  7118. }
  7119. stream_.state = STREAM_STOPPED;
  7120. MUTEX_UNLOCK( &stream_.mutex );
  7121. }
  7122. bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
  7123. unsigned int channels, unsigned int firstChannel,
  7124. unsigned int sampleRate, RtAudioFormat format,
  7125. unsigned int *bufferSize, RtAudio::StreamOptions *options )
  7126. {
  7127. PulseAudioHandle *pah = 0;
  7128. unsigned long bufferBytes = 0;
  7129. pa_sample_spec ss;
  7130. if ( device != 0 ) return false;
  7131. if ( mode != INPUT && mode != OUTPUT ) return false;
  7132. if ( channels != 1 && channels != 2 ) {
  7133. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";
  7134. return false;
  7135. }
  7136. ss.channels = channels;
  7137. if ( firstChannel != 0 ) return false;
  7138. bool sr_found = false;
  7139. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {
  7140. if ( sampleRate == *sr ) {
  7141. sr_found = true;
  7142. stream_.sampleRate = sampleRate;
  7143. ss.rate = sampleRate;
  7144. break;
  7145. }
  7146. }
  7147. if ( !sr_found ) {
  7148. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";
  7149. return false;
  7150. }
  7151. bool sf_found = 0;
  7152. for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;
  7153. sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {
  7154. if ( format == sf->rtaudio_format ) {
  7155. sf_found = true;
  7156. stream_.userFormat = sf->rtaudio_format;
  7157. stream_.deviceFormat[mode] = stream_.userFormat;
  7158. ss.format = sf->pa_format;
  7159. break;
  7160. }
  7161. }
  7162. if ( !sf_found ) { // Use internal data format conversion.
  7163. stream_.userFormat = format;
  7164. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  7165. ss.format = PA_SAMPLE_FLOAT32LE;
  7166. }
  7167. // Set other stream parameters.
  7168. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  7169. else stream_.userInterleaved = true;
  7170. stream_.deviceInterleaved[mode] = true;
  7171. stream_.nBuffers = 1;
  7172. stream_.doByteSwap[mode] = false;
  7173. stream_.nUserChannels[mode] = channels;
  7174. stream_.nDeviceChannels[mode] = channels + firstChannel;
  7175. stream_.channelOffset[mode] = 0;
  7176. std::string streamName = "RtAudio";
  7177. // Set flags for buffer conversion.
  7178. stream_.doConvertBuffer[mode] = false;
  7179. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7180. stream_.doConvertBuffer[mode] = true;
  7181. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7182. stream_.doConvertBuffer[mode] = true;
  7183. // Allocate necessary internal buffers.
  7184. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7185. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7186. if ( stream_.userBuffer[mode] == NULL ) {
  7187. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";
  7188. goto error;
  7189. }
  7190. stream_.bufferSize = *bufferSize;
  7191. if ( stream_.doConvertBuffer[mode] ) {
  7192. bool makeBuffer = true;
  7193. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7194. if ( mode == INPUT ) {
  7195. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7196. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7197. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7198. }
  7199. }
  7200. if ( makeBuffer ) {
  7201. bufferBytes *= *bufferSize;
  7202. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7203. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7204. if ( stream_.deviceBuffer == NULL ) {
  7205. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";
  7206. goto error;
  7207. }
  7208. }
  7209. }
  7210. stream_.device[mode] = device;
  7211. // Setup the buffer conversion information structure.
  7212. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7213. if ( !stream_.apiHandle ) {
  7214. PulseAudioHandle *pah = new PulseAudioHandle;
  7215. if ( !pah ) {
  7216. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";
  7217. goto error;
  7218. }
  7219. stream_.apiHandle = pah;
  7220. if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {
  7221. errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";
  7222. goto error;
  7223. }
  7224. }
  7225. pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7226. int error;
  7227. if ( !options->streamName.empty() ) streamName = options->streamName;
  7228. switch ( mode ) {
  7229. case INPUT:
  7230. pa_buffer_attr buffer_attr;
  7231. buffer_attr.fragsize = bufferBytes;
  7232. buffer_attr.maxlength = -1;
  7233. pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );
  7234. if ( !pah->s_rec ) {
  7235. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";
  7236. goto error;
  7237. }
  7238. break;
  7239. case OUTPUT:
  7240. pah->s_play = pa_simple_new( NULL, "RtAudio", PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );
  7241. if ( !pah->s_play ) {
  7242. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";
  7243. goto error;
  7244. }
  7245. break;
  7246. default:
  7247. goto error;
  7248. }
  7249. if ( stream_.mode == UNINITIALIZED )
  7250. stream_.mode = mode;
  7251. else if ( stream_.mode == mode )
  7252. goto error;
  7253. else
  7254. stream_.mode = DUPLEX;
  7255. if ( !stream_.callbackInfo.isRunning ) {
  7256. stream_.callbackInfo.object = this;
  7257. stream_.callbackInfo.isRunning = true;
  7258. if ( pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo) != 0 ) {
  7259. errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";
  7260. goto error;
  7261. }
  7262. }
  7263. stream_.state = STREAM_STOPPED;
  7264. return true;
  7265. error:
  7266. if ( pah && stream_.callbackInfo.isRunning ) {
  7267. pthread_cond_destroy( &pah->runnable_cv );
  7268. delete pah;
  7269. stream_.apiHandle = 0;
  7270. }
  7271. for ( int i=0; i<2; i++ ) {
  7272. if ( stream_.userBuffer[i] ) {
  7273. free( stream_.userBuffer[i] );
  7274. stream_.userBuffer[i] = 0;
  7275. }
  7276. }
  7277. if ( stream_.deviceBuffer ) {
  7278. free( stream_.deviceBuffer );
  7279. stream_.deviceBuffer = 0;
  7280. }
  7281. return FAILURE;
  7282. }
  7283. //******************** End of __LINUX_PULSE__ *********************//
  7284. #endif
  7285. #if defined(__LINUX_OSS__)
  7286. #include <unistd.h>
  7287. #include <sys/ioctl.h>
  7288. #include <unistd.h>
  7289. #include <fcntl.h>
  7290. #include <sys/soundcard.h>
  7291. #include <errno.h>
  7292. #include <math.h>
  7293. static void *ossCallbackHandler(void * ptr);
  7294. // A structure to hold various information related to the OSS API
  7295. // implementation.
  7296. struct OssHandle {
  7297. int id[2]; // device ids
  7298. bool xrun[2];
  7299. bool triggered;
  7300. pthread_cond_t runnable;
  7301. OssHandle()
  7302. :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  7303. };
  7304. RtApiOss :: RtApiOss()
  7305. {
  7306. // Nothing to do here.
  7307. }
  7308. RtApiOss :: ~RtApiOss()
  7309. {
  7310. if ( stream_.state != STREAM_CLOSED ) closeStream();
  7311. }
  7312. unsigned int RtApiOss :: getDeviceCount( void )
  7313. {
  7314. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7315. if ( mixerfd == -1 ) {
  7316. errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
  7317. error( RtAudioError::WARNING );
  7318. return 0;
  7319. }
  7320. oss_sysinfo sysinfo;
  7321. if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
  7322. close( mixerfd );
  7323. errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
  7324. error( RtAudioError::WARNING );
  7325. return 0;
  7326. }
  7327. close( mixerfd );
  7328. return sysinfo.numaudios;
  7329. }
  7330. RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
  7331. {
  7332. RtAudio::DeviceInfo info;
  7333. info.probed = false;
  7334. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7335. if ( mixerfd == -1 ) {
  7336. errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
  7337. error( RtAudioError::WARNING );
  7338. return info;
  7339. }
  7340. oss_sysinfo sysinfo;
  7341. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7342. if ( result == -1 ) {
  7343. close( mixerfd );
  7344. errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
  7345. error( RtAudioError::WARNING );
  7346. return info;
  7347. }
  7348. unsigned nDevices = sysinfo.numaudios;
  7349. if ( nDevices == 0 ) {
  7350. close( mixerfd );
  7351. errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
  7352. error( RtAudioError::INVALID_USE );
  7353. return info;
  7354. }
  7355. if ( device >= nDevices ) {
  7356. close( mixerfd );
  7357. errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
  7358. error( RtAudioError::INVALID_USE );
  7359. return info;
  7360. }
  7361. oss_audioinfo ainfo;
  7362. ainfo.dev = device;
  7363. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7364. close( mixerfd );
  7365. if ( result == -1 ) {
  7366. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7367. errorText_ = errorStream_.str();
  7368. error( RtAudioError::WARNING );
  7369. return info;
  7370. }
  7371. // Probe channels
  7372. if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
  7373. if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
  7374. if ( ainfo.caps & PCM_CAP_DUPLEX ) {
  7375. if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
  7376. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  7377. }
  7378. // Probe data formats ... do for input
  7379. unsigned long mask = ainfo.iformats;
  7380. if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
  7381. info.nativeFormats |= RTAUDIO_SINT16;
  7382. if ( mask & AFMT_S8 )
  7383. info.nativeFormats |= RTAUDIO_SINT8;
  7384. if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
  7385. info.nativeFormats |= RTAUDIO_SINT32;
  7386. if ( mask & AFMT_FLOAT )
  7387. info.nativeFormats |= RTAUDIO_FLOAT32;
  7388. if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
  7389. info.nativeFormats |= RTAUDIO_SINT24;
  7390. // Check that we have at least one supported format
  7391. if ( info.nativeFormats == 0 ) {
  7392. errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7393. errorText_ = errorStream_.str();
  7394. error( RtAudioError::WARNING );
  7395. return info;
  7396. }
  7397. // Probe the supported sample rates.
  7398. info.sampleRates.clear();
  7399. if ( ainfo.nrates ) {
  7400. for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
  7401. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7402. if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
  7403. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7404. break;
  7405. }
  7406. }
  7407. }
  7408. }
  7409. else {
  7410. // Check min and max rate values;
  7411. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7412. if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] )
  7413. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7414. }
  7415. }
  7416. if ( info.sampleRates.size() == 0 ) {
  7417. errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
  7418. errorText_ = errorStream_.str();
  7419. error( RtAudioError::WARNING );
  7420. }
  7421. else {
  7422. info.probed = true;
  7423. info.name = ainfo.name;
  7424. }
  7425. return info;
  7426. }
  7427. bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  7428. unsigned int firstChannel, unsigned int sampleRate,
  7429. RtAudioFormat format, unsigned int *bufferSize,
  7430. RtAudio::StreamOptions *options )
  7431. {
  7432. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7433. if ( mixerfd == -1 ) {
  7434. errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
  7435. return FAILURE;
  7436. }
  7437. oss_sysinfo sysinfo;
  7438. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7439. if ( result == -1 ) {
  7440. close( mixerfd );
  7441. errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
  7442. return FAILURE;
  7443. }
  7444. unsigned nDevices = sysinfo.numaudios;
  7445. if ( nDevices == 0 ) {
  7446. // This should not happen because a check is made before this function is called.
  7447. close( mixerfd );
  7448. errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
  7449. return FAILURE;
  7450. }
  7451. if ( device >= nDevices ) {
  7452. // This should not happen because a check is made before this function is called.
  7453. close( mixerfd );
  7454. errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
  7455. return FAILURE;
  7456. }
  7457. oss_audioinfo ainfo;
  7458. ainfo.dev = device;
  7459. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7460. close( mixerfd );
  7461. if ( result == -1 ) {
  7462. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7463. errorText_ = errorStream_.str();
  7464. return FAILURE;
  7465. }
  7466. // Check if device supports input or output
  7467. if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
  7468. ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
  7469. if ( mode == OUTPUT )
  7470. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
  7471. else
  7472. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
  7473. errorText_ = errorStream_.str();
  7474. return FAILURE;
  7475. }
  7476. int flags = 0;
  7477. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7478. if ( mode == OUTPUT )
  7479. flags |= O_WRONLY;
  7480. else { // mode == INPUT
  7481. if (stream_.mode == OUTPUT && stream_.device[0] == device) {
  7482. // We just set the same device for playback ... close and reopen for duplex (OSS only).
  7483. close( handle->id[0] );
  7484. handle->id[0] = 0;
  7485. if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
  7486. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
  7487. errorText_ = errorStream_.str();
  7488. return FAILURE;
  7489. }
  7490. // Check that the number previously set channels is the same.
  7491. if ( stream_.nUserChannels[0] != channels ) {
  7492. errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
  7493. errorText_ = errorStream_.str();
  7494. return FAILURE;
  7495. }
  7496. flags |= O_RDWR;
  7497. }
  7498. else
  7499. flags |= O_RDONLY;
  7500. }
  7501. // Set exclusive access if specified.
  7502. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
  7503. // Try to open the device.
  7504. int fd;
  7505. fd = open( ainfo.devnode, flags, 0 );
  7506. if ( fd == -1 ) {
  7507. if ( errno == EBUSY )
  7508. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
  7509. else
  7510. errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
  7511. errorText_ = errorStream_.str();
  7512. return FAILURE;
  7513. }
  7514. // For duplex operation, specifically set this mode (this doesn't seem to work).
  7515. /*
  7516. if ( flags | O_RDWR ) {
  7517. result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
  7518. if ( result == -1) {
  7519. errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
  7520. errorText_ = errorStream_.str();
  7521. return FAILURE;
  7522. }
  7523. }
  7524. */
  7525. // Check the device channel support.
  7526. stream_.nUserChannels[mode] = channels;
  7527. if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
  7528. close( fd );
  7529. errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
  7530. errorText_ = errorStream_.str();
  7531. return FAILURE;
  7532. }
  7533. // Set the number of channels.
  7534. int deviceChannels = channels + firstChannel;
  7535. result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
  7536. if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
  7537. close( fd );
  7538. errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
  7539. errorText_ = errorStream_.str();
  7540. return FAILURE;
  7541. }
  7542. stream_.nDeviceChannels[mode] = deviceChannels;
  7543. // Get the data format mask
  7544. int mask;
  7545. result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
  7546. if ( result == -1 ) {
  7547. close( fd );
  7548. errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
  7549. errorText_ = errorStream_.str();
  7550. return FAILURE;
  7551. }
  7552. // Determine how to set the device format.
  7553. stream_.userFormat = format;
  7554. int deviceFormat = -1;
  7555. stream_.doByteSwap[mode] = false;
  7556. if ( format == RTAUDIO_SINT8 ) {
  7557. if ( mask & AFMT_S8 ) {
  7558. deviceFormat = AFMT_S8;
  7559. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7560. }
  7561. }
  7562. else if ( format == RTAUDIO_SINT16 ) {
  7563. if ( mask & AFMT_S16_NE ) {
  7564. deviceFormat = AFMT_S16_NE;
  7565. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7566. }
  7567. else if ( mask & AFMT_S16_OE ) {
  7568. deviceFormat = AFMT_S16_OE;
  7569. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7570. stream_.doByteSwap[mode] = true;
  7571. }
  7572. }
  7573. else if ( format == RTAUDIO_SINT24 ) {
  7574. if ( mask & AFMT_S24_NE ) {
  7575. deviceFormat = AFMT_S24_NE;
  7576. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7577. }
  7578. else if ( mask & AFMT_S24_OE ) {
  7579. deviceFormat = AFMT_S24_OE;
  7580. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7581. stream_.doByteSwap[mode] = true;
  7582. }
  7583. }
  7584. else if ( format == RTAUDIO_SINT32 ) {
  7585. if ( mask & AFMT_S32_NE ) {
  7586. deviceFormat = AFMT_S32_NE;
  7587. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7588. }
  7589. else if ( mask & AFMT_S32_OE ) {
  7590. deviceFormat = AFMT_S32_OE;
  7591. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7592. stream_.doByteSwap[mode] = true;
  7593. }
  7594. }
  7595. if ( deviceFormat == -1 ) {
  7596. // The user requested format is not natively supported by the device.
  7597. if ( mask & AFMT_S16_NE ) {
  7598. deviceFormat = AFMT_S16_NE;
  7599. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7600. }
  7601. else if ( mask & AFMT_S32_NE ) {
  7602. deviceFormat = AFMT_S32_NE;
  7603. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7604. }
  7605. else if ( mask & AFMT_S24_NE ) {
  7606. deviceFormat = AFMT_S24_NE;
  7607. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7608. }
  7609. else if ( mask & AFMT_S16_OE ) {
  7610. deviceFormat = AFMT_S16_OE;
  7611. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7612. stream_.doByteSwap[mode] = true;
  7613. }
  7614. else if ( mask & AFMT_S32_OE ) {
  7615. deviceFormat = AFMT_S32_OE;
  7616. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7617. stream_.doByteSwap[mode] = true;
  7618. }
  7619. else if ( mask & AFMT_S24_OE ) {
  7620. deviceFormat = AFMT_S24_OE;
  7621. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7622. stream_.doByteSwap[mode] = true;
  7623. }
  7624. else if ( mask & AFMT_S8) {
  7625. deviceFormat = AFMT_S8;
  7626. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7627. }
  7628. }
  7629. if ( stream_.deviceFormat[mode] == 0 ) {
  7630. // This really shouldn't happen ...
  7631. close( fd );
  7632. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7633. errorText_ = errorStream_.str();
  7634. return FAILURE;
  7635. }
  7636. // Set the data format.
  7637. int temp = deviceFormat;
  7638. result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
  7639. if ( result == -1 || deviceFormat != temp ) {
  7640. close( fd );
  7641. errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
  7642. errorText_ = errorStream_.str();
  7643. return FAILURE;
  7644. }
  7645. // Attempt to set the buffer size. According to OSS, the minimum
  7646. // number of buffers is two. The supposed minimum buffer size is 16
  7647. // bytes, so that will be our lower bound. The argument to this
  7648. // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
  7649. // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
  7650. // We'll check the actual value used near the end of the setup
  7651. // procedure.
  7652. int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
  7653. if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
  7654. int buffers = 0;
  7655. if ( options ) buffers = options->numberOfBuffers;
  7656. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
  7657. if ( buffers < 2 ) buffers = 3;
  7658. temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
  7659. result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
  7660. if ( result == -1 ) {
  7661. close( fd );
  7662. errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
  7663. errorText_ = errorStream_.str();
  7664. return FAILURE;
  7665. }
  7666. stream_.nBuffers = buffers;
  7667. // Save buffer size (in sample frames).
  7668. *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
  7669. stream_.bufferSize = *bufferSize;
  7670. // Set the sample rate.
  7671. int srate = sampleRate;
  7672. result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
  7673. if ( result == -1 ) {
  7674. close( fd );
  7675. errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
  7676. errorText_ = errorStream_.str();
  7677. return FAILURE;
  7678. }
  7679. // Verify the sample rate setup worked.
  7680. if ( abs( srate - sampleRate ) > 100 ) {
  7681. close( fd );
  7682. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
  7683. errorText_ = errorStream_.str();
  7684. return FAILURE;
  7685. }
  7686. stream_.sampleRate = sampleRate;
  7687. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
  7688. // We're doing duplex setup here.
  7689. stream_.deviceFormat[0] = stream_.deviceFormat[1];
  7690. stream_.nDeviceChannels[0] = deviceChannels;
  7691. }
  7692. // Set interleaving parameters.
  7693. stream_.userInterleaved = true;
  7694. stream_.deviceInterleaved[mode] = true;
  7695. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  7696. stream_.userInterleaved = false;
  7697. // Set flags for buffer conversion
  7698. stream_.doConvertBuffer[mode] = false;
  7699. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7700. stream_.doConvertBuffer[mode] = true;
  7701. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7702. stream_.doConvertBuffer[mode] = true;
  7703. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  7704. stream_.nUserChannels[mode] > 1 )
  7705. stream_.doConvertBuffer[mode] = true;
  7706. // Allocate the stream handles if necessary and then save.
  7707. if ( stream_.apiHandle == 0 ) {
  7708. try {
  7709. handle = new OssHandle;
  7710. }
  7711. catch ( std::bad_alloc& ) {
  7712. errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
  7713. goto error;
  7714. }
  7715. if ( pthread_cond_init( &handle->runnable, NULL ) ) {
  7716. errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
  7717. goto error;
  7718. }
  7719. stream_.apiHandle = (void *) handle;
  7720. }
  7721. else {
  7722. handle = (OssHandle *) stream_.apiHandle;
  7723. }
  7724. handle->id[mode] = fd;
  7725. // Allocate necessary internal buffers.
  7726. unsigned long bufferBytes;
  7727. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7728. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7729. if ( stream_.userBuffer[mode] == NULL ) {
  7730. errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
  7731. goto error;
  7732. }
  7733. if ( stream_.doConvertBuffer[mode] ) {
  7734. bool makeBuffer = true;
  7735. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7736. if ( mode == INPUT ) {
  7737. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7738. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7739. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7740. }
  7741. }
  7742. if ( makeBuffer ) {
  7743. bufferBytes *= *bufferSize;
  7744. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7745. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7746. if ( stream_.deviceBuffer == NULL ) {
  7747. errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
  7748. goto error;
  7749. }
  7750. }
  7751. }
  7752. stream_.device[mode] = device;
  7753. stream_.state = STREAM_STOPPED;
  7754. // Setup the buffer conversion information structure.
  7755. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7756. // Setup thread if necessary.
  7757. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  7758. // We had already set up an output stream.
  7759. stream_.mode = DUPLEX;
  7760. if ( stream_.device[0] == device ) handle->id[0] = fd;
  7761. }
  7762. else {
  7763. stream_.mode = mode;
  7764. // Setup callback thread.
  7765. stream_.callbackInfo.object = (void *) this;
  7766. // Set the thread attributes for joinable and realtime scheduling
  7767. // priority. The higher priority will only take affect if the
  7768. // program is run as root or suid.
  7769. pthread_attr_t attr;
  7770. pthread_attr_init( &attr );
  7771. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  7772. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  7773. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  7774. struct sched_param param;
  7775. int priority = options->priority;
  7776. int min = sched_get_priority_min( SCHED_RR );
  7777. int max = sched_get_priority_max( SCHED_RR );
  7778. if ( priority < min ) priority = min;
  7779. else if ( priority > max ) priority = max;
  7780. param.sched_priority = priority;
  7781. pthread_attr_setschedparam( &attr, &param );
  7782. pthread_attr_setschedpolicy( &attr, SCHED_RR );
  7783. }
  7784. else
  7785. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7786. #else
  7787. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7788. #endif
  7789. stream_.callbackInfo.isRunning = true;
  7790. result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
  7791. pthread_attr_destroy( &attr );
  7792. if ( result ) {
  7793. stream_.callbackInfo.isRunning = false;
  7794. errorText_ = "RtApiOss::error creating callback thread!";
  7795. goto error;
  7796. }
  7797. }
  7798. return SUCCESS;
  7799. error:
  7800. if ( handle ) {
  7801. pthread_cond_destroy( &handle->runnable );
  7802. if ( handle->id[0] ) close( handle->id[0] );
  7803. if ( handle->id[1] ) close( handle->id[1] );
  7804. delete handle;
  7805. stream_.apiHandle = 0;
  7806. }
  7807. for ( int i=0; i<2; i++ ) {
  7808. if ( stream_.userBuffer[i] ) {
  7809. free( stream_.userBuffer[i] );
  7810. stream_.userBuffer[i] = 0;
  7811. }
  7812. }
  7813. if ( stream_.deviceBuffer ) {
  7814. free( stream_.deviceBuffer );
  7815. stream_.deviceBuffer = 0;
  7816. }
  7817. return FAILURE;
  7818. }
  7819. void RtApiOss :: closeStream()
  7820. {
  7821. if ( stream_.state == STREAM_CLOSED ) {
  7822. errorText_ = "RtApiOss::closeStream(): no open stream to close!";
  7823. error( RtAudioError::WARNING );
  7824. return;
  7825. }
  7826. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7827. stream_.callbackInfo.isRunning = false;
  7828. MUTEX_LOCK( &stream_.mutex );
  7829. if ( stream_.state == STREAM_STOPPED )
  7830. pthread_cond_signal( &handle->runnable );
  7831. MUTEX_UNLOCK( &stream_.mutex );
  7832. pthread_join( stream_.callbackInfo.thread, NULL );
  7833. if ( stream_.state == STREAM_RUNNING ) {
  7834. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  7835. ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  7836. else
  7837. ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  7838. stream_.state = STREAM_STOPPED;
  7839. }
  7840. if ( handle ) {
  7841. pthread_cond_destroy( &handle->runnable );
  7842. if ( handle->id[0] ) close( handle->id[0] );
  7843. if ( handle->id[1] ) close( handle->id[1] );
  7844. delete handle;
  7845. stream_.apiHandle = 0;
  7846. }
  7847. for ( int i=0; i<2; i++ ) {
  7848. if ( stream_.userBuffer[i] ) {
  7849. free( stream_.userBuffer[i] );
  7850. stream_.userBuffer[i] = 0;
  7851. }
  7852. }
  7853. if ( stream_.deviceBuffer ) {
  7854. free( stream_.deviceBuffer );
  7855. stream_.deviceBuffer = 0;
  7856. }
  7857. stream_.mode = UNINITIALIZED;
  7858. stream_.state = STREAM_CLOSED;
  7859. }
  7860. void RtApiOss :: startStream()
  7861. {
  7862. verifyStream();
  7863. if ( stream_.state == STREAM_RUNNING ) {
  7864. errorText_ = "RtApiOss::startStream(): the stream is already running!";
  7865. error( RtAudioError::WARNING );
  7866. return;
  7867. }
  7868. MUTEX_LOCK( &stream_.mutex );
  7869. stream_.state = STREAM_RUNNING;
  7870. // No need to do anything else here ... OSS automatically starts
  7871. // when fed samples.
  7872. MUTEX_UNLOCK( &stream_.mutex );
  7873. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7874. pthread_cond_signal( &handle->runnable );
  7875. }
  7876. void RtApiOss :: stopStream()
  7877. {
  7878. verifyStream();
  7879. if ( stream_.state == STREAM_STOPPED ) {
  7880. errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
  7881. error( RtAudioError::WARNING );
  7882. return;
  7883. }
  7884. MUTEX_LOCK( &stream_.mutex );
  7885. // The state might change while waiting on a mutex.
  7886. if ( stream_.state == STREAM_STOPPED ) {
  7887. MUTEX_UNLOCK( &stream_.mutex );
  7888. return;
  7889. }
  7890. int result = 0;
  7891. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7892. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7893. // Flush the output with zeros a few times.
  7894. char *buffer;
  7895. int samples;
  7896. RtAudioFormat format;
  7897. if ( stream_.doConvertBuffer[0] ) {
  7898. buffer = stream_.deviceBuffer;
  7899. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  7900. format = stream_.deviceFormat[0];
  7901. }
  7902. else {
  7903. buffer = stream_.userBuffer[0];
  7904. samples = stream_.bufferSize * stream_.nUserChannels[0];
  7905. format = stream_.userFormat;
  7906. }
  7907. memset( buffer, 0, samples * formatBytes(format) );
  7908. for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
  7909. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  7910. if ( result == -1 ) {
  7911. errorText_ = "RtApiOss::stopStream: audio write error.";
  7912. error( RtAudioError::WARNING );
  7913. }
  7914. }
  7915. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  7916. if ( result == -1 ) {
  7917. errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  7918. errorText_ = errorStream_.str();
  7919. goto unlock;
  7920. }
  7921. handle->triggered = false;
  7922. }
  7923. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  7924. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  7925. if ( result == -1 ) {
  7926. errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  7927. errorText_ = errorStream_.str();
  7928. goto unlock;
  7929. }
  7930. }
  7931. unlock:
  7932. stream_.state = STREAM_STOPPED;
  7933. MUTEX_UNLOCK( &stream_.mutex );
  7934. if ( result != -1 ) return;
  7935. error( RtAudioError::SYSTEM_ERROR );
  7936. }
  7937. void RtApiOss :: abortStream()
  7938. {
  7939. verifyStream();
  7940. if ( stream_.state == STREAM_STOPPED ) {
  7941. errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
  7942. error( RtAudioError::WARNING );
  7943. return;
  7944. }
  7945. MUTEX_LOCK( &stream_.mutex );
  7946. // The state might change while waiting on a mutex.
  7947. if ( stream_.state == STREAM_STOPPED ) {
  7948. MUTEX_UNLOCK( &stream_.mutex );
  7949. return;
  7950. }
  7951. int result = 0;
  7952. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7953. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7954. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  7955. if ( result == -1 ) {
  7956. errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  7957. errorText_ = errorStream_.str();
  7958. goto unlock;
  7959. }
  7960. handle->triggered = false;
  7961. }
  7962. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  7963. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  7964. if ( result == -1 ) {
  7965. errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  7966. errorText_ = errorStream_.str();
  7967. goto unlock;
  7968. }
  7969. }
  7970. unlock:
  7971. stream_.state = STREAM_STOPPED;
  7972. MUTEX_UNLOCK( &stream_.mutex );
  7973. if ( result != -1 ) return;
  7974. error( RtAudioError::SYSTEM_ERROR );
  7975. }
  7976. void RtApiOss :: callbackEvent()
  7977. {
  7978. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7979. if ( stream_.state == STREAM_STOPPED ) {
  7980. MUTEX_LOCK( &stream_.mutex );
  7981. pthread_cond_wait( &handle->runnable, &stream_.mutex );
  7982. if ( stream_.state != STREAM_RUNNING ) {
  7983. MUTEX_UNLOCK( &stream_.mutex );
  7984. return;
  7985. }
  7986. MUTEX_UNLOCK( &stream_.mutex );
  7987. }
  7988. if ( stream_.state == STREAM_CLOSED ) {
  7989. errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
  7990. error( RtAudioError::WARNING );
  7991. return;
  7992. }
  7993. // Invoke user callback to get fresh output data.
  7994. int doStopStream = 0;
  7995. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  7996. double streamTime = getStreamTime();
  7997. RtAudioStreamStatus status = 0;
  7998. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  7999. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  8000. handle->xrun[0] = false;
  8001. }
  8002. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  8003. status |= RTAUDIO_INPUT_OVERFLOW;
  8004. handle->xrun[1] = false;
  8005. }
  8006. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  8007. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  8008. if ( doStopStream == 2 ) {
  8009. this->abortStream();
  8010. return;
  8011. }
  8012. MUTEX_LOCK( &stream_.mutex );
  8013. // The state might change while waiting on a mutex.
  8014. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  8015. int result;
  8016. char *buffer;
  8017. int samples;
  8018. RtAudioFormat format;
  8019. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8020. // Setup parameters and do buffer conversion if necessary.
  8021. if ( stream_.doConvertBuffer[0] ) {
  8022. buffer = stream_.deviceBuffer;
  8023. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  8024. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  8025. format = stream_.deviceFormat[0];
  8026. }
  8027. else {
  8028. buffer = stream_.userBuffer[0];
  8029. samples = stream_.bufferSize * stream_.nUserChannels[0];
  8030. format = stream_.userFormat;
  8031. }
  8032. // Do byte swapping if necessary.
  8033. if ( stream_.doByteSwap[0] )
  8034. byteSwapBuffer( buffer, samples, format );
  8035. if ( stream_.mode == DUPLEX && handle->triggered == false ) {
  8036. int trig = 0;
  8037. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8038. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8039. trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
  8040. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8041. handle->triggered = true;
  8042. }
  8043. else
  8044. // Write samples to device.
  8045. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8046. if ( result == -1 ) {
  8047. // We'll assume this is an underrun, though there isn't a
  8048. // specific means for determining that.
  8049. handle->xrun[0] = true;
  8050. errorText_ = "RtApiOss::callbackEvent: audio write error.";
  8051. error( RtAudioError::WARNING );
  8052. // Continue on to input section.
  8053. }
  8054. }
  8055. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  8056. // Setup parameters.
  8057. if ( stream_.doConvertBuffer[1] ) {
  8058. buffer = stream_.deviceBuffer;
  8059. samples = stream_.bufferSize * stream_.nDeviceChannels[1];
  8060. format = stream_.deviceFormat[1];
  8061. }
  8062. else {
  8063. buffer = stream_.userBuffer[1];
  8064. samples = stream_.bufferSize * stream_.nUserChannels[1];
  8065. format = stream_.userFormat;
  8066. }
  8067. // Read samples from device.
  8068. result = read( handle->id[1], buffer, samples * formatBytes(format) );
  8069. if ( result == -1 ) {
  8070. // We'll assume this is an overrun, though there isn't a
  8071. // specific means for determining that.
  8072. handle->xrun[1] = true;
  8073. errorText_ = "RtApiOss::callbackEvent: audio read error.";
  8074. error( RtAudioError::WARNING );
  8075. goto unlock;
  8076. }
  8077. // Do byte swapping if necessary.
  8078. if ( stream_.doByteSwap[1] )
  8079. byteSwapBuffer( buffer, samples, format );
  8080. // Do buffer conversion if necessary.
  8081. if ( stream_.doConvertBuffer[1] )
  8082. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  8083. }
  8084. unlock:
  8085. MUTEX_UNLOCK( &stream_.mutex );
  8086. RtApi::tickStreamTime();
  8087. if ( doStopStream == 1 ) this->stopStream();
  8088. }
  8089. static void *ossCallbackHandler( void *ptr )
  8090. {
  8091. CallbackInfo *info = (CallbackInfo *) ptr;
  8092. RtApiOss *object = (RtApiOss *) info->object;
  8093. bool *isRunning = &info->isRunning;
  8094. while ( *isRunning == true ) {
  8095. pthread_testcancel();
  8096. object->callbackEvent();
  8097. }
  8098. pthread_exit( NULL );
  8099. }
  8100. //******************** End of __LINUX_OSS__ *********************//
  8101. #endif
  8102. // *************************************************** //
  8103. //
  8104. // Protected common (OS-independent) RtAudio methods.
  8105. //
  8106. // *************************************************** //
  8107. // This method can be modified to control the behavior of error
  8108. // message printing.
  8109. void RtApi :: error( RtAudioError::Type type )
  8110. {
  8111. errorStream_.str(""); // clear the ostringstream
  8112. RtAudioErrorCallback errorCallback = (RtAudioErrorCallback) stream_.callbackInfo.errorCallback;
  8113. if ( errorCallback ) {
  8114. // abortStream() can generate new error messages. Ignore them. Just keep original one.
  8115. if ( firstErrorOccurred_ )
  8116. return;
  8117. firstErrorOccurred_ = true;
  8118. const std::string errorMessage = errorText_;
  8119. if ( type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED) {
  8120. stream_.callbackInfo.isRunning = false; // exit from the thread
  8121. abortStream();
  8122. }
  8123. errorCallback( type, errorMessage );
  8124. firstErrorOccurred_ = false;
  8125. return;
  8126. }
  8127. if ( type == RtAudioError::WARNING && showWarnings_ == true )
  8128. std::cerr << '\n' << errorText_ << "\n\n";
  8129. else if ( type != RtAudioError::WARNING )
  8130. throw( RtAudioError( errorText_, type ) );
  8131. }
  8132. void RtApi :: verifyStream()
  8133. {
  8134. if ( stream_.state == STREAM_CLOSED ) {
  8135. errorText_ = "RtApi:: a stream is not open!";
  8136. error( RtAudioError::INVALID_USE );
  8137. }
  8138. }
  8139. void RtApi :: clearStreamInfo()
  8140. {
  8141. stream_.mode = UNINITIALIZED;
  8142. stream_.state = STREAM_CLOSED;
  8143. stream_.sampleRate = 0;
  8144. stream_.bufferSize = 0;
  8145. stream_.nBuffers = 0;
  8146. stream_.userFormat = 0;
  8147. stream_.userInterleaved = true;
  8148. stream_.streamTime = 0.0;
  8149. stream_.apiHandle = 0;
  8150. stream_.deviceBuffer = 0;
  8151. stream_.callbackInfo.callback = 0;
  8152. stream_.callbackInfo.userData = 0;
  8153. stream_.callbackInfo.isRunning = false;
  8154. stream_.callbackInfo.errorCallback = 0;
  8155. for ( int i=0; i<2; i++ ) {
  8156. stream_.device[i] = 11111;
  8157. stream_.doConvertBuffer[i] = false;
  8158. stream_.deviceInterleaved[i] = true;
  8159. stream_.doByteSwap[i] = false;
  8160. stream_.nUserChannels[i] = 0;
  8161. stream_.nDeviceChannels[i] = 0;
  8162. stream_.channelOffset[i] = 0;
  8163. stream_.deviceFormat[i] = 0;
  8164. stream_.latency[i] = 0;
  8165. stream_.userBuffer[i] = 0;
  8166. stream_.convertInfo[i].channels = 0;
  8167. stream_.convertInfo[i].inJump = 0;
  8168. stream_.convertInfo[i].outJump = 0;
  8169. stream_.convertInfo[i].inFormat = 0;
  8170. stream_.convertInfo[i].outFormat = 0;
  8171. stream_.convertInfo[i].inOffset.clear();
  8172. stream_.convertInfo[i].outOffset.clear();
  8173. }
  8174. }
  8175. unsigned int RtApi :: formatBytes( RtAudioFormat format )
  8176. {
  8177. if ( format == RTAUDIO_SINT16 )
  8178. return 2;
  8179. else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )
  8180. return 4;
  8181. else if ( format == RTAUDIO_FLOAT64 )
  8182. return 8;
  8183. else if ( format == RTAUDIO_SINT24 )
  8184. return 3;
  8185. else if ( format == RTAUDIO_SINT8 )
  8186. return 1;
  8187. errorText_ = "RtApi::formatBytes: undefined format.";
  8188. error( RtAudioError::WARNING );
  8189. return 0;
  8190. }
  8191. void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
  8192. {
  8193. if ( mode == INPUT ) { // convert device to user buffer
  8194. stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
  8195. stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
  8196. stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
  8197. stream_.convertInfo[mode].outFormat = stream_.userFormat;
  8198. }
  8199. else { // convert user to device buffer
  8200. stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
  8201. stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
  8202. stream_.convertInfo[mode].inFormat = stream_.userFormat;
  8203. stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
  8204. }
  8205. if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
  8206. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
  8207. else
  8208. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
  8209. // Set up the interleave/deinterleave offsets.
  8210. if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
  8211. if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
  8212. ( mode == INPUT && stream_.userInterleaved ) ) {
  8213. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8214. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8215. stream_.convertInfo[mode].outOffset.push_back( k );
  8216. stream_.convertInfo[mode].inJump = 1;
  8217. }
  8218. }
  8219. else {
  8220. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8221. stream_.convertInfo[mode].inOffset.push_back( k );
  8222. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8223. stream_.convertInfo[mode].outJump = 1;
  8224. }
  8225. }
  8226. }
  8227. else { // no (de)interleaving
  8228. if ( stream_.userInterleaved ) {
  8229. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8230. stream_.convertInfo[mode].inOffset.push_back( k );
  8231. stream_.convertInfo[mode].outOffset.push_back( k );
  8232. }
  8233. }
  8234. else {
  8235. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8236. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8237. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8238. stream_.convertInfo[mode].inJump = 1;
  8239. stream_.convertInfo[mode].outJump = 1;
  8240. }
  8241. }
  8242. }
  8243. // Add channel offset.
  8244. if ( firstChannel > 0 ) {
  8245. if ( stream_.deviceInterleaved[mode] ) {
  8246. if ( mode == OUTPUT ) {
  8247. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8248. stream_.convertInfo[mode].outOffset[k] += firstChannel;
  8249. }
  8250. else {
  8251. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8252. stream_.convertInfo[mode].inOffset[k] += firstChannel;
  8253. }
  8254. }
  8255. else {
  8256. if ( mode == OUTPUT ) {
  8257. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8258. stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
  8259. }
  8260. else {
  8261. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8262. stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize );
  8263. }
  8264. }
  8265. }
  8266. }
  8267. void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
  8268. {
  8269. // This function does format conversion, input/output channel compensation, and
  8270. // data interleaving/deinterleaving. 24-bit integers are assumed to occupy
  8271. // the lower three bytes of a 32-bit integer.
  8272. // Clear our device buffer when in/out duplex device channels are different
  8273. if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
  8274. ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
  8275. memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
  8276. int j;
  8277. if (info.outFormat == RTAUDIO_FLOAT64) {
  8278. Float64 scale;
  8279. Float64 *out = (Float64 *)outBuffer;
  8280. if (info.inFormat == RTAUDIO_SINT8) {
  8281. signed char *in = (signed char *)inBuffer;
  8282. scale = 1.0 / 127.5;
  8283. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8284. for (j=0; j<info.channels; j++) {
  8285. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8286. out[info.outOffset[j]] += 0.5;
  8287. out[info.outOffset[j]] *= scale;
  8288. }
  8289. in += info.inJump;
  8290. out += info.outJump;
  8291. }
  8292. }
  8293. else if (info.inFormat == RTAUDIO_SINT16) {
  8294. Int16 *in = (Int16 *)inBuffer;
  8295. scale = 1.0 / 32767.5;
  8296. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8297. for (j=0; j<info.channels; j++) {
  8298. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8299. out[info.outOffset[j]] += 0.5;
  8300. out[info.outOffset[j]] *= scale;
  8301. }
  8302. in += info.inJump;
  8303. out += info.outJump;
  8304. }
  8305. }
  8306. else if (info.inFormat == RTAUDIO_SINT24) {
  8307. Int24 *in = (Int24 *)inBuffer;
  8308. scale = 1.0 / 8388607.5;
  8309. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8310. for (j=0; j<info.channels; j++) {
  8311. out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());
  8312. out[info.outOffset[j]] += 0.5;
  8313. out[info.outOffset[j]] *= scale;
  8314. }
  8315. in += info.inJump;
  8316. out += info.outJump;
  8317. }
  8318. }
  8319. else if (info.inFormat == RTAUDIO_SINT32) {
  8320. Int32 *in = (Int32 *)inBuffer;
  8321. scale = 1.0 / 2147483647.5;
  8322. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8323. for (j=0; j<info.channels; j++) {
  8324. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8325. out[info.outOffset[j]] += 0.5;
  8326. out[info.outOffset[j]] *= scale;
  8327. }
  8328. in += info.inJump;
  8329. out += info.outJump;
  8330. }
  8331. }
  8332. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8333. Float32 *in = (Float32 *)inBuffer;
  8334. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8335. for (j=0; j<info.channels; j++) {
  8336. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8337. }
  8338. in += info.inJump;
  8339. out += info.outJump;
  8340. }
  8341. }
  8342. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8343. // Channel compensation and/or (de)interleaving only.
  8344. Float64 *in = (Float64 *)inBuffer;
  8345. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8346. for (j=0; j<info.channels; j++) {
  8347. out[info.outOffset[j]] = in[info.inOffset[j]];
  8348. }
  8349. in += info.inJump;
  8350. out += info.outJump;
  8351. }
  8352. }
  8353. }
  8354. else if (info.outFormat == RTAUDIO_FLOAT32) {
  8355. Float32 scale;
  8356. Float32 *out = (Float32 *)outBuffer;
  8357. if (info.inFormat == RTAUDIO_SINT8) {
  8358. signed char *in = (signed char *)inBuffer;
  8359. scale = (Float32) ( 1.0 / 127.5 );
  8360. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8361. for (j=0; j<info.channels; j++) {
  8362. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8363. out[info.outOffset[j]] += 0.5;
  8364. out[info.outOffset[j]] *= scale;
  8365. }
  8366. in += info.inJump;
  8367. out += info.outJump;
  8368. }
  8369. }
  8370. else if (info.inFormat == RTAUDIO_SINT16) {
  8371. Int16 *in = (Int16 *)inBuffer;
  8372. scale = (Float32) ( 1.0 / 32767.5 );
  8373. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8374. for (j=0; j<info.channels; j++) {
  8375. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8376. out[info.outOffset[j]] += 0.5;
  8377. out[info.outOffset[j]] *= scale;
  8378. }
  8379. in += info.inJump;
  8380. out += info.outJump;
  8381. }
  8382. }
  8383. else if (info.inFormat == RTAUDIO_SINT24) {
  8384. Int24 *in = (Int24 *)inBuffer;
  8385. scale = (Float32) ( 1.0 / 8388607.5 );
  8386. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8387. for (j=0; j<info.channels; j++) {
  8388. out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());
  8389. out[info.outOffset[j]] += 0.5;
  8390. out[info.outOffset[j]] *= scale;
  8391. }
  8392. in += info.inJump;
  8393. out += info.outJump;
  8394. }
  8395. }
  8396. else if (info.inFormat == RTAUDIO_SINT32) {
  8397. Int32 *in = (Int32 *)inBuffer;
  8398. scale = (Float32) ( 1.0 / 2147483647.5 );
  8399. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8400. for (j=0; j<info.channels; j++) {
  8401. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8402. out[info.outOffset[j]] += 0.5;
  8403. out[info.outOffset[j]] *= scale;
  8404. }
  8405. in += info.inJump;
  8406. out += info.outJump;
  8407. }
  8408. }
  8409. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8410. // Channel compensation and/or (de)interleaving only.
  8411. Float32 *in = (Float32 *)inBuffer;
  8412. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8413. for (j=0; j<info.channels; j++) {
  8414. out[info.outOffset[j]] = in[info.inOffset[j]];
  8415. }
  8416. in += info.inJump;
  8417. out += info.outJump;
  8418. }
  8419. }
  8420. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8421. Float64 *in = (Float64 *)inBuffer;
  8422. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8423. for (j=0; j<info.channels; j++) {
  8424. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8425. }
  8426. in += info.inJump;
  8427. out += info.outJump;
  8428. }
  8429. }
  8430. }
  8431. else if (info.outFormat == RTAUDIO_SINT32) {
  8432. Int32 *out = (Int32 *)outBuffer;
  8433. if (info.inFormat == RTAUDIO_SINT8) {
  8434. signed char *in = (signed char *)inBuffer;
  8435. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8436. for (j=0; j<info.channels; j++) {
  8437. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8438. out[info.outOffset[j]] <<= 24;
  8439. }
  8440. in += info.inJump;
  8441. out += info.outJump;
  8442. }
  8443. }
  8444. else if (info.inFormat == RTAUDIO_SINT16) {
  8445. Int16 *in = (Int16 *)inBuffer;
  8446. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8447. for (j=0; j<info.channels; j++) {
  8448. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8449. out[info.outOffset[j]] <<= 16;
  8450. }
  8451. in += info.inJump;
  8452. out += info.outJump;
  8453. }
  8454. }
  8455. else if (info.inFormat == RTAUDIO_SINT24) {
  8456. Int24 *in = (Int24 *)inBuffer;
  8457. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8458. for (j=0; j<info.channels; j++) {
  8459. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();
  8460. out[info.outOffset[j]] <<= 8;
  8461. }
  8462. in += info.inJump;
  8463. out += info.outJump;
  8464. }
  8465. }
  8466. else if (info.inFormat == RTAUDIO_SINT32) {
  8467. // Channel compensation and/or (de)interleaving only.
  8468. Int32 *in = (Int32 *)inBuffer;
  8469. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8470. for (j=0; j<info.channels; j++) {
  8471. out[info.outOffset[j]] = in[info.inOffset[j]];
  8472. }
  8473. in += info.inJump;
  8474. out += info.outJump;
  8475. }
  8476. }
  8477. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8478. Float32 *in = (Float32 *)inBuffer;
  8479. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8480. for (j=0; j<info.channels; j++) {
  8481. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8482. }
  8483. in += info.inJump;
  8484. out += info.outJump;
  8485. }
  8486. }
  8487. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8488. Float64 *in = (Float64 *)inBuffer;
  8489. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8490. for (j=0; j<info.channels; j++) {
  8491. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8492. }
  8493. in += info.inJump;
  8494. out += info.outJump;
  8495. }
  8496. }
  8497. }
  8498. else if (info.outFormat == RTAUDIO_SINT24) {
  8499. Int24 *out = (Int24 *)outBuffer;
  8500. if (info.inFormat == RTAUDIO_SINT8) {
  8501. signed char *in = (signed char *)inBuffer;
  8502. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8503. for (j=0; j<info.channels; j++) {
  8504. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);
  8505. //out[info.outOffset[j]] <<= 16;
  8506. }
  8507. in += info.inJump;
  8508. out += info.outJump;
  8509. }
  8510. }
  8511. else if (info.inFormat == RTAUDIO_SINT16) {
  8512. Int16 *in = (Int16 *)inBuffer;
  8513. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8514. for (j=0; j<info.channels; j++) {
  8515. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);
  8516. //out[info.outOffset[j]] <<= 8;
  8517. }
  8518. in += info.inJump;
  8519. out += info.outJump;
  8520. }
  8521. }
  8522. else if (info.inFormat == RTAUDIO_SINT24) {
  8523. // Channel compensation and/or (de)interleaving only.
  8524. Int24 *in = (Int24 *)inBuffer;
  8525. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8526. for (j=0; j<info.channels; j++) {
  8527. out[info.outOffset[j]] = in[info.inOffset[j]];
  8528. }
  8529. in += info.inJump;
  8530. out += info.outJump;
  8531. }
  8532. }
  8533. else if (info.inFormat == RTAUDIO_SINT32) {
  8534. Int32 *in = (Int32 *)inBuffer;
  8535. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8536. for (j=0; j<info.channels; j++) {
  8537. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);
  8538. //out[info.outOffset[j]] >>= 8;
  8539. }
  8540. in += info.inJump;
  8541. out += info.outJump;
  8542. }
  8543. }
  8544. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8545. Float32 *in = (Float32 *)inBuffer;
  8546. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8547. for (j=0; j<info.channels; j++) {
  8548. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8549. }
  8550. in += info.inJump;
  8551. out += info.outJump;
  8552. }
  8553. }
  8554. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8555. Float64 *in = (Float64 *)inBuffer;
  8556. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8557. for (j=0; j<info.channels; j++) {
  8558. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8559. }
  8560. in += info.inJump;
  8561. out += info.outJump;
  8562. }
  8563. }
  8564. }
  8565. else if (info.outFormat == RTAUDIO_SINT16) {
  8566. Int16 *out = (Int16 *)outBuffer;
  8567. if (info.inFormat == RTAUDIO_SINT8) {
  8568. signed char *in = (signed char *)inBuffer;
  8569. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8570. for (j=0; j<info.channels; j++) {
  8571. out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
  8572. out[info.outOffset[j]] <<= 8;
  8573. }
  8574. in += info.inJump;
  8575. out += info.outJump;
  8576. }
  8577. }
  8578. else if (info.inFormat == RTAUDIO_SINT16) {
  8579. // Channel compensation and/or (de)interleaving only.
  8580. Int16 *in = (Int16 *)inBuffer;
  8581. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8582. for (j=0; j<info.channels; j++) {
  8583. out[info.outOffset[j]] = in[info.inOffset[j]];
  8584. }
  8585. in += info.inJump;
  8586. out += info.outJump;
  8587. }
  8588. }
  8589. else if (info.inFormat == RTAUDIO_SINT24) {
  8590. Int24 *in = (Int24 *)inBuffer;
  8591. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8592. for (j=0; j<info.channels; j++) {
  8593. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);
  8594. }
  8595. in += info.inJump;
  8596. out += info.outJump;
  8597. }
  8598. }
  8599. else if (info.inFormat == RTAUDIO_SINT32) {
  8600. Int32 *in = (Int32 *)inBuffer;
  8601. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8602. for (j=0; j<info.channels; j++) {
  8603. out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
  8604. }
  8605. in += info.inJump;
  8606. out += info.outJump;
  8607. }
  8608. }
  8609. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8610. Float32 *in = (Float32 *)inBuffer;
  8611. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8612. for (j=0; j<info.channels; j++) {
  8613. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  8614. }
  8615. in += info.inJump;
  8616. out += info.outJump;
  8617. }
  8618. }
  8619. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8620. Float64 *in = (Float64 *)inBuffer;
  8621. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8622. for (j=0; j<info.channels; j++) {
  8623. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  8624. }
  8625. in += info.inJump;
  8626. out += info.outJump;
  8627. }
  8628. }
  8629. }
  8630. else if (info.outFormat == RTAUDIO_SINT8) {
  8631. signed char *out = (signed char *)outBuffer;
  8632. if (info.inFormat == RTAUDIO_SINT8) {
  8633. // Channel compensation and/or (de)interleaving only.
  8634. signed char *in = (signed char *)inBuffer;
  8635. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8636. for (j=0; j<info.channels; j++) {
  8637. out[info.outOffset[j]] = in[info.inOffset[j]];
  8638. }
  8639. in += info.inJump;
  8640. out += info.outJump;
  8641. }
  8642. }
  8643. if (info.inFormat == RTAUDIO_SINT16) {
  8644. Int16 *in = (Int16 *)inBuffer;
  8645. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8646. for (j=0; j<info.channels; j++) {
  8647. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
  8648. }
  8649. in += info.inJump;
  8650. out += info.outJump;
  8651. }
  8652. }
  8653. else if (info.inFormat == RTAUDIO_SINT24) {
  8654. Int24 *in = (Int24 *)inBuffer;
  8655. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8656. for (j=0; j<info.channels; j++) {
  8657. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);
  8658. }
  8659. in += info.inJump;
  8660. out += info.outJump;
  8661. }
  8662. }
  8663. else if (info.inFormat == RTAUDIO_SINT32) {
  8664. Int32 *in = (Int32 *)inBuffer;
  8665. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8666. for (j=0; j<info.channels; j++) {
  8667. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
  8668. }
  8669. in += info.inJump;
  8670. out += info.outJump;
  8671. }
  8672. }
  8673. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8674. Float32 *in = (Float32 *)inBuffer;
  8675. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8676. for (j=0; j<info.channels; j++) {
  8677. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  8678. }
  8679. in += info.inJump;
  8680. out += info.outJump;
  8681. }
  8682. }
  8683. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8684. Float64 *in = (Float64 *)inBuffer;
  8685. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8686. for (j=0; j<info.channels; j++) {
  8687. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  8688. }
  8689. in += info.inJump;
  8690. out += info.outJump;
  8691. }
  8692. }
  8693. }
  8694. }
  8695. //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
  8696. //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
  8697. //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
  8698. void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
  8699. {
  8700. register char val;
  8701. register char *ptr;
  8702. ptr = buffer;
  8703. if ( format == RTAUDIO_SINT16 ) {
  8704. for ( unsigned int i=0; i<samples; i++ ) {
  8705. // Swap 1st and 2nd bytes.
  8706. val = *(ptr);
  8707. *(ptr) = *(ptr+1);
  8708. *(ptr+1) = val;
  8709. // Increment 2 bytes.
  8710. ptr += 2;
  8711. }
  8712. }
  8713. else if ( format == RTAUDIO_SINT32 ||
  8714. format == RTAUDIO_FLOAT32 ) {
  8715. for ( unsigned int i=0; i<samples; i++ ) {
  8716. // Swap 1st and 4th bytes.
  8717. val = *(ptr);
  8718. *(ptr) = *(ptr+3);
  8719. *(ptr+3) = val;
  8720. // Swap 2nd and 3rd bytes.
  8721. ptr += 1;
  8722. val = *(ptr);
  8723. *(ptr) = *(ptr+1);
  8724. *(ptr+1) = val;
  8725. // Increment 3 more bytes.
  8726. ptr += 3;
  8727. }
  8728. }
  8729. else if ( format == RTAUDIO_SINT24 ) {
  8730. for ( unsigned int i=0; i<samples; i++ ) {
  8731. // Swap 1st and 3rd bytes.
  8732. val = *(ptr);
  8733. *(ptr) = *(ptr+2);
  8734. *(ptr+2) = val;
  8735. // Increment 2 more bytes.
  8736. ptr += 2;
  8737. }
  8738. }
  8739. else if ( format == RTAUDIO_FLOAT64 ) {
  8740. for ( unsigned int i=0; i<samples; i++ ) {
  8741. // Swap 1st and 8th bytes
  8742. val = *(ptr);
  8743. *(ptr) = *(ptr+7);
  8744. *(ptr+7) = val;
  8745. // Swap 2nd and 7th bytes
  8746. ptr += 1;
  8747. val = *(ptr);
  8748. *(ptr) = *(ptr+5);
  8749. *(ptr+5) = val;
  8750. // Swap 3rd and 6th bytes
  8751. ptr += 1;
  8752. val = *(ptr);
  8753. *(ptr) = *(ptr+3);
  8754. *(ptr+3) = val;
  8755. // Swap 4th and 5th bytes
  8756. ptr += 1;
  8757. val = *(ptr);
  8758. *(ptr) = *(ptr+1);
  8759. *(ptr+1) = val;
  8760. // Increment 5 more bytes.
  8761. ptr += 5;
  8762. }
  8763. }
  8764. }
  8765. // Indentation settings for Vim and Emacs
  8766. //
  8767. // Local Variables:
  8768. // c-basic-offset: 2
  8769. // indent-tabs-mode: nil
  8770. // End:
  8771. //
  8772. // vim: et sts=2 sw=2