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. // for cmath functions
  3345. using namespace std;
  3346. outSampleCount = ( unsigned int ) roundf( inSampleCount * sampleRatio );
  3347. // if inSampleRate is a multiple of outSampleRate (or vice versa) there's no need to interpolate
  3348. if ( floor( sampleRatio ) == sampleRatio || floor( sampleRatioInv ) == sampleRatioInv )
  3349. {
  3350. // frame-by-frame, copy each relative input sample into it's corresponding output sample
  3351. for ( unsigned int outSample = 0; outSample < outSampleCount; outSample++ )
  3352. {
  3353. unsigned int inSample = ( unsigned int ) inSampleFraction;
  3354. switch ( format )
  3355. {
  3356. case RTAUDIO_SINT8:
  3357. memcpy( &( ( char* ) outBuffer )[ outSample * channelCount ], &( ( char* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( char ) );
  3358. break;
  3359. case RTAUDIO_SINT16:
  3360. memcpy( &( ( short* ) outBuffer )[ outSample * channelCount ], &( ( short* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( short ) );
  3361. break;
  3362. case RTAUDIO_SINT24:
  3363. memcpy( &( ( S24* ) outBuffer )[ outSample * channelCount ], &( ( S24* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( S24 ) );
  3364. break;
  3365. case RTAUDIO_SINT32:
  3366. memcpy( &( ( int* ) outBuffer )[ outSample * channelCount ], &( ( int* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( int ) );
  3367. break;
  3368. case RTAUDIO_FLOAT32:
  3369. memcpy( &( ( float* ) outBuffer )[ outSample * channelCount ], &( ( float* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( float ) );
  3370. break;
  3371. case RTAUDIO_FLOAT64:
  3372. memcpy( &( ( double* ) outBuffer )[ outSample * channelCount ], &( ( double* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( double ) );
  3373. break;
  3374. }
  3375. // jump to next in sample
  3376. inSampleFraction += sampleStep;
  3377. }
  3378. }
  3379. else // else interpolate
  3380. {
  3381. // frame-by-frame, copy each relative input sample into it's corresponding output sample
  3382. for ( unsigned int outSample = 0; outSample < outSampleCount; outSample++ )
  3383. {
  3384. unsigned int inSample = ( unsigned int ) inSampleFraction;
  3385. float inSampleDec = inSampleFraction - inSample;
  3386. unsigned int frameInSample = inSample * channelCount;
  3387. unsigned int frameOutSample = outSample * channelCount;
  3388. switch ( format )
  3389. {
  3390. case RTAUDIO_SINT8:
  3391. {
  3392. for ( unsigned int channel = 0; channel < channelCount; channel++ )
  3393. {
  3394. char fromSample = ( ( char* ) inBuffer )[ frameInSample + channel ];
  3395. char toSample = ( ( char* ) inBuffer )[ frameInSample + channelCount + channel ];
  3396. char sampleDiff = ( char ) ( ( toSample - fromSample ) * inSampleDec );
  3397. ( ( char* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;
  3398. }
  3399. break;
  3400. }
  3401. case RTAUDIO_SINT16:
  3402. {
  3403. for ( unsigned int channel = 0; channel < channelCount; channel++ )
  3404. {
  3405. short fromSample = ( ( short* ) inBuffer )[ frameInSample + channel ];
  3406. short toSample = ( ( short* ) inBuffer )[ frameInSample + channelCount + channel ];
  3407. short sampleDiff = ( short ) ( ( toSample - fromSample ) * inSampleDec );
  3408. ( ( short* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;
  3409. }
  3410. break;
  3411. }
  3412. case RTAUDIO_SINT24:
  3413. {
  3414. for ( unsigned int channel = 0; channel < channelCount; channel++ )
  3415. {
  3416. int fromSample = ( ( S24* ) inBuffer )[ frameInSample + channel ].asInt();
  3417. int toSample = ( ( S24* ) inBuffer )[ frameInSample + channelCount + channel ].asInt();
  3418. int sampleDiff = ( int ) ( ( toSample - fromSample ) * inSampleDec );
  3419. ( ( S24* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;
  3420. }
  3421. break;
  3422. }
  3423. case RTAUDIO_SINT32:
  3424. {
  3425. for ( unsigned int channel = 0; channel < channelCount; channel++ )
  3426. {
  3427. int fromSample = ( ( int* ) inBuffer )[ frameInSample + channel ];
  3428. int toSample = ( ( int* ) inBuffer )[ frameInSample + channelCount + channel ];
  3429. int sampleDiff = ( int ) ( ( toSample - fromSample ) * inSampleDec );
  3430. ( ( int* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;
  3431. }
  3432. break;
  3433. }
  3434. case RTAUDIO_FLOAT32:
  3435. {
  3436. for ( unsigned int channel = 0; channel < channelCount; channel++ )
  3437. {
  3438. float fromSample = ( ( float* ) inBuffer )[ frameInSample + channel ];
  3439. float toSample = ( ( float* ) inBuffer )[ frameInSample + channelCount + channel ];
  3440. float sampleDiff = ( toSample - fromSample ) * inSampleDec;
  3441. ( ( float* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;
  3442. }
  3443. break;
  3444. }
  3445. case RTAUDIO_FLOAT64:
  3446. {
  3447. for ( unsigned int channel = 0; channel < channelCount; channel++ )
  3448. {
  3449. double fromSample = ( ( double* ) inBuffer )[ frameInSample + channel ];
  3450. double toSample = ( ( double* ) inBuffer )[ frameInSample + channelCount + channel ];
  3451. double sampleDiff = ( toSample - fromSample ) * inSampleDec;
  3452. ( ( double* ) outBuffer )[ frameOutSample + channel ] = fromSample + sampleDiff;
  3453. }
  3454. break;
  3455. }
  3456. }
  3457. // jump to next in sample
  3458. inSampleFraction += sampleStep;
  3459. }
  3460. }
  3461. }
  3462. //-----------------------------------------------------------------------------
  3463. // A structure to hold various information related to the WASAPI implementation.
  3464. struct WasapiHandle
  3465. {
  3466. IAudioClient* captureAudioClient;
  3467. IAudioClient* renderAudioClient;
  3468. IAudioCaptureClient* captureClient;
  3469. IAudioRenderClient* renderClient;
  3470. HANDLE captureEvent;
  3471. HANDLE renderEvent;
  3472. WasapiHandle()
  3473. : captureAudioClient( NULL ),
  3474. renderAudioClient( NULL ),
  3475. captureClient( NULL ),
  3476. renderClient( NULL ),
  3477. captureEvent( NULL ),
  3478. renderEvent( NULL ) {}
  3479. };
  3480. //=============================================================================
  3481. RtApiWasapi::RtApiWasapi()
  3482. : coInitialized_( false ), deviceEnumerator_( NULL )
  3483. {
  3484. // WASAPI can run either apartment or multi-threaded
  3485. HRESULT hr = CoInitialize( NULL );
  3486. if ( !FAILED( hr ) )
  3487. coInitialized_ = true;
  3488. // Instantiate device enumerator
  3489. hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
  3490. CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
  3491. ( void** ) &deviceEnumerator_ );
  3492. if ( FAILED( hr ) ) {
  3493. errorText_ = "RtApiWasapi::RtApiWasapi: Unable to instantiate device enumerator";
  3494. error( RtAudioError::DRIVER_ERROR );
  3495. }
  3496. }
  3497. //-----------------------------------------------------------------------------
  3498. RtApiWasapi::~RtApiWasapi()
  3499. {
  3500. if ( stream_.state != STREAM_CLOSED )
  3501. closeStream();
  3502. SAFE_RELEASE( deviceEnumerator_ );
  3503. // If this object previously called CoInitialize()
  3504. if ( coInitialized_ )
  3505. CoUninitialize();
  3506. }
  3507. //=============================================================================
  3508. unsigned int RtApiWasapi::getDeviceCount( void )
  3509. {
  3510. unsigned int captureDeviceCount = 0;
  3511. unsigned int renderDeviceCount = 0;
  3512. IMMDeviceCollection* captureDevices = NULL;
  3513. IMMDeviceCollection* renderDevices = NULL;
  3514. // Count capture devices
  3515. errorText_.clear();
  3516. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3517. if ( FAILED( hr ) ) {
  3518. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
  3519. goto Exit;
  3520. }
  3521. hr = captureDevices->GetCount( &captureDeviceCount );
  3522. if ( FAILED( hr ) ) {
  3523. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
  3524. goto Exit;
  3525. }
  3526. // Count render devices
  3527. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3528. if ( FAILED( hr ) ) {
  3529. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
  3530. goto Exit;
  3531. }
  3532. hr = renderDevices->GetCount( &renderDeviceCount );
  3533. if ( FAILED( hr ) ) {
  3534. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
  3535. goto Exit;
  3536. }
  3537. Exit:
  3538. // release all references
  3539. SAFE_RELEASE( captureDevices );
  3540. SAFE_RELEASE( renderDevices );
  3541. if ( errorText_.empty() )
  3542. return captureDeviceCount + renderDeviceCount;
  3543. error( RtAudioError::DRIVER_ERROR );
  3544. return 0;
  3545. }
  3546. //-----------------------------------------------------------------------------
  3547. RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
  3548. {
  3549. RtAudio::DeviceInfo info;
  3550. unsigned int captureDeviceCount = 0;
  3551. unsigned int renderDeviceCount = 0;
  3552. std::string defaultDeviceName;
  3553. bool isCaptureDevice = false;
  3554. PROPVARIANT deviceNameProp;
  3555. PROPVARIANT defaultDeviceNameProp;
  3556. IMMDeviceCollection* captureDevices = NULL;
  3557. IMMDeviceCollection* renderDevices = NULL;
  3558. IMMDevice* devicePtr = NULL;
  3559. IMMDevice* defaultDevicePtr = NULL;
  3560. IAudioClient* audioClient = NULL;
  3561. IPropertyStore* devicePropStore = NULL;
  3562. IPropertyStore* defaultDevicePropStore = NULL;
  3563. WAVEFORMATEX* deviceFormat = NULL;
  3564. WAVEFORMATEX* closestMatchFormat = NULL;
  3565. // probed
  3566. info.probed = false;
  3567. // Count capture devices
  3568. errorText_.clear();
  3569. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3570. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3571. if ( FAILED( hr ) ) {
  3572. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
  3573. goto Exit;
  3574. }
  3575. hr = captureDevices->GetCount( &captureDeviceCount );
  3576. if ( FAILED( hr ) ) {
  3577. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
  3578. goto Exit;
  3579. }
  3580. // Count render devices
  3581. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3582. if ( FAILED( hr ) ) {
  3583. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
  3584. goto Exit;
  3585. }
  3586. hr = renderDevices->GetCount( &renderDeviceCount );
  3587. if ( FAILED( hr ) ) {
  3588. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
  3589. goto Exit;
  3590. }
  3591. // validate device index
  3592. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3593. errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
  3594. errorType = RtAudioError::INVALID_USE;
  3595. goto Exit;
  3596. }
  3597. // determine whether index falls within capture or render devices
  3598. if ( device >= renderDeviceCount ) {
  3599. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3600. if ( FAILED( hr ) ) {
  3601. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
  3602. goto Exit;
  3603. }
  3604. isCaptureDevice = true;
  3605. }
  3606. else {
  3607. hr = renderDevices->Item( device, &devicePtr );
  3608. if ( FAILED( hr ) ) {
  3609. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
  3610. goto Exit;
  3611. }
  3612. isCaptureDevice = false;
  3613. }
  3614. // get default device name
  3615. if ( isCaptureDevice ) {
  3616. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );
  3617. if ( FAILED( hr ) ) {
  3618. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
  3619. goto Exit;
  3620. }
  3621. }
  3622. else {
  3623. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );
  3624. if ( FAILED( hr ) ) {
  3625. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
  3626. goto Exit;
  3627. }
  3628. }
  3629. hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );
  3630. if ( FAILED( hr ) ) {
  3631. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
  3632. goto Exit;
  3633. }
  3634. PropVariantInit( &defaultDeviceNameProp );
  3635. hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );
  3636. if ( FAILED( hr ) ) {
  3637. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
  3638. goto Exit;
  3639. }
  3640. defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);
  3641. // name
  3642. hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
  3643. if ( FAILED( hr ) ) {
  3644. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
  3645. goto Exit;
  3646. }
  3647. PropVariantInit( &deviceNameProp );
  3648. hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
  3649. if ( FAILED( hr ) ) {
  3650. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
  3651. goto Exit;
  3652. }
  3653. info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);
  3654. // is default
  3655. if ( isCaptureDevice ) {
  3656. info.isDefaultInput = info.name == defaultDeviceName;
  3657. info.isDefaultOutput = false;
  3658. }
  3659. else {
  3660. info.isDefaultInput = false;
  3661. info.isDefaultOutput = info.name == defaultDeviceName;
  3662. }
  3663. // channel count
  3664. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
  3665. if ( FAILED( hr ) ) {
  3666. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
  3667. goto Exit;
  3668. }
  3669. hr = audioClient->GetMixFormat( &deviceFormat );
  3670. if ( FAILED( hr ) ) {
  3671. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
  3672. goto Exit;
  3673. }
  3674. if ( isCaptureDevice ) {
  3675. info.inputChannels = deviceFormat->nChannels;
  3676. info.outputChannels = 0;
  3677. info.duplexChannels = 0;
  3678. }
  3679. else {
  3680. info.inputChannels = 0;
  3681. info.outputChannels = deviceFormat->nChannels;
  3682. info.duplexChannels = 0;
  3683. }
  3684. // sample rates
  3685. info.sampleRates.clear();
  3686. // allow support for all sample rates as we have a built-in sample rate converter
  3687. for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {
  3688. info.sampleRates.push_back( SAMPLE_RATES[i] );
  3689. }
  3690. info.preferredSampleRate = deviceFormat->nSamplesPerSec;
  3691. // native format
  3692. info.nativeFormats = 0;
  3693. if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
  3694. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3695. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
  3696. {
  3697. if ( deviceFormat->wBitsPerSample == 32 ) {
  3698. info.nativeFormats |= RTAUDIO_FLOAT32;
  3699. }
  3700. else if ( deviceFormat->wBitsPerSample == 64 ) {
  3701. info.nativeFormats |= RTAUDIO_FLOAT64;
  3702. }
  3703. }
  3704. else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
  3705. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3706. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
  3707. {
  3708. if ( deviceFormat->wBitsPerSample == 8 ) {
  3709. info.nativeFormats |= RTAUDIO_SINT8;
  3710. }
  3711. else if ( deviceFormat->wBitsPerSample == 16 ) {
  3712. info.nativeFormats |= RTAUDIO_SINT16;
  3713. }
  3714. else if ( deviceFormat->wBitsPerSample == 24 ) {
  3715. info.nativeFormats |= RTAUDIO_SINT24;
  3716. }
  3717. else if ( deviceFormat->wBitsPerSample == 32 ) {
  3718. info.nativeFormats |= RTAUDIO_SINT32;
  3719. }
  3720. }
  3721. // probed
  3722. info.probed = true;
  3723. Exit:
  3724. // release all references
  3725. PropVariantClear( &deviceNameProp );
  3726. PropVariantClear( &defaultDeviceNameProp );
  3727. SAFE_RELEASE( captureDevices );
  3728. SAFE_RELEASE( renderDevices );
  3729. SAFE_RELEASE( devicePtr );
  3730. SAFE_RELEASE( defaultDevicePtr );
  3731. SAFE_RELEASE( audioClient );
  3732. SAFE_RELEASE( devicePropStore );
  3733. SAFE_RELEASE( defaultDevicePropStore );
  3734. CoTaskMemFree( deviceFormat );
  3735. CoTaskMemFree( closestMatchFormat );
  3736. if ( !errorText_.empty() )
  3737. error( errorType );
  3738. return info;
  3739. }
  3740. //-----------------------------------------------------------------------------
  3741. unsigned int RtApiWasapi::getDefaultOutputDevice( void )
  3742. {
  3743. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3744. if ( getDeviceInfo( i ).isDefaultOutput ) {
  3745. return i;
  3746. }
  3747. }
  3748. return 0;
  3749. }
  3750. //-----------------------------------------------------------------------------
  3751. unsigned int RtApiWasapi::getDefaultInputDevice( void )
  3752. {
  3753. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3754. if ( getDeviceInfo( i ).isDefaultInput ) {
  3755. return i;
  3756. }
  3757. }
  3758. return 0;
  3759. }
  3760. //-----------------------------------------------------------------------------
  3761. void RtApiWasapi::closeStream( void )
  3762. {
  3763. if ( stream_.state == STREAM_CLOSED ) {
  3764. errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
  3765. error( RtAudioError::WARNING );
  3766. return;
  3767. }
  3768. if ( stream_.state != STREAM_STOPPED )
  3769. stopStream();
  3770. // clean up stream memory
  3771. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
  3772. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
  3773. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )
  3774. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )
  3775. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
  3776. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
  3777. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
  3778. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
  3779. delete ( WasapiHandle* ) stream_.apiHandle;
  3780. stream_.apiHandle = NULL;
  3781. for ( int i = 0; i < 2; i++ ) {
  3782. if ( stream_.userBuffer[i] ) {
  3783. free( stream_.userBuffer[i] );
  3784. stream_.userBuffer[i] = 0;
  3785. }
  3786. }
  3787. if ( stream_.deviceBuffer ) {
  3788. free( stream_.deviceBuffer );
  3789. stream_.deviceBuffer = 0;
  3790. }
  3791. // update stream state
  3792. stream_.state = STREAM_CLOSED;
  3793. }
  3794. //-----------------------------------------------------------------------------
  3795. void RtApiWasapi::startStream( void )
  3796. {
  3797. verifyStream();
  3798. if ( stream_.state == STREAM_RUNNING ) {
  3799. errorText_ = "RtApiWasapi::startStream: The stream is already running.";
  3800. error( RtAudioError::WARNING );
  3801. return;
  3802. }
  3803. // update stream state
  3804. stream_.state = STREAM_RUNNING;
  3805. // create WASAPI stream thread
  3806. stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
  3807. if ( !stream_.callbackInfo.thread ) {
  3808. errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
  3809. error( RtAudioError::THREAD_ERROR );
  3810. }
  3811. else {
  3812. SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
  3813. ResumeThread( ( void* ) stream_.callbackInfo.thread );
  3814. }
  3815. }
  3816. //-----------------------------------------------------------------------------
  3817. void RtApiWasapi::stopStream( void )
  3818. {
  3819. verifyStream();
  3820. if ( stream_.state == STREAM_STOPPED ) {
  3821. errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
  3822. error( RtAudioError::WARNING );
  3823. return;
  3824. }
  3825. // inform stream thread by setting stream state to STREAM_STOPPING
  3826. stream_.state = STREAM_STOPPING;
  3827. // wait until stream thread is stopped
  3828. while( stream_.state != STREAM_STOPPED ) {
  3829. Sleep( 1 );
  3830. }
  3831. // Wait for the last buffer to play before stopping.
  3832. Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );
  3833. // stop capture client if applicable
  3834. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3835. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3836. if ( FAILED( hr ) ) {
  3837. errorText_ = "RtApiWasapi::stopStream: Unable to stop capture stream.";
  3838. error( RtAudioError::DRIVER_ERROR );
  3839. return;
  3840. }
  3841. }
  3842. // stop render client if applicable
  3843. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3844. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3845. if ( FAILED( hr ) ) {
  3846. errorText_ = "RtApiWasapi::stopStream: Unable to stop render stream.";
  3847. error( RtAudioError::DRIVER_ERROR );
  3848. return;
  3849. }
  3850. }
  3851. // close thread handle
  3852. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3853. errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
  3854. error( RtAudioError::THREAD_ERROR );
  3855. return;
  3856. }
  3857. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3858. }
  3859. //-----------------------------------------------------------------------------
  3860. void RtApiWasapi::abortStream( void )
  3861. {
  3862. verifyStream();
  3863. if ( stream_.state == STREAM_STOPPED ) {
  3864. errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
  3865. error( RtAudioError::WARNING );
  3866. return;
  3867. }
  3868. // inform stream thread by setting stream state to STREAM_STOPPING
  3869. stream_.state = STREAM_STOPPING;
  3870. // wait until stream thread is stopped
  3871. while ( stream_.state != STREAM_STOPPED ) {
  3872. Sleep( 1 );
  3873. }
  3874. // stop capture client if applicable
  3875. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {
  3876. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();
  3877. if ( FAILED( hr ) ) {
  3878. errorText_ = "RtApiWasapi::abortStream: Unable to stop capture stream.";
  3879. error( RtAudioError::DRIVER_ERROR );
  3880. return;
  3881. }
  3882. }
  3883. // stop render client if applicable
  3884. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {
  3885. HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();
  3886. if ( FAILED( hr ) ) {
  3887. errorText_ = "RtApiWasapi::abortStream: Unable to stop render stream.";
  3888. error( RtAudioError::DRIVER_ERROR );
  3889. return;
  3890. }
  3891. }
  3892. // close thread handle
  3893. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3894. errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
  3895. error( RtAudioError::THREAD_ERROR );
  3896. return;
  3897. }
  3898. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3899. }
  3900. //-----------------------------------------------------------------------------
  3901. bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3902. unsigned int firstChannel, unsigned int sampleRate,
  3903. RtAudioFormat format, unsigned int* bufferSize,
  3904. RtAudio::StreamOptions* options )
  3905. {
  3906. bool methodResult = FAILURE;
  3907. unsigned int captureDeviceCount = 0;
  3908. unsigned int renderDeviceCount = 0;
  3909. IMMDeviceCollection* captureDevices = NULL;
  3910. IMMDeviceCollection* renderDevices = NULL;
  3911. IMMDevice* devicePtr = NULL;
  3912. WAVEFORMATEX* deviceFormat = NULL;
  3913. unsigned int bufferBytes;
  3914. stream_.state = STREAM_STOPPED;
  3915. // create API Handle if not already created
  3916. if ( !stream_.apiHandle )
  3917. stream_.apiHandle = ( void* ) new WasapiHandle();
  3918. // Count capture devices
  3919. errorText_.clear();
  3920. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3921. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3922. if ( FAILED( hr ) ) {
  3923. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
  3924. goto Exit;
  3925. }
  3926. hr = captureDevices->GetCount( &captureDeviceCount );
  3927. if ( FAILED( hr ) ) {
  3928. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
  3929. goto Exit;
  3930. }
  3931. // Count render devices
  3932. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3933. if ( FAILED( hr ) ) {
  3934. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
  3935. goto Exit;
  3936. }
  3937. hr = renderDevices->GetCount( &renderDeviceCount );
  3938. if ( FAILED( hr ) ) {
  3939. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
  3940. goto Exit;
  3941. }
  3942. // validate device index
  3943. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3944. errorType = RtAudioError::INVALID_USE;
  3945. errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
  3946. goto Exit;
  3947. }
  3948. // determine whether index falls within capture or render devices
  3949. if ( device >= renderDeviceCount ) {
  3950. if ( mode != INPUT ) {
  3951. errorType = RtAudioError::INVALID_USE;
  3952. errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
  3953. goto Exit;
  3954. }
  3955. // retrieve captureAudioClient from devicePtr
  3956. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  3957. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3958. if ( FAILED( hr ) ) {
  3959. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
  3960. goto Exit;
  3961. }
  3962. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3963. NULL, ( void** ) &captureAudioClient );
  3964. if ( FAILED( hr ) ) {
  3965. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3966. goto Exit;
  3967. }
  3968. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  3969. if ( FAILED( hr ) ) {
  3970. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3971. goto Exit;
  3972. }
  3973. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  3974. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  3975. }
  3976. else {
  3977. if ( mode != OUTPUT ) {
  3978. errorType = RtAudioError::INVALID_USE;
  3979. errorText_ = "RtApiWasapi::probeDeviceOpen: Render device selected as input device.";
  3980. goto Exit;
  3981. }
  3982. // retrieve renderAudioClient from devicePtr
  3983. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  3984. hr = renderDevices->Item( device, &devicePtr );
  3985. if ( FAILED( hr ) ) {
  3986. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  3987. goto Exit;
  3988. }
  3989. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  3990. NULL, ( void** ) &renderAudioClient );
  3991. if ( FAILED( hr ) ) {
  3992. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";
  3993. goto Exit;
  3994. }
  3995. hr = renderAudioClient->GetMixFormat( &deviceFormat );
  3996. if ( FAILED( hr ) ) {
  3997. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";
  3998. goto Exit;
  3999. }
  4000. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4001. renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4002. }
  4003. // fill stream data
  4004. if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
  4005. ( stream_.mode == INPUT && mode == OUTPUT ) ) {
  4006. stream_.mode = DUPLEX;
  4007. }
  4008. else {
  4009. stream_.mode = mode;
  4010. }
  4011. stream_.device[mode] = device;
  4012. stream_.doByteSwap[mode] = false;
  4013. stream_.sampleRate = sampleRate;
  4014. stream_.bufferSize = *bufferSize;
  4015. stream_.nBuffers = 1;
  4016. stream_.nUserChannels[mode] = channels;
  4017. stream_.channelOffset[mode] = firstChannel;
  4018. stream_.userFormat = format;
  4019. stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats;
  4020. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  4021. stream_.userInterleaved = false;
  4022. else
  4023. stream_.userInterleaved = true;
  4024. stream_.deviceInterleaved[mode] = true;
  4025. // Set flags for buffer conversion.
  4026. stream_.doConvertBuffer[mode] = false;
  4027. if ( stream_.userFormat != stream_.deviceFormat[mode] ||
  4028. stream_.nUserChannels != stream_.nDeviceChannels )
  4029. stream_.doConvertBuffer[mode] = true;
  4030. else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4031. stream_.nUserChannels[mode] > 1 )
  4032. stream_.doConvertBuffer[mode] = true;
  4033. if ( stream_.doConvertBuffer[mode] )
  4034. setConvertInfo( mode, 0 );
  4035. // Allocate necessary internal buffers
  4036. bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
  4037. stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
  4038. if ( !stream_.userBuffer[mode] ) {
  4039. errorType = RtAudioError::MEMORY_ERROR;
  4040. errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
  4041. goto Exit;
  4042. }
  4043. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
  4044. stream_.callbackInfo.priority = 15;
  4045. else
  4046. stream_.callbackInfo.priority = 0;
  4047. ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
  4048. ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
  4049. methodResult = SUCCESS;
  4050. Exit:
  4051. //clean up
  4052. SAFE_RELEASE( captureDevices );
  4053. SAFE_RELEASE( renderDevices );
  4054. SAFE_RELEASE( devicePtr );
  4055. CoTaskMemFree( deviceFormat );
  4056. // if method failed, close the stream
  4057. if ( methodResult == FAILURE )
  4058. closeStream();
  4059. if ( !errorText_.empty() )
  4060. error( errorType );
  4061. return methodResult;
  4062. }
  4063. //=============================================================================
  4064. DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
  4065. {
  4066. if ( wasapiPtr )
  4067. ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
  4068. return 0;
  4069. }
  4070. DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
  4071. {
  4072. if ( wasapiPtr )
  4073. ( ( RtApiWasapi* ) wasapiPtr )->stopStream();
  4074. return 0;
  4075. }
  4076. DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
  4077. {
  4078. if ( wasapiPtr )
  4079. ( ( RtApiWasapi* ) wasapiPtr )->abortStream();
  4080. return 0;
  4081. }
  4082. //-----------------------------------------------------------------------------
  4083. void RtApiWasapi::wasapiThread()
  4084. {
  4085. // as this is a new thread, we must CoInitialize it
  4086. CoInitialize( NULL );
  4087. HRESULT hr;
  4088. IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4089. IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4090. IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
  4091. IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
  4092. HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
  4093. HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
  4094. WAVEFORMATEX* captureFormat = NULL;
  4095. WAVEFORMATEX* renderFormat = NULL;
  4096. float captureSrRatio = 0.0f;
  4097. float renderSrRatio = 0.0f;
  4098. WasapiBuffer captureBuffer;
  4099. WasapiBuffer renderBuffer;
  4100. // declare local stream variables
  4101. RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
  4102. BYTE* streamBuffer = NULL;
  4103. unsigned long captureFlags = 0;
  4104. unsigned int bufferFrameCount = 0;
  4105. unsigned int numFramesPadding = 0;
  4106. unsigned int convBufferSize = 0;
  4107. bool callbackPushed = false;
  4108. bool callbackPulled = false;
  4109. bool callbackStopped = false;
  4110. int callbackResult = 0;
  4111. // convBuffer is used to store converted buffers between WASAPI and the user
  4112. char* convBuffer = NULL;
  4113. unsigned int convBuffSize = 0;
  4114. unsigned int deviceBuffSize = 0;
  4115. errorText_.clear();
  4116. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  4117. // Attempt to assign "Pro Audio" characteristic to thread
  4118. HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );
  4119. if ( AvrtDll ) {
  4120. DWORD taskIndex = 0;
  4121. TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = ( TAvSetMmThreadCharacteristicsPtr ) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
  4122. AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
  4123. FreeLibrary( AvrtDll );
  4124. }
  4125. // start capture stream if applicable
  4126. if ( captureAudioClient ) {
  4127. hr = captureAudioClient->GetMixFormat( &captureFormat );
  4128. if ( FAILED( hr ) ) {
  4129. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4130. goto Exit;
  4131. }
  4132. captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );
  4133. // initialize capture stream according to desire buffer size
  4134. float desiredBufferSize = stream_.bufferSize * captureSrRatio;
  4135. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / captureFormat->nSamplesPerSec );
  4136. if ( !captureClient ) {
  4137. hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4138. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4139. desiredBufferPeriod,
  4140. desiredBufferPeriod,
  4141. captureFormat,
  4142. NULL );
  4143. if ( FAILED( hr ) ) {
  4144. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
  4145. goto Exit;
  4146. }
  4147. hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
  4148. ( void** ) &captureClient );
  4149. if ( FAILED( hr ) ) {
  4150. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
  4151. goto Exit;
  4152. }
  4153. // configure captureEvent to trigger on every available capture buffer
  4154. captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4155. if ( !captureEvent ) {
  4156. errorType = RtAudioError::SYSTEM_ERROR;
  4157. errorText_ = "RtApiWasapi::wasapiThread: Unable to create capture event.";
  4158. goto Exit;
  4159. }
  4160. hr = captureAudioClient->SetEventHandle( captureEvent );
  4161. if ( FAILED( hr ) ) {
  4162. errorText_ = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
  4163. goto Exit;
  4164. }
  4165. ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
  4166. ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
  4167. }
  4168. unsigned int inBufferSize = 0;
  4169. hr = captureAudioClient->GetBufferSize( &inBufferSize );
  4170. if ( FAILED( hr ) ) {
  4171. errorText_ = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
  4172. goto Exit;
  4173. }
  4174. // scale outBufferSize according to stream->user sample rate ratio
  4175. unsigned int outBufferSize = ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];
  4176. inBufferSize *= stream_.nDeviceChannels[INPUT];
  4177. // set captureBuffer size
  4178. captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
  4179. // reset the capture stream
  4180. hr = captureAudioClient->Reset();
  4181. if ( FAILED( hr ) ) {
  4182. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
  4183. goto Exit;
  4184. }
  4185. // start the capture stream
  4186. hr = captureAudioClient->Start();
  4187. if ( FAILED( hr ) ) {
  4188. errorText_ = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
  4189. goto Exit;
  4190. }
  4191. }
  4192. // start render stream if applicable
  4193. if ( renderAudioClient ) {
  4194. hr = renderAudioClient->GetMixFormat( &renderFormat );
  4195. if ( FAILED( hr ) ) {
  4196. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4197. goto Exit;
  4198. }
  4199. renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );
  4200. // initialize render stream according to desire buffer size
  4201. float desiredBufferSize = stream_.bufferSize * renderSrRatio;
  4202. REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / renderFormat->nSamplesPerSec );
  4203. if ( !renderClient ) {
  4204. hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4205. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4206. desiredBufferPeriod,
  4207. desiredBufferPeriod,
  4208. renderFormat,
  4209. NULL );
  4210. if ( FAILED( hr ) ) {
  4211. errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
  4212. goto Exit;
  4213. }
  4214. hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
  4215. ( void** ) &renderClient );
  4216. if ( FAILED( hr ) ) {
  4217. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
  4218. goto Exit;
  4219. }
  4220. // configure renderEvent to trigger on every available render buffer
  4221. renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4222. if ( !renderEvent ) {
  4223. errorType = RtAudioError::SYSTEM_ERROR;
  4224. errorText_ = "RtApiWasapi::wasapiThread: Unable to create render event.";
  4225. goto Exit;
  4226. }
  4227. hr = renderAudioClient->SetEventHandle( renderEvent );
  4228. if ( FAILED( hr ) ) {
  4229. errorText_ = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
  4230. goto Exit;
  4231. }
  4232. ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
  4233. ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
  4234. }
  4235. unsigned int outBufferSize = 0;
  4236. hr = renderAudioClient->GetBufferSize( &outBufferSize );
  4237. if ( FAILED( hr ) ) {
  4238. errorText_ = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
  4239. goto Exit;
  4240. }
  4241. // scale inBufferSize according to user->stream sample rate ratio
  4242. unsigned int inBufferSize = ( unsigned int ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];
  4243. outBufferSize *= stream_.nDeviceChannels[OUTPUT];
  4244. // set renderBuffer size
  4245. renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4246. // reset the render stream
  4247. hr = renderAudioClient->Reset();
  4248. if ( FAILED( hr ) ) {
  4249. errorText_ = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
  4250. goto Exit;
  4251. }
  4252. // start the render stream
  4253. hr = renderAudioClient->Start();
  4254. if ( FAILED( hr ) ) {
  4255. errorText_ = "RtApiWasapi::wasapiThread: Unable to start render stream.";
  4256. goto Exit;
  4257. }
  4258. }
  4259. if ( stream_.mode == INPUT ) {
  4260. using namespace std; // for roundf
  4261. convBuffSize = ( size_t ) roundf( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4262. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4263. }
  4264. else if ( stream_.mode == OUTPUT ) {
  4265. convBuffSize = ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4266. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4267. }
  4268. else if ( stream_.mode == DUPLEX ) {
  4269. convBuffSize = std::max( ( size_t ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4270. ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4271. deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4272. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4273. }
  4274. convBuffer = ( char* ) malloc( convBuffSize );
  4275. stream_.deviceBuffer = ( char* ) malloc( deviceBuffSize );
  4276. if ( !convBuffer || !stream_.deviceBuffer ) {
  4277. errorType = RtAudioError::MEMORY_ERROR;
  4278. errorText_ = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
  4279. goto Exit;
  4280. }
  4281. // stream process loop
  4282. while ( stream_.state != STREAM_STOPPING ) {
  4283. if ( !callbackPulled ) {
  4284. // Callback Input
  4285. // ==============
  4286. // 1. Pull callback buffer from inputBuffer
  4287. // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count
  4288. // Convert callback buffer to user format
  4289. if ( captureAudioClient ) {
  4290. // Pull callback buffer from inputBuffer
  4291. callbackPulled = captureBuffer.pullBuffer( convBuffer,
  4292. ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT],
  4293. stream_.deviceFormat[INPUT] );
  4294. if ( callbackPulled ) {
  4295. // Convert callback buffer to user sample rate
  4296. convertBufferWasapi( stream_.deviceBuffer,
  4297. convBuffer,
  4298. stream_.nDeviceChannels[INPUT],
  4299. captureFormat->nSamplesPerSec,
  4300. stream_.sampleRate,
  4301. ( unsigned int ) ( stream_.bufferSize * captureSrRatio ),
  4302. convBufferSize,
  4303. stream_.deviceFormat[INPUT] );
  4304. if ( stream_.doConvertBuffer[INPUT] ) {
  4305. // Convert callback buffer to user format
  4306. convertBuffer( stream_.userBuffer[INPUT],
  4307. stream_.deviceBuffer,
  4308. stream_.convertInfo[INPUT] );
  4309. }
  4310. else {
  4311. // no further conversion, simple copy deviceBuffer to userBuffer
  4312. memcpy( stream_.userBuffer[INPUT],
  4313. stream_.deviceBuffer,
  4314. stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
  4315. }
  4316. }
  4317. }
  4318. else {
  4319. // if there is no capture stream, set callbackPulled flag
  4320. callbackPulled = true;
  4321. }
  4322. // Execute Callback
  4323. // ================
  4324. // 1. Execute user callback method
  4325. // 2. Handle return value from callback
  4326. // if callback has not requested the stream to stop
  4327. if ( callbackPulled && !callbackStopped ) {
  4328. // Execute user callback method
  4329. callbackResult = callback( stream_.userBuffer[OUTPUT],
  4330. stream_.userBuffer[INPUT],
  4331. stream_.bufferSize,
  4332. getStreamTime(),
  4333. captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
  4334. stream_.callbackInfo.userData );
  4335. // Handle return value from callback
  4336. if ( callbackResult == 1 ) {
  4337. // instantiate a thread to stop this thread
  4338. HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
  4339. if ( !threadHandle ) {
  4340. errorType = RtAudioError::THREAD_ERROR;
  4341. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
  4342. goto Exit;
  4343. }
  4344. else if ( !CloseHandle( threadHandle ) ) {
  4345. errorType = RtAudioError::THREAD_ERROR;
  4346. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
  4347. goto Exit;
  4348. }
  4349. callbackStopped = true;
  4350. }
  4351. else if ( callbackResult == 2 ) {
  4352. // instantiate a thread to stop this thread
  4353. HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
  4354. if ( !threadHandle ) {
  4355. errorType = RtAudioError::THREAD_ERROR;
  4356. errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
  4357. goto Exit;
  4358. }
  4359. else if ( !CloseHandle( threadHandle ) ) {
  4360. errorType = RtAudioError::THREAD_ERROR;
  4361. errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
  4362. goto Exit;
  4363. }
  4364. callbackStopped = true;
  4365. }
  4366. }
  4367. }
  4368. // Callback Output
  4369. // ===============
  4370. // 1. Convert callback buffer to stream format
  4371. // 2. Convert callback buffer to stream sample rate and channel count
  4372. // 3. Push callback buffer into outputBuffer
  4373. if ( renderAudioClient && callbackPulled ) {
  4374. if ( stream_.doConvertBuffer[OUTPUT] ) {
  4375. // Convert callback buffer to stream format
  4376. convertBuffer( stream_.deviceBuffer,
  4377. stream_.userBuffer[OUTPUT],
  4378. stream_.convertInfo[OUTPUT] );
  4379. }
  4380. // Convert callback buffer to stream sample rate
  4381. convertBufferWasapi( convBuffer,
  4382. stream_.deviceBuffer,
  4383. stream_.nDeviceChannels[OUTPUT],
  4384. stream_.sampleRate,
  4385. renderFormat->nSamplesPerSec,
  4386. stream_.bufferSize,
  4387. convBufferSize,
  4388. stream_.deviceFormat[OUTPUT] );
  4389. // Push callback buffer into outputBuffer
  4390. callbackPushed = renderBuffer.pushBuffer( convBuffer,
  4391. convBufferSize * stream_.nDeviceChannels[OUTPUT],
  4392. stream_.deviceFormat[OUTPUT] );
  4393. }
  4394. else {
  4395. // if there is no render stream, set callbackPushed flag
  4396. callbackPushed = true;
  4397. }
  4398. // Stream Capture
  4399. // ==============
  4400. // 1. Get capture buffer from stream
  4401. // 2. Push capture buffer into inputBuffer
  4402. // 3. If 2. was successful: Release capture buffer
  4403. if ( captureAudioClient ) {
  4404. // if the callback input buffer was not pulled from captureBuffer, wait for next capture event
  4405. if ( !callbackPulled ) {
  4406. WaitForSingleObject( captureEvent, INFINITE );
  4407. }
  4408. // Get capture buffer from stream
  4409. hr = captureClient->GetBuffer( &streamBuffer,
  4410. &bufferFrameCount,
  4411. &captureFlags, NULL, NULL );
  4412. if ( FAILED( hr ) ) {
  4413. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
  4414. goto Exit;
  4415. }
  4416. if ( bufferFrameCount != 0 ) {
  4417. // Push capture buffer into inputBuffer
  4418. if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
  4419. bufferFrameCount * stream_.nDeviceChannels[INPUT],
  4420. stream_.deviceFormat[INPUT] ) )
  4421. {
  4422. // Release capture buffer
  4423. hr = captureClient->ReleaseBuffer( bufferFrameCount );
  4424. if ( FAILED( hr ) ) {
  4425. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4426. goto Exit;
  4427. }
  4428. }
  4429. else
  4430. {
  4431. // Inform WASAPI that capture was unsuccessful
  4432. hr = captureClient->ReleaseBuffer( 0 );
  4433. if ( FAILED( hr ) ) {
  4434. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4435. goto Exit;
  4436. }
  4437. }
  4438. }
  4439. else
  4440. {
  4441. // Inform WASAPI that capture was unsuccessful
  4442. hr = captureClient->ReleaseBuffer( 0 );
  4443. if ( FAILED( hr ) ) {
  4444. errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4445. goto Exit;
  4446. }
  4447. }
  4448. }
  4449. // Stream Render
  4450. // =============
  4451. // 1. Get render buffer from stream
  4452. // 2. Pull next buffer from outputBuffer
  4453. // 3. If 2. was successful: Fill render buffer with next buffer
  4454. // Release render buffer
  4455. if ( renderAudioClient ) {
  4456. // if the callback output buffer was not pushed to renderBuffer, wait for next render event
  4457. if ( callbackPulled && !callbackPushed ) {
  4458. WaitForSingleObject( renderEvent, INFINITE );
  4459. }
  4460. // Get render buffer from stream
  4461. hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
  4462. if ( FAILED( hr ) ) {
  4463. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
  4464. goto Exit;
  4465. }
  4466. hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
  4467. if ( FAILED( hr ) ) {
  4468. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
  4469. goto Exit;
  4470. }
  4471. bufferFrameCount -= numFramesPadding;
  4472. if ( bufferFrameCount != 0 ) {
  4473. hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
  4474. if ( FAILED( hr ) ) {
  4475. errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
  4476. goto Exit;
  4477. }
  4478. // Pull next buffer from outputBuffer
  4479. // Fill render buffer with next buffer
  4480. if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
  4481. bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
  4482. stream_.deviceFormat[OUTPUT] ) )
  4483. {
  4484. // Release render buffer
  4485. hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
  4486. if ( FAILED( hr ) ) {
  4487. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4488. goto Exit;
  4489. }
  4490. }
  4491. else
  4492. {
  4493. // Inform WASAPI that render was unsuccessful
  4494. hr = renderClient->ReleaseBuffer( 0, 0 );
  4495. if ( FAILED( hr ) ) {
  4496. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4497. goto Exit;
  4498. }
  4499. }
  4500. }
  4501. else
  4502. {
  4503. // Inform WASAPI that render was unsuccessful
  4504. hr = renderClient->ReleaseBuffer( 0, 0 );
  4505. if ( FAILED( hr ) ) {
  4506. errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4507. goto Exit;
  4508. }
  4509. }
  4510. }
  4511. // if the callback buffer was pushed renderBuffer reset callbackPulled flag
  4512. if ( callbackPushed ) {
  4513. callbackPulled = false;
  4514. // tick stream time
  4515. RtApi::tickStreamTime();
  4516. }
  4517. }
  4518. Exit:
  4519. // clean up
  4520. CoTaskMemFree( captureFormat );
  4521. CoTaskMemFree( renderFormat );
  4522. free ( convBuffer );
  4523. CoUninitialize();
  4524. // update stream state
  4525. stream_.state = STREAM_STOPPED;
  4526. if ( errorText_.empty() )
  4527. return;
  4528. else
  4529. error( errorType );
  4530. }
  4531. //******************** End of __WINDOWS_WASAPI__ *********************//
  4532. #endif
  4533. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  4534. // Modified by Robin Davies, October 2005
  4535. // - Improvements to DirectX pointer chasing.
  4536. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  4537. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  4538. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  4539. // Changed device query structure for RtAudio 4.0.7, January 2010
  4540. #include <mmsystem.h>
  4541. #include <mmreg.h>
  4542. #include <dsound.h>
  4543. #include <assert.h>
  4544. #include <algorithm>
  4545. #if defined(__MINGW32__)
  4546. // missing from latest mingw winapi
  4547. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  4548. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  4549. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  4550. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  4551. #endif
  4552. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  4553. #ifdef _MSC_VER // if Microsoft Visual C++
  4554. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  4555. #endif
  4556. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  4557. {
  4558. if ( pointer > bufferSize ) pointer -= bufferSize;
  4559. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  4560. if ( pointer < earlierPointer ) pointer += bufferSize;
  4561. return pointer >= earlierPointer && pointer < laterPointer;
  4562. }
  4563. // A structure to hold various information related to the DirectSound
  4564. // API implementation.
  4565. struct DsHandle {
  4566. unsigned int drainCounter; // Tracks callback counts when draining
  4567. bool internalDrain; // Indicates if stop is initiated from callback or not.
  4568. void *id[2];
  4569. void *buffer[2];
  4570. bool xrun[2];
  4571. UINT bufferPointer[2];
  4572. DWORD dsBufferSize[2];
  4573. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  4574. HANDLE condition;
  4575. DsHandle()
  4576. :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; }
  4577. };
  4578. // Declarations for utility functions, callbacks, and structures
  4579. // specific to the DirectSound implementation.
  4580. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4581. LPCTSTR description,
  4582. LPCTSTR module,
  4583. LPVOID lpContext );
  4584. static const char* getErrorString( int code );
  4585. static unsigned __stdcall callbackHandler( void *ptr );
  4586. struct DsDevice {
  4587. LPGUID id[2];
  4588. bool validId[2];
  4589. bool found;
  4590. std::string name;
  4591. DsDevice()
  4592. : found(false) { validId[0] = false; validId[1] = false; }
  4593. };
  4594. struct DsProbeData {
  4595. bool isInput;
  4596. std::vector<struct DsDevice>* dsDevices;
  4597. };
  4598. RtApiDs :: RtApiDs()
  4599. {
  4600. // Dsound will run both-threaded. If CoInitialize fails, then just
  4601. // accept whatever the mainline chose for a threading model.
  4602. coInitialized_ = false;
  4603. HRESULT hr = CoInitialize( NULL );
  4604. if ( !FAILED( hr ) ) coInitialized_ = true;
  4605. }
  4606. RtApiDs :: ~RtApiDs()
  4607. {
  4608. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4609. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  4610. }
  4611. // The DirectSound default output is always the first device.
  4612. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  4613. {
  4614. return 0;
  4615. }
  4616. // The DirectSound default input is always the first input device,
  4617. // which is the first capture device enumerated.
  4618. unsigned int RtApiDs :: getDefaultInputDevice( void )
  4619. {
  4620. return 0;
  4621. }
  4622. unsigned int RtApiDs :: getDeviceCount( void )
  4623. {
  4624. // Set query flag for previously found devices to false, so that we
  4625. // can check for any devices that have disappeared.
  4626. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4627. dsDevices[i].found = false;
  4628. // Query DirectSound devices.
  4629. struct DsProbeData probeInfo;
  4630. probeInfo.isInput = false;
  4631. probeInfo.dsDevices = &dsDevices;
  4632. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4633. if ( FAILED( result ) ) {
  4634. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  4635. errorText_ = errorStream_.str();
  4636. error( RtAudioError::WARNING );
  4637. }
  4638. // Query DirectSoundCapture devices.
  4639. probeInfo.isInput = true;
  4640. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4641. if ( FAILED( result ) ) {
  4642. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  4643. errorText_ = errorStream_.str();
  4644. error( RtAudioError::WARNING );
  4645. }
  4646. // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).
  4647. for ( unsigned int i=0; i<dsDevices.size(); ) {
  4648. if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );
  4649. else i++;
  4650. }
  4651. return static_cast<unsigned int>(dsDevices.size());
  4652. }
  4653. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  4654. {
  4655. RtAudio::DeviceInfo info;
  4656. info.probed = false;
  4657. if ( dsDevices.size() == 0 ) {
  4658. // Force a query of all devices
  4659. getDeviceCount();
  4660. if ( dsDevices.size() == 0 ) {
  4661. errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
  4662. error( RtAudioError::INVALID_USE );
  4663. return info;
  4664. }
  4665. }
  4666. if ( device >= dsDevices.size() ) {
  4667. errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
  4668. error( RtAudioError::INVALID_USE );
  4669. return info;
  4670. }
  4671. HRESULT result;
  4672. if ( dsDevices[ device ].validId[0] == false ) goto probeInput;
  4673. LPDIRECTSOUND output;
  4674. DSCAPS outCaps;
  4675. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4676. if ( FAILED( result ) ) {
  4677. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4678. errorText_ = errorStream_.str();
  4679. error( RtAudioError::WARNING );
  4680. goto probeInput;
  4681. }
  4682. outCaps.dwSize = sizeof( outCaps );
  4683. result = output->GetCaps( &outCaps );
  4684. if ( FAILED( result ) ) {
  4685. output->Release();
  4686. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  4687. errorText_ = errorStream_.str();
  4688. error( RtAudioError::WARNING );
  4689. goto probeInput;
  4690. }
  4691. // Get output channel information.
  4692. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  4693. // Get sample rate information.
  4694. info.sampleRates.clear();
  4695. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  4696. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  4697. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {
  4698. info.sampleRates.push_back( SAMPLE_RATES[k] );
  4699. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  4700. info.preferredSampleRate = SAMPLE_RATES[k];
  4701. }
  4702. }
  4703. // Get format information.
  4704. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  4705. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  4706. output->Release();
  4707. if ( getDefaultOutputDevice() == device )
  4708. info.isDefaultOutput = true;
  4709. if ( dsDevices[ device ].validId[1] == false ) {
  4710. info.name = dsDevices[ device ].name;
  4711. info.probed = true;
  4712. return info;
  4713. }
  4714. probeInput:
  4715. LPDIRECTSOUNDCAPTURE input;
  4716. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4717. if ( FAILED( result ) ) {
  4718. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4719. errorText_ = errorStream_.str();
  4720. error( RtAudioError::WARNING );
  4721. return info;
  4722. }
  4723. DSCCAPS inCaps;
  4724. inCaps.dwSize = sizeof( inCaps );
  4725. result = input->GetCaps( &inCaps );
  4726. if ( FAILED( result ) ) {
  4727. input->Release();
  4728. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";
  4729. errorText_ = errorStream_.str();
  4730. error( RtAudioError::WARNING );
  4731. return info;
  4732. }
  4733. // Get input channel information.
  4734. info.inputChannels = inCaps.dwChannels;
  4735. // Get sample rate and format information.
  4736. std::vector<unsigned int> rates;
  4737. if ( inCaps.dwChannels >= 2 ) {
  4738. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4739. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4740. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4741. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4742. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4743. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4744. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4745. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4746. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4747. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
  4748. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
  4749. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
  4750. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
  4751. }
  4752. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4753. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
  4754. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
  4755. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
  4756. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
  4757. }
  4758. }
  4759. else if ( inCaps.dwChannels == 1 ) {
  4760. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4761. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4762. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4763. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4764. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4765. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4766. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4767. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4768. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4769. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
  4770. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
  4771. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
  4772. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
  4773. }
  4774. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4775. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
  4776. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
  4777. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
  4778. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
  4779. }
  4780. }
  4781. else info.inputChannels = 0; // technically, this would be an error
  4782. input->Release();
  4783. if ( info.inputChannels == 0 ) return info;
  4784. // Copy the supported rates to the info structure but avoid duplication.
  4785. bool found;
  4786. for ( unsigned int i=0; i<rates.size(); i++ ) {
  4787. found = false;
  4788. for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
  4789. if ( rates[i] == info.sampleRates[j] ) {
  4790. found = true;
  4791. break;
  4792. }
  4793. }
  4794. if ( found == false ) info.sampleRates.push_back( rates[i] );
  4795. }
  4796. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  4797. // If device opens for both playback and capture, we determine the channels.
  4798. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4799. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4800. if ( device == 0 ) info.isDefaultInput = true;
  4801. // Copy name and return.
  4802. info.name = dsDevices[ device ].name;
  4803. info.probed = true;
  4804. return info;
  4805. }
  4806. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4807. unsigned int firstChannel, unsigned int sampleRate,
  4808. RtAudioFormat format, unsigned int *bufferSize,
  4809. RtAudio::StreamOptions *options )
  4810. {
  4811. if ( channels + firstChannel > 2 ) {
  4812. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  4813. return FAILURE;
  4814. }
  4815. size_t nDevices = dsDevices.size();
  4816. if ( nDevices == 0 ) {
  4817. // This should not happen because a check is made before this function is called.
  4818. errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
  4819. return FAILURE;
  4820. }
  4821. if ( device >= nDevices ) {
  4822. // This should not happen because a check is made before this function is called.
  4823. errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
  4824. return FAILURE;
  4825. }
  4826. if ( mode == OUTPUT ) {
  4827. if ( dsDevices[ device ].validId[0] == false ) {
  4828. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  4829. errorText_ = errorStream_.str();
  4830. return FAILURE;
  4831. }
  4832. }
  4833. else { // mode == INPUT
  4834. if ( dsDevices[ device ].validId[1] == false ) {
  4835. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  4836. errorText_ = errorStream_.str();
  4837. return FAILURE;
  4838. }
  4839. }
  4840. // According to a note in PortAudio, using GetDesktopWindow()
  4841. // instead of GetForegroundWindow() is supposed to avoid problems
  4842. // that occur when the application's window is not the foreground
  4843. // window. Also, if the application window closes before the
  4844. // DirectSound buffer, DirectSound can crash. In the past, I had
  4845. // problems when using GetDesktopWindow() but it seems fine now
  4846. // (January 2010). I'll leave it commented here.
  4847. // HWND hWnd = GetForegroundWindow();
  4848. HWND hWnd = GetDesktopWindow();
  4849. // Check the numberOfBuffers parameter and limit the lowest value to
  4850. // two. This is a judgement call and a value of two is probably too
  4851. // low for capture, but it should work for playback.
  4852. int nBuffers = 0;
  4853. if ( options ) nBuffers = options->numberOfBuffers;
  4854. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  4855. if ( nBuffers < 2 ) nBuffers = 3;
  4856. // Check the lower range of the user-specified buffer size and set
  4857. // (arbitrarily) to a lower bound of 32.
  4858. if ( *bufferSize < 32 ) *bufferSize = 32;
  4859. // Create the wave format structure. The data format setting will
  4860. // be determined later.
  4861. WAVEFORMATEX waveFormat;
  4862. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  4863. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  4864. waveFormat.nChannels = channels + firstChannel;
  4865. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  4866. // Determine the device buffer size. By default, we'll use the value
  4867. // defined above (32K), but we will grow it to make allowances for
  4868. // very large software buffer sizes.
  4869. DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
  4870. DWORD dsPointerLeadTime = 0;
  4871. void *ohandle = 0, *bhandle = 0;
  4872. HRESULT result;
  4873. if ( mode == OUTPUT ) {
  4874. LPDIRECTSOUND output;
  4875. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4876. if ( FAILED( result ) ) {
  4877. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4878. errorText_ = errorStream_.str();
  4879. return FAILURE;
  4880. }
  4881. DSCAPS outCaps;
  4882. outCaps.dwSize = sizeof( outCaps );
  4883. result = output->GetCaps( &outCaps );
  4884. if ( FAILED( result ) ) {
  4885. output->Release();
  4886. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";
  4887. errorText_ = errorStream_.str();
  4888. return FAILURE;
  4889. }
  4890. // Check channel information.
  4891. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  4892. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";
  4893. errorText_ = errorStream_.str();
  4894. return FAILURE;
  4895. }
  4896. // Check format information. Use 16-bit format unless not
  4897. // supported or user requests 8-bit.
  4898. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  4899. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  4900. waveFormat.wBitsPerSample = 16;
  4901. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  4902. }
  4903. else {
  4904. waveFormat.wBitsPerSample = 8;
  4905. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  4906. }
  4907. stream_.userFormat = format;
  4908. // Update wave format structure and buffer information.
  4909. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  4910. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  4911. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  4912. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  4913. while ( dsPointerLeadTime * 2U > dsBufferSize )
  4914. dsBufferSize *= 2;
  4915. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  4916. // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  4917. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  4918. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  4919. if ( FAILED( result ) ) {
  4920. output->Release();
  4921. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";
  4922. errorText_ = errorStream_.str();
  4923. return FAILURE;
  4924. }
  4925. // Even though we will write to the secondary buffer, we need to
  4926. // access the primary buffer to set the correct output format
  4927. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  4928. // buffer description.
  4929. DSBUFFERDESC bufferDescription;
  4930. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4931. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4932. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  4933. // Obtain the primary buffer
  4934. LPDIRECTSOUNDBUFFER buffer;
  4935. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4936. if ( FAILED( result ) ) {
  4937. output->Release();
  4938. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";
  4939. errorText_ = errorStream_.str();
  4940. return FAILURE;
  4941. }
  4942. // Set the primary DS buffer sound format.
  4943. result = buffer->SetFormat( &waveFormat );
  4944. if ( FAILED( result ) ) {
  4945. output->Release();
  4946. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";
  4947. errorText_ = errorStream_.str();
  4948. return FAILURE;
  4949. }
  4950. // Setup the secondary DS buffer description.
  4951. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  4952. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  4953. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4954. DSBCAPS_GLOBALFOCUS |
  4955. DSBCAPS_GETCURRENTPOSITION2 |
  4956. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  4957. bufferDescription.dwBufferBytes = dsBufferSize;
  4958. bufferDescription.lpwfxFormat = &waveFormat;
  4959. // Try to create the secondary DS buffer. If that doesn't work,
  4960. // try to use software mixing. Otherwise, there's a problem.
  4961. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4962. if ( FAILED( result ) ) {
  4963. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  4964. DSBCAPS_GLOBALFOCUS |
  4965. DSBCAPS_GETCURRENTPOSITION2 |
  4966. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  4967. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  4968. if ( FAILED( result ) ) {
  4969. output->Release();
  4970. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";
  4971. errorText_ = errorStream_.str();
  4972. return FAILURE;
  4973. }
  4974. }
  4975. // Get the buffer size ... might be different from what we specified.
  4976. DSBCAPS dsbcaps;
  4977. dsbcaps.dwSize = sizeof( DSBCAPS );
  4978. result = buffer->GetCaps( &dsbcaps );
  4979. if ( FAILED( result ) ) {
  4980. output->Release();
  4981. buffer->Release();
  4982. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  4983. errorText_ = errorStream_.str();
  4984. return FAILURE;
  4985. }
  4986. dsBufferSize = dsbcaps.dwBufferBytes;
  4987. // Lock the DS buffer
  4988. LPVOID audioPtr;
  4989. DWORD dataLen;
  4990. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  4991. if ( FAILED( result ) ) {
  4992. output->Release();
  4993. buffer->Release();
  4994. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";
  4995. errorText_ = errorStream_.str();
  4996. return FAILURE;
  4997. }
  4998. // Zero the DS buffer
  4999. ZeroMemory( audioPtr, dataLen );
  5000. // Unlock the DS buffer
  5001. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5002. if ( FAILED( result ) ) {
  5003. output->Release();
  5004. buffer->Release();
  5005. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";
  5006. errorText_ = errorStream_.str();
  5007. return FAILURE;
  5008. }
  5009. ohandle = (void *) output;
  5010. bhandle = (void *) buffer;
  5011. }
  5012. if ( mode == INPUT ) {
  5013. LPDIRECTSOUNDCAPTURE input;
  5014. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  5015. if ( FAILED( result ) ) {
  5016. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  5017. errorText_ = errorStream_.str();
  5018. return FAILURE;
  5019. }
  5020. DSCCAPS inCaps;
  5021. inCaps.dwSize = sizeof( inCaps );
  5022. result = input->GetCaps( &inCaps );
  5023. if ( FAILED( result ) ) {
  5024. input->Release();
  5025. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";
  5026. errorText_ = errorStream_.str();
  5027. return FAILURE;
  5028. }
  5029. // Check channel information.
  5030. if ( inCaps.dwChannels < channels + firstChannel ) {
  5031. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  5032. return FAILURE;
  5033. }
  5034. // Check format information. Use 16-bit format unless user
  5035. // requests 8-bit.
  5036. DWORD deviceFormats;
  5037. if ( channels + firstChannel == 2 ) {
  5038. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  5039. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5040. waveFormat.wBitsPerSample = 8;
  5041. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5042. }
  5043. else { // assume 16-bit is supported
  5044. waveFormat.wBitsPerSample = 16;
  5045. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5046. }
  5047. }
  5048. else { // channel == 1
  5049. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  5050. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5051. waveFormat.wBitsPerSample = 8;
  5052. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5053. }
  5054. else { // assume 16-bit is supported
  5055. waveFormat.wBitsPerSample = 16;
  5056. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5057. }
  5058. }
  5059. stream_.userFormat = format;
  5060. // Update wave format structure and buffer information.
  5061. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  5062. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  5063. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  5064. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  5065. while ( dsPointerLeadTime * 2U > dsBufferSize )
  5066. dsBufferSize *= 2;
  5067. // Setup the secondary DS buffer description.
  5068. DSCBUFFERDESC bufferDescription;
  5069. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  5070. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  5071. bufferDescription.dwFlags = 0;
  5072. bufferDescription.dwReserved = 0;
  5073. bufferDescription.dwBufferBytes = dsBufferSize;
  5074. bufferDescription.lpwfxFormat = &waveFormat;
  5075. // Create the capture buffer.
  5076. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  5077. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  5078. if ( FAILED( result ) ) {
  5079. input->Release();
  5080. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";
  5081. errorText_ = errorStream_.str();
  5082. return FAILURE;
  5083. }
  5084. // Get the buffer size ... might be different from what we specified.
  5085. DSCBCAPS dscbcaps;
  5086. dscbcaps.dwSize = sizeof( DSCBCAPS );
  5087. result = buffer->GetCaps( &dscbcaps );
  5088. if ( FAILED( result ) ) {
  5089. input->Release();
  5090. buffer->Release();
  5091. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  5092. errorText_ = errorStream_.str();
  5093. return FAILURE;
  5094. }
  5095. dsBufferSize = dscbcaps.dwBufferBytes;
  5096. // NOTE: We could have a problem here if this is a duplex stream
  5097. // and the play and capture hardware buffer sizes are different
  5098. // (I'm actually not sure if that is a problem or not).
  5099. // Currently, we are not verifying that.
  5100. // Lock the capture buffer
  5101. LPVOID audioPtr;
  5102. DWORD dataLen;
  5103. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  5104. if ( FAILED( result ) ) {
  5105. input->Release();
  5106. buffer->Release();
  5107. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";
  5108. errorText_ = errorStream_.str();
  5109. return FAILURE;
  5110. }
  5111. // Zero the buffer
  5112. ZeroMemory( audioPtr, dataLen );
  5113. // Unlock the buffer
  5114. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5115. if ( FAILED( result ) ) {
  5116. input->Release();
  5117. buffer->Release();
  5118. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";
  5119. errorText_ = errorStream_.str();
  5120. return FAILURE;
  5121. }
  5122. ohandle = (void *) input;
  5123. bhandle = (void *) buffer;
  5124. }
  5125. // Set various stream parameters
  5126. DsHandle *handle = 0;
  5127. stream_.nDeviceChannels[mode] = channels + firstChannel;
  5128. stream_.nUserChannels[mode] = channels;
  5129. stream_.bufferSize = *bufferSize;
  5130. stream_.channelOffset[mode] = firstChannel;
  5131. stream_.deviceInterleaved[mode] = true;
  5132. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  5133. else stream_.userInterleaved = true;
  5134. // Set flag for buffer conversion
  5135. stream_.doConvertBuffer[mode] = false;
  5136. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  5137. stream_.doConvertBuffer[mode] = true;
  5138. if (stream_.userFormat != stream_.deviceFormat[mode])
  5139. stream_.doConvertBuffer[mode] = true;
  5140. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  5141. stream_.nUserChannels[mode] > 1 )
  5142. stream_.doConvertBuffer[mode] = true;
  5143. // Allocate necessary internal buffers
  5144. long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  5145. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  5146. if ( stream_.userBuffer[mode] == NULL ) {
  5147. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  5148. goto error;
  5149. }
  5150. if ( stream_.doConvertBuffer[mode] ) {
  5151. bool makeBuffer = true;
  5152. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  5153. if ( mode == INPUT ) {
  5154. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  5155. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  5156. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  5157. }
  5158. }
  5159. if ( makeBuffer ) {
  5160. bufferBytes *= *bufferSize;
  5161. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  5162. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  5163. if ( stream_.deviceBuffer == NULL ) {
  5164. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  5165. goto error;
  5166. }
  5167. }
  5168. }
  5169. // Allocate our DsHandle structures for the stream.
  5170. if ( stream_.apiHandle == 0 ) {
  5171. try {
  5172. handle = new DsHandle;
  5173. }
  5174. catch ( std::bad_alloc& ) {
  5175. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  5176. goto error;
  5177. }
  5178. // Create a manual-reset event.
  5179. handle->condition = CreateEvent( NULL, // no security
  5180. TRUE, // manual-reset
  5181. FALSE, // non-signaled initially
  5182. NULL ); // unnamed
  5183. stream_.apiHandle = (void *) handle;
  5184. }
  5185. else
  5186. handle = (DsHandle *) stream_.apiHandle;
  5187. handle->id[mode] = ohandle;
  5188. handle->buffer[mode] = bhandle;
  5189. handle->dsBufferSize[mode] = dsBufferSize;
  5190. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  5191. stream_.device[mode] = device;
  5192. stream_.state = STREAM_STOPPED;
  5193. if ( stream_.mode == OUTPUT && mode == INPUT )
  5194. // We had already set up an output stream.
  5195. stream_.mode = DUPLEX;
  5196. else
  5197. stream_.mode = mode;
  5198. stream_.nBuffers = nBuffers;
  5199. stream_.sampleRate = sampleRate;
  5200. // Setup the buffer conversion information structure.
  5201. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  5202. // Setup the callback thread.
  5203. if ( stream_.callbackInfo.isRunning == false ) {
  5204. unsigned threadId;
  5205. stream_.callbackInfo.isRunning = true;
  5206. stream_.callbackInfo.object = (void *) this;
  5207. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  5208. &stream_.callbackInfo, 0, &threadId );
  5209. if ( stream_.callbackInfo.thread == 0 ) {
  5210. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  5211. goto error;
  5212. }
  5213. // Boost DS thread priority
  5214. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  5215. }
  5216. return SUCCESS;
  5217. error:
  5218. if ( handle ) {
  5219. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5220. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5221. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5222. if ( buffer ) buffer->Release();
  5223. object->Release();
  5224. }
  5225. if ( handle->buffer[1] ) {
  5226. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5227. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5228. if ( buffer ) buffer->Release();
  5229. object->Release();
  5230. }
  5231. CloseHandle( handle->condition );
  5232. delete handle;
  5233. stream_.apiHandle = 0;
  5234. }
  5235. for ( int i=0; i<2; i++ ) {
  5236. if ( stream_.userBuffer[i] ) {
  5237. free( stream_.userBuffer[i] );
  5238. stream_.userBuffer[i] = 0;
  5239. }
  5240. }
  5241. if ( stream_.deviceBuffer ) {
  5242. free( stream_.deviceBuffer );
  5243. stream_.deviceBuffer = 0;
  5244. }
  5245. stream_.state = STREAM_CLOSED;
  5246. return FAILURE;
  5247. }
  5248. void RtApiDs :: closeStream()
  5249. {
  5250. if ( stream_.state == STREAM_CLOSED ) {
  5251. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  5252. error( RtAudioError::WARNING );
  5253. return;
  5254. }
  5255. // Stop the callback thread.
  5256. stream_.callbackInfo.isRunning = false;
  5257. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  5258. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  5259. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5260. if ( handle ) {
  5261. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5262. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5263. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5264. if ( buffer ) {
  5265. buffer->Stop();
  5266. buffer->Release();
  5267. }
  5268. object->Release();
  5269. }
  5270. if ( handle->buffer[1] ) {
  5271. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5272. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5273. if ( buffer ) {
  5274. buffer->Stop();
  5275. buffer->Release();
  5276. }
  5277. object->Release();
  5278. }
  5279. CloseHandle( handle->condition );
  5280. delete handle;
  5281. stream_.apiHandle = 0;
  5282. }
  5283. for ( int i=0; i<2; i++ ) {
  5284. if ( stream_.userBuffer[i] ) {
  5285. free( stream_.userBuffer[i] );
  5286. stream_.userBuffer[i] = 0;
  5287. }
  5288. }
  5289. if ( stream_.deviceBuffer ) {
  5290. free( stream_.deviceBuffer );
  5291. stream_.deviceBuffer = 0;
  5292. }
  5293. stream_.mode = UNINITIALIZED;
  5294. stream_.state = STREAM_CLOSED;
  5295. }
  5296. void RtApiDs :: startStream()
  5297. {
  5298. verifyStream();
  5299. if ( stream_.state == STREAM_RUNNING ) {
  5300. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  5301. error( RtAudioError::WARNING );
  5302. return;
  5303. }
  5304. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5305. // Increase scheduler frequency on lesser windows (a side-effect of
  5306. // increasing timer accuracy). On greater windows (Win2K or later),
  5307. // this is already in effect.
  5308. timeBeginPeriod( 1 );
  5309. buffersRolling = false;
  5310. duplexPrerollBytes = 0;
  5311. if ( stream_.mode == DUPLEX ) {
  5312. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  5313. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  5314. }
  5315. HRESULT result = 0;
  5316. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5317. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5318. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  5319. if ( FAILED( result ) ) {
  5320. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  5321. errorText_ = errorStream_.str();
  5322. goto unlock;
  5323. }
  5324. }
  5325. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5326. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5327. result = buffer->Start( DSCBSTART_LOOPING );
  5328. if ( FAILED( result ) ) {
  5329. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  5330. errorText_ = errorStream_.str();
  5331. goto unlock;
  5332. }
  5333. }
  5334. handle->drainCounter = 0;
  5335. handle->internalDrain = false;
  5336. ResetEvent( handle->condition );
  5337. stream_.state = STREAM_RUNNING;
  5338. unlock:
  5339. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5340. }
  5341. void RtApiDs :: stopStream()
  5342. {
  5343. verifyStream();
  5344. if ( stream_.state == STREAM_STOPPED ) {
  5345. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  5346. error( RtAudioError::WARNING );
  5347. return;
  5348. }
  5349. HRESULT result = 0;
  5350. LPVOID audioPtr;
  5351. DWORD dataLen;
  5352. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5353. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5354. if ( handle->drainCounter == 0 ) {
  5355. handle->drainCounter = 2;
  5356. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  5357. }
  5358. stream_.state = STREAM_STOPPED;
  5359. MUTEX_LOCK( &stream_.mutex );
  5360. // Stop the buffer and clear memory
  5361. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5362. result = buffer->Stop();
  5363. if ( FAILED( result ) ) {
  5364. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  5365. errorText_ = errorStream_.str();
  5366. goto unlock;
  5367. }
  5368. // Lock the buffer and clear it so that if we start to play again,
  5369. // we won't have old data playing.
  5370. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  5371. if ( FAILED( result ) ) {
  5372. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
  5373. errorText_ = errorStream_.str();
  5374. goto unlock;
  5375. }
  5376. // Zero the DS buffer
  5377. ZeroMemory( audioPtr, dataLen );
  5378. // Unlock the DS buffer
  5379. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5380. if ( FAILED( result ) ) {
  5381. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  5382. errorText_ = errorStream_.str();
  5383. goto unlock;
  5384. }
  5385. // If we start playing again, we must begin at beginning of buffer.
  5386. handle->bufferPointer[0] = 0;
  5387. }
  5388. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5389. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5390. audioPtr = NULL;
  5391. dataLen = 0;
  5392. stream_.state = STREAM_STOPPED;
  5393. if ( stream_.mode != DUPLEX )
  5394. MUTEX_LOCK( &stream_.mutex );
  5395. result = buffer->Stop();
  5396. if ( FAILED( result ) ) {
  5397. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  5398. errorText_ = errorStream_.str();
  5399. goto unlock;
  5400. }
  5401. // Lock the buffer and clear it so that if we start to play again,
  5402. // we won't have old data playing.
  5403. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  5404. if ( FAILED( result ) ) {
  5405. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
  5406. errorText_ = errorStream_.str();
  5407. goto unlock;
  5408. }
  5409. // Zero the DS buffer
  5410. ZeroMemory( audioPtr, dataLen );
  5411. // Unlock the DS buffer
  5412. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5413. if ( FAILED( result ) ) {
  5414. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  5415. errorText_ = errorStream_.str();
  5416. goto unlock;
  5417. }
  5418. // If we start recording again, we must begin at beginning of buffer.
  5419. handle->bufferPointer[1] = 0;
  5420. }
  5421. unlock:
  5422. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  5423. MUTEX_UNLOCK( &stream_.mutex );
  5424. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5425. }
  5426. void RtApiDs :: abortStream()
  5427. {
  5428. verifyStream();
  5429. if ( stream_.state == STREAM_STOPPED ) {
  5430. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  5431. error( RtAudioError::WARNING );
  5432. return;
  5433. }
  5434. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5435. handle->drainCounter = 2;
  5436. stopStream();
  5437. }
  5438. void RtApiDs :: callbackEvent()
  5439. {
  5440. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
  5441. Sleep( 50 ); // sleep 50 milliseconds
  5442. return;
  5443. }
  5444. if ( stream_.state == STREAM_CLOSED ) {
  5445. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5446. error( RtAudioError::WARNING );
  5447. return;
  5448. }
  5449. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  5450. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5451. // Check if we were draining the stream and signal is finished.
  5452. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  5453. stream_.state = STREAM_STOPPING;
  5454. if ( handle->internalDrain == false )
  5455. SetEvent( handle->condition );
  5456. else
  5457. stopStream();
  5458. return;
  5459. }
  5460. // Invoke user callback to get fresh output data UNLESS we are
  5461. // draining stream.
  5462. if ( handle->drainCounter == 0 ) {
  5463. RtAudioCallback callback = (RtAudioCallback) info->callback;
  5464. double streamTime = getStreamTime();
  5465. RtAudioStreamStatus status = 0;
  5466. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  5467. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5468. handle->xrun[0] = false;
  5469. }
  5470. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  5471. status |= RTAUDIO_INPUT_OVERFLOW;
  5472. handle->xrun[1] = false;
  5473. }
  5474. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5475. stream_.bufferSize, streamTime, status, info->userData );
  5476. if ( cbReturnValue == 2 ) {
  5477. stream_.state = STREAM_STOPPING;
  5478. handle->drainCounter = 2;
  5479. abortStream();
  5480. return;
  5481. }
  5482. else if ( cbReturnValue == 1 ) {
  5483. handle->drainCounter = 1;
  5484. handle->internalDrain = true;
  5485. }
  5486. }
  5487. HRESULT result;
  5488. DWORD currentWritePointer, safeWritePointer;
  5489. DWORD currentReadPointer, safeReadPointer;
  5490. UINT nextWritePointer;
  5491. LPVOID buffer1 = NULL;
  5492. LPVOID buffer2 = NULL;
  5493. DWORD bufferSize1 = 0;
  5494. DWORD bufferSize2 = 0;
  5495. char *buffer;
  5496. long bufferBytes;
  5497. MUTEX_LOCK( &stream_.mutex );
  5498. if ( stream_.state == STREAM_STOPPED ) {
  5499. MUTEX_UNLOCK( &stream_.mutex );
  5500. return;
  5501. }
  5502. if ( buffersRolling == false ) {
  5503. if ( stream_.mode == DUPLEX ) {
  5504. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5505. // It takes a while for the devices to get rolling. As a result,
  5506. // there's no guarantee that the capture and write device pointers
  5507. // will move in lockstep. Wait here for both devices to start
  5508. // rolling, and then set our buffer pointers accordingly.
  5509. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  5510. // bytes later than the write buffer.
  5511. // Stub: a serious risk of having a pre-emptive scheduling round
  5512. // take place between the two GetCurrentPosition calls... but I'm
  5513. // really not sure how to solve the problem. Temporarily boost to
  5514. // Realtime priority, maybe; but I'm not sure what priority the
  5515. // DirectSound service threads run at. We *should* be roughly
  5516. // within a ms or so of correct.
  5517. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5518. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5519. DWORD startSafeWritePointer, startSafeReadPointer;
  5520. result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
  5521. if ( FAILED( result ) ) {
  5522. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5523. errorText_ = errorStream_.str();
  5524. MUTEX_UNLOCK( &stream_.mutex );
  5525. error( RtAudioError::SYSTEM_ERROR );
  5526. return;
  5527. }
  5528. result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
  5529. if ( FAILED( result ) ) {
  5530. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5531. errorText_ = errorStream_.str();
  5532. MUTEX_UNLOCK( &stream_.mutex );
  5533. error( RtAudioError::SYSTEM_ERROR );
  5534. return;
  5535. }
  5536. while ( true ) {
  5537. result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
  5538. if ( FAILED( result ) ) {
  5539. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5540. errorText_ = errorStream_.str();
  5541. MUTEX_UNLOCK( &stream_.mutex );
  5542. error( RtAudioError::SYSTEM_ERROR );
  5543. return;
  5544. }
  5545. result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
  5546. if ( FAILED( result ) ) {
  5547. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5548. errorText_ = errorStream_.str();
  5549. MUTEX_UNLOCK( &stream_.mutex );
  5550. error( RtAudioError::SYSTEM_ERROR );
  5551. return;
  5552. }
  5553. if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
  5554. Sleep( 1 );
  5555. }
  5556. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5557. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5558. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5559. handle->bufferPointer[1] = safeReadPointer;
  5560. }
  5561. else if ( stream_.mode == OUTPUT ) {
  5562. // Set the proper nextWritePosition after initial startup.
  5563. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5564. result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5565. if ( FAILED( result ) ) {
  5566. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5567. errorText_ = errorStream_.str();
  5568. MUTEX_UNLOCK( &stream_.mutex );
  5569. error( RtAudioError::SYSTEM_ERROR );
  5570. return;
  5571. }
  5572. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5573. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5574. }
  5575. buffersRolling = true;
  5576. }
  5577. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5578. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5579. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  5580. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5581. bufferBytes *= formatBytes( stream_.userFormat );
  5582. memset( stream_.userBuffer[0], 0, bufferBytes );
  5583. }
  5584. // Setup parameters and do buffer conversion if necessary.
  5585. if ( stream_.doConvertBuffer[0] ) {
  5586. buffer = stream_.deviceBuffer;
  5587. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5588. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  5589. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  5590. }
  5591. else {
  5592. buffer = stream_.userBuffer[0];
  5593. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5594. bufferBytes *= formatBytes( stream_.userFormat );
  5595. }
  5596. // No byte swapping necessary in DirectSound implementation.
  5597. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  5598. // unsigned. So, we need to convert our signed 8-bit data here to
  5599. // unsigned.
  5600. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  5601. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  5602. DWORD dsBufferSize = handle->dsBufferSize[0];
  5603. nextWritePointer = handle->bufferPointer[0];
  5604. DWORD endWrite, leadPointer;
  5605. while ( true ) {
  5606. // Find out where the read and "safe write" pointers are.
  5607. result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5608. if ( FAILED( result ) ) {
  5609. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5610. errorText_ = errorStream_.str();
  5611. MUTEX_UNLOCK( &stream_.mutex );
  5612. error( RtAudioError::SYSTEM_ERROR );
  5613. return;
  5614. }
  5615. // We will copy our output buffer into the region between
  5616. // safeWritePointer and leadPointer. If leadPointer is not
  5617. // beyond the next endWrite position, wait until it is.
  5618. leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
  5619. //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
  5620. if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
  5621. if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
  5622. endWrite = nextWritePointer + bufferBytes;
  5623. // Check whether the entire write region is behind the play pointer.
  5624. if ( leadPointer >= endWrite ) break;
  5625. // If we are here, then we must wait until the leadPointer advances
  5626. // beyond the end of our next write region. We use the
  5627. // Sleep() function to suspend operation until that happens.
  5628. double millis = ( endWrite - leadPointer ) * 1000.0;
  5629. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  5630. if ( millis < 1.0 ) millis = 1.0;
  5631. Sleep( (DWORD) millis );
  5632. }
  5633. if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
  5634. || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
  5635. // We've strayed into the forbidden zone ... resync the read pointer.
  5636. handle->xrun[0] = true;
  5637. nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
  5638. if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
  5639. handle->bufferPointer[0] = nextWritePointer;
  5640. endWrite = nextWritePointer + bufferBytes;
  5641. }
  5642. // Lock free space in the buffer
  5643. result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
  5644. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5645. if ( FAILED( result ) ) {
  5646. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  5647. errorText_ = errorStream_.str();
  5648. MUTEX_UNLOCK( &stream_.mutex );
  5649. error( RtAudioError::SYSTEM_ERROR );
  5650. return;
  5651. }
  5652. // Copy our buffer into the DS buffer
  5653. CopyMemory( buffer1, buffer, bufferSize1 );
  5654. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  5655. // Update our buffer offset and unlock sound buffer
  5656. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5657. if ( FAILED( result ) ) {
  5658. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  5659. errorText_ = errorStream_.str();
  5660. MUTEX_UNLOCK( &stream_.mutex );
  5661. error( RtAudioError::SYSTEM_ERROR );
  5662. return;
  5663. }
  5664. nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5665. handle->bufferPointer[0] = nextWritePointer;
  5666. }
  5667. // Don't bother draining input
  5668. if ( handle->drainCounter ) {
  5669. handle->drainCounter++;
  5670. goto unlock;
  5671. }
  5672. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5673. // Setup parameters.
  5674. if ( stream_.doConvertBuffer[1] ) {
  5675. buffer = stream_.deviceBuffer;
  5676. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  5677. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  5678. }
  5679. else {
  5680. buffer = stream_.userBuffer[1];
  5681. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  5682. bufferBytes *= formatBytes( stream_.userFormat );
  5683. }
  5684. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5685. long nextReadPointer = handle->bufferPointer[1];
  5686. DWORD dsBufferSize = handle->dsBufferSize[1];
  5687. // Find out where the write and "safe read" pointers are.
  5688. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5689. if ( FAILED( result ) ) {
  5690. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5691. errorText_ = errorStream_.str();
  5692. MUTEX_UNLOCK( &stream_.mutex );
  5693. error( RtAudioError::SYSTEM_ERROR );
  5694. return;
  5695. }
  5696. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5697. DWORD endRead = nextReadPointer + bufferBytes;
  5698. // Handling depends on whether we are INPUT or DUPLEX.
  5699. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  5700. // then a wait here will drag the write pointers into the forbidden zone.
  5701. //
  5702. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  5703. // it's in a safe position. This causes dropouts, but it seems to be the only
  5704. // practical way to sync up the read and write pointers reliably, given the
  5705. // the very complex relationship between phase and increment of the read and write
  5706. // pointers.
  5707. //
  5708. // In order to minimize audible dropouts in DUPLEX mode, we will
  5709. // provide a pre-roll period of 0.5 seconds in which we return
  5710. // zeros from the read buffer while the pointers sync up.
  5711. if ( stream_.mode == DUPLEX ) {
  5712. if ( safeReadPointer < endRead ) {
  5713. if ( duplexPrerollBytes <= 0 ) {
  5714. // Pre-roll time over. Be more agressive.
  5715. int adjustment = endRead-safeReadPointer;
  5716. handle->xrun[1] = true;
  5717. // Two cases:
  5718. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  5719. // and perform fine adjustments later.
  5720. // - small adjustments: back off by twice as much.
  5721. if ( adjustment >= 2*bufferBytes )
  5722. nextReadPointer = safeReadPointer-2*bufferBytes;
  5723. else
  5724. nextReadPointer = safeReadPointer-bufferBytes-adjustment;
  5725. if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5726. }
  5727. else {
  5728. // In pre=roll time. Just do it.
  5729. nextReadPointer = safeReadPointer - bufferBytes;
  5730. while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5731. }
  5732. endRead = nextReadPointer + bufferBytes;
  5733. }
  5734. }
  5735. else { // mode == INPUT
  5736. while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
  5737. // See comments for playback.
  5738. double millis = (endRead - safeReadPointer) * 1000.0;
  5739. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  5740. if ( millis < 1.0 ) millis = 1.0;
  5741. Sleep( (DWORD) millis );
  5742. // Wake up and find out where we are now.
  5743. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5744. if ( FAILED( result ) ) {
  5745. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5746. errorText_ = errorStream_.str();
  5747. MUTEX_UNLOCK( &stream_.mutex );
  5748. error( RtAudioError::SYSTEM_ERROR );
  5749. return;
  5750. }
  5751. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5752. }
  5753. }
  5754. // Lock free space in the buffer
  5755. result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
  5756. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5757. if ( FAILED( result ) ) {
  5758. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  5759. errorText_ = errorStream_.str();
  5760. MUTEX_UNLOCK( &stream_.mutex );
  5761. error( RtAudioError::SYSTEM_ERROR );
  5762. return;
  5763. }
  5764. if ( duplexPrerollBytes <= 0 ) {
  5765. // Copy our buffer into the DS buffer
  5766. CopyMemory( buffer, buffer1, bufferSize1 );
  5767. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  5768. }
  5769. else {
  5770. memset( buffer, 0, bufferSize1 );
  5771. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  5772. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  5773. }
  5774. // Update our buffer offset and unlock sound buffer
  5775. nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5776. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5777. if ( FAILED( result ) ) {
  5778. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  5779. errorText_ = errorStream_.str();
  5780. MUTEX_UNLOCK( &stream_.mutex );
  5781. error( RtAudioError::SYSTEM_ERROR );
  5782. return;
  5783. }
  5784. handle->bufferPointer[1] = nextReadPointer;
  5785. // No byte swapping necessary in DirectSound implementation.
  5786. // If necessary, convert 8-bit data from unsigned to signed.
  5787. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  5788. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  5789. // Do buffer conversion if necessary.
  5790. if ( stream_.doConvertBuffer[1] )
  5791. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5792. }
  5793. unlock:
  5794. MUTEX_UNLOCK( &stream_.mutex );
  5795. RtApi::tickStreamTime();
  5796. }
  5797. // Definitions for utility functions and callbacks
  5798. // specific to the DirectSound implementation.
  5799. static unsigned __stdcall callbackHandler( void *ptr )
  5800. {
  5801. CallbackInfo *info = (CallbackInfo *) ptr;
  5802. RtApiDs *object = (RtApiDs *) info->object;
  5803. bool* isRunning = &info->isRunning;
  5804. while ( *isRunning == true ) {
  5805. object->callbackEvent();
  5806. }
  5807. _endthreadex( 0 );
  5808. return 0;
  5809. }
  5810. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  5811. LPCTSTR description,
  5812. LPCTSTR /*module*/,
  5813. LPVOID lpContext )
  5814. {
  5815. struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
  5816. std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
  5817. HRESULT hr;
  5818. bool validDevice = false;
  5819. if ( probeInfo.isInput == true ) {
  5820. DSCCAPS caps;
  5821. LPDIRECTSOUNDCAPTURE object;
  5822. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  5823. if ( hr != DS_OK ) return TRUE;
  5824. caps.dwSize = sizeof(caps);
  5825. hr = object->GetCaps( &caps );
  5826. if ( hr == DS_OK ) {
  5827. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  5828. validDevice = true;
  5829. }
  5830. object->Release();
  5831. }
  5832. else {
  5833. DSCAPS caps;
  5834. LPDIRECTSOUND object;
  5835. hr = DirectSoundCreate( lpguid, &object, NULL );
  5836. if ( hr != DS_OK ) return TRUE;
  5837. caps.dwSize = sizeof(caps);
  5838. hr = object->GetCaps( &caps );
  5839. if ( hr == DS_OK ) {
  5840. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  5841. validDevice = true;
  5842. }
  5843. object->Release();
  5844. }
  5845. // If good device, then save its name and guid.
  5846. std::string name = convertCharPointerToStdString( description );
  5847. //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
  5848. if ( lpguid == NULL )
  5849. name = "Default Device";
  5850. if ( validDevice ) {
  5851. for ( unsigned int i=0; i<dsDevices.size(); i++ ) {
  5852. if ( dsDevices[i].name == name ) {
  5853. dsDevices[i].found = true;
  5854. if ( probeInfo.isInput ) {
  5855. dsDevices[i].id[1] = lpguid;
  5856. dsDevices[i].validId[1] = true;
  5857. }
  5858. else {
  5859. dsDevices[i].id[0] = lpguid;
  5860. dsDevices[i].validId[0] = true;
  5861. }
  5862. return TRUE;
  5863. }
  5864. }
  5865. DsDevice device;
  5866. device.name = name;
  5867. device.found = true;
  5868. if ( probeInfo.isInput ) {
  5869. device.id[1] = lpguid;
  5870. device.validId[1] = true;
  5871. }
  5872. else {
  5873. device.id[0] = lpguid;
  5874. device.validId[0] = true;
  5875. }
  5876. dsDevices.push_back( device );
  5877. }
  5878. return TRUE;
  5879. }
  5880. static const char* getErrorString( int code )
  5881. {
  5882. switch ( code ) {
  5883. case DSERR_ALLOCATED:
  5884. return "Already allocated";
  5885. case DSERR_CONTROLUNAVAIL:
  5886. return "Control unavailable";
  5887. case DSERR_INVALIDPARAM:
  5888. return "Invalid parameter";
  5889. case DSERR_INVALIDCALL:
  5890. return "Invalid call";
  5891. case DSERR_GENERIC:
  5892. return "Generic error";
  5893. case DSERR_PRIOLEVELNEEDED:
  5894. return "Priority level needed";
  5895. case DSERR_OUTOFMEMORY:
  5896. return "Out of memory";
  5897. case DSERR_BADFORMAT:
  5898. return "The sample rate or the channel format is not supported";
  5899. case DSERR_UNSUPPORTED:
  5900. return "Not supported";
  5901. case DSERR_NODRIVER:
  5902. return "No driver";
  5903. case DSERR_ALREADYINITIALIZED:
  5904. return "Already initialized";
  5905. case DSERR_NOAGGREGATION:
  5906. return "No aggregation";
  5907. case DSERR_BUFFERLOST:
  5908. return "Buffer lost";
  5909. case DSERR_OTHERAPPHASPRIO:
  5910. return "Another application already has priority";
  5911. case DSERR_UNINITIALIZED:
  5912. return "Uninitialized";
  5913. default:
  5914. return "DirectSound unknown error";
  5915. }
  5916. }
  5917. //******************** End of __WINDOWS_DS__ *********************//
  5918. #endif
  5919. #if defined(__LINUX_ALSA__)
  5920. #include <alsa/asoundlib.h>
  5921. #include <unistd.h>
  5922. // A structure to hold various information related to the ALSA API
  5923. // implementation.
  5924. struct AlsaHandle {
  5925. snd_pcm_t *handles[2];
  5926. bool synchronized;
  5927. bool xrun[2];
  5928. pthread_cond_t runnable_cv;
  5929. bool runnable;
  5930. AlsaHandle()
  5931. :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
  5932. };
  5933. static void *alsaCallbackHandler( void * ptr );
  5934. RtApiAlsa :: RtApiAlsa()
  5935. {
  5936. // Nothing to do here.
  5937. }
  5938. RtApiAlsa :: ~RtApiAlsa()
  5939. {
  5940. if ( stream_.state != STREAM_CLOSED ) closeStream();
  5941. }
  5942. unsigned int RtApiAlsa :: getDeviceCount( void )
  5943. {
  5944. unsigned nDevices = 0;
  5945. int result, subdevice, card;
  5946. char name[64];
  5947. snd_ctl_t *handle;
  5948. // Count cards and devices
  5949. card = -1;
  5950. snd_card_next( &card );
  5951. while ( card >= 0 ) {
  5952. sprintf( name, "hw:%d", card );
  5953. result = snd_ctl_open( &handle, name, 0 );
  5954. if ( result < 0 ) {
  5955. errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  5956. errorText_ = errorStream_.str();
  5957. error( RtAudioError::WARNING );
  5958. goto nextcard;
  5959. }
  5960. subdevice = -1;
  5961. while( 1 ) {
  5962. result = snd_ctl_pcm_next_device( handle, &subdevice );
  5963. if ( result < 0 ) {
  5964. errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  5965. errorText_ = errorStream_.str();
  5966. error( RtAudioError::WARNING );
  5967. break;
  5968. }
  5969. if ( subdevice < 0 )
  5970. break;
  5971. nDevices++;
  5972. }
  5973. nextcard:
  5974. snd_ctl_close( handle );
  5975. snd_card_next( &card );
  5976. }
  5977. result = snd_ctl_open( &handle, "default", 0 );
  5978. if (result == 0) {
  5979. nDevices++;
  5980. snd_ctl_close( handle );
  5981. }
  5982. return nDevices;
  5983. }
  5984. RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
  5985. {
  5986. RtAudio::DeviceInfo info;
  5987. info.probed = false;
  5988. unsigned nDevices = 0;
  5989. int result, subdevice, card;
  5990. char name[64];
  5991. snd_ctl_t *chandle;
  5992. // Count cards and devices
  5993. card = -1;
  5994. subdevice = -1;
  5995. snd_card_next( &card );
  5996. while ( card >= 0 ) {
  5997. sprintf( name, "hw:%d", card );
  5998. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  5999. if ( result < 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. snd_ctl_close( chandle );
  6023. snd_card_next( &card );
  6024. }
  6025. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6026. if ( result == 0 ) {
  6027. if ( nDevices == device ) {
  6028. strcpy( name, "default" );
  6029. goto foundDevice;
  6030. }
  6031. nDevices++;
  6032. }
  6033. if ( nDevices == 0 ) {
  6034. errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
  6035. error( RtAudioError::INVALID_USE );
  6036. return info;
  6037. }
  6038. if ( device >= nDevices ) {
  6039. errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
  6040. error( RtAudioError::INVALID_USE );
  6041. return info;
  6042. }
  6043. foundDevice:
  6044. // If a stream is already open, we cannot probe the stream devices.
  6045. // Thus, use the saved results.
  6046. if ( stream_.state != STREAM_CLOSED &&
  6047. ( stream_.device[0] == device || stream_.device[1] == device ) ) {
  6048. snd_ctl_close( chandle );
  6049. if ( device >= devices_.size() ) {
  6050. errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
  6051. error( RtAudioError::WARNING );
  6052. return info;
  6053. }
  6054. return devices_[ device ];
  6055. }
  6056. int openMode = SND_PCM_ASYNC;
  6057. snd_pcm_stream_t stream;
  6058. snd_pcm_info_t *pcminfo;
  6059. snd_pcm_info_alloca( &pcminfo );
  6060. snd_pcm_t *phandle;
  6061. snd_pcm_hw_params_t *params;
  6062. snd_pcm_hw_params_alloca( &params );
  6063. // First try for playback unless default device (which has subdev -1)
  6064. stream = SND_PCM_STREAM_PLAYBACK;
  6065. snd_pcm_info_set_stream( pcminfo, stream );
  6066. if ( subdevice != -1 ) {
  6067. snd_pcm_info_set_device( pcminfo, subdevice );
  6068. snd_pcm_info_set_subdevice( pcminfo, 0 );
  6069. result = snd_ctl_pcm_info( chandle, pcminfo );
  6070. if ( result < 0 ) {
  6071. // Device probably doesn't support playback.
  6072. goto captureProbe;
  6073. }
  6074. }
  6075. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
  6076. if ( result < 0 ) {
  6077. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6078. errorText_ = errorStream_.str();
  6079. error( RtAudioError::WARNING );
  6080. goto captureProbe;
  6081. }
  6082. // The device is open ... fill the parameter structure.
  6083. result = snd_pcm_hw_params_any( phandle, params );
  6084. if ( result < 0 ) {
  6085. snd_pcm_close( phandle );
  6086. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6087. errorText_ = errorStream_.str();
  6088. error( RtAudioError::WARNING );
  6089. goto captureProbe;
  6090. }
  6091. // Get output channel information.
  6092. unsigned int value;
  6093. result = snd_pcm_hw_params_get_channels_max( params, &value );
  6094. if ( result < 0 ) {
  6095. snd_pcm_close( phandle );
  6096. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
  6097. errorText_ = errorStream_.str();
  6098. error( RtAudioError::WARNING );
  6099. goto captureProbe;
  6100. }
  6101. info.outputChannels = value;
  6102. snd_pcm_close( phandle );
  6103. captureProbe:
  6104. stream = SND_PCM_STREAM_CAPTURE;
  6105. snd_pcm_info_set_stream( pcminfo, stream );
  6106. // Now try for capture unless default device (with subdev = -1)
  6107. if ( subdevice != -1 ) {
  6108. result = snd_ctl_pcm_info( chandle, pcminfo );
  6109. snd_ctl_close( chandle );
  6110. if ( result < 0 ) {
  6111. // Device probably doesn't support capture.
  6112. if ( info.outputChannels == 0 ) return info;
  6113. goto probeParameters;
  6114. }
  6115. }
  6116. else
  6117. snd_ctl_close( chandle );
  6118. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  6119. if ( result < 0 ) {
  6120. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6121. errorText_ = errorStream_.str();
  6122. error( RtAudioError::WARNING );
  6123. if ( info.outputChannels == 0 ) return info;
  6124. goto probeParameters;
  6125. }
  6126. // The device is open ... fill the parameter structure.
  6127. result = snd_pcm_hw_params_any( phandle, params );
  6128. if ( result < 0 ) {
  6129. snd_pcm_close( phandle );
  6130. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6131. errorText_ = errorStream_.str();
  6132. error( RtAudioError::WARNING );
  6133. if ( info.outputChannels == 0 ) return info;
  6134. goto probeParameters;
  6135. }
  6136. result = snd_pcm_hw_params_get_channels_max( params, &value );
  6137. if ( result < 0 ) {
  6138. snd_pcm_close( phandle );
  6139. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
  6140. errorText_ = errorStream_.str();
  6141. error( RtAudioError::WARNING );
  6142. if ( info.outputChannels == 0 ) return info;
  6143. goto probeParameters;
  6144. }
  6145. info.inputChannels = value;
  6146. snd_pcm_close( phandle );
  6147. // If device opens for both playback and capture, we determine the channels.
  6148. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  6149. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  6150. // ALSA doesn't provide default devices so we'll use the first available one.
  6151. if ( device == 0 && info.outputChannels > 0 )
  6152. info.isDefaultOutput = true;
  6153. if ( device == 0 && info.inputChannels > 0 )
  6154. info.isDefaultInput = true;
  6155. probeParameters:
  6156. // At this point, we just need to figure out the supported data
  6157. // formats and sample rates. We'll proceed by opening the device in
  6158. // the direction with the maximum number of channels, or playback if
  6159. // they are equal. This might limit our sample rate options, but so
  6160. // be it.
  6161. if ( info.outputChannels >= info.inputChannels )
  6162. stream = SND_PCM_STREAM_PLAYBACK;
  6163. else
  6164. stream = SND_PCM_STREAM_CAPTURE;
  6165. snd_pcm_info_set_stream( pcminfo, stream );
  6166. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  6167. if ( result < 0 ) {
  6168. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6169. errorText_ = errorStream_.str();
  6170. error( RtAudioError::WARNING );
  6171. return info;
  6172. }
  6173. // The device is open ... fill the parameter structure.
  6174. result = snd_pcm_hw_params_any( phandle, params );
  6175. if ( result < 0 ) {
  6176. snd_pcm_close( phandle );
  6177. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6178. errorText_ = errorStream_.str();
  6179. error( RtAudioError::WARNING );
  6180. return info;
  6181. }
  6182. // Test our discrete set of sample rate values.
  6183. info.sampleRates.clear();
  6184. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  6185. if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {
  6186. info.sampleRates.push_back( SAMPLE_RATES[i] );
  6187. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  6188. info.preferredSampleRate = SAMPLE_RATES[i];
  6189. }
  6190. }
  6191. if ( info.sampleRates.size() == 0 ) {
  6192. snd_pcm_close( phandle );
  6193. errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
  6194. errorText_ = errorStream_.str();
  6195. error( RtAudioError::WARNING );
  6196. return info;
  6197. }
  6198. // Probe the supported data formats ... we don't care about endian-ness just yet
  6199. snd_pcm_format_t format;
  6200. info.nativeFormats = 0;
  6201. format = SND_PCM_FORMAT_S8;
  6202. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6203. info.nativeFormats |= RTAUDIO_SINT8;
  6204. format = SND_PCM_FORMAT_S16;
  6205. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6206. info.nativeFormats |= RTAUDIO_SINT16;
  6207. format = SND_PCM_FORMAT_S24;
  6208. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6209. info.nativeFormats |= RTAUDIO_SINT24;
  6210. format = SND_PCM_FORMAT_S32;
  6211. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6212. info.nativeFormats |= RTAUDIO_SINT32;
  6213. format = SND_PCM_FORMAT_FLOAT;
  6214. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6215. info.nativeFormats |= RTAUDIO_FLOAT32;
  6216. format = SND_PCM_FORMAT_FLOAT64;
  6217. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6218. info.nativeFormats |= RTAUDIO_FLOAT64;
  6219. // Check that we have at least one supported format
  6220. if ( info.nativeFormats == 0 ) {
  6221. snd_pcm_close( phandle );
  6222. errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
  6223. errorText_ = errorStream_.str();
  6224. error( RtAudioError::WARNING );
  6225. return info;
  6226. }
  6227. // Get the device name
  6228. char *cardname;
  6229. result = snd_card_get_name( card, &cardname );
  6230. if ( result >= 0 ) {
  6231. sprintf( name, "hw:%s,%d", cardname, subdevice );
  6232. free( cardname );
  6233. }
  6234. info.name = name;
  6235. // That's all ... close the device and return
  6236. snd_pcm_close( phandle );
  6237. info.probed = true;
  6238. return info;
  6239. }
  6240. void RtApiAlsa :: saveDeviceInfo( void )
  6241. {
  6242. devices_.clear();
  6243. unsigned int nDevices = getDeviceCount();
  6244. devices_.resize( nDevices );
  6245. for ( unsigned int i=0; i<nDevices; i++ )
  6246. devices_[i] = getDeviceInfo( i );
  6247. }
  6248. bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  6249. unsigned int firstChannel, unsigned int sampleRate,
  6250. RtAudioFormat format, unsigned int *bufferSize,
  6251. RtAudio::StreamOptions *options )
  6252. {
  6253. #if defined(__RTAUDIO_DEBUG__)
  6254. snd_output_t *out;
  6255. snd_output_stdio_attach(&out, stderr, 0);
  6256. #endif
  6257. // I'm not using the "plug" interface ... too much inconsistent behavior.
  6258. unsigned nDevices = 0;
  6259. int result, subdevice, card;
  6260. char name[64];
  6261. snd_ctl_t *chandle;
  6262. if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )
  6263. snprintf(name, sizeof(name), "%s", "default");
  6264. else {
  6265. // Count cards and devices
  6266. card = -1;
  6267. snd_card_next( &card );
  6268. while ( card >= 0 ) {
  6269. sprintf( name, "hw:%d", card );
  6270. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  6271. if ( result < 0 ) {
  6272. errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6273. errorText_ = errorStream_.str();
  6274. return FAILURE;
  6275. }
  6276. subdevice = -1;
  6277. while( 1 ) {
  6278. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  6279. if ( result < 0 ) break;
  6280. if ( subdevice < 0 ) break;
  6281. if ( nDevices == device ) {
  6282. sprintf( name, "hw:%d,%d", card, subdevice );
  6283. snd_ctl_close( chandle );
  6284. goto foundDevice;
  6285. }
  6286. nDevices++;
  6287. }
  6288. snd_ctl_close( chandle );
  6289. snd_card_next( &card );
  6290. }
  6291. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6292. if ( result == 0 ) {
  6293. if ( nDevices == device ) {
  6294. strcpy( name, "default" );
  6295. goto foundDevice;
  6296. }
  6297. nDevices++;
  6298. }
  6299. if ( nDevices == 0 ) {
  6300. // This should not happen because a check is made before this function is called.
  6301. errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
  6302. return FAILURE;
  6303. }
  6304. if ( device >= nDevices ) {
  6305. // This should not happen because a check is made before this function is called.
  6306. errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
  6307. return FAILURE;
  6308. }
  6309. }
  6310. foundDevice:
  6311. // The getDeviceInfo() function will not work for a device that is
  6312. // already open. Thus, we'll probe the system before opening a
  6313. // stream and save the results for use by getDeviceInfo().
  6314. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
  6315. this->saveDeviceInfo();
  6316. snd_pcm_stream_t stream;
  6317. if ( mode == OUTPUT )
  6318. stream = SND_PCM_STREAM_PLAYBACK;
  6319. else
  6320. stream = SND_PCM_STREAM_CAPTURE;
  6321. snd_pcm_t *phandle;
  6322. int openMode = SND_PCM_ASYNC;
  6323. result = snd_pcm_open( &phandle, name, stream, openMode );
  6324. if ( result < 0 ) {
  6325. if ( mode == OUTPUT )
  6326. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
  6327. else
  6328. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
  6329. errorText_ = errorStream_.str();
  6330. return FAILURE;
  6331. }
  6332. // Fill the parameter structure.
  6333. snd_pcm_hw_params_t *hw_params;
  6334. snd_pcm_hw_params_alloca( &hw_params );
  6335. result = snd_pcm_hw_params_any( phandle, hw_params );
  6336. if ( result < 0 ) {
  6337. snd_pcm_close( phandle );
  6338. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
  6339. errorText_ = errorStream_.str();
  6340. return FAILURE;
  6341. }
  6342. #if defined(__RTAUDIO_DEBUG__)
  6343. fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
  6344. snd_pcm_hw_params_dump( hw_params, out );
  6345. #endif
  6346. // Set access ... check user preference.
  6347. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
  6348. stream_.userInterleaved = false;
  6349. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6350. if ( result < 0 ) {
  6351. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6352. stream_.deviceInterleaved[mode] = true;
  6353. }
  6354. else
  6355. stream_.deviceInterleaved[mode] = false;
  6356. }
  6357. else {
  6358. stream_.userInterleaved = true;
  6359. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6360. if ( result < 0 ) {
  6361. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6362. stream_.deviceInterleaved[mode] = false;
  6363. }
  6364. else
  6365. stream_.deviceInterleaved[mode] = true;
  6366. }
  6367. if ( result < 0 ) {
  6368. snd_pcm_close( phandle );
  6369. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
  6370. errorText_ = errorStream_.str();
  6371. return FAILURE;
  6372. }
  6373. // Determine how to set the device format.
  6374. stream_.userFormat = format;
  6375. snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
  6376. if ( format == RTAUDIO_SINT8 )
  6377. deviceFormat = SND_PCM_FORMAT_S8;
  6378. else if ( format == RTAUDIO_SINT16 )
  6379. deviceFormat = SND_PCM_FORMAT_S16;
  6380. else if ( format == RTAUDIO_SINT24 )
  6381. deviceFormat = SND_PCM_FORMAT_S24;
  6382. else if ( format == RTAUDIO_SINT32 )
  6383. deviceFormat = SND_PCM_FORMAT_S32;
  6384. else if ( format == RTAUDIO_FLOAT32 )
  6385. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6386. else if ( format == RTAUDIO_FLOAT64 )
  6387. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6388. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
  6389. stream_.deviceFormat[mode] = format;
  6390. goto setFormat;
  6391. }
  6392. // The user requested format is not natively supported by the device.
  6393. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6394. if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
  6395. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  6396. goto setFormat;
  6397. }
  6398. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6399. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6400. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  6401. goto setFormat;
  6402. }
  6403. deviceFormat = SND_PCM_FORMAT_S32;
  6404. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6405. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  6406. goto setFormat;
  6407. }
  6408. deviceFormat = SND_PCM_FORMAT_S24;
  6409. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6410. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  6411. goto setFormat;
  6412. }
  6413. deviceFormat = SND_PCM_FORMAT_S16;
  6414. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6415. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  6416. goto setFormat;
  6417. }
  6418. deviceFormat = SND_PCM_FORMAT_S8;
  6419. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6420. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  6421. goto setFormat;
  6422. }
  6423. // If we get here, no supported format was found.
  6424. snd_pcm_close( phandle );
  6425. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
  6426. errorText_ = errorStream_.str();
  6427. return FAILURE;
  6428. setFormat:
  6429. result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
  6430. if ( result < 0 ) {
  6431. snd_pcm_close( phandle );
  6432. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
  6433. errorText_ = errorStream_.str();
  6434. return FAILURE;
  6435. }
  6436. // Determine whether byte-swaping is necessary.
  6437. stream_.doByteSwap[mode] = false;
  6438. if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
  6439. result = snd_pcm_format_cpu_endian( deviceFormat );
  6440. if ( result == 0 )
  6441. stream_.doByteSwap[mode] = true;
  6442. else if (result < 0) {
  6443. snd_pcm_close( phandle );
  6444. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
  6445. errorText_ = errorStream_.str();
  6446. return FAILURE;
  6447. }
  6448. }
  6449. // Set the sample rate.
  6450. result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
  6451. if ( result < 0 ) {
  6452. snd_pcm_close( phandle );
  6453. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
  6454. errorText_ = errorStream_.str();
  6455. return FAILURE;
  6456. }
  6457. // Determine the number of channels for this device. We support a possible
  6458. // minimum device channel number > than the value requested by the user.
  6459. stream_.nUserChannels[mode] = channels;
  6460. unsigned int value;
  6461. result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
  6462. unsigned int deviceChannels = value;
  6463. if ( result < 0 || deviceChannels < channels + firstChannel ) {
  6464. snd_pcm_close( phandle );
  6465. errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
  6466. errorText_ = errorStream_.str();
  6467. return FAILURE;
  6468. }
  6469. result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
  6470. if ( result < 0 ) {
  6471. snd_pcm_close( phandle );
  6472. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6473. errorText_ = errorStream_.str();
  6474. return FAILURE;
  6475. }
  6476. deviceChannels = value;
  6477. if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
  6478. stream_.nDeviceChannels[mode] = deviceChannels;
  6479. // Set the device channels.
  6480. result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
  6481. if ( result < 0 ) {
  6482. snd_pcm_close( phandle );
  6483. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6484. errorText_ = errorStream_.str();
  6485. return FAILURE;
  6486. }
  6487. // Set the buffer (or period) size.
  6488. int dir = 0;
  6489. snd_pcm_uframes_t periodSize = *bufferSize;
  6490. result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
  6491. if ( result < 0 ) {
  6492. snd_pcm_close( phandle );
  6493. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
  6494. errorText_ = errorStream_.str();
  6495. return FAILURE;
  6496. }
  6497. *bufferSize = periodSize;
  6498. // Set the buffer number, which in ALSA is referred to as the "period".
  6499. unsigned int periods = 0;
  6500. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
  6501. if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;
  6502. if ( periods < 2 ) periods = 4; // a fairly safe default value
  6503. result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
  6504. if ( result < 0 ) {
  6505. snd_pcm_close( phandle );
  6506. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
  6507. errorText_ = errorStream_.str();
  6508. return FAILURE;
  6509. }
  6510. // If attempting to setup a duplex stream, the bufferSize parameter
  6511. // MUST be the same in both directions!
  6512. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  6513. snd_pcm_close( phandle );
  6514. errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
  6515. errorText_ = errorStream_.str();
  6516. return FAILURE;
  6517. }
  6518. stream_.bufferSize = *bufferSize;
  6519. // Install the hardware configuration
  6520. result = snd_pcm_hw_params( phandle, hw_params );
  6521. if ( result < 0 ) {
  6522. snd_pcm_close( phandle );
  6523. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6524. errorText_ = errorStream_.str();
  6525. return FAILURE;
  6526. }
  6527. #if defined(__RTAUDIO_DEBUG__)
  6528. fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
  6529. snd_pcm_hw_params_dump( hw_params, out );
  6530. #endif
  6531. // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
  6532. snd_pcm_sw_params_t *sw_params = NULL;
  6533. snd_pcm_sw_params_alloca( &sw_params );
  6534. snd_pcm_sw_params_current( phandle, sw_params );
  6535. snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
  6536. snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
  6537. snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
  6538. // The following two settings were suggested by Theo Veenker
  6539. //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
  6540. //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
  6541. // here are two options for a fix
  6542. //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
  6543. snd_pcm_uframes_t val;
  6544. snd_pcm_sw_params_get_boundary( sw_params, &val );
  6545. snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
  6546. result = snd_pcm_sw_params( phandle, sw_params );
  6547. if ( result < 0 ) {
  6548. snd_pcm_close( phandle );
  6549. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6550. errorText_ = errorStream_.str();
  6551. return FAILURE;
  6552. }
  6553. #if defined(__RTAUDIO_DEBUG__)
  6554. fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
  6555. snd_pcm_sw_params_dump( sw_params, out );
  6556. #endif
  6557. // Set flags for buffer conversion
  6558. stream_.doConvertBuffer[mode] = false;
  6559. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  6560. stream_.doConvertBuffer[mode] = true;
  6561. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  6562. stream_.doConvertBuffer[mode] = true;
  6563. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  6564. stream_.nUserChannels[mode] > 1 )
  6565. stream_.doConvertBuffer[mode] = true;
  6566. // Allocate the ApiHandle if necessary and then save.
  6567. AlsaHandle *apiInfo = 0;
  6568. if ( stream_.apiHandle == 0 ) {
  6569. try {
  6570. apiInfo = (AlsaHandle *) new AlsaHandle;
  6571. }
  6572. catch ( std::bad_alloc& ) {
  6573. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
  6574. goto error;
  6575. }
  6576. if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {
  6577. errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
  6578. goto error;
  6579. }
  6580. stream_.apiHandle = (void *) apiInfo;
  6581. apiInfo->handles[0] = 0;
  6582. apiInfo->handles[1] = 0;
  6583. }
  6584. else {
  6585. apiInfo = (AlsaHandle *) stream_.apiHandle;
  6586. }
  6587. apiInfo->handles[mode] = phandle;
  6588. phandle = 0;
  6589. // Allocate necessary internal buffers.
  6590. unsigned long bufferBytes;
  6591. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  6592. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  6593. if ( stream_.userBuffer[mode] == NULL ) {
  6594. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
  6595. goto error;
  6596. }
  6597. if ( stream_.doConvertBuffer[mode] ) {
  6598. bool makeBuffer = true;
  6599. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  6600. if ( mode == INPUT ) {
  6601. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  6602. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  6603. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  6604. }
  6605. }
  6606. if ( makeBuffer ) {
  6607. bufferBytes *= *bufferSize;
  6608. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  6609. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  6610. if ( stream_.deviceBuffer == NULL ) {
  6611. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
  6612. goto error;
  6613. }
  6614. }
  6615. }
  6616. stream_.sampleRate = sampleRate;
  6617. stream_.nBuffers = periods;
  6618. stream_.device[mode] = device;
  6619. stream_.state = STREAM_STOPPED;
  6620. // Setup the buffer conversion information structure.
  6621. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  6622. // Setup thread if necessary.
  6623. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  6624. // We had already set up an output stream.
  6625. stream_.mode = DUPLEX;
  6626. // Link the streams if possible.
  6627. apiInfo->synchronized = false;
  6628. if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
  6629. apiInfo->synchronized = true;
  6630. else {
  6631. errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
  6632. error( RtAudioError::WARNING );
  6633. }
  6634. }
  6635. else {
  6636. stream_.mode = mode;
  6637. // Setup callback thread.
  6638. stream_.callbackInfo.object = (void *) this;
  6639. // Set the thread attributes for joinable and realtime scheduling
  6640. // priority (optional). The higher priority will only take affect
  6641. // if the program is run as root or suid. Note, under Linux
  6642. // processes with CAP_SYS_NICE privilege, a user can change
  6643. // scheduling policy and priority (thus need not be root). See
  6644. // POSIX "capabilities".
  6645. pthread_attr_t attr;
  6646. pthread_attr_init( &attr );
  6647. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  6648. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  6649. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  6650. // We previously attempted to increase the audio callback priority
  6651. // to SCHED_RR here via the attributes. However, while no errors
  6652. // were reported in doing so, it did not work. So, now this is
  6653. // done in the alsaCallbackHandler function.
  6654. stream_.callbackInfo.doRealtime = true;
  6655. int priority = options->priority;
  6656. int min = sched_get_priority_min( SCHED_RR );
  6657. int max = sched_get_priority_max( SCHED_RR );
  6658. if ( priority < min ) priority = min;
  6659. else if ( priority > max ) priority = max;
  6660. stream_.callbackInfo.priority = priority;
  6661. }
  6662. #endif
  6663. stream_.callbackInfo.isRunning = true;
  6664. result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
  6665. pthread_attr_destroy( &attr );
  6666. if ( result ) {
  6667. stream_.callbackInfo.isRunning = false;
  6668. errorText_ = "RtApiAlsa::error creating callback thread!";
  6669. goto error;
  6670. }
  6671. }
  6672. return SUCCESS;
  6673. error:
  6674. if ( apiInfo ) {
  6675. pthread_cond_destroy( &apiInfo->runnable_cv );
  6676. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6677. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6678. delete apiInfo;
  6679. stream_.apiHandle = 0;
  6680. }
  6681. if ( phandle) snd_pcm_close( phandle );
  6682. for ( int i=0; i<2; i++ ) {
  6683. if ( stream_.userBuffer[i] ) {
  6684. free( stream_.userBuffer[i] );
  6685. stream_.userBuffer[i] = 0;
  6686. }
  6687. }
  6688. if ( stream_.deviceBuffer ) {
  6689. free( stream_.deviceBuffer );
  6690. stream_.deviceBuffer = 0;
  6691. }
  6692. stream_.state = STREAM_CLOSED;
  6693. return FAILURE;
  6694. }
  6695. void RtApiAlsa :: closeStream()
  6696. {
  6697. if ( stream_.state == STREAM_CLOSED ) {
  6698. errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
  6699. error( RtAudioError::WARNING );
  6700. return;
  6701. }
  6702. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6703. stream_.callbackInfo.isRunning = false;
  6704. MUTEX_LOCK( &stream_.mutex );
  6705. if ( stream_.state == STREAM_STOPPED ) {
  6706. apiInfo->runnable = true;
  6707. pthread_cond_signal( &apiInfo->runnable_cv );
  6708. }
  6709. MUTEX_UNLOCK( &stream_.mutex );
  6710. pthread_join( stream_.callbackInfo.thread, NULL );
  6711. if ( stream_.state == STREAM_RUNNING ) {
  6712. stream_.state = STREAM_STOPPED;
  6713. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  6714. snd_pcm_drop( apiInfo->handles[0] );
  6715. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  6716. snd_pcm_drop( apiInfo->handles[1] );
  6717. }
  6718. if ( apiInfo ) {
  6719. pthread_cond_destroy( &apiInfo->runnable_cv );
  6720. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6721. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6722. delete apiInfo;
  6723. stream_.apiHandle = 0;
  6724. }
  6725. for ( int i=0; i<2; i++ ) {
  6726. if ( stream_.userBuffer[i] ) {
  6727. free( stream_.userBuffer[i] );
  6728. stream_.userBuffer[i] = 0;
  6729. }
  6730. }
  6731. if ( stream_.deviceBuffer ) {
  6732. free( stream_.deviceBuffer );
  6733. stream_.deviceBuffer = 0;
  6734. }
  6735. stream_.mode = UNINITIALIZED;
  6736. stream_.state = STREAM_CLOSED;
  6737. }
  6738. void RtApiAlsa :: startStream()
  6739. {
  6740. // This method calls snd_pcm_prepare if the device isn't already in that state.
  6741. verifyStream();
  6742. if ( stream_.state == STREAM_RUNNING ) {
  6743. errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
  6744. error( RtAudioError::WARNING );
  6745. return;
  6746. }
  6747. MUTEX_LOCK( &stream_.mutex );
  6748. int result = 0;
  6749. snd_pcm_state_t state;
  6750. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6751. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6752. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6753. state = snd_pcm_state( handle[0] );
  6754. if ( state != SND_PCM_STATE_PREPARED ) {
  6755. result = snd_pcm_prepare( handle[0] );
  6756. if ( result < 0 ) {
  6757. errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
  6758. errorText_ = errorStream_.str();
  6759. goto unlock;
  6760. }
  6761. }
  6762. }
  6763. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6764. result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open
  6765. state = snd_pcm_state( handle[1] );
  6766. if ( state != SND_PCM_STATE_PREPARED ) {
  6767. result = snd_pcm_prepare( handle[1] );
  6768. if ( result < 0 ) {
  6769. errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
  6770. errorText_ = errorStream_.str();
  6771. goto unlock;
  6772. }
  6773. }
  6774. }
  6775. stream_.state = STREAM_RUNNING;
  6776. unlock:
  6777. apiInfo->runnable = true;
  6778. pthread_cond_signal( &apiInfo->runnable_cv );
  6779. MUTEX_UNLOCK( &stream_.mutex );
  6780. if ( result >= 0 ) return;
  6781. error( RtAudioError::SYSTEM_ERROR );
  6782. }
  6783. void RtApiAlsa :: stopStream()
  6784. {
  6785. verifyStream();
  6786. if ( stream_.state == STREAM_STOPPED ) {
  6787. errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
  6788. error( RtAudioError::WARNING );
  6789. return;
  6790. }
  6791. stream_.state = STREAM_STOPPED;
  6792. MUTEX_LOCK( &stream_.mutex );
  6793. int result = 0;
  6794. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6795. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6796. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6797. if ( apiInfo->synchronized )
  6798. result = snd_pcm_drop( handle[0] );
  6799. else
  6800. result = snd_pcm_drain( handle[0] );
  6801. if ( result < 0 ) {
  6802. errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
  6803. errorText_ = errorStream_.str();
  6804. goto unlock;
  6805. }
  6806. }
  6807. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6808. result = snd_pcm_drop( handle[1] );
  6809. if ( result < 0 ) {
  6810. errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
  6811. errorText_ = errorStream_.str();
  6812. goto unlock;
  6813. }
  6814. }
  6815. unlock:
  6816. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6817. MUTEX_UNLOCK( &stream_.mutex );
  6818. if ( result >= 0 ) return;
  6819. error( RtAudioError::SYSTEM_ERROR );
  6820. }
  6821. void RtApiAlsa :: abortStream()
  6822. {
  6823. verifyStream();
  6824. if ( stream_.state == STREAM_STOPPED ) {
  6825. errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
  6826. error( RtAudioError::WARNING );
  6827. return;
  6828. }
  6829. stream_.state = STREAM_STOPPED;
  6830. MUTEX_LOCK( &stream_.mutex );
  6831. int result = 0;
  6832. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6833. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6834. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6835. result = snd_pcm_drop( handle[0] );
  6836. if ( result < 0 ) {
  6837. errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
  6838. errorText_ = errorStream_.str();
  6839. goto unlock;
  6840. }
  6841. }
  6842. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6843. result = snd_pcm_drop( handle[1] );
  6844. if ( result < 0 ) {
  6845. errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
  6846. errorText_ = errorStream_.str();
  6847. goto unlock;
  6848. }
  6849. }
  6850. unlock:
  6851. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6852. MUTEX_UNLOCK( &stream_.mutex );
  6853. if ( result >= 0 ) return;
  6854. error( RtAudioError::SYSTEM_ERROR );
  6855. }
  6856. void RtApiAlsa :: callbackEvent()
  6857. {
  6858. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6859. if ( stream_.state == STREAM_STOPPED ) {
  6860. MUTEX_LOCK( &stream_.mutex );
  6861. while ( !apiInfo->runnable )
  6862. pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );
  6863. if ( stream_.state != STREAM_RUNNING ) {
  6864. MUTEX_UNLOCK( &stream_.mutex );
  6865. return;
  6866. }
  6867. MUTEX_UNLOCK( &stream_.mutex );
  6868. }
  6869. if ( stream_.state == STREAM_CLOSED ) {
  6870. errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
  6871. error( RtAudioError::WARNING );
  6872. return;
  6873. }
  6874. int doStopStream = 0;
  6875. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  6876. double streamTime = getStreamTime();
  6877. RtAudioStreamStatus status = 0;
  6878. if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
  6879. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  6880. apiInfo->xrun[0] = false;
  6881. }
  6882. if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
  6883. status |= RTAUDIO_INPUT_OVERFLOW;
  6884. apiInfo->xrun[1] = false;
  6885. }
  6886. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  6887. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  6888. if ( doStopStream == 2 ) {
  6889. abortStream();
  6890. return;
  6891. }
  6892. MUTEX_LOCK( &stream_.mutex );
  6893. // The state might change while waiting on a mutex.
  6894. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  6895. int result;
  6896. char *buffer;
  6897. int channels;
  6898. snd_pcm_t **handle;
  6899. snd_pcm_sframes_t frames;
  6900. RtAudioFormat format;
  6901. handle = (snd_pcm_t **) apiInfo->handles;
  6902. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  6903. // Setup parameters.
  6904. if ( stream_.doConvertBuffer[1] ) {
  6905. buffer = stream_.deviceBuffer;
  6906. channels = stream_.nDeviceChannels[1];
  6907. format = stream_.deviceFormat[1];
  6908. }
  6909. else {
  6910. buffer = stream_.userBuffer[1];
  6911. channels = stream_.nUserChannels[1];
  6912. format = stream_.userFormat;
  6913. }
  6914. // Read samples from device in interleaved/non-interleaved format.
  6915. if ( stream_.deviceInterleaved[1] )
  6916. result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
  6917. else {
  6918. void *bufs[channels];
  6919. size_t offset = stream_.bufferSize * formatBytes( format );
  6920. for ( int i=0; i<channels; i++ )
  6921. bufs[i] = (void *) (buffer + (i * offset));
  6922. result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
  6923. }
  6924. if ( result < (int) stream_.bufferSize ) {
  6925. // Either an error or overrun occured.
  6926. if ( result == -EPIPE ) {
  6927. snd_pcm_state_t state = snd_pcm_state( handle[1] );
  6928. if ( state == SND_PCM_STATE_XRUN ) {
  6929. apiInfo->xrun[1] = true;
  6930. result = snd_pcm_prepare( handle[1] );
  6931. if ( result < 0 ) {
  6932. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
  6933. errorText_ = errorStream_.str();
  6934. }
  6935. }
  6936. else {
  6937. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  6938. errorText_ = errorStream_.str();
  6939. }
  6940. }
  6941. else {
  6942. errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
  6943. errorText_ = errorStream_.str();
  6944. }
  6945. error( RtAudioError::WARNING );
  6946. goto tryOutput;
  6947. }
  6948. // Do byte swapping if necessary.
  6949. if ( stream_.doByteSwap[1] )
  6950. byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
  6951. // Do buffer conversion if necessary.
  6952. if ( stream_.doConvertBuffer[1] )
  6953. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  6954. // Check stream latency
  6955. result = snd_pcm_delay( handle[1], &frames );
  6956. if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
  6957. }
  6958. tryOutput:
  6959. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6960. // Setup parameters and do buffer conversion if necessary.
  6961. if ( stream_.doConvertBuffer[0] ) {
  6962. buffer = stream_.deviceBuffer;
  6963. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  6964. channels = stream_.nDeviceChannels[0];
  6965. format = stream_.deviceFormat[0];
  6966. }
  6967. else {
  6968. buffer = stream_.userBuffer[0];
  6969. channels = stream_.nUserChannels[0];
  6970. format = stream_.userFormat;
  6971. }
  6972. // Do byte swapping if necessary.
  6973. if ( stream_.doByteSwap[0] )
  6974. byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
  6975. // Write samples to device in interleaved/non-interleaved format.
  6976. if ( stream_.deviceInterleaved[0] )
  6977. result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
  6978. else {
  6979. void *bufs[channels];
  6980. size_t offset = stream_.bufferSize * formatBytes( format );
  6981. for ( int i=0; i<channels; i++ )
  6982. bufs[i] = (void *) (buffer + (i * offset));
  6983. result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
  6984. }
  6985. if ( result < (int) stream_.bufferSize ) {
  6986. // Either an error or underrun occured.
  6987. if ( result == -EPIPE ) {
  6988. snd_pcm_state_t state = snd_pcm_state( handle[0] );
  6989. if ( state == SND_PCM_STATE_XRUN ) {
  6990. apiInfo->xrun[0] = true;
  6991. result = snd_pcm_prepare( handle[0] );
  6992. if ( result < 0 ) {
  6993. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
  6994. errorText_ = errorStream_.str();
  6995. }
  6996. else
  6997. errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun.";
  6998. }
  6999. else {
  7000. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  7001. errorText_ = errorStream_.str();
  7002. }
  7003. }
  7004. else {
  7005. errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
  7006. errorText_ = errorStream_.str();
  7007. }
  7008. error( RtAudioError::WARNING );
  7009. goto unlock;
  7010. }
  7011. // Check stream latency
  7012. result = snd_pcm_delay( handle[0], &frames );
  7013. if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
  7014. }
  7015. unlock:
  7016. MUTEX_UNLOCK( &stream_.mutex );
  7017. RtApi::tickStreamTime();
  7018. if ( doStopStream == 1 ) this->stopStream();
  7019. }
  7020. static void *alsaCallbackHandler( void *ptr )
  7021. {
  7022. CallbackInfo *info = (CallbackInfo *) ptr;
  7023. RtApiAlsa *object = (RtApiAlsa *) info->object;
  7024. bool *isRunning = &info->isRunning;
  7025. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  7026. if ( info->doRealtime ) {
  7027. pthread_t tID = pthread_self(); // ID of this thread
  7028. sched_param prio = { info->priority }; // scheduling priority of thread
  7029. pthread_setschedparam( tID, SCHED_RR, &prio );
  7030. }
  7031. #endif
  7032. while ( *isRunning == true ) {
  7033. pthread_testcancel();
  7034. object->callbackEvent();
  7035. }
  7036. pthread_exit( NULL );
  7037. }
  7038. //******************** End of __LINUX_ALSA__ *********************//
  7039. #endif
  7040. #if defined(__LINUX_PULSE__)
  7041. // Code written by Peter Meerwald, pmeerw@pmeerw.net
  7042. // and Tristan Matthews.
  7043. #include <pulse/error.h>
  7044. #include <pulse/simple.h>
  7045. #include <cstdio>
  7046. static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,
  7047. 44100, 48000, 96000, 0};
  7048. struct rtaudio_pa_format_mapping_t {
  7049. RtAudioFormat rtaudio_format;
  7050. pa_sample_format_t pa_format;
  7051. };
  7052. static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {
  7053. {RTAUDIO_SINT16, PA_SAMPLE_S16LE},
  7054. {RTAUDIO_SINT32, PA_SAMPLE_S32LE},
  7055. {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},
  7056. {0, PA_SAMPLE_INVALID}};
  7057. struct PulseAudioHandle {
  7058. pa_simple *s_play;
  7059. pa_simple *s_rec;
  7060. pthread_t thread;
  7061. pthread_cond_t runnable_cv;
  7062. bool runnable;
  7063. PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }
  7064. };
  7065. RtApiPulse::~RtApiPulse()
  7066. {
  7067. if ( stream_.state != STREAM_CLOSED )
  7068. closeStream();
  7069. }
  7070. unsigned int RtApiPulse::getDeviceCount( void )
  7071. {
  7072. return 1;
  7073. }
  7074. RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )
  7075. {
  7076. RtAudio::DeviceInfo info;
  7077. info.probed = true;
  7078. info.name = "PulseAudio";
  7079. info.outputChannels = 2;
  7080. info.inputChannels = 2;
  7081. info.duplexChannels = 2;
  7082. info.isDefaultOutput = true;
  7083. info.isDefaultInput = true;
  7084. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )
  7085. info.sampleRates.push_back( *sr );
  7086. info.preferredSampleRate = 48000;
  7087. info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;
  7088. return info;
  7089. }
  7090. static void *pulseaudio_callback( void * user )
  7091. {
  7092. CallbackInfo *cbi = static_cast<CallbackInfo *>( user );
  7093. RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );
  7094. volatile bool *isRunning = &cbi->isRunning;
  7095. while ( *isRunning ) {
  7096. pthread_testcancel();
  7097. context->callbackEvent();
  7098. }
  7099. pthread_exit( NULL );
  7100. }
  7101. void RtApiPulse::closeStream( void )
  7102. {
  7103. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7104. stream_.callbackInfo.isRunning = false;
  7105. if ( pah ) {
  7106. MUTEX_LOCK( &stream_.mutex );
  7107. if ( stream_.state == STREAM_STOPPED ) {
  7108. pah->runnable = true;
  7109. pthread_cond_signal( &pah->runnable_cv );
  7110. }
  7111. MUTEX_UNLOCK( &stream_.mutex );
  7112. pthread_join( pah->thread, 0 );
  7113. if ( pah->s_play ) {
  7114. pa_simple_flush( pah->s_play, NULL );
  7115. pa_simple_free( pah->s_play );
  7116. }
  7117. if ( pah->s_rec )
  7118. pa_simple_free( pah->s_rec );
  7119. pthread_cond_destroy( &pah->runnable_cv );
  7120. delete pah;
  7121. stream_.apiHandle = 0;
  7122. }
  7123. if ( stream_.userBuffer[0] ) {
  7124. free( stream_.userBuffer[0] );
  7125. stream_.userBuffer[0] = 0;
  7126. }
  7127. if ( stream_.userBuffer[1] ) {
  7128. free( stream_.userBuffer[1] );
  7129. stream_.userBuffer[1] = 0;
  7130. }
  7131. stream_.state = STREAM_CLOSED;
  7132. stream_.mode = UNINITIALIZED;
  7133. }
  7134. void RtApiPulse::callbackEvent( void )
  7135. {
  7136. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7137. if ( stream_.state == STREAM_STOPPED ) {
  7138. MUTEX_LOCK( &stream_.mutex );
  7139. while ( !pah->runnable )
  7140. pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );
  7141. if ( stream_.state != STREAM_RUNNING ) {
  7142. MUTEX_UNLOCK( &stream_.mutex );
  7143. return;
  7144. }
  7145. MUTEX_UNLOCK( &stream_.mutex );
  7146. }
  7147. if ( stream_.state == STREAM_CLOSED ) {
  7148. errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "
  7149. "this shouldn't happen!";
  7150. error( RtAudioError::WARNING );
  7151. return;
  7152. }
  7153. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  7154. double streamTime = getStreamTime();
  7155. RtAudioStreamStatus status = 0;
  7156. int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],
  7157. stream_.bufferSize, streamTime, status,
  7158. stream_.callbackInfo.userData );
  7159. if ( doStopStream == 2 ) {
  7160. abortStream();
  7161. return;
  7162. }
  7163. MUTEX_LOCK( &stream_.mutex );
  7164. void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];
  7165. void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];
  7166. if ( stream_.state != STREAM_RUNNING )
  7167. goto unlock;
  7168. int pa_error;
  7169. size_t bytes;
  7170. if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7171. if ( stream_.doConvertBuffer[OUTPUT] ) {
  7172. convertBuffer( stream_.deviceBuffer,
  7173. stream_.userBuffer[OUTPUT],
  7174. stream_.convertInfo[OUTPUT] );
  7175. bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *
  7176. formatBytes( stream_.deviceFormat[OUTPUT] );
  7177. } else
  7178. bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *
  7179. formatBytes( stream_.userFormat );
  7180. if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {
  7181. errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<
  7182. pa_strerror( pa_error ) << ".";
  7183. errorText_ = errorStream_.str();
  7184. error( RtAudioError::WARNING );
  7185. }
  7186. }
  7187. if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {
  7188. if ( stream_.doConvertBuffer[INPUT] )
  7189. bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *
  7190. formatBytes( stream_.deviceFormat[INPUT] );
  7191. else
  7192. bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *
  7193. formatBytes( stream_.userFormat );
  7194. if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {
  7195. errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<
  7196. pa_strerror( pa_error ) << ".";
  7197. errorText_ = errorStream_.str();
  7198. error( RtAudioError::WARNING );
  7199. }
  7200. if ( stream_.doConvertBuffer[INPUT] ) {
  7201. convertBuffer( stream_.userBuffer[INPUT],
  7202. stream_.deviceBuffer,
  7203. stream_.convertInfo[INPUT] );
  7204. }
  7205. }
  7206. unlock:
  7207. MUTEX_UNLOCK( &stream_.mutex );
  7208. RtApi::tickStreamTime();
  7209. if ( doStopStream == 1 )
  7210. stopStream();
  7211. }
  7212. void RtApiPulse::startStream( void )
  7213. {
  7214. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7215. if ( stream_.state == STREAM_CLOSED ) {
  7216. errorText_ = "RtApiPulse::startStream(): the stream is not open!";
  7217. error( RtAudioError::INVALID_USE );
  7218. return;
  7219. }
  7220. if ( stream_.state == STREAM_RUNNING ) {
  7221. errorText_ = "RtApiPulse::startStream(): the stream is already running!";
  7222. error( RtAudioError::WARNING );
  7223. return;
  7224. }
  7225. MUTEX_LOCK( &stream_.mutex );
  7226. stream_.state = STREAM_RUNNING;
  7227. pah->runnable = true;
  7228. pthread_cond_signal( &pah->runnable_cv );
  7229. MUTEX_UNLOCK( &stream_.mutex );
  7230. }
  7231. void RtApiPulse::stopStream( void )
  7232. {
  7233. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7234. if ( stream_.state == STREAM_CLOSED ) {
  7235. errorText_ = "RtApiPulse::stopStream(): the stream is not open!";
  7236. error( RtAudioError::INVALID_USE );
  7237. return;
  7238. }
  7239. if ( stream_.state == STREAM_STOPPED ) {
  7240. errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";
  7241. error( RtAudioError::WARNING );
  7242. return;
  7243. }
  7244. stream_.state = STREAM_STOPPED;
  7245. MUTEX_LOCK( &stream_.mutex );
  7246. if ( pah && pah->s_play ) {
  7247. int pa_error;
  7248. if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {
  7249. errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<
  7250. pa_strerror( pa_error ) << ".";
  7251. errorText_ = errorStream_.str();
  7252. MUTEX_UNLOCK( &stream_.mutex );
  7253. error( RtAudioError::SYSTEM_ERROR );
  7254. return;
  7255. }
  7256. }
  7257. stream_.state = STREAM_STOPPED;
  7258. MUTEX_UNLOCK( &stream_.mutex );
  7259. }
  7260. void RtApiPulse::abortStream( void )
  7261. {
  7262. PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );
  7263. if ( stream_.state == STREAM_CLOSED ) {
  7264. errorText_ = "RtApiPulse::abortStream(): the stream is not open!";
  7265. error( RtAudioError::INVALID_USE );
  7266. return;
  7267. }
  7268. if ( stream_.state == STREAM_STOPPED ) {
  7269. errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";
  7270. error( RtAudioError::WARNING );
  7271. return;
  7272. }
  7273. stream_.state = STREAM_STOPPED;
  7274. MUTEX_LOCK( &stream_.mutex );
  7275. if ( pah && pah->s_play ) {
  7276. int pa_error;
  7277. if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {
  7278. errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<
  7279. pa_strerror( pa_error ) << ".";
  7280. errorText_ = errorStream_.str();
  7281. MUTEX_UNLOCK( &stream_.mutex );
  7282. error( RtAudioError::SYSTEM_ERROR );
  7283. return;
  7284. }
  7285. }
  7286. stream_.state = STREAM_STOPPED;
  7287. MUTEX_UNLOCK( &stream_.mutex );
  7288. }
  7289. bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
  7290. unsigned int channels, unsigned int firstChannel,
  7291. unsigned int sampleRate, RtAudioFormat format,
  7292. unsigned int *bufferSize, RtAudio::StreamOptions *options )
  7293. {
  7294. PulseAudioHandle *pah = 0;
  7295. unsigned long bufferBytes = 0;
  7296. pa_sample_spec ss;
  7297. if ( device != 0 ) return false;
  7298. if ( mode != INPUT && mode != OUTPUT ) return false;
  7299. if ( channels != 1 && channels != 2 ) {
  7300. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";
  7301. return false;
  7302. }
  7303. ss.channels = channels;
  7304. if ( firstChannel != 0 ) return false;
  7305. bool sr_found = false;
  7306. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {
  7307. if ( sampleRate == *sr ) {
  7308. sr_found = true;
  7309. stream_.sampleRate = sampleRate;
  7310. ss.rate = sampleRate;
  7311. break;
  7312. }
  7313. }
  7314. if ( !sr_found ) {
  7315. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";
  7316. return false;
  7317. }
  7318. bool sf_found = 0;
  7319. for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;
  7320. sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {
  7321. if ( format == sf->rtaudio_format ) {
  7322. sf_found = true;
  7323. stream_.userFormat = sf->rtaudio_format;
  7324. stream_.deviceFormat[mode] = stream_.userFormat;
  7325. ss.format = sf->pa_format;
  7326. break;
  7327. }
  7328. }
  7329. if ( !sf_found ) { // Use internal data format conversion.
  7330. stream_.userFormat = format;
  7331. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  7332. ss.format = PA_SAMPLE_FLOAT32LE;
  7333. }
  7334. // Set other stream parameters.
  7335. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  7336. else stream_.userInterleaved = true;
  7337. stream_.deviceInterleaved[mode] = true;
  7338. stream_.nBuffers = 1;
  7339. stream_.doByteSwap[mode] = false;
  7340. stream_.nUserChannels[mode] = channels;
  7341. stream_.nDeviceChannels[mode] = channels + firstChannel;
  7342. stream_.channelOffset[mode] = 0;
  7343. std::string streamName = "RtAudio";
  7344. // Set flags for buffer conversion.
  7345. stream_.doConvertBuffer[mode] = false;
  7346. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7347. stream_.doConvertBuffer[mode] = true;
  7348. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7349. stream_.doConvertBuffer[mode] = true;
  7350. // Allocate necessary internal buffers.
  7351. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7352. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7353. if ( stream_.userBuffer[mode] == NULL ) {
  7354. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";
  7355. goto error;
  7356. }
  7357. stream_.bufferSize = *bufferSize;
  7358. if ( stream_.doConvertBuffer[mode] ) {
  7359. bool makeBuffer = true;
  7360. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7361. if ( mode == INPUT ) {
  7362. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7363. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7364. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7365. }
  7366. }
  7367. if ( makeBuffer ) {
  7368. bufferBytes *= *bufferSize;
  7369. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7370. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7371. if ( stream_.deviceBuffer == NULL ) {
  7372. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";
  7373. goto error;
  7374. }
  7375. }
  7376. }
  7377. stream_.device[mode] = device;
  7378. // Setup the buffer conversion information structure.
  7379. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7380. if ( !stream_.apiHandle ) {
  7381. PulseAudioHandle *pah = new PulseAudioHandle;
  7382. if ( !pah ) {
  7383. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";
  7384. goto error;
  7385. }
  7386. stream_.apiHandle = pah;
  7387. if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {
  7388. errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";
  7389. goto error;
  7390. }
  7391. }
  7392. pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7393. int error;
  7394. if ( options && !options->streamName.empty() ) streamName = options->streamName;
  7395. switch ( mode ) {
  7396. case INPUT:
  7397. pa_buffer_attr buffer_attr;
  7398. buffer_attr.fragsize = bufferBytes;
  7399. buffer_attr.maxlength = -1;
  7400. pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );
  7401. if ( !pah->s_rec ) {
  7402. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";
  7403. goto error;
  7404. }
  7405. break;
  7406. case OUTPUT:
  7407. pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );
  7408. if ( !pah->s_play ) {
  7409. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";
  7410. goto error;
  7411. }
  7412. break;
  7413. default:
  7414. goto error;
  7415. }
  7416. if ( stream_.mode == UNINITIALIZED )
  7417. stream_.mode = mode;
  7418. else if ( stream_.mode == mode )
  7419. goto error;
  7420. else
  7421. stream_.mode = DUPLEX;
  7422. if ( !stream_.callbackInfo.isRunning ) {
  7423. stream_.callbackInfo.object = this;
  7424. stream_.callbackInfo.isRunning = true;
  7425. if ( pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo) != 0 ) {
  7426. errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";
  7427. goto error;
  7428. }
  7429. }
  7430. stream_.state = STREAM_STOPPED;
  7431. return true;
  7432. error:
  7433. if ( pah && stream_.callbackInfo.isRunning ) {
  7434. pthread_cond_destroy( &pah->runnable_cv );
  7435. delete pah;
  7436. stream_.apiHandle = 0;
  7437. }
  7438. for ( int i=0; i<2; i++ ) {
  7439. if ( stream_.userBuffer[i] ) {
  7440. free( stream_.userBuffer[i] );
  7441. stream_.userBuffer[i] = 0;
  7442. }
  7443. }
  7444. if ( stream_.deviceBuffer ) {
  7445. free( stream_.deviceBuffer );
  7446. stream_.deviceBuffer = 0;
  7447. }
  7448. return FAILURE;
  7449. }
  7450. //******************** End of __LINUX_PULSE__ *********************//
  7451. #endif
  7452. #if defined(__LINUX_OSS__)
  7453. #include <unistd.h>
  7454. #include <sys/ioctl.h>
  7455. #include <unistd.h>
  7456. #include <fcntl.h>
  7457. #include <sys/soundcard.h>
  7458. #include <errno.h>
  7459. #include <math.h>
  7460. static void *ossCallbackHandler(void * ptr);
  7461. // A structure to hold various information related to the OSS API
  7462. // implementation.
  7463. struct OssHandle {
  7464. int id[2]; // device ids
  7465. bool xrun[2];
  7466. bool triggered;
  7467. pthread_cond_t runnable;
  7468. OssHandle()
  7469. :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  7470. };
  7471. RtApiOss :: RtApiOss()
  7472. {
  7473. // Nothing to do here.
  7474. }
  7475. RtApiOss :: ~RtApiOss()
  7476. {
  7477. if ( stream_.state != STREAM_CLOSED ) closeStream();
  7478. }
  7479. unsigned int RtApiOss :: getDeviceCount( void )
  7480. {
  7481. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7482. if ( mixerfd == -1 ) {
  7483. errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
  7484. error( RtAudioError::WARNING );
  7485. return 0;
  7486. }
  7487. oss_sysinfo sysinfo;
  7488. if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
  7489. close( mixerfd );
  7490. errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
  7491. error( RtAudioError::WARNING );
  7492. return 0;
  7493. }
  7494. close( mixerfd );
  7495. return sysinfo.numaudios;
  7496. }
  7497. RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
  7498. {
  7499. RtAudio::DeviceInfo info;
  7500. info.probed = false;
  7501. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7502. if ( mixerfd == -1 ) {
  7503. errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
  7504. error( RtAudioError::WARNING );
  7505. return info;
  7506. }
  7507. oss_sysinfo sysinfo;
  7508. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7509. if ( result == -1 ) {
  7510. close( mixerfd );
  7511. errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
  7512. error( RtAudioError::WARNING );
  7513. return info;
  7514. }
  7515. unsigned nDevices = sysinfo.numaudios;
  7516. if ( nDevices == 0 ) {
  7517. close( mixerfd );
  7518. errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
  7519. error( RtAudioError::INVALID_USE );
  7520. return info;
  7521. }
  7522. if ( device >= nDevices ) {
  7523. close( mixerfd );
  7524. errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
  7525. error( RtAudioError::INVALID_USE );
  7526. return info;
  7527. }
  7528. oss_audioinfo ainfo;
  7529. ainfo.dev = device;
  7530. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7531. close( mixerfd );
  7532. if ( result == -1 ) {
  7533. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7534. errorText_ = errorStream_.str();
  7535. error( RtAudioError::WARNING );
  7536. return info;
  7537. }
  7538. // Probe channels
  7539. if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
  7540. if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
  7541. if ( ainfo.caps & PCM_CAP_DUPLEX ) {
  7542. if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
  7543. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  7544. }
  7545. // Probe data formats ... do for input
  7546. unsigned long mask = ainfo.iformats;
  7547. if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
  7548. info.nativeFormats |= RTAUDIO_SINT16;
  7549. if ( mask & AFMT_S8 )
  7550. info.nativeFormats |= RTAUDIO_SINT8;
  7551. if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
  7552. info.nativeFormats |= RTAUDIO_SINT32;
  7553. #ifdef AFMT_FLOAT
  7554. if ( mask & AFMT_FLOAT )
  7555. info.nativeFormats |= RTAUDIO_FLOAT32;
  7556. #endif
  7557. if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
  7558. info.nativeFormats |= RTAUDIO_SINT24;
  7559. // Check that we have at least one supported format
  7560. if ( info.nativeFormats == 0 ) {
  7561. errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7562. errorText_ = errorStream_.str();
  7563. error( RtAudioError::WARNING );
  7564. return info;
  7565. }
  7566. // Probe the supported sample rates.
  7567. info.sampleRates.clear();
  7568. if ( ainfo.nrates ) {
  7569. for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
  7570. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7571. if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
  7572. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7573. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7574. info.preferredSampleRate = SAMPLE_RATES[k];
  7575. break;
  7576. }
  7577. }
  7578. }
  7579. }
  7580. else {
  7581. // Check min and max rate values;
  7582. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7583. if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {
  7584. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7585. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7586. info.preferredSampleRate = SAMPLE_RATES[k];
  7587. }
  7588. }
  7589. }
  7590. if ( info.sampleRates.size() == 0 ) {
  7591. errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
  7592. errorText_ = errorStream_.str();
  7593. error( RtAudioError::WARNING );
  7594. }
  7595. else {
  7596. info.probed = true;
  7597. info.name = ainfo.name;
  7598. }
  7599. return info;
  7600. }
  7601. bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  7602. unsigned int firstChannel, unsigned int sampleRate,
  7603. RtAudioFormat format, unsigned int *bufferSize,
  7604. RtAudio::StreamOptions *options )
  7605. {
  7606. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7607. if ( mixerfd == -1 ) {
  7608. errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
  7609. return FAILURE;
  7610. }
  7611. oss_sysinfo sysinfo;
  7612. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7613. if ( result == -1 ) {
  7614. close( mixerfd );
  7615. errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
  7616. return FAILURE;
  7617. }
  7618. unsigned nDevices = sysinfo.numaudios;
  7619. if ( nDevices == 0 ) {
  7620. // This should not happen because a check is made before this function is called.
  7621. close( mixerfd );
  7622. errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
  7623. return FAILURE;
  7624. }
  7625. if ( device >= nDevices ) {
  7626. // This should not happen because a check is made before this function is called.
  7627. close( mixerfd );
  7628. errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
  7629. return FAILURE;
  7630. }
  7631. oss_audioinfo ainfo;
  7632. ainfo.dev = device;
  7633. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7634. close( mixerfd );
  7635. if ( result == -1 ) {
  7636. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7637. errorText_ = errorStream_.str();
  7638. return FAILURE;
  7639. }
  7640. // Check if device supports input or output
  7641. if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
  7642. ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
  7643. if ( mode == OUTPUT )
  7644. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
  7645. else
  7646. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
  7647. errorText_ = errorStream_.str();
  7648. return FAILURE;
  7649. }
  7650. int flags = 0;
  7651. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7652. if ( mode == OUTPUT )
  7653. flags |= O_WRONLY;
  7654. else { // mode == INPUT
  7655. if (stream_.mode == OUTPUT && stream_.device[0] == device) {
  7656. // We just set the same device for playback ... close and reopen for duplex (OSS only).
  7657. close( handle->id[0] );
  7658. handle->id[0] = 0;
  7659. if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
  7660. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
  7661. errorText_ = errorStream_.str();
  7662. return FAILURE;
  7663. }
  7664. // Check that the number previously set channels is the same.
  7665. if ( stream_.nUserChannels[0] != channels ) {
  7666. errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
  7667. errorText_ = errorStream_.str();
  7668. return FAILURE;
  7669. }
  7670. flags |= O_RDWR;
  7671. }
  7672. else
  7673. flags |= O_RDONLY;
  7674. }
  7675. // Set exclusive access if specified.
  7676. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
  7677. // Try to open the device.
  7678. int fd;
  7679. fd = open( ainfo.devnode, flags, 0 );
  7680. if ( fd == -1 ) {
  7681. if ( errno == EBUSY )
  7682. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
  7683. else
  7684. errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
  7685. errorText_ = errorStream_.str();
  7686. return FAILURE;
  7687. }
  7688. // For duplex operation, specifically set this mode (this doesn't seem to work).
  7689. /*
  7690. if ( flags | O_RDWR ) {
  7691. result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
  7692. if ( result == -1) {
  7693. errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
  7694. errorText_ = errorStream_.str();
  7695. return FAILURE;
  7696. }
  7697. }
  7698. */
  7699. // Check the device channel support.
  7700. stream_.nUserChannels[mode] = channels;
  7701. if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
  7702. close( fd );
  7703. errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
  7704. errorText_ = errorStream_.str();
  7705. return FAILURE;
  7706. }
  7707. // Set the number of channels.
  7708. int deviceChannels = channels + firstChannel;
  7709. result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
  7710. if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
  7711. close( fd );
  7712. errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
  7713. errorText_ = errorStream_.str();
  7714. return FAILURE;
  7715. }
  7716. stream_.nDeviceChannels[mode] = deviceChannels;
  7717. // Get the data format mask
  7718. int mask;
  7719. result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
  7720. if ( result == -1 ) {
  7721. close( fd );
  7722. errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
  7723. errorText_ = errorStream_.str();
  7724. return FAILURE;
  7725. }
  7726. // Determine how to set the device format.
  7727. stream_.userFormat = format;
  7728. int deviceFormat = -1;
  7729. stream_.doByteSwap[mode] = false;
  7730. if ( format == RTAUDIO_SINT8 ) {
  7731. if ( mask & AFMT_S8 ) {
  7732. deviceFormat = AFMT_S8;
  7733. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7734. }
  7735. }
  7736. else if ( format == RTAUDIO_SINT16 ) {
  7737. if ( mask & AFMT_S16_NE ) {
  7738. deviceFormat = AFMT_S16_NE;
  7739. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7740. }
  7741. else if ( mask & AFMT_S16_OE ) {
  7742. deviceFormat = AFMT_S16_OE;
  7743. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7744. stream_.doByteSwap[mode] = true;
  7745. }
  7746. }
  7747. else if ( format == RTAUDIO_SINT24 ) {
  7748. if ( mask & AFMT_S24_NE ) {
  7749. deviceFormat = AFMT_S24_NE;
  7750. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7751. }
  7752. else if ( mask & AFMT_S24_OE ) {
  7753. deviceFormat = AFMT_S24_OE;
  7754. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7755. stream_.doByteSwap[mode] = true;
  7756. }
  7757. }
  7758. else if ( format == RTAUDIO_SINT32 ) {
  7759. if ( mask & AFMT_S32_NE ) {
  7760. deviceFormat = AFMT_S32_NE;
  7761. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7762. }
  7763. else if ( mask & AFMT_S32_OE ) {
  7764. deviceFormat = AFMT_S32_OE;
  7765. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7766. stream_.doByteSwap[mode] = true;
  7767. }
  7768. }
  7769. if ( deviceFormat == -1 ) {
  7770. // The user requested format is not natively supported by the device.
  7771. if ( mask & AFMT_S16_NE ) {
  7772. deviceFormat = AFMT_S16_NE;
  7773. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7774. }
  7775. else if ( mask & AFMT_S32_NE ) {
  7776. deviceFormat = AFMT_S32_NE;
  7777. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7778. }
  7779. else if ( mask & AFMT_S24_NE ) {
  7780. deviceFormat = AFMT_S24_NE;
  7781. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7782. }
  7783. else if ( mask & AFMT_S16_OE ) {
  7784. deviceFormat = AFMT_S16_OE;
  7785. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7786. stream_.doByteSwap[mode] = true;
  7787. }
  7788. else if ( mask & AFMT_S32_OE ) {
  7789. deviceFormat = AFMT_S32_OE;
  7790. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7791. stream_.doByteSwap[mode] = true;
  7792. }
  7793. else if ( mask & AFMT_S24_OE ) {
  7794. deviceFormat = AFMT_S24_OE;
  7795. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7796. stream_.doByteSwap[mode] = true;
  7797. }
  7798. else if ( mask & AFMT_S8) {
  7799. deviceFormat = AFMT_S8;
  7800. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7801. }
  7802. }
  7803. if ( stream_.deviceFormat[mode] == 0 ) {
  7804. // This really shouldn't happen ...
  7805. close( fd );
  7806. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7807. errorText_ = errorStream_.str();
  7808. return FAILURE;
  7809. }
  7810. // Set the data format.
  7811. int temp = deviceFormat;
  7812. result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
  7813. if ( result == -1 || deviceFormat != temp ) {
  7814. close( fd );
  7815. errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
  7816. errorText_ = errorStream_.str();
  7817. return FAILURE;
  7818. }
  7819. // Attempt to set the buffer size. According to OSS, the minimum
  7820. // number of buffers is two. The supposed minimum buffer size is 16
  7821. // bytes, so that will be our lower bound. The argument to this
  7822. // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
  7823. // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
  7824. // We'll check the actual value used near the end of the setup
  7825. // procedure.
  7826. int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
  7827. if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
  7828. int buffers = 0;
  7829. if ( options ) buffers = options->numberOfBuffers;
  7830. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
  7831. if ( buffers < 2 ) buffers = 3;
  7832. temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
  7833. result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
  7834. if ( result == -1 ) {
  7835. close( fd );
  7836. errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
  7837. errorText_ = errorStream_.str();
  7838. return FAILURE;
  7839. }
  7840. stream_.nBuffers = buffers;
  7841. // Save buffer size (in sample frames).
  7842. *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
  7843. stream_.bufferSize = *bufferSize;
  7844. // Set the sample rate.
  7845. int srate = sampleRate;
  7846. result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
  7847. if ( result == -1 ) {
  7848. close( fd );
  7849. errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
  7850. errorText_ = errorStream_.str();
  7851. return FAILURE;
  7852. }
  7853. // Verify the sample rate setup worked.
  7854. if ( abs( srate - (int)sampleRate ) > 100 ) {
  7855. close( fd );
  7856. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
  7857. errorText_ = errorStream_.str();
  7858. return FAILURE;
  7859. }
  7860. stream_.sampleRate = sampleRate;
  7861. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
  7862. // We're doing duplex setup here.
  7863. stream_.deviceFormat[0] = stream_.deviceFormat[1];
  7864. stream_.nDeviceChannels[0] = deviceChannels;
  7865. }
  7866. // Set interleaving parameters.
  7867. stream_.userInterleaved = true;
  7868. stream_.deviceInterleaved[mode] = true;
  7869. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  7870. stream_.userInterleaved = false;
  7871. // Set flags for buffer conversion
  7872. stream_.doConvertBuffer[mode] = false;
  7873. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7874. stream_.doConvertBuffer[mode] = true;
  7875. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7876. stream_.doConvertBuffer[mode] = true;
  7877. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  7878. stream_.nUserChannels[mode] > 1 )
  7879. stream_.doConvertBuffer[mode] = true;
  7880. // Allocate the stream handles if necessary and then save.
  7881. if ( stream_.apiHandle == 0 ) {
  7882. try {
  7883. handle = new OssHandle;
  7884. }
  7885. catch ( std::bad_alloc& ) {
  7886. errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
  7887. goto error;
  7888. }
  7889. if ( pthread_cond_init( &handle->runnable, NULL ) ) {
  7890. errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
  7891. goto error;
  7892. }
  7893. stream_.apiHandle = (void *) handle;
  7894. }
  7895. else {
  7896. handle = (OssHandle *) stream_.apiHandle;
  7897. }
  7898. handle->id[mode] = fd;
  7899. // Allocate necessary internal buffers.
  7900. unsigned long bufferBytes;
  7901. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7902. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7903. if ( stream_.userBuffer[mode] == NULL ) {
  7904. errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
  7905. goto error;
  7906. }
  7907. if ( stream_.doConvertBuffer[mode] ) {
  7908. bool makeBuffer = true;
  7909. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7910. if ( mode == INPUT ) {
  7911. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7912. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7913. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7914. }
  7915. }
  7916. if ( makeBuffer ) {
  7917. bufferBytes *= *bufferSize;
  7918. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7919. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7920. if ( stream_.deviceBuffer == NULL ) {
  7921. errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
  7922. goto error;
  7923. }
  7924. }
  7925. }
  7926. stream_.device[mode] = device;
  7927. stream_.state = STREAM_STOPPED;
  7928. // Setup the buffer conversion information structure.
  7929. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7930. // Setup thread if necessary.
  7931. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  7932. // We had already set up an output stream.
  7933. stream_.mode = DUPLEX;
  7934. if ( stream_.device[0] == device ) handle->id[0] = fd;
  7935. }
  7936. else {
  7937. stream_.mode = mode;
  7938. // Setup callback thread.
  7939. stream_.callbackInfo.object = (void *) this;
  7940. // Set the thread attributes for joinable and realtime scheduling
  7941. // priority. The higher priority will only take affect if the
  7942. // program is run as root or suid.
  7943. pthread_attr_t attr;
  7944. pthread_attr_init( &attr );
  7945. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  7946. #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
  7947. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  7948. struct sched_param param;
  7949. int priority = options->priority;
  7950. int min = sched_get_priority_min( SCHED_RR );
  7951. int max = sched_get_priority_max( SCHED_RR );
  7952. if ( priority < min ) priority = min;
  7953. else if ( priority > max ) priority = max;
  7954. param.sched_priority = priority;
  7955. pthread_attr_setschedparam( &attr, &param );
  7956. pthread_attr_setschedpolicy( &attr, SCHED_RR );
  7957. }
  7958. else
  7959. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7960. #else
  7961. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7962. #endif
  7963. stream_.callbackInfo.isRunning = true;
  7964. result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
  7965. pthread_attr_destroy( &attr );
  7966. if ( result ) {
  7967. stream_.callbackInfo.isRunning = false;
  7968. errorText_ = "RtApiOss::error creating callback thread!";
  7969. goto error;
  7970. }
  7971. }
  7972. return SUCCESS;
  7973. error:
  7974. if ( handle ) {
  7975. pthread_cond_destroy( &handle->runnable );
  7976. if ( handle->id[0] ) close( handle->id[0] );
  7977. if ( handle->id[1] ) close( handle->id[1] );
  7978. delete handle;
  7979. stream_.apiHandle = 0;
  7980. }
  7981. for ( int i=0; i<2; i++ ) {
  7982. if ( stream_.userBuffer[i] ) {
  7983. free( stream_.userBuffer[i] );
  7984. stream_.userBuffer[i] = 0;
  7985. }
  7986. }
  7987. if ( stream_.deviceBuffer ) {
  7988. free( stream_.deviceBuffer );
  7989. stream_.deviceBuffer = 0;
  7990. }
  7991. return FAILURE;
  7992. }
  7993. void RtApiOss :: closeStream()
  7994. {
  7995. if ( stream_.state == STREAM_CLOSED ) {
  7996. errorText_ = "RtApiOss::closeStream(): no open stream to close!";
  7997. error( RtAudioError::WARNING );
  7998. return;
  7999. }
  8000. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8001. stream_.callbackInfo.isRunning = false;
  8002. MUTEX_LOCK( &stream_.mutex );
  8003. if ( stream_.state == STREAM_STOPPED )
  8004. pthread_cond_signal( &handle->runnable );
  8005. MUTEX_UNLOCK( &stream_.mutex );
  8006. pthread_join( stream_.callbackInfo.thread, NULL );
  8007. if ( stream_.state == STREAM_RUNNING ) {
  8008. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  8009. ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8010. else
  8011. ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8012. stream_.state = STREAM_STOPPED;
  8013. }
  8014. if ( handle ) {
  8015. pthread_cond_destroy( &handle->runnable );
  8016. if ( handle->id[0] ) close( handle->id[0] );
  8017. if ( handle->id[1] ) close( handle->id[1] );
  8018. delete handle;
  8019. stream_.apiHandle = 0;
  8020. }
  8021. for ( int i=0; i<2; i++ ) {
  8022. if ( stream_.userBuffer[i] ) {
  8023. free( stream_.userBuffer[i] );
  8024. stream_.userBuffer[i] = 0;
  8025. }
  8026. }
  8027. if ( stream_.deviceBuffer ) {
  8028. free( stream_.deviceBuffer );
  8029. stream_.deviceBuffer = 0;
  8030. }
  8031. stream_.mode = UNINITIALIZED;
  8032. stream_.state = STREAM_CLOSED;
  8033. }
  8034. void RtApiOss :: startStream()
  8035. {
  8036. verifyStream();
  8037. if ( stream_.state == STREAM_RUNNING ) {
  8038. errorText_ = "RtApiOss::startStream(): the stream is already running!";
  8039. error( RtAudioError::WARNING );
  8040. return;
  8041. }
  8042. MUTEX_LOCK( &stream_.mutex );
  8043. stream_.state = STREAM_RUNNING;
  8044. // No need to do anything else here ... OSS automatically starts
  8045. // when fed samples.
  8046. MUTEX_UNLOCK( &stream_.mutex );
  8047. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8048. pthread_cond_signal( &handle->runnable );
  8049. }
  8050. void RtApiOss :: stopStream()
  8051. {
  8052. verifyStream();
  8053. if ( stream_.state == STREAM_STOPPED ) {
  8054. errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
  8055. error( RtAudioError::WARNING );
  8056. return;
  8057. }
  8058. MUTEX_LOCK( &stream_.mutex );
  8059. // The state might change while waiting on a mutex.
  8060. if ( stream_.state == STREAM_STOPPED ) {
  8061. MUTEX_UNLOCK( &stream_.mutex );
  8062. return;
  8063. }
  8064. int result = 0;
  8065. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8066. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8067. // Flush the output with zeros a few times.
  8068. char *buffer;
  8069. int samples;
  8070. RtAudioFormat format;
  8071. if ( stream_.doConvertBuffer[0] ) {
  8072. buffer = stream_.deviceBuffer;
  8073. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  8074. format = stream_.deviceFormat[0];
  8075. }
  8076. else {
  8077. buffer = stream_.userBuffer[0];
  8078. samples = stream_.bufferSize * stream_.nUserChannels[0];
  8079. format = stream_.userFormat;
  8080. }
  8081. memset( buffer, 0, samples * formatBytes(format) );
  8082. for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
  8083. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8084. if ( result == -1 ) {
  8085. errorText_ = "RtApiOss::stopStream: audio write error.";
  8086. error( RtAudioError::WARNING );
  8087. }
  8088. }
  8089. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8090. if ( result == -1 ) {
  8091. errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  8092. errorText_ = errorStream_.str();
  8093. goto unlock;
  8094. }
  8095. handle->triggered = false;
  8096. }
  8097. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  8098. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8099. if ( result == -1 ) {
  8100. errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  8101. errorText_ = errorStream_.str();
  8102. goto unlock;
  8103. }
  8104. }
  8105. unlock:
  8106. stream_.state = STREAM_STOPPED;
  8107. MUTEX_UNLOCK( &stream_.mutex );
  8108. if ( result != -1 ) return;
  8109. error( RtAudioError::SYSTEM_ERROR );
  8110. }
  8111. void RtApiOss :: abortStream()
  8112. {
  8113. verifyStream();
  8114. if ( stream_.state == STREAM_STOPPED ) {
  8115. errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
  8116. error( RtAudioError::WARNING );
  8117. return;
  8118. }
  8119. MUTEX_LOCK( &stream_.mutex );
  8120. // The state might change while waiting on a mutex.
  8121. if ( stream_.state == STREAM_STOPPED ) {
  8122. MUTEX_UNLOCK( &stream_.mutex );
  8123. return;
  8124. }
  8125. int result = 0;
  8126. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8127. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8128. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8129. if ( result == -1 ) {
  8130. errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  8131. errorText_ = errorStream_.str();
  8132. goto unlock;
  8133. }
  8134. handle->triggered = false;
  8135. }
  8136. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  8137. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8138. if ( result == -1 ) {
  8139. errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  8140. errorText_ = errorStream_.str();
  8141. goto unlock;
  8142. }
  8143. }
  8144. unlock:
  8145. stream_.state = STREAM_STOPPED;
  8146. MUTEX_UNLOCK( &stream_.mutex );
  8147. if ( result != -1 ) return;
  8148. error( RtAudioError::SYSTEM_ERROR );
  8149. }
  8150. void RtApiOss :: callbackEvent()
  8151. {
  8152. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8153. if ( stream_.state == STREAM_STOPPED ) {
  8154. MUTEX_LOCK( &stream_.mutex );
  8155. pthread_cond_wait( &handle->runnable, &stream_.mutex );
  8156. if ( stream_.state != STREAM_RUNNING ) {
  8157. MUTEX_UNLOCK( &stream_.mutex );
  8158. return;
  8159. }
  8160. MUTEX_UNLOCK( &stream_.mutex );
  8161. }
  8162. if ( stream_.state == STREAM_CLOSED ) {
  8163. errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
  8164. error( RtAudioError::WARNING );
  8165. return;
  8166. }
  8167. // Invoke user callback to get fresh output data.
  8168. int doStopStream = 0;
  8169. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  8170. double streamTime = getStreamTime();
  8171. RtAudioStreamStatus status = 0;
  8172. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  8173. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  8174. handle->xrun[0] = false;
  8175. }
  8176. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  8177. status |= RTAUDIO_INPUT_OVERFLOW;
  8178. handle->xrun[1] = false;
  8179. }
  8180. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  8181. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  8182. if ( doStopStream == 2 ) {
  8183. this->abortStream();
  8184. return;
  8185. }
  8186. MUTEX_LOCK( &stream_.mutex );
  8187. // The state might change while waiting on a mutex.
  8188. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  8189. int result;
  8190. char *buffer;
  8191. int samples;
  8192. RtAudioFormat format;
  8193. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8194. // Setup parameters and do buffer conversion if necessary.
  8195. if ( stream_.doConvertBuffer[0] ) {
  8196. buffer = stream_.deviceBuffer;
  8197. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  8198. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  8199. format = stream_.deviceFormat[0];
  8200. }
  8201. else {
  8202. buffer = stream_.userBuffer[0];
  8203. samples = stream_.bufferSize * stream_.nUserChannels[0];
  8204. format = stream_.userFormat;
  8205. }
  8206. // Do byte swapping if necessary.
  8207. if ( stream_.doByteSwap[0] )
  8208. byteSwapBuffer( buffer, samples, format );
  8209. if ( stream_.mode == DUPLEX && handle->triggered == false ) {
  8210. int trig = 0;
  8211. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8212. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8213. trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
  8214. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8215. handle->triggered = true;
  8216. }
  8217. else
  8218. // Write samples to device.
  8219. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8220. if ( result == -1 ) {
  8221. // We'll assume this is an underrun, though there isn't a
  8222. // specific means for determining that.
  8223. handle->xrun[0] = true;
  8224. errorText_ = "RtApiOss::callbackEvent: audio write error.";
  8225. error( RtAudioError::WARNING );
  8226. // Continue on to input section.
  8227. }
  8228. }
  8229. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  8230. // Setup parameters.
  8231. if ( stream_.doConvertBuffer[1] ) {
  8232. buffer = stream_.deviceBuffer;
  8233. samples = stream_.bufferSize * stream_.nDeviceChannels[1];
  8234. format = stream_.deviceFormat[1];
  8235. }
  8236. else {
  8237. buffer = stream_.userBuffer[1];
  8238. samples = stream_.bufferSize * stream_.nUserChannels[1];
  8239. format = stream_.userFormat;
  8240. }
  8241. // Read samples from device.
  8242. result = read( handle->id[1], buffer, samples * formatBytes(format) );
  8243. if ( result == -1 ) {
  8244. // We'll assume this is an overrun, though there isn't a
  8245. // specific means for determining that.
  8246. handle->xrun[1] = true;
  8247. errorText_ = "RtApiOss::callbackEvent: audio read error.";
  8248. error( RtAudioError::WARNING );
  8249. goto unlock;
  8250. }
  8251. // Do byte swapping if necessary.
  8252. if ( stream_.doByteSwap[1] )
  8253. byteSwapBuffer( buffer, samples, format );
  8254. // Do buffer conversion if necessary.
  8255. if ( stream_.doConvertBuffer[1] )
  8256. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  8257. }
  8258. unlock:
  8259. MUTEX_UNLOCK( &stream_.mutex );
  8260. RtApi::tickStreamTime();
  8261. if ( doStopStream == 1 ) this->stopStream();
  8262. }
  8263. static void *ossCallbackHandler( void *ptr )
  8264. {
  8265. CallbackInfo *info = (CallbackInfo *) ptr;
  8266. RtApiOss *object = (RtApiOss *) info->object;
  8267. bool *isRunning = &info->isRunning;
  8268. while ( *isRunning == true ) {
  8269. pthread_testcancel();
  8270. object->callbackEvent();
  8271. }
  8272. pthread_exit( NULL );
  8273. }
  8274. //******************** End of __LINUX_OSS__ *********************//
  8275. #endif
  8276. // *************************************************** //
  8277. //
  8278. // Protected common (OS-independent) RtAudio methods.
  8279. //
  8280. // *************************************************** //
  8281. // This method can be modified to control the behavior of error
  8282. // message printing.
  8283. void RtApi :: error( RtAudioError::Type type )
  8284. {
  8285. errorStream_.str(""); // clear the ostringstream
  8286. RtAudioErrorCallback errorCallback = (RtAudioErrorCallback) stream_.callbackInfo.errorCallback;
  8287. if ( errorCallback ) {
  8288. // abortStream() can generate new error messages. Ignore them. Just keep original one.
  8289. if ( firstErrorOccurred_ )
  8290. return;
  8291. firstErrorOccurred_ = true;
  8292. const std::string errorMessage = errorText_;
  8293. if ( type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED) {
  8294. stream_.callbackInfo.isRunning = false; // exit from the thread
  8295. abortStream();
  8296. }
  8297. errorCallback( type, errorMessage );
  8298. firstErrorOccurred_ = false;
  8299. return;
  8300. }
  8301. if ( type == RtAudioError::WARNING && showWarnings_ == true )
  8302. std::cerr << '\n' << errorText_ << "\n\n";
  8303. else if ( type != RtAudioError::WARNING )
  8304. throw( RtAudioError( errorText_, type ) );
  8305. }
  8306. void RtApi :: verifyStream()
  8307. {
  8308. if ( stream_.state == STREAM_CLOSED ) {
  8309. errorText_ = "RtApi:: a stream is not open!";
  8310. error( RtAudioError::INVALID_USE );
  8311. }
  8312. }
  8313. void RtApi :: clearStreamInfo()
  8314. {
  8315. stream_.mode = UNINITIALIZED;
  8316. stream_.state = STREAM_CLOSED;
  8317. stream_.sampleRate = 0;
  8318. stream_.bufferSize = 0;
  8319. stream_.nBuffers = 0;
  8320. stream_.userFormat = 0;
  8321. stream_.userInterleaved = true;
  8322. stream_.streamTime = 0.0;
  8323. stream_.apiHandle = 0;
  8324. stream_.deviceBuffer = 0;
  8325. stream_.callbackInfo.callback = 0;
  8326. stream_.callbackInfo.userData = 0;
  8327. stream_.callbackInfo.isRunning = false;
  8328. stream_.callbackInfo.errorCallback = 0;
  8329. for ( int i=0; i<2; i++ ) {
  8330. stream_.device[i] = 11111;
  8331. stream_.doConvertBuffer[i] = false;
  8332. stream_.deviceInterleaved[i] = true;
  8333. stream_.doByteSwap[i] = false;
  8334. stream_.nUserChannels[i] = 0;
  8335. stream_.nDeviceChannels[i] = 0;
  8336. stream_.channelOffset[i] = 0;
  8337. stream_.deviceFormat[i] = 0;
  8338. stream_.latency[i] = 0;
  8339. stream_.userBuffer[i] = 0;
  8340. stream_.convertInfo[i].channels = 0;
  8341. stream_.convertInfo[i].inJump = 0;
  8342. stream_.convertInfo[i].outJump = 0;
  8343. stream_.convertInfo[i].inFormat = 0;
  8344. stream_.convertInfo[i].outFormat = 0;
  8345. stream_.convertInfo[i].inOffset.clear();
  8346. stream_.convertInfo[i].outOffset.clear();
  8347. }
  8348. }
  8349. unsigned int RtApi :: formatBytes( RtAudioFormat format )
  8350. {
  8351. if ( format == RTAUDIO_SINT16 )
  8352. return 2;
  8353. else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )
  8354. return 4;
  8355. else if ( format == RTAUDIO_FLOAT64 )
  8356. return 8;
  8357. else if ( format == RTAUDIO_SINT24 )
  8358. return 3;
  8359. else if ( format == RTAUDIO_SINT8 )
  8360. return 1;
  8361. errorText_ = "RtApi::formatBytes: undefined format.";
  8362. error( RtAudioError::WARNING );
  8363. return 0;
  8364. }
  8365. void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
  8366. {
  8367. if ( mode == INPUT ) { // convert device to user buffer
  8368. stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
  8369. stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
  8370. stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
  8371. stream_.convertInfo[mode].outFormat = stream_.userFormat;
  8372. }
  8373. else { // convert user to device buffer
  8374. stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
  8375. stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
  8376. stream_.convertInfo[mode].inFormat = stream_.userFormat;
  8377. stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
  8378. }
  8379. if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
  8380. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
  8381. else
  8382. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
  8383. // Set up the interleave/deinterleave offsets.
  8384. if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
  8385. if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
  8386. ( mode == INPUT && stream_.userInterleaved ) ) {
  8387. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8388. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8389. stream_.convertInfo[mode].outOffset.push_back( k );
  8390. stream_.convertInfo[mode].inJump = 1;
  8391. }
  8392. }
  8393. else {
  8394. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8395. stream_.convertInfo[mode].inOffset.push_back( k );
  8396. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8397. stream_.convertInfo[mode].outJump = 1;
  8398. }
  8399. }
  8400. }
  8401. else { // no (de)interleaving
  8402. if ( stream_.userInterleaved ) {
  8403. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8404. stream_.convertInfo[mode].inOffset.push_back( k );
  8405. stream_.convertInfo[mode].outOffset.push_back( k );
  8406. }
  8407. }
  8408. else {
  8409. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8410. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8411. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8412. stream_.convertInfo[mode].inJump = 1;
  8413. stream_.convertInfo[mode].outJump = 1;
  8414. }
  8415. }
  8416. }
  8417. // Add channel offset.
  8418. if ( firstChannel > 0 ) {
  8419. if ( stream_.deviceInterleaved[mode] ) {
  8420. if ( mode == OUTPUT ) {
  8421. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8422. stream_.convertInfo[mode].outOffset[k] += firstChannel;
  8423. }
  8424. else {
  8425. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8426. stream_.convertInfo[mode].inOffset[k] += firstChannel;
  8427. }
  8428. }
  8429. else {
  8430. if ( mode == OUTPUT ) {
  8431. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8432. stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
  8433. }
  8434. else {
  8435. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8436. stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize );
  8437. }
  8438. }
  8439. }
  8440. }
  8441. void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
  8442. {
  8443. // This function does format conversion, input/output channel compensation, and
  8444. // data interleaving/deinterleaving. 24-bit integers are assumed to occupy
  8445. // the lower three bytes of a 32-bit integer.
  8446. // Clear our device buffer when in/out duplex device channels are different
  8447. if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
  8448. ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
  8449. memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
  8450. int j;
  8451. if (info.outFormat == RTAUDIO_FLOAT64) {
  8452. Float64 scale;
  8453. Float64 *out = (Float64 *)outBuffer;
  8454. if (info.inFormat == RTAUDIO_SINT8) {
  8455. signed char *in = (signed char *)inBuffer;
  8456. scale = 1.0 / 127.5;
  8457. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8458. for (j=0; j<info.channels; j++) {
  8459. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8460. out[info.outOffset[j]] += 0.5;
  8461. out[info.outOffset[j]] *= scale;
  8462. }
  8463. in += info.inJump;
  8464. out += info.outJump;
  8465. }
  8466. }
  8467. else if (info.inFormat == RTAUDIO_SINT16) {
  8468. Int16 *in = (Int16 *)inBuffer;
  8469. scale = 1.0 / 32767.5;
  8470. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8471. for (j=0; j<info.channels; j++) {
  8472. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8473. out[info.outOffset[j]] += 0.5;
  8474. out[info.outOffset[j]] *= scale;
  8475. }
  8476. in += info.inJump;
  8477. out += info.outJump;
  8478. }
  8479. }
  8480. else if (info.inFormat == RTAUDIO_SINT24) {
  8481. Int24 *in = (Int24 *)inBuffer;
  8482. scale = 1.0 / 8388607.5;
  8483. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8484. for (j=0; j<info.channels; j++) {
  8485. out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());
  8486. out[info.outOffset[j]] += 0.5;
  8487. out[info.outOffset[j]] *= scale;
  8488. }
  8489. in += info.inJump;
  8490. out += info.outJump;
  8491. }
  8492. }
  8493. else if (info.inFormat == RTAUDIO_SINT32) {
  8494. Int32 *in = (Int32 *)inBuffer;
  8495. scale = 1.0 / 2147483647.5;
  8496. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8497. for (j=0; j<info.channels; j++) {
  8498. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8499. out[info.outOffset[j]] += 0.5;
  8500. out[info.outOffset[j]] *= scale;
  8501. }
  8502. in += info.inJump;
  8503. out += info.outJump;
  8504. }
  8505. }
  8506. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8507. Float32 *in = (Float32 *)inBuffer;
  8508. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8509. for (j=0; j<info.channels; j++) {
  8510. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8511. }
  8512. in += info.inJump;
  8513. out += info.outJump;
  8514. }
  8515. }
  8516. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8517. // Channel compensation and/or (de)interleaving only.
  8518. Float64 *in = (Float64 *)inBuffer;
  8519. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8520. for (j=0; j<info.channels; j++) {
  8521. out[info.outOffset[j]] = in[info.inOffset[j]];
  8522. }
  8523. in += info.inJump;
  8524. out += info.outJump;
  8525. }
  8526. }
  8527. }
  8528. else if (info.outFormat == RTAUDIO_FLOAT32) {
  8529. Float32 scale;
  8530. Float32 *out = (Float32 *)outBuffer;
  8531. if (info.inFormat == RTAUDIO_SINT8) {
  8532. signed char *in = (signed char *)inBuffer;
  8533. scale = (Float32) ( 1.0 / 127.5 );
  8534. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8535. for (j=0; j<info.channels; j++) {
  8536. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8537. out[info.outOffset[j]] += 0.5;
  8538. out[info.outOffset[j]] *= scale;
  8539. }
  8540. in += info.inJump;
  8541. out += info.outJump;
  8542. }
  8543. }
  8544. else if (info.inFormat == RTAUDIO_SINT16) {
  8545. Int16 *in = (Int16 *)inBuffer;
  8546. scale = (Float32) ( 1.0 / 32767.5 );
  8547. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8548. for (j=0; j<info.channels; j++) {
  8549. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8550. out[info.outOffset[j]] += 0.5;
  8551. out[info.outOffset[j]] *= scale;
  8552. }
  8553. in += info.inJump;
  8554. out += info.outJump;
  8555. }
  8556. }
  8557. else if (info.inFormat == RTAUDIO_SINT24) {
  8558. Int24 *in = (Int24 *)inBuffer;
  8559. scale = (Float32) ( 1.0 / 8388607.5 );
  8560. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8561. for (j=0; j<info.channels; j++) {
  8562. out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());
  8563. out[info.outOffset[j]] += 0.5;
  8564. out[info.outOffset[j]] *= scale;
  8565. }
  8566. in += info.inJump;
  8567. out += info.outJump;
  8568. }
  8569. }
  8570. else if (info.inFormat == RTAUDIO_SINT32) {
  8571. Int32 *in = (Int32 *)inBuffer;
  8572. scale = (Float32) ( 1.0 / 2147483647.5 );
  8573. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8574. for (j=0; j<info.channels; j++) {
  8575. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8576. out[info.outOffset[j]] += 0.5;
  8577. out[info.outOffset[j]] *= scale;
  8578. }
  8579. in += info.inJump;
  8580. out += info.outJump;
  8581. }
  8582. }
  8583. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8584. // Channel compensation and/or (de)interleaving only.
  8585. Float32 *in = (Float32 *)inBuffer;
  8586. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8587. for (j=0; j<info.channels; j++) {
  8588. out[info.outOffset[j]] = in[info.inOffset[j]];
  8589. }
  8590. in += info.inJump;
  8591. out += info.outJump;
  8592. }
  8593. }
  8594. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8595. Float64 *in = (Float64 *)inBuffer;
  8596. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8597. for (j=0; j<info.channels; j++) {
  8598. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8599. }
  8600. in += info.inJump;
  8601. out += info.outJump;
  8602. }
  8603. }
  8604. }
  8605. else if (info.outFormat == RTAUDIO_SINT32) {
  8606. Int32 *out = (Int32 *)outBuffer;
  8607. if (info.inFormat == RTAUDIO_SINT8) {
  8608. signed char *in = (signed char *)inBuffer;
  8609. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8610. for (j=0; j<info.channels; j++) {
  8611. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8612. out[info.outOffset[j]] <<= 24;
  8613. }
  8614. in += info.inJump;
  8615. out += info.outJump;
  8616. }
  8617. }
  8618. else if (info.inFormat == RTAUDIO_SINT16) {
  8619. Int16 *in = (Int16 *)inBuffer;
  8620. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8621. for (j=0; j<info.channels; j++) {
  8622. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8623. out[info.outOffset[j]] <<= 16;
  8624. }
  8625. in += info.inJump;
  8626. out += info.outJump;
  8627. }
  8628. }
  8629. else if (info.inFormat == RTAUDIO_SINT24) {
  8630. Int24 *in = (Int24 *)inBuffer;
  8631. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8632. for (j=0; j<info.channels; j++) {
  8633. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();
  8634. out[info.outOffset[j]] <<= 8;
  8635. }
  8636. in += info.inJump;
  8637. out += info.outJump;
  8638. }
  8639. }
  8640. else if (info.inFormat == RTAUDIO_SINT32) {
  8641. // Channel compensation and/or (de)interleaving only.
  8642. Int32 *in = (Int32 *)inBuffer;
  8643. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8644. for (j=0; j<info.channels; j++) {
  8645. out[info.outOffset[j]] = in[info.inOffset[j]];
  8646. }
  8647. in += info.inJump;
  8648. out += info.outJump;
  8649. }
  8650. }
  8651. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8652. Float32 *in = (Float32 *)inBuffer;
  8653. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8654. for (j=0; j<info.channels; j++) {
  8655. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8656. }
  8657. in += info.inJump;
  8658. out += info.outJump;
  8659. }
  8660. }
  8661. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8662. Float64 *in = (Float64 *)inBuffer;
  8663. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8664. for (j=0; j<info.channels; j++) {
  8665. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8666. }
  8667. in += info.inJump;
  8668. out += info.outJump;
  8669. }
  8670. }
  8671. }
  8672. else if (info.outFormat == RTAUDIO_SINT24) {
  8673. Int24 *out = (Int24 *)outBuffer;
  8674. if (info.inFormat == RTAUDIO_SINT8) {
  8675. signed char *in = (signed char *)inBuffer;
  8676. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8677. for (j=0; j<info.channels; j++) {
  8678. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);
  8679. //out[info.outOffset[j]] <<= 16;
  8680. }
  8681. in += info.inJump;
  8682. out += info.outJump;
  8683. }
  8684. }
  8685. else if (info.inFormat == RTAUDIO_SINT16) {
  8686. Int16 *in = (Int16 *)inBuffer;
  8687. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8688. for (j=0; j<info.channels; j++) {
  8689. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);
  8690. //out[info.outOffset[j]] <<= 8;
  8691. }
  8692. in += info.inJump;
  8693. out += info.outJump;
  8694. }
  8695. }
  8696. else if (info.inFormat == RTAUDIO_SINT24) {
  8697. // Channel compensation and/or (de)interleaving only.
  8698. Int24 *in = (Int24 *)inBuffer;
  8699. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8700. for (j=0; j<info.channels; j++) {
  8701. out[info.outOffset[j]] = in[info.inOffset[j]];
  8702. }
  8703. in += info.inJump;
  8704. out += info.outJump;
  8705. }
  8706. }
  8707. else if (info.inFormat == RTAUDIO_SINT32) {
  8708. Int32 *in = (Int32 *)inBuffer;
  8709. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8710. for (j=0; j<info.channels; j++) {
  8711. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);
  8712. //out[info.outOffset[j]] >>= 8;
  8713. }
  8714. in += info.inJump;
  8715. out += info.outJump;
  8716. }
  8717. }
  8718. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8719. Float32 *in = (Float32 *)inBuffer;
  8720. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8721. for (j=0; j<info.channels; j++) {
  8722. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8723. }
  8724. in += info.inJump;
  8725. out += info.outJump;
  8726. }
  8727. }
  8728. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8729. Float64 *in = (Float64 *)inBuffer;
  8730. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8731. for (j=0; j<info.channels; j++) {
  8732. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8733. }
  8734. in += info.inJump;
  8735. out += info.outJump;
  8736. }
  8737. }
  8738. }
  8739. else if (info.outFormat == RTAUDIO_SINT16) {
  8740. Int16 *out = (Int16 *)outBuffer;
  8741. if (info.inFormat == RTAUDIO_SINT8) {
  8742. signed char *in = (signed char *)inBuffer;
  8743. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8744. for (j=0; j<info.channels; j++) {
  8745. out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
  8746. out[info.outOffset[j]] <<= 8;
  8747. }
  8748. in += info.inJump;
  8749. out += info.outJump;
  8750. }
  8751. }
  8752. else if (info.inFormat == RTAUDIO_SINT16) {
  8753. // Channel compensation and/or (de)interleaving only.
  8754. Int16 *in = (Int16 *)inBuffer;
  8755. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8756. for (j=0; j<info.channels; j++) {
  8757. out[info.outOffset[j]] = in[info.inOffset[j]];
  8758. }
  8759. in += info.inJump;
  8760. out += info.outJump;
  8761. }
  8762. }
  8763. else if (info.inFormat == RTAUDIO_SINT24) {
  8764. Int24 *in = (Int24 *)inBuffer;
  8765. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8766. for (j=0; j<info.channels; j++) {
  8767. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);
  8768. }
  8769. in += info.inJump;
  8770. out += info.outJump;
  8771. }
  8772. }
  8773. else if (info.inFormat == RTAUDIO_SINT32) {
  8774. Int32 *in = (Int32 *)inBuffer;
  8775. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8776. for (j=0; j<info.channels; j++) {
  8777. out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
  8778. }
  8779. in += info.inJump;
  8780. out += info.outJump;
  8781. }
  8782. }
  8783. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8784. Float32 *in = (Float32 *)inBuffer;
  8785. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8786. for (j=0; j<info.channels; j++) {
  8787. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  8788. }
  8789. in += info.inJump;
  8790. out += info.outJump;
  8791. }
  8792. }
  8793. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8794. Float64 *in = (Float64 *)inBuffer;
  8795. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8796. for (j=0; j<info.channels; j++) {
  8797. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  8798. }
  8799. in += info.inJump;
  8800. out += info.outJump;
  8801. }
  8802. }
  8803. }
  8804. else if (info.outFormat == RTAUDIO_SINT8) {
  8805. signed char *out = (signed char *)outBuffer;
  8806. if (info.inFormat == RTAUDIO_SINT8) {
  8807. // Channel compensation and/or (de)interleaving only.
  8808. signed char *in = (signed char *)inBuffer;
  8809. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8810. for (j=0; j<info.channels; j++) {
  8811. out[info.outOffset[j]] = in[info.inOffset[j]];
  8812. }
  8813. in += info.inJump;
  8814. out += info.outJump;
  8815. }
  8816. }
  8817. if (info.inFormat == RTAUDIO_SINT16) {
  8818. Int16 *in = (Int16 *)inBuffer;
  8819. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8820. for (j=0; j<info.channels; j++) {
  8821. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
  8822. }
  8823. in += info.inJump;
  8824. out += info.outJump;
  8825. }
  8826. }
  8827. else if (info.inFormat == RTAUDIO_SINT24) {
  8828. Int24 *in = (Int24 *)inBuffer;
  8829. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8830. for (j=0; j<info.channels; j++) {
  8831. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);
  8832. }
  8833. in += info.inJump;
  8834. out += info.outJump;
  8835. }
  8836. }
  8837. else if (info.inFormat == RTAUDIO_SINT32) {
  8838. Int32 *in = (Int32 *)inBuffer;
  8839. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8840. for (j=0; j<info.channels; j++) {
  8841. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
  8842. }
  8843. in += info.inJump;
  8844. out += info.outJump;
  8845. }
  8846. }
  8847. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8848. Float32 *in = (Float32 *)inBuffer;
  8849. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8850. for (j=0; j<info.channels; j++) {
  8851. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  8852. }
  8853. in += info.inJump;
  8854. out += info.outJump;
  8855. }
  8856. }
  8857. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8858. Float64 *in = (Float64 *)inBuffer;
  8859. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8860. for (j=0; j<info.channels; j++) {
  8861. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  8862. }
  8863. in += info.inJump;
  8864. out += info.outJump;
  8865. }
  8866. }
  8867. }
  8868. }
  8869. //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
  8870. //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
  8871. //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
  8872. void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
  8873. {
  8874. char val;
  8875. char *ptr;
  8876. ptr = buffer;
  8877. if ( format == RTAUDIO_SINT16 ) {
  8878. for ( unsigned int i=0; i<samples; i++ ) {
  8879. // Swap 1st and 2nd bytes.
  8880. val = *(ptr);
  8881. *(ptr) = *(ptr+1);
  8882. *(ptr+1) = val;
  8883. // Increment 2 bytes.
  8884. ptr += 2;
  8885. }
  8886. }
  8887. else if ( format == RTAUDIO_SINT32 ||
  8888. format == RTAUDIO_FLOAT32 ) {
  8889. for ( unsigned int i=0; i<samples; i++ ) {
  8890. // Swap 1st and 4th bytes.
  8891. val = *(ptr);
  8892. *(ptr) = *(ptr+3);
  8893. *(ptr+3) = val;
  8894. // Swap 2nd and 3rd bytes.
  8895. ptr += 1;
  8896. val = *(ptr);
  8897. *(ptr) = *(ptr+1);
  8898. *(ptr+1) = val;
  8899. // Increment 3 more bytes.
  8900. ptr += 3;
  8901. }
  8902. }
  8903. else if ( format == RTAUDIO_SINT24 ) {
  8904. for ( unsigned int i=0; i<samples; i++ ) {
  8905. // Swap 1st and 3rd bytes.
  8906. val = *(ptr);
  8907. *(ptr) = *(ptr+2);
  8908. *(ptr+2) = val;
  8909. // Increment 2 more bytes.
  8910. ptr += 2;
  8911. }
  8912. }
  8913. else if ( format == RTAUDIO_FLOAT64 ) {
  8914. for ( unsigned int i=0; i<samples; i++ ) {
  8915. // Swap 1st and 8th bytes
  8916. val = *(ptr);
  8917. *(ptr) = *(ptr+7);
  8918. *(ptr+7) = val;
  8919. // Swap 2nd and 7th bytes
  8920. ptr += 1;
  8921. val = *(ptr);
  8922. *(ptr) = *(ptr+5);
  8923. *(ptr+5) = val;
  8924. // Swap 3rd and 6th bytes
  8925. ptr += 1;
  8926. val = *(ptr);
  8927. *(ptr) = *(ptr+3);
  8928. *(ptr+3) = val;
  8929. // Swap 4th and 5th bytes
  8930. ptr += 1;
  8931. val = *(ptr);
  8932. *(ptr) = *(ptr+1);
  8933. *(ptr+1) = val;
  8934. // Increment 5 more bytes.
  8935. ptr += 5;
  8936. }
  8937. }
  8938. }
  8939. // Indentation settings for Vim and Emacs
  8940. //
  8941. // Local Variables:
  8942. // c-basic-offset: 2
  8943. // indent-tabs-mode: nil
  8944. // End:
  8945. //
  8946. // vim: et sts=2 sw=2