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.

10230 lines
361KB

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