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.

10334 lines
355KB

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