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.

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