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.

10138 lines
357KB

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