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.

10669 lines
365KB

  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 GitHub site: https://github.com/thestk/rtaudio
  9. RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
  10. RtAudio: realtime audio i/o C++ classes
  11. Copyright (c) 2001-2019 Gary P. Scavone
  12. Permission is hereby granted, free of charge, to any person
  13. obtaining a copy of this software and associated documentation files
  14. (the "Software"), to deal in the Software without restriction,
  15. including without limitation the rights to use, copy, modify, merge,
  16. publish, distribute, sublicense, and/or sell copies of the Software,
  17. and to permit persons to whom the Software is furnished to do so,
  18. subject to the following conditions:
  19. The above copyright notice and this permission notice shall be
  20. included in all copies or substantial portions of the Software.
  21. Any person wishing to distribute modifications to the Software is
  22. asked to send the modifications to the original developer so that
  23. they can be incorporated into the canonical version. This is,
  24. however, not a binding provision of this license.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  28. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  29. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  30. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. /************************************************************************/
  34. // RtAudio: Version 5.1.0
  35. #include "RtAudio.h"
  36. #include <iostream>
  37. #include <cstdlib>
  38. #include <cstring>
  39. #include <climits>
  40. #include <cmath>
  41. #include <algorithm>
  42. // Static variable definitions.
  43. const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
  44. const unsigned int RtApi::SAMPLE_RATES[] = {
  45. 4000, 5512, 8000, 9600, 11025, 16000, 22050,
  46. 32000, 44100, 48000, 88200, 96000, 176400, 192000
  47. };
  48. #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
  49. #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
  50. #define MUTEX_DESTROY(A) DeleteCriticalSection(A)
  51. #define MUTEX_LOCK(A) EnterCriticalSection(A)
  52. #define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
  53. #include "tchar.h"
  54. static std::string convertCharPointerToStdString(const char *text)
  55. {
  56. return std::string(text);
  57. }
  58. static std::string convertCharPointerToStdString(const wchar_t *text)
  59. {
  60. int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);
  61. std::string s( length-1, '\0' );
  62. WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);
  63. return s;
  64. }
  65. #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
  66. // pthread API
  67. #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
  68. #define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
  69. #define MUTEX_LOCK(A) pthread_mutex_lock(A)
  70. #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
  71. #else
  72. #define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions
  73. #define MUTEX_DESTROY(A) abs(*A) // dummy definitions
  74. #endif
  75. // *************************************************** //
  76. //
  77. // RtAudio definitions.
  78. //
  79. // *************************************************** //
  80. std::string RtAudio :: getVersion( void )
  81. {
  82. return RTAUDIO_VERSION;
  83. }
  84. // Define API names and display names.
  85. // Must be in same order as API enum.
  86. extern "C" {
  87. const char* rtaudio_api_names[][2] = {
  88. { "unspecified" , "Unknown" },
  89. { "alsa" , "ALSA" },
  90. { "pulse" , "Pulse" },
  91. { "oss" , "OpenSoundSystem" },
  92. { "jack" , "Jack" },
  93. { "core" , "CoreAudio" },
  94. { "wasapi" , "WASAPI" },
  95. { "asio" , "ASIO" },
  96. { "ds" , "DirectSound" },
  97. { "dummy" , "Dummy" },
  98. };
  99. const unsigned int rtaudio_num_api_names =
  100. sizeof(rtaudio_api_names)/sizeof(rtaudio_api_names[0]);
  101. // The order here will control the order of RtAudio's API search in
  102. // the constructor.
  103. extern "C" const RtAudio::Api rtaudio_compiled_apis[] = {
  104. #if defined(__UNIX_JACK__)
  105. RtAudio::UNIX_JACK,
  106. #endif
  107. #if defined(__LINUX_PULSE__)
  108. RtAudio::LINUX_PULSE,
  109. #endif
  110. #if defined(__LINUX_ALSA__)
  111. RtAudio::LINUX_ALSA,
  112. #endif
  113. #if defined(__LINUX_OSS__)
  114. RtAudio::LINUX_OSS,
  115. #endif
  116. #if defined(__WINDOWS_ASIO__)
  117. RtAudio::WINDOWS_ASIO,
  118. #endif
  119. #if defined(__WINDOWS_WASAPI__)
  120. RtAudio::WINDOWS_WASAPI,
  121. #endif
  122. #if defined(__WINDOWS_DS__)
  123. RtAudio::WINDOWS_DS,
  124. #endif
  125. #if defined(__MACOSX_CORE__)
  126. RtAudio::MACOSX_CORE,
  127. #endif
  128. #if defined(__RTAUDIO_DUMMY__)
  129. RtAudio::RTAUDIO_DUMMY,
  130. #endif
  131. RtAudio::UNSPECIFIED,
  132. };
  133. extern "C" const unsigned int rtaudio_num_compiled_apis =
  134. sizeof(rtaudio_compiled_apis)/sizeof(rtaudio_compiled_apis[0])-1;
  135. }
  136. // This is a compile-time check that rtaudio_num_api_names == RtAudio::NUM_APIS.
  137. // If the build breaks here, check that they match.
  138. template<bool b> class StaticAssert { private: StaticAssert() {} };
  139. template<> class StaticAssert<true>{ public: StaticAssert() {} };
  140. class StaticAssertions { StaticAssertions() {
  141. StaticAssert<rtaudio_num_api_names == RtAudio::NUM_APIS>();
  142. }};
  143. void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis )
  144. {
  145. apis = std::vector<RtAudio::Api>(rtaudio_compiled_apis,
  146. rtaudio_compiled_apis + rtaudio_num_compiled_apis);
  147. }
  148. std::string RtAudio :: getApiName( RtAudio::Api api )
  149. {
  150. if (api < 0 || api >= RtAudio::NUM_APIS)
  151. return "";
  152. return rtaudio_api_names[api][0];
  153. }
  154. std::string RtAudio :: getApiDisplayName( RtAudio::Api api )
  155. {
  156. if (api < 0 || api >= RtAudio::NUM_APIS)
  157. return "Unknown";
  158. return rtaudio_api_names[api][1];
  159. }
  160. RtAudio::Api RtAudio :: getCompiledApiByName( const std::string &name )
  161. {
  162. unsigned int i=0;
  163. for (i = 0; i < rtaudio_num_compiled_apis; ++i)
  164. if (name == rtaudio_api_names[rtaudio_compiled_apis[i]][0])
  165. return rtaudio_compiled_apis[i];
  166. return RtAudio::UNSPECIFIED;
  167. }
  168. void RtAudio :: openRtApi( RtAudio::Api api )
  169. {
  170. if ( rtapi_ )
  171. delete rtapi_;
  172. rtapi_ = 0;
  173. #if defined(__UNIX_JACK__)
  174. if ( api == UNIX_JACK )
  175. rtapi_ = new RtApiJack();
  176. #endif
  177. #if defined(__LINUX_ALSA__)
  178. if ( api == LINUX_ALSA )
  179. rtapi_ = new RtApiAlsa();
  180. #endif
  181. #if defined(__LINUX_PULSE__)
  182. if ( api == LINUX_PULSE )
  183. rtapi_ = new RtApiPulse();
  184. #endif
  185. #if defined(__LINUX_OSS__)
  186. if ( api == LINUX_OSS )
  187. rtapi_ = new RtApiOss();
  188. #endif
  189. #if defined(__WINDOWS_ASIO__)
  190. if ( api == WINDOWS_ASIO )
  191. rtapi_ = new RtApiAsio();
  192. #endif
  193. #if defined(__WINDOWS_WASAPI__)
  194. if ( api == WINDOWS_WASAPI )
  195. rtapi_ = new RtApiWasapi();
  196. #endif
  197. #if defined(__WINDOWS_DS__)
  198. if ( api == WINDOWS_DS )
  199. rtapi_ = new RtApiDs();
  200. #endif
  201. #if defined(__MACOSX_CORE__)
  202. if ( api == MACOSX_CORE )
  203. rtapi_ = new RtApiCore();
  204. #endif
  205. #if defined(__RTAUDIO_DUMMY__)
  206. if ( api == RTAUDIO_DUMMY )
  207. rtapi_ = new RtApiDummy();
  208. #endif
  209. }
  210. RtAudio :: RtAudio( RtAudio::Api api )
  211. {
  212. rtapi_ = 0;
  213. if ( api != UNSPECIFIED ) {
  214. // Attempt to open the specified API.
  215. openRtApi( api );
  216. if ( rtapi_ ) return;
  217. // No compiled support for specified API value. Issue a debug
  218. // warning and continue as if no API was specified.
  219. std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;
  220. }
  221. // Iterate through the compiled APIs and return as soon as we find
  222. // one with at least one device or we reach the end of the list.
  223. std::vector< RtAudio::Api > apis;
  224. getCompiledApi( apis );
  225. for ( unsigned int i=0; i<apis.size(); i++ ) {
  226. openRtApi( apis[i] );
  227. if ( rtapi_ && rtapi_->getDeviceCount() ) break;
  228. }
  229. if ( rtapi_ ) return;
  230. // It should not be possible to get here because the preprocessor
  231. // definition __RTAUDIO_DUMMY__ is automatically defined if no
  232. // API-specific definitions are passed to the compiler. But just in
  233. // case something weird happens, we'll thow an error.
  234. std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";
  235. throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );
  236. }
  237. RtAudio :: ~RtAudio()
  238. {
  239. if ( rtapi_ )
  240. delete rtapi_;
  241. }
  242. void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
  243. RtAudio::StreamParameters *inputParameters,
  244. RtAudioFormat format, unsigned int sampleRate,
  245. unsigned int *bufferFrames,
  246. RtAudioCallback callback, void *userData,
  247. RtAudio::StreamOptions *options,
  248. RtAudioErrorCallback errorCallback )
  249. {
  250. return rtapi_->openStream( outputParameters, inputParameters, format,
  251. sampleRate, bufferFrames, callback,
  252. userData, options, errorCallback );
  253. }
  254. // *************************************************** //
  255. //
  256. // Public RtApi definitions (see end of file for
  257. // private or protected utility functions).
  258. //
  259. // *************************************************** //
  260. RtApi :: RtApi()
  261. {
  262. stream_.state = STREAM_CLOSED;
  263. stream_.mode = UNINITIALIZED;
  264. stream_.apiHandle = 0;
  265. stream_.userBuffer[0] = 0;
  266. stream_.userBuffer[1] = 0;
  267. MUTEX_INITIALIZE( &stream_.mutex );
  268. showWarnings_ = true;
  269. firstErrorOccurred_ = false;
  270. }
  271. RtApi :: ~RtApi()
  272. {
  273. MUTEX_DESTROY( &stream_.mutex );
  274. }
  275. void RtApi :: openStream( RtAudio::StreamParameters *oParams,
  276. RtAudio::StreamParameters *iParams,
  277. RtAudioFormat format, unsigned int sampleRate,
  278. unsigned int *bufferFrames,
  279. RtAudioCallback callback, void *userData,
  280. RtAudio::StreamOptions *options,
  281. RtAudioErrorCallback errorCallback )
  282. {
  283. if ( stream_.state != STREAM_CLOSED ) {
  284. errorText_ = "RtApi::openStream: a stream is already open!";
  285. error( RtAudioError::INVALID_USE );
  286. return;
  287. }
  288. // Clear stream information potentially left from a previously open stream.
  289. clearStreamInfo();
  290. if ( oParams && oParams->nChannels < 1 ) {
  291. errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
  292. error( RtAudioError::INVALID_USE );
  293. return;
  294. }
  295. if ( iParams && iParams->nChannels < 1 ) {
  296. errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
  297. error( RtAudioError::INVALID_USE );
  298. return;
  299. }
  300. if ( oParams == NULL && iParams == NULL ) {
  301. errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
  302. error( RtAudioError::INVALID_USE );
  303. return;
  304. }
  305. if ( formatBytes(format) == 0 ) {
  306. errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
  307. error( RtAudioError::INVALID_USE );
  308. return;
  309. }
  310. unsigned int nDevices = getDeviceCount();
  311. unsigned int oChannels = 0;
  312. if ( oParams ) {
  313. oChannels = oParams->nChannels;
  314. if ( oParams->deviceId >= nDevices ) {
  315. errorText_ = "RtApi::openStream: output device parameter value is invalid.";
  316. error( RtAudioError::INVALID_USE );
  317. return;
  318. }
  319. }
  320. unsigned int iChannels = 0;
  321. if ( iParams ) {
  322. iChannels = iParams->nChannels;
  323. if ( iParams->deviceId >= nDevices ) {
  324. errorText_ = "RtApi::openStream: input device parameter value is invalid.";
  325. error( RtAudioError::INVALID_USE );
  326. return;
  327. }
  328. }
  329. bool result;
  330. if ( oChannels > 0 ) {
  331. result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
  332. sampleRate, format, bufferFrames, options );
  333. if ( result == false ) {
  334. error( RtAudioError::SYSTEM_ERROR );
  335. return;
  336. }
  337. }
  338. if ( iChannels > 0 ) {
  339. result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
  340. sampleRate, format, bufferFrames, options );
  341. if ( result == false ) {
  342. if ( oChannels > 0 ) closeStream();
  343. error( RtAudioError::SYSTEM_ERROR );
  344. return;
  345. }
  346. }
  347. stream_.callbackInfo.callback = (void *) callback;
  348. stream_.callbackInfo.userData = userData;
  349. stream_.callbackInfo.errorCallback = (void *) errorCallback;
  350. if ( options ) options->numberOfBuffers = stream_.nBuffers;
  351. stream_.state = STREAM_STOPPED;
  352. }
  353. unsigned int RtApi :: getDefaultInputDevice( void )
  354. {
  355. // Should be implemented in subclasses if possible.
  356. return 0;
  357. }
  358. unsigned int RtApi :: getDefaultOutputDevice( void )
  359. {
  360. // Should be implemented in subclasses if possible.
  361. return 0;
  362. }
  363. void RtApi :: closeStream( void )
  364. {
  365. // MUST be implemented in subclasses!
  366. return;
  367. }
  368. bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
  369. unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
  370. RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
  371. RtAudio::StreamOptions * /*options*/ )
  372. {
  373. // MUST be implemented in subclasses!
  374. return FAILURE;
  375. }
  376. void RtApi :: tickStreamTime( void )
  377. {
  378. // Subclasses that do not provide their own implementation of
  379. // getStreamTime should call this function once per buffer I/O to
  380. // provide basic stream time support.
  381. stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
  382. #if defined( HAVE_GETTIMEOFDAY )
  383. gettimeofday( &stream_.lastTickTimestamp, NULL );
  384. #endif
  385. }
  386. long RtApi :: getStreamLatency( void )
  387. {
  388. verifyStream();
  389. long totalLatency = 0;
  390. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  391. totalLatency = stream_.latency[0];
  392. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  393. totalLatency += stream_.latency[1];
  394. return totalLatency;
  395. }
  396. double RtApi :: getStreamTime( void )
  397. {
  398. verifyStream();
  399. #if defined( HAVE_GETTIMEOFDAY )
  400. // Return a very accurate estimate of the stream time by
  401. // adding in the elapsed time since the last tick.
  402. struct timeval then;
  403. struct timeval now;
  404. if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
  405. return stream_.streamTime;
  406. gettimeofday( &now, NULL );
  407. then = stream_.lastTickTimestamp;
  408. return stream_.streamTime +
  409. ((now.tv_sec + 0.000001 * now.tv_usec) -
  410. (then.tv_sec + 0.000001 * then.tv_usec));
  411. #else
  412. return stream_.streamTime;
  413. #endif
  414. }
  415. void RtApi :: setStreamTime( double time )
  416. {
  417. verifyStream();
  418. if ( time >= 0.0 )
  419. stream_.streamTime = time;
  420. #if defined( HAVE_GETTIMEOFDAY )
  421. gettimeofday( &stream_.lastTickTimestamp, NULL );
  422. #endif
  423. }
  424. unsigned int RtApi :: getStreamSampleRate( void )
  425. {
  426. verifyStream();
  427. return stream_.sampleRate;
  428. }
  429. // *************************************************** //
  430. //
  431. // OS/API-specific methods.
  432. //
  433. // *************************************************** //
  434. #if defined(__MACOSX_CORE__)
  435. // The OS X CoreAudio API is designed to use a separate callback
  436. // procedure for each of its audio devices. A single RtAudio duplex
  437. // stream using two different devices is supported here, though it
  438. // cannot be guaranteed to always behave correctly because we cannot
  439. // synchronize these two callbacks.
  440. //
  441. // A property listener is installed for over/underrun information.
  442. // However, no functionality is currently provided to allow property
  443. // listeners to trigger user handlers because it is unclear what could
  444. // be done if a critical stream parameter (buffer size, sample rate,
  445. // device disconnect) notification arrived. The listeners entail
  446. // quite a bit of extra code and most likely, a user program wouldn't
  447. // be prepared for the result anyway. However, we do provide a flag
  448. // to the client callback function to inform of an over/underrun.
  449. // A structure to hold various information related to the CoreAudio API
  450. // implementation.
  451. struct CoreHandle {
  452. AudioDeviceID id[2]; // device ids
  453. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  454. AudioDeviceIOProcID procId[2];
  455. #endif
  456. UInt32 iStream[2]; // device stream index (or first if using multiple)
  457. UInt32 nStreams[2]; // number of streams to use
  458. bool xrun[2];
  459. char *deviceBuffer;
  460. pthread_cond_t condition;
  461. int drainCounter; // Tracks callback counts when draining
  462. bool internalDrain; // Indicates if stop is initiated from callback or not.
  463. CoreHandle()
  464. :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  465. };
  466. RtApiCore:: RtApiCore()
  467. {
  468. #if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )
  469. // This is a largely undocumented but absolutely necessary
  470. // requirement starting with OS-X 10.6. If not called, queries and
  471. // updates to various audio device properties are not handled
  472. // correctly.
  473. CFRunLoopRef theRunLoop = NULL;
  474. AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,
  475. kAudioObjectPropertyScopeGlobal,
  476. kAudioObjectPropertyElementMaster };
  477. OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  478. if ( result != noErr ) {
  479. errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
  480. error( RtAudioError::WARNING );
  481. }
  482. #endif
  483. }
  484. RtApiCore :: ~RtApiCore()
  485. {
  486. // The subclass destructor gets called before the base class
  487. // destructor, so close an existing stream before deallocating
  488. // apiDeviceId memory.
  489. if ( stream_.state != STREAM_CLOSED ) closeStream();
  490. }
  491. unsigned int RtApiCore :: getDeviceCount( void )
  492. {
  493. // Find out how many audio devices there are, if any.
  494. UInt32 dataSize;
  495. AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  496. OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );
  497. if ( result != noErr ) {
  498. errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
  499. error( RtAudioError::WARNING );
  500. return 0;
  501. }
  502. return dataSize / sizeof( AudioDeviceID );
  503. }
  504. unsigned int RtApiCore :: getDefaultInputDevice( void )
  505. {
  506. unsigned int nDevices = getDeviceCount();
  507. if ( nDevices <= 1 ) return 0;
  508. AudioDeviceID id;
  509. UInt32 dataSize = sizeof( AudioDeviceID );
  510. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  511. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  512. if ( result != noErr ) {
  513. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
  514. error( RtAudioError::WARNING );
  515. return 0;
  516. }
  517. dataSize *= nDevices;
  518. AudioDeviceID deviceList[ nDevices ];
  519. property.mSelector = kAudioHardwarePropertyDevices;
  520. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  521. if ( result != noErr ) {
  522. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
  523. error( RtAudioError::WARNING );
  524. return 0;
  525. }
  526. for ( unsigned int i=0; i<nDevices; i++ )
  527. if ( id == deviceList[i] ) return i;
  528. errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
  529. error( RtAudioError::WARNING );
  530. return 0;
  531. }
  532. unsigned int RtApiCore :: getDefaultOutputDevice( void )
  533. {
  534. unsigned int nDevices = getDeviceCount();
  535. if ( nDevices <= 1 ) return 0;
  536. AudioDeviceID id;
  537. UInt32 dataSize = sizeof( AudioDeviceID );
  538. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  539. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  540. if ( result != noErr ) {
  541. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
  542. error( RtAudioError::WARNING );
  543. return 0;
  544. }
  545. dataSize = sizeof( AudioDeviceID ) * nDevices;
  546. AudioDeviceID deviceList[ nDevices ];
  547. property.mSelector = kAudioHardwarePropertyDevices;
  548. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  549. if ( result != noErr ) {
  550. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
  551. error( RtAudioError::WARNING );
  552. return 0;
  553. }
  554. for ( unsigned int i=0; i<nDevices; i++ )
  555. if ( id == deviceList[i] ) return i;
  556. errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
  557. error( RtAudioError::WARNING );
  558. return 0;
  559. }
  560. RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
  561. {
  562. RtAudio::DeviceInfo info;
  563. info.probed = false;
  564. // Get device ID
  565. unsigned int nDevices = getDeviceCount();
  566. if ( nDevices == 0 ) {
  567. errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
  568. error( RtAudioError::INVALID_USE );
  569. return info;
  570. }
  571. if ( device >= nDevices ) {
  572. errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
  573. error( RtAudioError::INVALID_USE );
  574. return info;
  575. }
  576. AudioDeviceID deviceList[ nDevices ];
  577. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  578. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  579. kAudioObjectPropertyScopeGlobal,
  580. kAudioObjectPropertyElementMaster };
  581. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  582. 0, NULL, &dataSize, (void *) &deviceList );
  583. if ( result != noErr ) {
  584. errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
  585. error( RtAudioError::WARNING );
  586. return info;
  587. }
  588. AudioDeviceID id = deviceList[ device ];
  589. // Get the device name.
  590. info.name.erase();
  591. CFStringRef cfname;
  592. dataSize = sizeof( CFStringRef );
  593. property.mSelector = kAudioObjectPropertyManufacturer;
  594. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  595. if ( result != noErr ) {
  596. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
  597. errorText_ = errorStream_.str();
  598. error( RtAudioError::WARNING );
  599. return info;
  600. }
  601. //const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  602. int length = CFStringGetLength(cfname);
  603. char *mname = (char *)malloc(length * 3 + 1);
  604. #if defined( UNICODE ) || defined( _UNICODE )
  605. CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
  606. #else
  607. CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
  608. #endif
  609. info.name.append( (const char *)mname, strlen(mname) );
  610. info.name.append( ": " );
  611. CFRelease( cfname );
  612. free(mname);
  613. property.mSelector = kAudioObjectPropertyName;
  614. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  615. if ( result != noErr ) {
  616. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
  617. errorText_ = errorStream_.str();
  618. error( RtAudioError::WARNING );
  619. return info;
  620. }
  621. //const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  622. length = CFStringGetLength(cfname);
  623. char *name = (char *)malloc(length * 3 + 1);
  624. #if defined( UNICODE ) || defined( _UNICODE )
  625. CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
  626. #else
  627. CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
  628. #endif
  629. info.name.append( (const char *)name, strlen(name) );
  630. CFRelease( cfname );
  631. free(name);
  632. // Get the output stream "configuration".
  633. AudioBufferList *bufferList = nil;
  634. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  635. property.mScope = kAudioDevicePropertyScopeOutput;
  636. // property.mElement = kAudioObjectPropertyElementWildcard;
  637. dataSize = 0;
  638. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  639. if ( result != noErr || dataSize == 0 ) {
  640. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";
  641. errorText_ = errorStream_.str();
  642. error( RtAudioError::WARNING );
  643. return info;
  644. }
  645. // Allocate the AudioBufferList.
  646. bufferList = (AudioBufferList *) malloc( dataSize );
  647. if ( bufferList == NULL ) {
  648. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
  649. error( RtAudioError::WARNING );
  650. return info;
  651. }
  652. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  653. if ( result != noErr || dataSize == 0 ) {
  654. free( bufferList );
  655. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";
  656. errorText_ = errorStream_.str();
  657. error( RtAudioError::WARNING );
  658. return info;
  659. }
  660. // Get output channel information.
  661. unsigned int i, nStreams = bufferList->mNumberBuffers;
  662. for ( i=0; i<nStreams; i++ )
  663. info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
  664. free( bufferList );
  665. // Get the input stream "configuration".
  666. property.mScope = kAudioDevicePropertyScopeInput;
  667. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  668. if ( result != noErr || dataSize == 0 ) {
  669. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";
  670. errorText_ = errorStream_.str();
  671. error( RtAudioError::WARNING );
  672. return info;
  673. }
  674. // Allocate the AudioBufferList.
  675. bufferList = (AudioBufferList *) malloc( dataSize );
  676. if ( bufferList == NULL ) {
  677. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
  678. error( RtAudioError::WARNING );
  679. return info;
  680. }
  681. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  682. if (result != noErr || dataSize == 0) {
  683. free( bufferList );
  684. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";
  685. errorText_ = errorStream_.str();
  686. error( RtAudioError::WARNING );
  687. return info;
  688. }
  689. // Get input channel information.
  690. nStreams = bufferList->mNumberBuffers;
  691. for ( i=0; i<nStreams; i++ )
  692. info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
  693. free( bufferList );
  694. // If device opens for both playback and capture, we determine the channels.
  695. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  696. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  697. // Probe the device sample rates.
  698. bool isInput = false;
  699. if ( info.outputChannels == 0 ) isInput = true;
  700. // Determine the supported sample rates.
  701. property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  702. if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;
  703. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  704. if ( result != kAudioHardwareNoError || dataSize == 0 ) {
  705. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
  706. errorText_ = errorStream_.str();
  707. error( RtAudioError::WARNING );
  708. return info;
  709. }
  710. UInt32 nRanges = dataSize / sizeof( AudioValueRange );
  711. AudioValueRange rangeList[ nRanges ];
  712. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );
  713. if ( result != kAudioHardwareNoError ) {
  714. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
  715. errorText_ = errorStream_.str();
  716. error( RtAudioError::WARNING );
  717. return info;
  718. }
  719. // The sample rate reporting mechanism is a bit of a mystery. It
  720. // seems that it can either return individual rates or a range of
  721. // rates. I assume that if the min / max range values are the same,
  722. // then that represents a single supported rate and if the min / max
  723. // range values are different, the device supports an arbitrary
  724. // range of values (though there might be multiple ranges, so we'll
  725. // use the most conservative range).
  726. Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
  727. bool haveValueRange = false;
  728. info.sampleRates.clear();
  729. for ( UInt32 i=0; i<nRanges; i++ ) {
  730. if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {
  731. unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;
  732. info.sampleRates.push_back( tmpSr );
  733. if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )
  734. info.preferredSampleRate = tmpSr;
  735. } else {
  736. haveValueRange = true;
  737. if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;
  738. if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;
  739. }
  740. }
  741. if ( haveValueRange ) {
  742. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  743. if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {
  744. info.sampleRates.push_back( SAMPLE_RATES[k] );
  745. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  746. info.preferredSampleRate = SAMPLE_RATES[k];
  747. }
  748. }
  749. }
  750. // Sort and remove any redundant values
  751. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  752. info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );
  753. if ( info.sampleRates.size() == 0 ) {
  754. errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
  755. errorText_ = errorStream_.str();
  756. error( RtAudioError::WARNING );
  757. return info;
  758. }
  759. // CoreAudio always uses 32-bit floating point data for PCM streams.
  760. // Thus, any other "physical" formats supported by the device are of
  761. // no interest to the client.
  762. info.nativeFormats = RTAUDIO_FLOAT32;
  763. if ( info.outputChannels > 0 )
  764. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  765. if ( info.inputChannels > 0 )
  766. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  767. info.probed = true;
  768. return info;
  769. }
  770. static OSStatus callbackHandler( AudioDeviceID inDevice,
  771. const AudioTimeStamp* /*inNow*/,
  772. const AudioBufferList* inInputData,
  773. const AudioTimeStamp* /*inInputTime*/,
  774. AudioBufferList* outOutputData,
  775. const AudioTimeStamp* /*inOutputTime*/,
  776. void* infoPointer )
  777. {
  778. CallbackInfo *info = (CallbackInfo *) infoPointer;
  779. RtApiCore *object = (RtApiCore *) info->object;
  780. if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
  781. return kAudioHardwareUnspecifiedError;
  782. else
  783. return kAudioHardwareNoError;
  784. }
  785. static OSStatus xrunListener( AudioObjectID /*inDevice*/,
  786. UInt32 nAddresses,
  787. const AudioObjectPropertyAddress properties[],
  788. void* handlePointer )
  789. {
  790. CoreHandle *handle = (CoreHandle *) handlePointer;
  791. for ( UInt32 i=0; i<nAddresses; i++ ) {
  792. if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {
  793. if ( properties[i].mScope == kAudioDevicePropertyScopeInput )
  794. handle->xrun[1] = true;
  795. else
  796. handle->xrun[0] = true;
  797. }
  798. }
  799. return kAudioHardwareNoError;
  800. }
  801. static OSStatus rateListener( AudioObjectID inDevice,
  802. UInt32 /*nAddresses*/,
  803. const AudioObjectPropertyAddress /*properties*/[],
  804. void* ratePointer )
  805. {
  806. Float64 *rate = (Float64 *) ratePointer;
  807. UInt32 dataSize = sizeof( Float64 );
  808. AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,
  809. kAudioObjectPropertyScopeGlobal,
  810. kAudioObjectPropertyElementMaster };
  811. AudioObjectGetPropertyData( inDevice, &property, 0, NULL, &dataSize, rate );
  812. return kAudioHardwareNoError;
  813. }
  814. bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  815. unsigned int firstChannel, unsigned int sampleRate,
  816. RtAudioFormat format, unsigned int *bufferSize,
  817. RtAudio::StreamOptions *options )
  818. {
  819. // Get device ID
  820. unsigned int nDevices = getDeviceCount();
  821. if ( nDevices == 0 ) {
  822. // This should not happen because a check is made before this function is called.
  823. errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
  824. return FAILURE;
  825. }
  826. if ( device >= nDevices ) {
  827. // This should not happen because a check is made before this function is called.
  828. errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
  829. return FAILURE;
  830. }
  831. AudioDeviceID deviceList[ nDevices ];
  832. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  833. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  834. kAudioObjectPropertyScopeGlobal,
  835. kAudioObjectPropertyElementMaster };
  836. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  837. 0, NULL, &dataSize, (void *) &deviceList );
  838. if ( result != noErr ) {
  839. errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
  840. return FAILURE;
  841. }
  842. AudioDeviceID id = deviceList[ device ];
  843. // Setup for stream mode.
  844. bool isInput = false;
  845. if ( mode == INPUT ) {
  846. isInput = true;
  847. property.mScope = kAudioDevicePropertyScopeInput;
  848. }
  849. else
  850. property.mScope = kAudioDevicePropertyScopeOutput;
  851. // Get the stream "configuration".
  852. AudioBufferList *bufferList = nil;
  853. dataSize = 0;
  854. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  855. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  856. if ( result != noErr || dataSize == 0 ) {
  857. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";
  858. errorText_ = errorStream_.str();
  859. return FAILURE;
  860. }
  861. // Allocate the AudioBufferList.
  862. bufferList = (AudioBufferList *) malloc( dataSize );
  863. if ( bufferList == NULL ) {
  864. errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
  865. return FAILURE;
  866. }
  867. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  868. if (result != noErr || dataSize == 0) {
  869. free( bufferList );
  870. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";
  871. errorText_ = errorStream_.str();
  872. return FAILURE;
  873. }
  874. // Search for one or more streams that contain the desired number of
  875. // channels. CoreAudio devices can have an arbitrary number of
  876. // streams and each stream can have an arbitrary number of channels.
  877. // For each stream, a single buffer of interleaved samples is
  878. // provided. RtAudio prefers the use of one stream of interleaved
  879. // data or multiple consecutive single-channel streams. However, we
  880. // now support multiple consecutive multi-channel streams of
  881. // interleaved data as well.
  882. UInt32 iStream, offsetCounter = firstChannel;
  883. UInt32 nStreams = bufferList->mNumberBuffers;
  884. bool monoMode = false;
  885. bool foundStream = false;
  886. // First check that the device supports the requested number of
  887. // channels.
  888. UInt32 deviceChannels = 0;
  889. for ( iStream=0; iStream<nStreams; iStream++ )
  890. deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
  891. if ( deviceChannels < ( channels + firstChannel ) ) {
  892. free( bufferList );
  893. errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";
  894. errorText_ = errorStream_.str();
  895. return FAILURE;
  896. }
  897. // Look for a single stream meeting our needs.
  898. UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;
  899. for ( iStream=0; iStream<nStreams; iStream++ ) {
  900. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  901. if ( streamChannels >= channels + offsetCounter ) {
  902. firstStream = iStream;
  903. channelOffset = offsetCounter;
  904. foundStream = true;
  905. break;
  906. }
  907. if ( streamChannels > offsetCounter ) break;
  908. offsetCounter -= streamChannels;
  909. }
  910. // If we didn't find a single stream above, then we should be able
  911. // to meet the channel specification with multiple streams.
  912. if ( foundStream == false ) {
  913. monoMode = true;
  914. offsetCounter = firstChannel;
  915. for ( iStream=0; iStream<nStreams; iStream++ ) {
  916. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  917. if ( streamChannels > offsetCounter ) break;
  918. offsetCounter -= streamChannels;
  919. }
  920. firstStream = iStream;
  921. channelOffset = offsetCounter;
  922. Int32 channelCounter = channels + offsetCounter - streamChannels;
  923. if ( streamChannels > 1 ) monoMode = false;
  924. while ( channelCounter > 0 ) {
  925. streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
  926. if ( streamChannels > 1 ) monoMode = false;
  927. channelCounter -= streamChannels;
  928. streamCount++;
  929. }
  930. }
  931. free( bufferList );
  932. // Determine the buffer size.
  933. AudioValueRange bufferRange;
  934. dataSize = sizeof( AudioValueRange );
  935. property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  936. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange );
  937. if ( result != noErr ) {
  938. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ").";
  939. errorText_ = errorStream_.str();
  940. return FAILURE;
  941. }
  942. if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  943. else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMaximum;
  944. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  945. // Set the buffer size. For multiple streams, I'm assuming we only
  946. // need to make this setting for the master channel.
  947. UInt32 theSize = (UInt32) *bufferSize;
  948. dataSize = sizeof( UInt32 );
  949. property.mSelector = kAudioDevicePropertyBufferFrameSize;
  950. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize );
  951. if ( result != noErr ) {
  952. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ").";
  953. errorText_ = errorStream_.str();
  954. return FAILURE;
  955. }
  956. // If attempting to setup a duplex stream, the bufferSize parameter
  957. // MUST be the same in both directions!
  958. *bufferSize = theSize;
  959. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  960. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";
  961. errorText_ = errorStream_.str();
  962. return FAILURE;
  963. }
  964. stream_.bufferSize = *bufferSize;
  965. stream_.nBuffers = 1;
  966. // Try to set "hog" mode ... it's not clear to me this is working.
  967. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) {
  968. pid_t hog_pid;
  969. dataSize = sizeof( hog_pid );
  970. property.mSelector = kAudioDevicePropertyHogMode;
  971. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid );
  972. if ( result != noErr ) {
  973. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!";
  974. errorText_ = errorStream_.str();
  975. return FAILURE;
  976. }
  977. if ( hog_pid != getpid() ) {
  978. hog_pid = getpid();
  979. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid );
  980. if ( result != noErr ) {
  981. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";
  982. errorText_ = errorStream_.str();
  983. return FAILURE;
  984. }
  985. }
  986. }
  987. // Check and if necessary, change the sample rate for the device.
  988. Float64 nominalRate;
  989. dataSize = sizeof( Float64 );
  990. property.mSelector = kAudioDevicePropertyNominalSampleRate;
  991. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );
  992. if ( result != noErr ) {
  993. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";
  994. errorText_ = errorStream_.str();
  995. return FAILURE;
  996. }
  997. // Only change the sample rate if off by more than 1 Hz.
  998. if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) {
  999. // Set a property listener for the sample rate change
  1000. Float64 reportedRate = 0.0;
  1001. AudioObjectPropertyAddress tmp = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  1002. result = AudioObjectAddPropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1003. if ( result != noErr ) {
  1004. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate property listener for device (" << device << ").";
  1005. errorText_ = errorStream_.str();
  1006. return FAILURE;
  1007. }
  1008. nominalRate = (Float64) sampleRate;
  1009. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );
  1010. if ( result != noErr ) {
  1011. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1012. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ").";
  1013. errorText_ = errorStream_.str();
  1014. return FAILURE;
  1015. }
  1016. // Now wait until the reported nominal rate is what we just set.
  1017. UInt32 microCounter = 0;
  1018. while ( reportedRate != nominalRate ) {
  1019. microCounter += 5000;
  1020. if ( microCounter > 5000000 ) break;
  1021. usleep( 5000 );
  1022. }
  1023. // Remove the property listener.
  1024. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1025. if ( microCounter > 5000000 ) {
  1026. errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ").";
  1027. errorText_ = errorStream_.str();
  1028. return FAILURE;
  1029. }
  1030. }
  1031. // Now set the stream format for all streams. Also, check the
  1032. // physical format of the device and change that if necessary.
  1033. AudioStreamBasicDescription description;
  1034. dataSize = sizeof( AudioStreamBasicDescription );
  1035. property.mSelector = kAudioStreamPropertyVirtualFormat;
  1036. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  1037. if ( result != noErr ) {
  1038. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ").";
  1039. errorText_ = errorStream_.str();
  1040. return FAILURE;
  1041. }
  1042. // Set the sample rate and data format id. However, only make the
  1043. // change if the sample rate is not within 1.0 of the desired
  1044. // rate and the format is not linear pcm.
  1045. bool updateFormat = false;
  1046. if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) {
  1047. description.mSampleRate = (Float64) sampleRate;
  1048. updateFormat = true;
  1049. }
  1050. if ( description.mFormatID != kAudioFormatLinearPCM ) {
  1051. description.mFormatID = kAudioFormatLinearPCM;
  1052. updateFormat = true;
  1053. }
  1054. if ( updateFormat ) {
  1055. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description );
  1056. if ( result != noErr ) {
  1057. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ").";
  1058. errorText_ = errorStream_.str();
  1059. return FAILURE;
  1060. }
  1061. }
  1062. // Now check the physical format.
  1063. property.mSelector = kAudioStreamPropertyPhysicalFormat;
  1064. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  1065. if ( result != noErr ) {
  1066. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ").";
  1067. errorText_ = errorStream_.str();
  1068. return FAILURE;
  1069. }
  1070. //std::cout << "Current physical stream format:" << std::endl;
  1071. //std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl;
  1072. //std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1073. //std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl;
  1074. //std::cout << " sample rate = " << description.mSampleRate << std::endl;
  1075. if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) {
  1076. description.mFormatID = kAudioFormatLinearPCM;
  1077. //description.mSampleRate = (Float64) sampleRate;
  1078. AudioStreamBasicDescription testDescription = description;
  1079. UInt32 formatFlags;
  1080. // We'll try higher bit rates first and then work our way down.
  1081. std::vector< std::pair<UInt32, UInt32> > physicalFormats;
  1082. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;
  1083. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1084. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1085. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1086. physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) ); // 24-bit packed
  1087. formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh );
  1088. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low
  1089. formatFlags |= kAudioFormatFlagIsAlignedHigh;
  1090. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high
  1091. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1092. physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) );
  1093. physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) );
  1094. bool setPhysicalFormat = false;
  1095. for( unsigned int i=0; i<physicalFormats.size(); i++ ) {
  1096. testDescription = description;
  1097. testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first;
  1098. testDescription.mFormatFlags = physicalFormats[i].second;
  1099. if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) )
  1100. testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame;
  1101. else
  1102. testDescription.mBytesPerFrame = testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame;
  1103. testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;
  1104. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription );
  1105. if ( result == noErr ) {
  1106. setPhysicalFormat = true;
  1107. //std::cout << "Updated physical stream format:" << std::endl;
  1108. //std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;
  1109. //std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1110. //std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;
  1111. //std::cout << " sample rate = " << testDescription.mSampleRate << std::endl;
  1112. break;
  1113. }
  1114. }
  1115. if ( !setPhysicalFormat ) {
  1116. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ").";
  1117. errorText_ = errorStream_.str();
  1118. return FAILURE;
  1119. }
  1120. } // done setting virtual/physical formats.
  1121. // Get the stream / device latency.
  1122. UInt32 latency;
  1123. dataSize = sizeof( UInt32 );
  1124. property.mSelector = kAudioDevicePropertyLatency;
  1125. if ( AudioObjectHasProperty( id, &property ) == true ) {
  1126. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency );
  1127. if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;
  1128. else {
  1129. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";
  1130. errorText_ = errorStream_.str();
  1131. error( RtAudioError::WARNING );
  1132. }
  1133. }
  1134. // Byte-swapping: According to AudioHardware.h, the stream data will
  1135. // always be presented in native-endian format, so we should never
  1136. // need to byte swap.
  1137. stream_.doByteSwap[mode] = false;
  1138. // From the CoreAudio documentation, PCM data must be supplied as
  1139. // 32-bit floats.
  1140. stream_.userFormat = format;
  1141. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1142. if ( streamCount == 1 )
  1143. stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
  1144. else // multiple streams
  1145. stream_.nDeviceChannels[mode] = channels;
  1146. stream_.nUserChannels[mode] = channels;
  1147. stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
  1148. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1149. else stream_.userInterleaved = true;
  1150. stream_.deviceInterleaved[mode] = true;
  1151. if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;
  1152. // Set flags for buffer conversion.
  1153. stream_.doConvertBuffer[mode] = false;
  1154. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1155. stream_.doConvertBuffer[mode] = true;
  1156. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  1157. stream_.doConvertBuffer[mode] = true;
  1158. if ( streamCount == 1 ) {
  1159. if ( stream_.nUserChannels[mode] > 1 &&
  1160. stream_.userInterleaved != stream_.deviceInterleaved[mode] )
  1161. stream_.doConvertBuffer[mode] = true;
  1162. }
  1163. else if ( monoMode && stream_.userInterleaved )
  1164. stream_.doConvertBuffer[mode] = true;
  1165. // Allocate our CoreHandle structure for the stream.
  1166. CoreHandle *handle = 0;
  1167. if ( stream_.apiHandle == 0 ) {
  1168. try {
  1169. handle = new CoreHandle;
  1170. }
  1171. catch ( std::bad_alloc& ) {
  1172. errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
  1173. goto error;
  1174. }
  1175. if ( pthread_cond_init( &handle->condition, NULL ) ) {
  1176. errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
  1177. goto error;
  1178. }
  1179. stream_.apiHandle = (void *) handle;
  1180. }
  1181. else
  1182. handle = (CoreHandle *) stream_.apiHandle;
  1183. handle->iStream[mode] = firstStream;
  1184. handle->nStreams[mode] = streamCount;
  1185. handle->id[mode] = id;
  1186. // Allocate necessary internal buffers.
  1187. unsigned long bufferBytes;
  1188. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  1189. // stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1190. stream_.userBuffer[mode] = (char *) malloc( bufferBytes * sizeof(char) );
  1191. memset( stream_.userBuffer[mode], 0, bufferBytes * sizeof(char) );
  1192. if ( stream_.userBuffer[mode] == NULL ) {
  1193. errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
  1194. goto error;
  1195. }
  1196. // If possible, we will make use of the CoreAudio stream buffers as
  1197. // "device buffers". However, we can't do this if using multiple
  1198. // streams.
  1199. if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {
  1200. bool makeBuffer = true;
  1201. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  1202. if ( mode == INPUT ) {
  1203. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1204. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1205. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  1206. }
  1207. }
  1208. if ( makeBuffer ) {
  1209. bufferBytes *= *bufferSize;
  1210. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1211. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1212. if ( stream_.deviceBuffer == NULL ) {
  1213. errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
  1214. goto error;
  1215. }
  1216. }
  1217. }
  1218. stream_.sampleRate = sampleRate;
  1219. stream_.device[mode] = device;
  1220. stream_.state = STREAM_STOPPED;
  1221. stream_.callbackInfo.object = (void *) this;
  1222. // Setup the buffer conversion information structure.
  1223. if ( stream_.doConvertBuffer[mode] ) {
  1224. if ( streamCount > 1 ) setConvertInfo( mode, 0 );
  1225. else setConvertInfo( mode, channelOffset );
  1226. }
  1227. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device )
  1228. // Only one callback procedure per device.
  1229. stream_.mode = DUPLEX;
  1230. else {
  1231. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1232. result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );
  1233. #else
  1234. // deprecated in favor of AudioDeviceCreateIOProcID()
  1235. result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
  1236. #endif
  1237. if ( result != noErr ) {
  1238. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";
  1239. errorText_ = errorStream_.str();
  1240. goto error;
  1241. }
  1242. if ( stream_.mode == OUTPUT && mode == INPUT )
  1243. stream_.mode = DUPLEX;
  1244. else
  1245. stream_.mode = mode;
  1246. }
  1247. // Setup the device property listener for over/underload.
  1248. property.mSelector = kAudioDeviceProcessorOverload;
  1249. property.mScope = kAudioObjectPropertyScopeGlobal;
  1250. result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );
  1251. return SUCCESS;
  1252. error:
  1253. if ( handle ) {
  1254. pthread_cond_destroy( &handle->condition );
  1255. delete handle;
  1256. stream_.apiHandle = 0;
  1257. }
  1258. for ( int i=0; i<2; i++ ) {
  1259. if ( stream_.userBuffer[i] ) {
  1260. free( stream_.userBuffer[i] );
  1261. stream_.userBuffer[i] = 0;
  1262. }
  1263. }
  1264. if ( stream_.deviceBuffer ) {
  1265. free( stream_.deviceBuffer );
  1266. stream_.deviceBuffer = 0;
  1267. }
  1268. stream_.state = STREAM_CLOSED;
  1269. return FAILURE;
  1270. }
  1271. void RtApiCore :: closeStream( void )
  1272. {
  1273. if ( stream_.state == STREAM_CLOSED ) {
  1274. errorText_ = "RtApiCore::closeStream(): no open stream to close!";
  1275. error( RtAudioError::WARNING );
  1276. return;
  1277. }
  1278. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1279. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1280. if (handle) {
  1281. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1282. kAudioObjectPropertyScopeGlobal,
  1283. kAudioObjectPropertyElementMaster };
  1284. property.mSelector = kAudioDeviceProcessorOverload;
  1285. property.mScope = kAudioObjectPropertyScopeGlobal;
  1286. if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {
  1287. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1288. error( RtAudioError::WARNING );
  1289. }
  1290. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1291. if ( stream_.state == STREAM_RUNNING )
  1292. AudioDeviceStop( handle->id[0], handle->procId[0] );
  1293. AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );
  1294. #else // deprecated behaviour
  1295. if ( stream_.state == STREAM_RUNNING )
  1296. AudioDeviceStop( handle->id[0], callbackHandler );
  1297. AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );
  1298. #endif
  1299. }
  1300. }
  1301. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1302. if (handle) {
  1303. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1304. kAudioObjectPropertyScopeGlobal,
  1305. kAudioObjectPropertyElementMaster };
  1306. property.mSelector = kAudioDeviceProcessorOverload;
  1307. property.mScope = kAudioObjectPropertyScopeGlobal;
  1308. if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {
  1309. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1310. error( RtAudioError::WARNING );
  1311. }
  1312. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1313. if ( stream_.state == STREAM_RUNNING )
  1314. AudioDeviceStop( handle->id[1], handle->procId[1] );
  1315. AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );
  1316. #else // deprecated behaviour
  1317. if ( stream_.state == STREAM_RUNNING )
  1318. AudioDeviceStop( handle->id[1], callbackHandler );
  1319. AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );
  1320. #endif
  1321. }
  1322. }
  1323. for ( int i=0; i<2; i++ ) {
  1324. if ( stream_.userBuffer[i] ) {
  1325. free( stream_.userBuffer[i] );
  1326. stream_.userBuffer[i] = 0;
  1327. }
  1328. }
  1329. if ( stream_.deviceBuffer ) {
  1330. free( stream_.deviceBuffer );
  1331. stream_.deviceBuffer = 0;
  1332. }
  1333. // Destroy pthread condition variable.
  1334. pthread_cond_destroy( &handle->condition );
  1335. delete handle;
  1336. stream_.apiHandle = 0;
  1337. stream_.mode = UNINITIALIZED;
  1338. stream_.state = STREAM_CLOSED;
  1339. }
  1340. void RtApiCore :: startStream( void )
  1341. {
  1342. verifyStream();
  1343. if ( stream_.state == STREAM_RUNNING ) {
  1344. errorText_ = "RtApiCore::startStream(): the stream is already running!";
  1345. error( RtAudioError::WARNING );
  1346. return;
  1347. }
  1348. #if defined( HAVE_GETTIMEOFDAY )
  1349. gettimeofday( &stream_.lastTickTimestamp, NULL );
  1350. #endif
  1351. OSStatus result = noErr;
  1352. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1353. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1354. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1355. result = AudioDeviceStart( handle->id[0], handle->procId[0] );
  1356. #else // deprecated behaviour
  1357. result = AudioDeviceStart( handle->id[0], callbackHandler );
  1358. #endif
  1359. if ( result != noErr ) {
  1360. errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ").";
  1361. errorText_ = errorStream_.str();
  1362. goto unlock;
  1363. }
  1364. }
  1365. if ( stream_.mode == INPUT ||
  1366. ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1367. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1368. result = AudioDeviceStart( handle->id[1], handle->procId[1] );
  1369. #else // deprecated behaviour
  1370. result = AudioDeviceStart( handle->id[1], callbackHandler );
  1371. #endif
  1372. if ( result != noErr ) {
  1373. errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";
  1374. errorText_ = errorStream_.str();
  1375. goto unlock;
  1376. }
  1377. }
  1378. handle->drainCounter = 0;
  1379. handle->internalDrain = false;
  1380. stream_.state = STREAM_RUNNING;
  1381. unlock:
  1382. if ( result == noErr ) return;
  1383. error( RtAudioError::SYSTEM_ERROR );
  1384. }
  1385. void RtApiCore :: stopStream( void )
  1386. {
  1387. verifyStream();
  1388. if ( stream_.state == STREAM_STOPPED ) {
  1389. errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
  1390. error( RtAudioError::WARNING );
  1391. return;
  1392. }
  1393. OSStatus result = noErr;
  1394. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1395. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1396. if ( handle->drainCounter == 0 ) {
  1397. handle->drainCounter = 2;
  1398. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  1399. }
  1400. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1401. result = AudioDeviceStop( handle->id[0], handle->procId[0] );
  1402. #else // deprecated behaviour
  1403. result = AudioDeviceStop( handle->id[0], callbackHandler );
  1404. #endif
  1405. if ( result != noErr ) {
  1406. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";
  1407. errorText_ = errorStream_.str();
  1408. goto unlock;
  1409. }
  1410. }
  1411. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1412. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1413. result = AudioDeviceStop( handle->id[0], handle->procId[1] );
  1414. #else // deprecated behaviour
  1415. result = AudioDeviceStop( handle->id[1], callbackHandler );
  1416. #endif
  1417. if ( result != noErr ) {
  1418. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";
  1419. errorText_ = errorStream_.str();
  1420. goto unlock;
  1421. }
  1422. }
  1423. stream_.state = STREAM_STOPPED;
  1424. unlock:
  1425. if ( result == noErr ) return;
  1426. error( RtAudioError::SYSTEM_ERROR );
  1427. }
  1428. void RtApiCore :: abortStream( void )
  1429. {
  1430. verifyStream();
  1431. if ( stream_.state == STREAM_STOPPED ) {
  1432. errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
  1433. error( RtAudioError::WARNING );
  1434. return;
  1435. }
  1436. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1437. handle->drainCounter = 2;
  1438. stopStream();
  1439. }
  1440. // This function will be called by a spawned thread when the user
  1441. // callback function signals that the stream should be stopped or
  1442. // aborted. It is better to handle it this way because the
  1443. // callbackEvent() function probably should return before the AudioDeviceStop()
  1444. // function is called.
  1445. static void *coreStopStream( void *ptr )
  1446. {
  1447. CallbackInfo *info = (CallbackInfo *) ptr;
  1448. RtApiCore *object = (RtApiCore *) info->object;
  1449. object->stopStream();
  1450. pthread_exit( NULL );
  1451. }
  1452. bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
  1453. const AudioBufferList *inBufferList,
  1454. const AudioBufferList *outBufferList )
  1455. {
  1456. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  1457. if ( stream_.state == STREAM_CLOSED ) {
  1458. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  1459. error( RtAudioError::WARNING );
  1460. return FAILURE;
  1461. }
  1462. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  1463. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1464. // Check if we were draining the stream and signal is finished.
  1465. if ( handle->drainCounter > 3 ) {
  1466. ThreadHandle threadId;
  1467. stream_.state = STREAM_STOPPING;
  1468. if ( handle->internalDrain == true )
  1469. pthread_create( &threadId, NULL, coreStopStream, info );
  1470. else // external call to stopStream()
  1471. pthread_cond_signal( &handle->condition );
  1472. return SUCCESS;
  1473. }
  1474. AudioDeviceID outputDevice = handle->id[0];
  1475. // Invoke user callback to get fresh output data UNLESS we are
  1476. // draining stream or duplex mode AND the input/output devices are
  1477. // different AND this function is called for the input device.
  1478. if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {
  1479. RtAudioCallback callback = (RtAudioCallback) info->callback;
  1480. double streamTime = getStreamTime();
  1481. RtAudioStreamStatus status = 0;
  1482. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  1483. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  1484. handle->xrun[0] = false;
  1485. }
  1486. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  1487. status |= RTAUDIO_INPUT_OVERFLOW;
  1488. handle->xrun[1] = false;
  1489. }
  1490. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  1491. stream_.bufferSize, streamTime, status, info->userData );
  1492. if ( cbReturnValue == 2 ) {
  1493. stream_.state = STREAM_STOPPING;
  1494. handle->drainCounter = 2;
  1495. abortStream();
  1496. return SUCCESS;
  1497. }
  1498. else if ( cbReturnValue == 1 ) {
  1499. handle->drainCounter = 1;
  1500. handle->internalDrain = true;
  1501. }
  1502. }
  1503. if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {
  1504. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  1505. if ( handle->nStreams[0] == 1 ) {
  1506. memset( outBufferList->mBuffers[handle->iStream[0]].mData,
  1507. 0,
  1508. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1509. }
  1510. else { // fill multiple streams with zeros
  1511. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1512. memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1513. 0,
  1514. outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );
  1515. }
  1516. }
  1517. }
  1518. else if ( handle->nStreams[0] == 1 ) {
  1519. if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer
  1520. convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,
  1521. stream_.userBuffer[0], stream_.convertInfo[0] );
  1522. }
  1523. else { // copy from user buffer
  1524. memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,
  1525. stream_.userBuffer[0],
  1526. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1527. }
  1528. }
  1529. else { // fill multiple streams
  1530. Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];
  1531. if ( stream_.doConvertBuffer[0] ) {
  1532. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  1533. inBuffer = (Float32 *) stream_.deviceBuffer;
  1534. }
  1535. if ( stream_.deviceInterleaved[0] == false ) { // mono mode
  1536. UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
  1537. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1538. memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1539. (void *)&inBuffer[i*stream_.bufferSize], bufferBytes );
  1540. }
  1541. }
  1542. else { // fill multiple multi-channel streams with interleaved data
  1543. UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
  1544. Float32 *out, *in;
  1545. bool inInterleaved = ( stream_.userInterleaved ) ? true : false;
  1546. UInt32 inChannels = stream_.nUserChannels[0];
  1547. if ( stream_.doConvertBuffer[0] ) {
  1548. inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1549. inChannels = stream_.nDeviceChannels[0];
  1550. }
  1551. if ( inInterleaved ) inOffset = 1;
  1552. else inOffset = stream_.bufferSize;
  1553. channelsLeft = inChannels;
  1554. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1555. in = inBuffer;
  1556. out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;
  1557. streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;
  1558. outJump = 0;
  1559. // Account for possible channel offset in first stream
  1560. if ( i == 0 && stream_.channelOffset[0] > 0 ) {
  1561. streamChannels -= stream_.channelOffset[0];
  1562. outJump = stream_.channelOffset[0];
  1563. out += outJump;
  1564. }
  1565. // Account for possible unfilled channels at end of the last stream
  1566. if ( streamChannels > channelsLeft ) {
  1567. outJump = streamChannels - channelsLeft;
  1568. streamChannels = channelsLeft;
  1569. }
  1570. // Determine input buffer offsets and skips
  1571. if ( inInterleaved ) {
  1572. inJump = inChannels;
  1573. in += inChannels - channelsLeft;
  1574. }
  1575. else {
  1576. inJump = 1;
  1577. in += (inChannels - channelsLeft) * inOffset;
  1578. }
  1579. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1580. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1581. *out++ = in[j*inOffset];
  1582. }
  1583. out += outJump;
  1584. in += inJump;
  1585. }
  1586. channelsLeft -= streamChannels;
  1587. }
  1588. }
  1589. }
  1590. }
  1591. // Don't bother draining input
  1592. if ( handle->drainCounter ) {
  1593. handle->drainCounter++;
  1594. goto unlock;
  1595. }
  1596. AudioDeviceID inputDevice;
  1597. inputDevice = handle->id[1];
  1598. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {
  1599. if ( handle->nStreams[1] == 1 ) {
  1600. if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer
  1601. convertBuffer( stream_.userBuffer[1],
  1602. (char *) inBufferList->mBuffers[handle->iStream[1]].mData,
  1603. stream_.convertInfo[1] );
  1604. }
  1605. else { // copy to user buffer
  1606. memcpy( stream_.userBuffer[1],
  1607. inBufferList->mBuffers[handle->iStream[1]].mData,
  1608. inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );
  1609. }
  1610. }
  1611. else { // read from multiple streams
  1612. Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];
  1613. if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;
  1614. if ( stream_.deviceInterleaved[1] == false ) { // mono mode
  1615. UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
  1616. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1617. memcpy( (void *)&outBuffer[i*stream_.bufferSize],
  1618. inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );
  1619. }
  1620. }
  1621. else { // read from multiple multi-channel streams
  1622. UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
  1623. Float32 *out, *in;
  1624. bool outInterleaved = ( stream_.userInterleaved ) ? true : false;
  1625. UInt32 outChannels = stream_.nUserChannels[1];
  1626. if ( stream_.doConvertBuffer[1] ) {
  1627. outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1628. outChannels = stream_.nDeviceChannels[1];
  1629. }
  1630. if ( outInterleaved ) outOffset = 1;
  1631. else outOffset = stream_.bufferSize;
  1632. channelsLeft = outChannels;
  1633. for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {
  1634. out = outBuffer;
  1635. in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;
  1636. streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;
  1637. inJump = 0;
  1638. // Account for possible channel offset in first stream
  1639. if ( i == 0 && stream_.channelOffset[1] > 0 ) {
  1640. streamChannels -= stream_.channelOffset[1];
  1641. inJump = stream_.channelOffset[1];
  1642. in += inJump;
  1643. }
  1644. // Account for possible unread channels at end of the last stream
  1645. if ( streamChannels > channelsLeft ) {
  1646. inJump = streamChannels - channelsLeft;
  1647. streamChannels = channelsLeft;
  1648. }
  1649. // Determine output buffer offsets and skips
  1650. if ( outInterleaved ) {
  1651. outJump = outChannels;
  1652. out += outChannels - channelsLeft;
  1653. }
  1654. else {
  1655. outJump = 1;
  1656. out += (outChannels - channelsLeft) * outOffset;
  1657. }
  1658. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1659. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1660. out[j*outOffset] = *in++;
  1661. }
  1662. out += outJump;
  1663. in += inJump;
  1664. }
  1665. channelsLeft -= streamChannels;
  1666. }
  1667. }
  1668. if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer
  1669. convertBuffer( stream_.userBuffer[1],
  1670. stream_.deviceBuffer,
  1671. stream_.convertInfo[1] );
  1672. }
  1673. }
  1674. }
  1675. unlock:
  1676. //MUTEX_UNLOCK( &stream_.mutex );
  1677. // Make sure to only tick duplex stream time once if using two devices
  1678. if ( stream_.mode != DUPLEX || (stream_.mode == DUPLEX && handle->id[0] != handle->id[1] && deviceId == handle->id[0] ) )
  1679. RtApi::tickStreamTime();
  1680. return SUCCESS;
  1681. }
  1682. const char* RtApiCore :: getErrorCode( OSStatus code )
  1683. {
  1684. switch( code ) {
  1685. case kAudioHardwareNotRunningError:
  1686. return "kAudioHardwareNotRunningError";
  1687. case kAudioHardwareUnspecifiedError:
  1688. return "kAudioHardwareUnspecifiedError";
  1689. case kAudioHardwareUnknownPropertyError:
  1690. return "kAudioHardwareUnknownPropertyError";
  1691. case kAudioHardwareBadPropertySizeError:
  1692. return "kAudioHardwareBadPropertySizeError";
  1693. case kAudioHardwareIllegalOperationError:
  1694. return "kAudioHardwareIllegalOperationError";
  1695. case kAudioHardwareBadObjectError:
  1696. return "kAudioHardwareBadObjectError";
  1697. case kAudioHardwareBadDeviceError:
  1698. return "kAudioHardwareBadDeviceError";
  1699. case kAudioHardwareBadStreamError:
  1700. return "kAudioHardwareBadStreamError";
  1701. case kAudioHardwareUnsupportedOperationError:
  1702. return "kAudioHardwareUnsupportedOperationError";
  1703. case kAudioDeviceUnsupportedFormatError:
  1704. return "kAudioDeviceUnsupportedFormatError";
  1705. case kAudioDevicePermissionsError:
  1706. return "kAudioDevicePermissionsError";
  1707. default:
  1708. return "CoreAudio unknown error";
  1709. }
  1710. }
  1711. //******************** End of __MACOSX_CORE__ *********************//
  1712. #endif
  1713. #if defined(__UNIX_JACK__)
  1714. // JACK is a low-latency audio server, originally written for the
  1715. // GNU/Linux operating system and now also ported to OS-X. It can
  1716. // connect a number of different applications to an audio device, as
  1717. // well as allowing them to share audio between themselves.
  1718. //
  1719. // When using JACK with RtAudio, "devices" refer to JACK clients that
  1720. // have ports connected to the server. The JACK server is typically
  1721. // started in a terminal as follows:
  1722. //
  1723. // .jackd -d alsa -d hw:0
  1724. //
  1725. // or through an interface program such as qjackctl. Many of the
  1726. // parameters normally set for a stream are fixed by the JACK server
  1727. // and can be specified when the JACK server is started. In
  1728. // particular,
  1729. //
  1730. // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
  1731. //
  1732. // specifies a sample rate of 44100 Hz, a buffer size of 512 sample
  1733. // frames, and number of buffers = 4. Once the server is running, it
  1734. // is not possible to override these values. If the values are not
  1735. // specified in the command-line, the JACK server uses default values.
  1736. //
  1737. // The JACK server does not have to be running when an instance of
  1738. // RtApiJack is created, though the function getDeviceCount() will
  1739. // report 0 devices found until JACK has been started. When no
  1740. // devices are available (i.e., the JACK server is not running), a
  1741. // stream cannot be opened.
  1742. #include <jack/jack.h>
  1743. #include <unistd.h>
  1744. #include <cstdio>
  1745. // A structure to hold various information related to the Jack API
  1746. // implementation.
  1747. struct JackHandle {
  1748. jack_client_t *client;
  1749. jack_port_t **ports[2];
  1750. std::string deviceName[2];
  1751. bool xrun[2];
  1752. pthread_cond_t condition;
  1753. int drainCounter; // Tracks callback counts when draining
  1754. bool internalDrain; // Indicates if stop is initiated from callback or not.
  1755. JackHandle()
  1756. :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
  1757. };
  1758. #if !defined(__RTAUDIO_DEBUG__)
  1759. static void jackSilentError( const char * ) {};
  1760. #endif
  1761. RtApiJack :: RtApiJack()
  1762. :shouldAutoconnect_(true) {
  1763. // Nothing to do here.
  1764. #if !defined(__RTAUDIO_DEBUG__)
  1765. // Turn off Jack's internal error reporting.
  1766. jack_set_error_function( &jackSilentError );
  1767. #endif
  1768. }
  1769. RtApiJack :: ~RtApiJack()
  1770. {
  1771. if ( stream_.state != STREAM_CLOSED ) closeStream();
  1772. }
  1773. unsigned int RtApiJack :: getDeviceCount( void )
  1774. {
  1775. // See if we can become a jack client.
  1776. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1777. jack_status_t *status = NULL;
  1778. jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );
  1779. if ( client == 0 ) return 0;
  1780. const char **ports;
  1781. std::string port, previousPort;
  1782. unsigned int nChannels = 0, nDevices = 0;
  1783. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1784. if ( ports ) {
  1785. // Parse the port names up to the first colon (:).
  1786. size_t iColon = 0;
  1787. do {
  1788. port = (char *) ports[ nChannels ];
  1789. iColon = port.find(":");
  1790. if ( iColon != std::string::npos ) {
  1791. port = port.substr( 0, iColon + 1 );
  1792. if ( port != previousPort ) {
  1793. nDevices++;
  1794. previousPort = port;
  1795. }
  1796. }
  1797. } while ( ports[++nChannels] );
  1798. free( ports );
  1799. }
  1800. jack_client_close( client );
  1801. return nDevices;
  1802. }
  1803. RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
  1804. {
  1805. RtAudio::DeviceInfo info;
  1806. info.probed = false;
  1807. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption
  1808. jack_status_t *status = NULL;
  1809. jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );
  1810. if ( client == 0 ) {
  1811. errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
  1812. error( RtAudioError::WARNING );
  1813. return info;
  1814. }
  1815. const char **ports;
  1816. std::string port, previousPort;
  1817. unsigned int nPorts = 0, nDevices = 0;
  1818. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1819. if ( ports ) {
  1820. // Parse the port names up to the first colon (:).
  1821. size_t iColon = 0;
  1822. do {
  1823. port = (char *) ports[ nPorts ];
  1824. iColon = port.find(":");
  1825. if ( iColon != std::string::npos ) {
  1826. port = port.substr( 0, iColon );
  1827. if ( port != previousPort ) {
  1828. if ( nDevices == device ) info.name = port;
  1829. nDevices++;
  1830. previousPort = port;
  1831. }
  1832. }
  1833. } while ( ports[++nPorts] );
  1834. free( ports );
  1835. }
  1836. if ( device >= nDevices ) {
  1837. jack_client_close( client );
  1838. errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
  1839. error( RtAudioError::INVALID_USE );
  1840. return info;
  1841. }
  1842. // Get the current jack server sample rate.
  1843. info.sampleRates.clear();
  1844. info.preferredSampleRate = jack_get_sample_rate( client );
  1845. info.sampleRates.push_back( info.preferredSampleRate );
  1846. // Count the available ports containing the client name as device
  1847. // channels. Jack "input ports" equal RtAudio output channels.
  1848. unsigned int nChannels = 0;
  1849. ports = jack_get_ports( client, info.name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput );
  1850. if ( ports ) {
  1851. while ( ports[ nChannels ] ) nChannels++;
  1852. free( ports );
  1853. info.outputChannels = nChannels;
  1854. }
  1855. // Jack "output ports" equal RtAudio input channels.
  1856. nChannels = 0;
  1857. ports = jack_get_ports( client, info.name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
  1858. if ( ports ) {
  1859. while ( ports[ nChannels ] ) nChannels++;
  1860. free( ports );
  1861. info.inputChannels = nChannels;
  1862. }
  1863. if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
  1864. jack_client_close(client);
  1865. errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
  1866. error( RtAudioError::WARNING );
  1867. return info;
  1868. }
  1869. // If device opens for both playback and capture, we determine the channels.
  1870. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  1871. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  1872. // Jack always uses 32-bit floats.
  1873. info.nativeFormats = RTAUDIO_FLOAT32;
  1874. // Jack doesn't provide default devices so we'll use the first available one.
  1875. if ( device == 0 && info.outputChannels > 0 )
  1876. info.isDefaultOutput = true;
  1877. if ( device == 0 && info.inputChannels > 0 )
  1878. info.isDefaultInput = true;
  1879. jack_client_close(client);
  1880. info.probed = true;
  1881. return info;
  1882. }
  1883. static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
  1884. {
  1885. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1886. RtApiJack *object = (RtApiJack *) info->object;
  1887. if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
  1888. return 0;
  1889. }
  1890. // This function will be called by a spawned thread when the Jack
  1891. // server signals that it is shutting down. It is necessary to handle
  1892. // it this way because the jackShutdown() function must return before
  1893. // the jack_deactivate() function (in closeStream()) will return.
  1894. static void *jackCloseStream( void *ptr )
  1895. {
  1896. CallbackInfo *info = (CallbackInfo *) ptr;
  1897. RtApiJack *object = (RtApiJack *) info->object;
  1898. object->closeStream();
  1899. pthread_exit( NULL );
  1900. }
  1901. static void jackShutdown( void *infoPointer )
  1902. {
  1903. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1904. RtApiJack *object = (RtApiJack *) info->object;
  1905. // Check current stream state. If stopped, then we'll assume this
  1906. // was called as a result of a call to RtApiJack::stopStream (the
  1907. // deactivation of a client handle causes this function to be called).
  1908. // If not, we'll assume the Jack server is shutting down or some
  1909. // other problem occurred and we should close the stream.
  1910. if ( object->isStreamRunning() == false ) return;
  1911. ThreadHandle threadId;
  1912. pthread_create( &threadId, NULL, jackCloseStream, info );
  1913. std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
  1914. }
  1915. static int jackXrun( void *infoPointer )
  1916. {
  1917. JackHandle *handle = *((JackHandle **) infoPointer);
  1918. if ( handle->ports[0] ) handle->xrun[0] = true;
  1919. if ( handle->ports[1] ) handle->xrun[1] = true;
  1920. return 0;
  1921. }
  1922. bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  1923. unsigned int firstChannel, unsigned int sampleRate,
  1924. RtAudioFormat format, unsigned int *bufferSize,
  1925. RtAudio::StreamOptions *options )
  1926. {
  1927. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1928. // Look for jack server and try to become a client (only do once per stream).
  1929. jack_client_t *client = 0;
  1930. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
  1931. jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1932. jack_status_t *status = NULL;
  1933. if ( options && !options->streamName.empty() )
  1934. client = jack_client_open( options->streamName.c_str(), jackoptions, status );
  1935. else
  1936. client = jack_client_open( "RtApiJack", jackoptions, status );
  1937. if ( client == 0 ) {
  1938. errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
  1939. error( RtAudioError::WARNING );
  1940. return FAILURE;
  1941. }
  1942. }
  1943. else {
  1944. // The handle must have been created on an earlier pass.
  1945. client = handle->client;
  1946. }
  1947. const char **ports;
  1948. std::string port, previousPort, deviceName;
  1949. unsigned int nPorts = 0, nDevices = 0;
  1950. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1951. if ( ports ) {
  1952. // Parse the port names up to the first colon (:).
  1953. size_t iColon = 0;
  1954. do {
  1955. port = (char *) ports[ nPorts ];
  1956. iColon = port.find(":");
  1957. if ( iColon != std::string::npos ) {
  1958. port = port.substr( 0, iColon );
  1959. if ( port != previousPort ) {
  1960. if ( nDevices == device ) deviceName = port;
  1961. nDevices++;
  1962. previousPort = port;
  1963. }
  1964. }
  1965. } while ( ports[++nPorts] );
  1966. free( ports );
  1967. }
  1968. if ( device >= nDevices ) {
  1969. errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
  1970. return FAILURE;
  1971. }
  1972. unsigned long flag = JackPortIsInput;
  1973. if ( mode == INPUT ) flag = JackPortIsOutput;
  1974. if ( ! (options && (options->flags & RTAUDIO_JACK_DONT_CONNECT)) ) {
  1975. // Count the available ports containing the client name as device
  1976. // channels. Jack "input ports" equal RtAudio output channels.
  1977. unsigned int nChannels = 0;
  1978. ports = jack_get_ports( client, deviceName.c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
  1979. if ( ports ) {
  1980. while ( ports[ nChannels ] ) nChannels++;
  1981. free( ports );
  1982. }
  1983. // Compare the jack ports for specified client to the requested number of channels.
  1984. if ( nChannels < (channels + firstChannel) ) {
  1985. errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
  1986. errorText_ = errorStream_.str();
  1987. return FAILURE;
  1988. }
  1989. }
  1990. // Check the jack server sample rate.
  1991. unsigned int jackRate = jack_get_sample_rate( client );
  1992. if ( sampleRate != jackRate ) {
  1993. jack_client_close( client );
  1994. errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
  1995. errorText_ = errorStream_.str();
  1996. return FAILURE;
  1997. }
  1998. stream_.sampleRate = jackRate;
  1999. // Get the latency of the JACK port.
  2000. ports = jack_get_ports( client, deviceName.c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
  2001. if ( ports[ firstChannel ] ) {
  2002. // Added by Ge Wang
  2003. jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
  2004. // the range (usually the min and max are equal)
  2005. jack_latency_range_t latrange; latrange.min = latrange.max = 0;
  2006. // get the latency range
  2007. jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );
  2008. // be optimistic, use the min!
  2009. stream_.latency[mode] = latrange.min;
  2010. //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
  2011. }
  2012. free( ports );
  2013. // The jack server always uses 32-bit floating-point data.
  2014. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2015. stream_.userFormat = format;
  2016. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2017. else stream_.userInterleaved = true;
  2018. // Jack always uses non-interleaved buffers.
  2019. stream_.deviceInterleaved[mode] = false;
  2020. // Jack always provides host byte-ordered data.
  2021. stream_.doByteSwap[mode] = false;
  2022. // Get the buffer size. The buffer size and number of buffers
  2023. // (periods) is set when the jack server is started.
  2024. stream_.bufferSize = (int) jack_get_buffer_size( client );
  2025. *bufferSize = stream_.bufferSize;
  2026. stream_.nDeviceChannels[mode] = channels;
  2027. stream_.nUserChannels[mode] = channels;
  2028. // Set flags for buffer conversion.
  2029. stream_.doConvertBuffer[mode] = false;
  2030. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2031. stream_.doConvertBuffer[mode] = true;
  2032. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2033. stream_.nUserChannels[mode] > 1 )
  2034. stream_.doConvertBuffer[mode] = true;
  2035. // Allocate our JackHandle structure for the stream.
  2036. if ( handle == 0 ) {
  2037. try {
  2038. handle = new JackHandle;
  2039. }
  2040. catch ( std::bad_alloc& ) {
  2041. errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
  2042. goto error;
  2043. }
  2044. if ( pthread_cond_init(&handle->condition, NULL) ) {
  2045. errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
  2046. goto error;
  2047. }
  2048. stream_.apiHandle = (void *) handle;
  2049. handle->client = client;
  2050. }
  2051. handle->deviceName[mode] = deviceName;
  2052. // Allocate necessary internal buffers.
  2053. unsigned long bufferBytes;
  2054. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2055. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2056. if ( stream_.userBuffer[mode] == NULL ) {
  2057. errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
  2058. goto error;
  2059. }
  2060. if ( stream_.doConvertBuffer[mode] ) {
  2061. bool makeBuffer = true;
  2062. if ( mode == OUTPUT )
  2063. bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2064. else { // mode == INPUT
  2065. bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
  2066. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  2067. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
  2068. if ( bufferBytes < bytesOut ) makeBuffer = false;
  2069. }
  2070. }
  2071. if ( makeBuffer ) {
  2072. bufferBytes *= *bufferSize;
  2073. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2074. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2075. if ( stream_.deviceBuffer == NULL ) {
  2076. errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
  2077. goto error;
  2078. }
  2079. }
  2080. }
  2081. // Allocate memory for the Jack ports (channels) identifiers.
  2082. handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
  2083. if ( handle->ports[mode] == NULL ) {
  2084. errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
  2085. goto error;
  2086. }
  2087. stream_.device[mode] = device;
  2088. stream_.channelOffset[mode] = firstChannel;
  2089. stream_.state = STREAM_STOPPED;
  2090. stream_.callbackInfo.object = (void *) this;
  2091. if ( stream_.mode == OUTPUT && mode == INPUT )
  2092. // We had already set up the stream for output.
  2093. stream_.mode = DUPLEX;
  2094. else {
  2095. stream_.mode = mode;
  2096. jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
  2097. jack_set_xrun_callback( handle->client, jackXrun, (void *) &stream_.apiHandle );
  2098. jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
  2099. }
  2100. // Register our ports.
  2101. char label[64];
  2102. if ( mode == OUTPUT ) {
  2103. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2104. snprintf( label, 64, "outport %d", i );
  2105. handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
  2106. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
  2107. }
  2108. }
  2109. else {
  2110. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2111. snprintf( label, 64, "inport %d", i );
  2112. handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
  2113. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
  2114. }
  2115. }
  2116. // Setup the buffer conversion information structure. We don't use
  2117. // buffers to do channel offsets, so we override that parameter
  2118. // here.
  2119. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2120. if ( options && options->flags & RTAUDIO_JACK_DONT_CONNECT ) shouldAutoconnect_ = false;
  2121. return SUCCESS;
  2122. error:
  2123. if ( handle ) {
  2124. pthread_cond_destroy( &handle->condition );
  2125. jack_client_close( handle->client );
  2126. if ( handle->ports[0] ) free( handle->ports[0] );
  2127. if ( handle->ports[1] ) free( handle->ports[1] );
  2128. delete handle;
  2129. stream_.apiHandle = 0;
  2130. }
  2131. for ( int i=0; i<2; i++ ) {
  2132. if ( stream_.userBuffer[i] ) {
  2133. free( stream_.userBuffer[i] );
  2134. stream_.userBuffer[i] = 0;
  2135. }
  2136. }
  2137. if ( stream_.deviceBuffer ) {
  2138. free( stream_.deviceBuffer );
  2139. stream_.deviceBuffer = 0;
  2140. }
  2141. return FAILURE;
  2142. }
  2143. void RtApiJack :: closeStream( void )
  2144. {
  2145. if ( stream_.state == STREAM_CLOSED ) {
  2146. errorText_ = "RtApiJack::closeStream(): no open stream to close!";
  2147. error( RtAudioError::WARNING );
  2148. return;
  2149. }
  2150. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2151. if ( handle ) {
  2152. if ( stream_.state == STREAM_RUNNING )
  2153. jack_deactivate( handle->client );
  2154. jack_client_close( handle->client );
  2155. }
  2156. if ( handle ) {
  2157. if ( handle->ports[0] ) free( handle->ports[0] );
  2158. if ( handle->ports[1] ) free( handle->ports[1] );
  2159. pthread_cond_destroy( &handle->condition );
  2160. delete handle;
  2161. stream_.apiHandle = 0;
  2162. }
  2163. for ( int i=0; i<2; i++ ) {
  2164. if ( stream_.userBuffer[i] ) {
  2165. free( stream_.userBuffer[i] );
  2166. stream_.userBuffer[i] = 0;
  2167. }
  2168. }
  2169. if ( stream_.deviceBuffer ) {
  2170. free( stream_.deviceBuffer );
  2171. stream_.deviceBuffer = 0;
  2172. }
  2173. stream_.mode = UNINITIALIZED;
  2174. stream_.state = STREAM_CLOSED;
  2175. }
  2176. void RtApiJack :: startStream( void )
  2177. {
  2178. verifyStream();
  2179. if ( stream_.state == STREAM_RUNNING ) {
  2180. errorText_ = "RtApiJack::startStream(): the stream is already running!";
  2181. error( RtAudioError::WARNING );
  2182. return;
  2183. }
  2184. #if defined( HAVE_GETTIMEOFDAY )
  2185. gettimeofday( &stream_.lastTickTimestamp, NULL );
  2186. #endif
  2187. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2188. int result = jack_activate( handle->client );
  2189. if ( result ) {
  2190. errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
  2191. goto unlock;
  2192. }
  2193. const char **ports;
  2194. // Get the list of available ports.
  2195. if ( shouldAutoconnect_ && (stream_.mode == OUTPUT || stream_.mode == DUPLEX) ) {
  2196. result = 1;
  2197. ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput);
  2198. if ( ports == NULL) {
  2199. errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
  2200. goto unlock;
  2201. }
  2202. // Now make the port connections. Since RtAudio wasn't designed to
  2203. // allow the user to select particular channels of a device, we'll
  2204. // just open the first "nChannels" ports with offset.
  2205. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2206. result = 1;
  2207. if ( ports[ stream_.channelOffset[0] + i ] )
  2208. result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
  2209. if ( result ) {
  2210. free( ports );
  2211. errorText_ = "RtApiJack::startStream(): error connecting output ports!";
  2212. goto unlock;
  2213. }
  2214. }
  2215. free(ports);
  2216. }
  2217. if ( shouldAutoconnect_ && (stream_.mode == INPUT || stream_.mode == DUPLEX) ) {
  2218. result = 1;
  2219. ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
  2220. if ( ports == NULL) {
  2221. errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
  2222. goto unlock;
  2223. }
  2224. // Now make the port connections. See note above.
  2225. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2226. result = 1;
  2227. if ( ports[ stream_.channelOffset[1] + i ] )
  2228. result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
  2229. if ( result ) {
  2230. free( ports );
  2231. errorText_ = "RtApiJack::startStream(): error connecting input ports!";
  2232. goto unlock;
  2233. }
  2234. }
  2235. free(ports);
  2236. }
  2237. handle->drainCounter = 0;
  2238. handle->internalDrain = false;
  2239. stream_.state = STREAM_RUNNING;
  2240. unlock:
  2241. if ( result == 0 ) return;
  2242. error( RtAudioError::SYSTEM_ERROR );
  2243. }
  2244. void RtApiJack :: stopStream( void )
  2245. {
  2246. verifyStream();
  2247. if ( stream_.state == STREAM_STOPPED ) {
  2248. errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
  2249. error( RtAudioError::WARNING );
  2250. return;
  2251. }
  2252. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2253. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2254. if ( handle->drainCounter == 0 ) {
  2255. handle->drainCounter = 2;
  2256. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  2257. }
  2258. }
  2259. jack_deactivate( handle->client );
  2260. stream_.state = STREAM_STOPPED;
  2261. }
  2262. void RtApiJack :: abortStream( void )
  2263. {
  2264. verifyStream();
  2265. if ( stream_.state == STREAM_STOPPED ) {
  2266. errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
  2267. error( RtAudioError::WARNING );
  2268. return;
  2269. }
  2270. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2271. handle->drainCounter = 2;
  2272. stopStream();
  2273. }
  2274. // This function will be called by a spawned thread when the user
  2275. // callback function signals that the stream should be stopped or
  2276. // aborted. It is necessary to handle it this way because the
  2277. // callbackEvent() function must return before the jack_deactivate()
  2278. // function will return.
  2279. static void *jackStopStream( void *ptr )
  2280. {
  2281. CallbackInfo *info = (CallbackInfo *) ptr;
  2282. RtApiJack *object = (RtApiJack *) info->object;
  2283. object->stopStream();
  2284. pthread_exit( NULL );
  2285. }
  2286. bool RtApiJack :: callbackEvent( unsigned long nframes )
  2287. {
  2288. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2289. if ( stream_.state == STREAM_CLOSED ) {
  2290. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2291. error( RtAudioError::WARNING );
  2292. return FAILURE;
  2293. }
  2294. if ( stream_.bufferSize != nframes ) {
  2295. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
  2296. error( RtAudioError::WARNING );
  2297. return FAILURE;
  2298. }
  2299. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2300. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2301. // Check if we were draining the stream and signal is finished.
  2302. if ( handle->drainCounter > 3 ) {
  2303. ThreadHandle threadId;
  2304. stream_.state = STREAM_STOPPING;
  2305. if ( handle->internalDrain == true )
  2306. pthread_create( &threadId, NULL, jackStopStream, info );
  2307. else
  2308. pthread_cond_signal( &handle->condition );
  2309. return SUCCESS;
  2310. }
  2311. // Invoke user callback first, to get fresh output data.
  2312. if ( handle->drainCounter == 0 ) {
  2313. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2314. double streamTime = getStreamTime();
  2315. RtAudioStreamStatus status = 0;
  2316. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  2317. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2318. handle->xrun[0] = false;
  2319. }
  2320. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  2321. status |= RTAUDIO_INPUT_OVERFLOW;
  2322. handle->xrun[1] = false;
  2323. }
  2324. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2325. stream_.bufferSize, streamTime, status, info->userData );
  2326. if ( cbReturnValue == 2 ) {
  2327. stream_.state = STREAM_STOPPING;
  2328. handle->drainCounter = 2;
  2329. ThreadHandle id;
  2330. pthread_create( &id, NULL, jackStopStream, info );
  2331. return SUCCESS;
  2332. }
  2333. else if ( cbReturnValue == 1 ) {
  2334. handle->drainCounter = 1;
  2335. handle->internalDrain = true;
  2336. }
  2337. }
  2338. jack_default_audio_sample_t *jackbuffer;
  2339. unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
  2340. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2341. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2342. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2343. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2344. memset( jackbuffer, 0, bufferBytes );
  2345. }
  2346. }
  2347. else if ( stream_.doConvertBuffer[0] ) {
  2348. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2349. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2350. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2351. memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
  2352. }
  2353. }
  2354. else { // no buffer conversion
  2355. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2356. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2357. memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
  2358. }
  2359. }
  2360. }
  2361. // Don't bother draining input
  2362. if ( handle->drainCounter ) {
  2363. handle->drainCounter++;
  2364. goto unlock;
  2365. }
  2366. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2367. if ( stream_.doConvertBuffer[1] ) {
  2368. for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
  2369. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2370. memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
  2371. }
  2372. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2373. }
  2374. else { // no buffer conversion
  2375. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2376. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2377. memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
  2378. }
  2379. }
  2380. }
  2381. unlock:
  2382. RtApi::tickStreamTime();
  2383. return SUCCESS;
  2384. }
  2385. //******************** End of __UNIX_JACK__ *********************//
  2386. #endif
  2387. #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2388. // The ASIO API is designed around a callback scheme, so this
  2389. // implementation is similar to that used for OS-X CoreAudio and Linux
  2390. // Jack. The primary constraint with ASIO is that it only allows
  2391. // access to a single driver at a time. Thus, it is not possible to
  2392. // have more than one simultaneous RtAudio stream.
  2393. //
  2394. // This implementation also requires a number of external ASIO files
  2395. // and a few global variables. The ASIO callback scheme does not
  2396. // allow for the passing of user data, so we must create a global
  2397. // pointer to our callbackInfo structure.
  2398. //
  2399. // On unix systems, we make use of a pthread condition variable.
  2400. // Since there is no equivalent in Windows, I hacked something based
  2401. // on information found in
  2402. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
  2403. #include "asiosys.h"
  2404. #include "asio.h"
  2405. #include "iasiothiscallresolver.h"
  2406. #include "asiodrivers.h"
  2407. #include <cmath>
  2408. static AsioDrivers drivers;
  2409. static ASIOCallbacks asioCallbacks;
  2410. static ASIODriverInfo driverInfo;
  2411. static CallbackInfo *asioCallbackInfo;
  2412. static bool asioXRun;
  2413. struct AsioHandle {
  2414. int drainCounter; // Tracks callback counts when draining
  2415. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2416. ASIOBufferInfo *bufferInfos;
  2417. HANDLE condition;
  2418. AsioHandle()
  2419. :drainCounter(0), internalDrain(false), bufferInfos(0) {}
  2420. };
  2421. // Function declarations (definitions at end of section)
  2422. static const char* getAsioErrorString( ASIOError result );
  2423. static void sampleRateChanged( ASIOSampleRate sRate );
  2424. static long asioMessages( long selector, long value, void* message, double* opt );
  2425. RtApiAsio :: RtApiAsio()
  2426. {
  2427. // ASIO cannot run on a multi-threaded appartment. You can call
  2428. // CoInitialize beforehand, but it must be for appartment threading
  2429. // (in which case, CoInitilialize will return S_FALSE here).
  2430. coInitialized_ = false;
  2431. HRESULT hr = CoInitialize( NULL );
  2432. if ( FAILED(hr) ) {
  2433. errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
  2434. error( RtAudioError::WARNING );
  2435. }
  2436. coInitialized_ = true;
  2437. drivers.removeCurrentDriver();
  2438. driverInfo.asioVersion = 2;
  2439. // See note in DirectSound implementation about GetDesktopWindow().
  2440. driverInfo.sysRef = GetForegroundWindow();
  2441. }
  2442. RtApiAsio :: ~RtApiAsio()
  2443. {
  2444. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2445. if ( coInitialized_ ) CoUninitialize();
  2446. }
  2447. unsigned int RtApiAsio :: getDeviceCount( void )
  2448. {
  2449. return (unsigned int) drivers.asioGetNumDev();
  2450. }
  2451. RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
  2452. {
  2453. RtAudio::DeviceInfo info;
  2454. info.probed = false;
  2455. // Get device ID
  2456. unsigned int nDevices = getDeviceCount();
  2457. if ( nDevices == 0 ) {
  2458. errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
  2459. error( RtAudioError::INVALID_USE );
  2460. return info;
  2461. }
  2462. if ( device >= nDevices ) {
  2463. errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
  2464. error( RtAudioError::INVALID_USE );
  2465. return info;
  2466. }
  2467. // If a stream is already open, we cannot probe other devices. Thus, use the saved results.
  2468. if ( stream_.state != STREAM_CLOSED ) {
  2469. if ( device >= devices_.size() ) {
  2470. errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
  2471. error( RtAudioError::WARNING );
  2472. return info;
  2473. }
  2474. return devices_[ device ];
  2475. }
  2476. char driverName[32];
  2477. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2478. if ( result != ASE_OK ) {
  2479. errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2480. errorText_ = errorStream_.str();
  2481. error( RtAudioError::WARNING );
  2482. return info;
  2483. }
  2484. info.name = driverName;
  2485. if ( !drivers.loadDriver( driverName ) ) {
  2486. errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
  2487. errorText_ = errorStream_.str();
  2488. error( RtAudioError::WARNING );
  2489. return info;
  2490. }
  2491. result = ASIOInit( &driverInfo );
  2492. if ( result != ASE_OK ) {
  2493. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2494. errorText_ = errorStream_.str();
  2495. error( RtAudioError::WARNING );
  2496. return info;
  2497. }
  2498. // Determine the device channel information.
  2499. long inputChannels, outputChannels;
  2500. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2501. if ( result != ASE_OK ) {
  2502. drivers.removeCurrentDriver();
  2503. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2504. errorText_ = errorStream_.str();
  2505. error( RtAudioError::WARNING );
  2506. return info;
  2507. }
  2508. info.outputChannels = outputChannels;
  2509. info.inputChannels = inputChannels;
  2510. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  2511. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  2512. // Determine the supported sample rates.
  2513. info.sampleRates.clear();
  2514. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  2515. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  2516. if ( result == ASE_OK ) {
  2517. info.sampleRates.push_back( SAMPLE_RATES[i] );
  2518. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  2519. info.preferredSampleRate = SAMPLE_RATES[i];
  2520. }
  2521. }
  2522. // Determine supported data types ... just check first channel and assume rest are the same.
  2523. ASIOChannelInfo channelInfo;
  2524. channelInfo.channel = 0;
  2525. channelInfo.isInput = true;
  2526. if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
  2527. result = ASIOGetChannelInfo( &channelInfo );
  2528. if ( result != ASE_OK ) {
  2529. drivers.removeCurrentDriver();
  2530. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
  2531. errorText_ = errorStream_.str();
  2532. error( RtAudioError::WARNING );
  2533. return info;
  2534. }
  2535. info.nativeFormats = 0;
  2536. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  2537. info.nativeFormats |= RTAUDIO_SINT16;
  2538. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  2539. info.nativeFormats |= RTAUDIO_SINT32;
  2540. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  2541. info.nativeFormats |= RTAUDIO_FLOAT32;
  2542. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  2543. info.nativeFormats |= RTAUDIO_FLOAT64;
  2544. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )
  2545. info.nativeFormats |= RTAUDIO_SINT24;
  2546. if ( info.outputChannels > 0 )
  2547. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  2548. if ( info.inputChannels > 0 )
  2549. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  2550. info.probed = true;
  2551. drivers.removeCurrentDriver();
  2552. return info;
  2553. }
  2554. static void bufferSwitch( long index, ASIOBool /*processNow*/ )
  2555. {
  2556. RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
  2557. object->callbackEvent( index );
  2558. }
  2559. void RtApiAsio :: saveDeviceInfo( void )
  2560. {
  2561. devices_.clear();
  2562. unsigned int nDevices = getDeviceCount();
  2563. devices_.resize( nDevices );
  2564. for ( unsigned int i=0; i<nDevices; i++ )
  2565. devices_[i] = getDeviceInfo( i );
  2566. }
  2567. bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  2568. unsigned int firstChannel, unsigned int sampleRate,
  2569. RtAudioFormat format, unsigned int *bufferSize,
  2570. RtAudio::StreamOptions *options )
  2571. {////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2572. bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;
  2573. // For ASIO, a duplex stream MUST use the same driver.
  2574. if ( isDuplexInput && stream_.device[0] != device ) {
  2575. errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
  2576. return FAILURE;
  2577. }
  2578. char driverName[32];
  2579. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2580. if ( result != ASE_OK ) {
  2581. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2582. errorText_ = errorStream_.str();
  2583. return FAILURE;
  2584. }
  2585. // Only load the driver once for duplex stream.
  2586. if ( !isDuplexInput ) {
  2587. // The getDeviceInfo() function will not work when a stream is open
  2588. // because ASIO does not allow multiple devices to run at the same
  2589. // time. Thus, we'll probe the system before opening a stream and
  2590. // save the results for use by getDeviceInfo().
  2591. this->saveDeviceInfo();
  2592. if ( !drivers.loadDriver( driverName ) ) {
  2593. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
  2594. errorText_ = errorStream_.str();
  2595. return FAILURE;
  2596. }
  2597. result = ASIOInit( &driverInfo );
  2598. if ( result != ASE_OK ) {
  2599. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2600. errorText_ = errorStream_.str();
  2601. return FAILURE;
  2602. }
  2603. }
  2604. // keep them before any "goto error", they are used for error cleanup + goto device boundary checks
  2605. bool buffersAllocated = false;
  2606. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2607. unsigned int nChannels;
  2608. // Check the device channel count.
  2609. long inputChannels, outputChannels;
  2610. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2611. if ( result != ASE_OK ) {
  2612. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2613. errorText_ = errorStream_.str();
  2614. goto error;
  2615. }
  2616. if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
  2617. ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
  2618. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
  2619. errorText_ = errorStream_.str();
  2620. goto error;
  2621. }
  2622. stream_.nDeviceChannels[mode] = channels;
  2623. stream_.nUserChannels[mode] = channels;
  2624. stream_.channelOffset[mode] = firstChannel;
  2625. // Verify the sample rate is supported.
  2626. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  2627. if ( result != ASE_OK ) {
  2628. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
  2629. errorText_ = errorStream_.str();
  2630. goto error;
  2631. }
  2632. // Get the current sample rate
  2633. ASIOSampleRate currentRate;
  2634. result = ASIOGetSampleRate( &currentRate );
  2635. if ( result != ASE_OK ) {
  2636. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
  2637. errorText_ = errorStream_.str();
  2638. goto error;
  2639. }
  2640. // Set the sample rate only if necessary
  2641. if ( currentRate != sampleRate ) {
  2642. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  2643. if ( result != ASE_OK ) {
  2644. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
  2645. errorText_ = errorStream_.str();
  2646. goto error;
  2647. }
  2648. }
  2649. // Determine the driver data type.
  2650. ASIOChannelInfo channelInfo;
  2651. channelInfo.channel = 0;
  2652. if ( mode == OUTPUT ) channelInfo.isInput = false;
  2653. else channelInfo.isInput = true;
  2654. result = ASIOGetChannelInfo( &channelInfo );
  2655. if ( result != ASE_OK ) {
  2656. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
  2657. errorText_ = errorStream_.str();
  2658. goto error;
  2659. }
  2660. // Assuming WINDOWS host is always little-endian.
  2661. stream_.doByteSwap[mode] = false;
  2662. stream_.userFormat = format;
  2663. stream_.deviceFormat[mode] = 0;
  2664. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  2665. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  2666. if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
  2667. }
  2668. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  2669. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  2670. if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
  2671. }
  2672. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  2673. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2674. if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
  2675. }
  2676. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  2677. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  2678. if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
  2679. }
  2680. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {
  2681. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  2682. if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;
  2683. }
  2684. if ( stream_.deviceFormat[mode] == 0 ) {
  2685. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
  2686. errorText_ = errorStream_.str();
  2687. goto error;
  2688. }
  2689. // Set the buffer size. For a duplex stream, this will end up
  2690. // setting the buffer size based on the input constraints, which
  2691. // should be ok.
  2692. long minSize, maxSize, preferSize, granularity;
  2693. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  2694. if ( result != ASE_OK ) {
  2695. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
  2696. errorText_ = errorStream_.str();
  2697. goto error;
  2698. }
  2699. if ( isDuplexInput ) {
  2700. // When this is the duplex input (output was opened before), then we have to use the same
  2701. // buffersize as the output, because it might use the preferred buffer size, which most
  2702. // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,
  2703. // So instead of throwing an error, make them equal. The caller uses the reference
  2704. // to the "bufferSize" param as usual to set up processing buffers.
  2705. *bufferSize = stream_.bufferSize;
  2706. } else {
  2707. if ( *bufferSize == 0 ) *bufferSize = preferSize;
  2708. else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2709. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2710. else if ( granularity == -1 ) {
  2711. // Make sure bufferSize is a power of two.
  2712. int log2_of_min_size = 0;
  2713. int log2_of_max_size = 0;
  2714. for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
  2715. if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
  2716. if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
  2717. }
  2718. long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
  2719. int min_delta_num = log2_of_min_size;
  2720. for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
  2721. long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
  2722. if (current_delta < min_delta) {
  2723. min_delta = current_delta;
  2724. min_delta_num = i;
  2725. }
  2726. }
  2727. *bufferSize = ( (unsigned int)1 << min_delta_num );
  2728. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2729. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2730. }
  2731. else if ( granularity != 0 ) {
  2732. // Set to an even multiple of granularity, rounding up.
  2733. *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
  2734. }
  2735. }
  2736. /*
  2737. // we don't use it anymore, see above!
  2738. // Just left it here for the case...
  2739. if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {
  2740. errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
  2741. goto error;
  2742. }
  2743. */
  2744. stream_.bufferSize = *bufferSize;
  2745. stream_.nBuffers = 2;
  2746. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2747. else stream_.userInterleaved = true;
  2748. // ASIO always uses non-interleaved buffers.
  2749. stream_.deviceInterleaved[mode] = false;
  2750. // Allocate, if necessary, our AsioHandle structure for the stream.
  2751. if ( handle == 0 ) {
  2752. try {
  2753. handle = new AsioHandle;
  2754. }
  2755. catch ( std::bad_alloc& ) {
  2756. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
  2757. goto error;
  2758. }
  2759. handle->bufferInfos = 0;
  2760. // Create a manual-reset event.
  2761. handle->condition = CreateEvent( NULL, // no security
  2762. TRUE, // manual-reset
  2763. FALSE, // non-signaled initially
  2764. NULL ); // unnamed
  2765. stream_.apiHandle = (void *) handle;
  2766. }
  2767. // Create the ASIO internal buffers. Since RtAudio sets up input
  2768. // and output separately, we'll have to dispose of previously
  2769. // created output buffers for a duplex stream.
  2770. if ( mode == INPUT && stream_.mode == OUTPUT ) {
  2771. ASIODisposeBuffers();
  2772. if ( handle->bufferInfos ) free( handle->bufferInfos );
  2773. }
  2774. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  2775. unsigned int i;
  2776. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2777. handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  2778. if ( handle->bufferInfos == NULL ) {
  2779. errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
  2780. errorText_ = errorStream_.str();
  2781. goto error;
  2782. }
  2783. ASIOBufferInfo *infos;
  2784. infos = handle->bufferInfos;
  2785. for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
  2786. infos->isInput = ASIOFalse;
  2787. infos->channelNum = i + stream_.channelOffset[0];
  2788. infos->buffers[0] = infos->buffers[1] = 0;
  2789. }
  2790. for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
  2791. infos->isInput = ASIOTrue;
  2792. infos->channelNum = i + stream_.channelOffset[1];
  2793. infos->buffers[0] = infos->buffers[1] = 0;
  2794. }
  2795. // prepare for callbacks
  2796. stream_.sampleRate = sampleRate;
  2797. stream_.device[mode] = device;
  2798. stream_.mode = isDuplexInput ? DUPLEX : mode;
  2799. // store this class instance before registering callbacks, that are going to use it
  2800. asioCallbackInfo = &stream_.callbackInfo;
  2801. stream_.callbackInfo.object = (void *) this;
  2802. // Set up the ASIO callback structure and create the ASIO data buffers.
  2803. asioCallbacks.bufferSwitch = &bufferSwitch;
  2804. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  2805. asioCallbacks.asioMessage = &asioMessages;
  2806. asioCallbacks.bufferSwitchTimeInfo = NULL;
  2807. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2808. if ( result != ASE_OK ) {
  2809. // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges
  2810. // but only accept the preferred buffer size as parameter for ASIOCreateBuffers (e.g. Creative's ASIO driver).
  2811. // In that case, let's be naïve and try that instead.
  2812. *bufferSize = preferSize;
  2813. stream_.bufferSize = *bufferSize;
  2814. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2815. }
  2816. if ( result != ASE_OK ) {
  2817. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
  2818. errorText_ = errorStream_.str();
  2819. goto error;
  2820. }
  2821. buffersAllocated = true;
  2822. stream_.state = STREAM_STOPPED;
  2823. // Set flags for buffer conversion.
  2824. stream_.doConvertBuffer[mode] = false;
  2825. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2826. stream_.doConvertBuffer[mode] = true;
  2827. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2828. stream_.nUserChannels[mode] > 1 )
  2829. stream_.doConvertBuffer[mode] = true;
  2830. // Allocate necessary internal buffers
  2831. unsigned long bufferBytes;
  2832. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2833. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2834. if ( stream_.userBuffer[mode] == NULL ) {
  2835. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
  2836. goto error;
  2837. }
  2838. if ( stream_.doConvertBuffer[mode] ) {
  2839. bool makeBuffer = true;
  2840. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  2841. if ( isDuplexInput && stream_.deviceBuffer ) {
  2842. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2843. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  2844. }
  2845. if ( makeBuffer ) {
  2846. bufferBytes *= *bufferSize;
  2847. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2848. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2849. if ( stream_.deviceBuffer == NULL ) {
  2850. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
  2851. goto error;
  2852. }
  2853. }
  2854. }
  2855. // Determine device latencies
  2856. long inputLatency, outputLatency;
  2857. result = ASIOGetLatencies( &inputLatency, &outputLatency );
  2858. if ( result != ASE_OK ) {
  2859. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
  2860. errorText_ = errorStream_.str();
  2861. error( RtAudioError::WARNING); // warn but don't fail
  2862. }
  2863. else {
  2864. stream_.latency[0] = outputLatency;
  2865. stream_.latency[1] = inputLatency;
  2866. }
  2867. // Setup the buffer conversion information structure. We don't use
  2868. // buffers to do channel offsets, so we override that parameter
  2869. // here.
  2870. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2871. return SUCCESS;
  2872. error:
  2873. if ( !isDuplexInput ) {
  2874. // the cleanup for error in the duplex input, is done by RtApi::openStream
  2875. // So we clean up for single channel only
  2876. if ( buffersAllocated )
  2877. ASIODisposeBuffers();
  2878. drivers.removeCurrentDriver();
  2879. if ( handle ) {
  2880. CloseHandle( handle->condition );
  2881. if ( handle->bufferInfos )
  2882. free( handle->bufferInfos );
  2883. delete handle;
  2884. stream_.apiHandle = 0;
  2885. }
  2886. if ( stream_.userBuffer[mode] ) {
  2887. free( stream_.userBuffer[mode] );
  2888. stream_.userBuffer[mode] = 0;
  2889. }
  2890. if ( stream_.deviceBuffer ) {
  2891. free( stream_.deviceBuffer );
  2892. stream_.deviceBuffer = 0;
  2893. }
  2894. }
  2895. return FAILURE;
  2896. }////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2897. void RtApiAsio :: closeStream()
  2898. {
  2899. if ( stream_.state == STREAM_CLOSED ) {
  2900. errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
  2901. error( RtAudioError::WARNING );
  2902. return;
  2903. }
  2904. if ( stream_.state == STREAM_RUNNING ) {
  2905. stream_.state = STREAM_STOPPED;
  2906. ASIOStop();
  2907. }
  2908. ASIODisposeBuffers();
  2909. drivers.removeCurrentDriver();
  2910. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2911. if ( handle ) {
  2912. CloseHandle( handle->condition );
  2913. if ( handle->bufferInfos )
  2914. free( handle->bufferInfos );
  2915. delete handle;
  2916. stream_.apiHandle = 0;
  2917. }
  2918. for ( int i=0; i<2; i++ ) {
  2919. if ( stream_.userBuffer[i] ) {
  2920. free( stream_.userBuffer[i] );
  2921. stream_.userBuffer[i] = 0;
  2922. }
  2923. }
  2924. if ( stream_.deviceBuffer ) {
  2925. free( stream_.deviceBuffer );
  2926. stream_.deviceBuffer = 0;
  2927. }
  2928. stream_.mode = UNINITIALIZED;
  2929. stream_.state = STREAM_CLOSED;
  2930. }
  2931. bool stopThreadCalled = false;
  2932. void RtApiAsio :: startStream()
  2933. {
  2934. verifyStream();
  2935. if ( stream_.state == STREAM_RUNNING ) {
  2936. errorText_ = "RtApiAsio::startStream(): the stream is already running!";
  2937. error( RtAudioError::WARNING );
  2938. return;
  2939. }
  2940. #if defined( HAVE_GETTIMEOFDAY )
  2941. gettimeofday( &stream_.lastTickTimestamp, NULL );
  2942. #endif
  2943. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2944. ASIOError result = ASIOStart();
  2945. if ( result != ASE_OK ) {
  2946. errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
  2947. errorText_ = errorStream_.str();
  2948. goto unlock;
  2949. }
  2950. handle->drainCounter = 0;
  2951. handle->internalDrain = false;
  2952. ResetEvent( handle->condition );
  2953. stream_.state = STREAM_RUNNING;
  2954. asioXRun = false;
  2955. unlock:
  2956. stopThreadCalled = false;
  2957. if ( result == ASE_OK ) return;
  2958. error( RtAudioError::SYSTEM_ERROR );
  2959. }
  2960. void RtApiAsio :: stopStream()
  2961. {
  2962. verifyStream();
  2963. if ( stream_.state == STREAM_STOPPED ) {
  2964. errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
  2965. error( RtAudioError::WARNING );
  2966. return;
  2967. }
  2968. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2969. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2970. if ( handle->drainCounter == 0 ) {
  2971. handle->drainCounter = 2;
  2972. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  2973. }
  2974. }
  2975. stream_.state = STREAM_STOPPED;
  2976. ASIOError result = ASIOStop();
  2977. if ( result != ASE_OK ) {
  2978. errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
  2979. errorText_ = errorStream_.str();
  2980. }
  2981. if ( result == ASE_OK ) return;
  2982. error( RtAudioError::SYSTEM_ERROR );
  2983. }
  2984. void RtApiAsio :: abortStream()
  2985. {
  2986. verifyStream();
  2987. if ( stream_.state == STREAM_STOPPED ) {
  2988. errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
  2989. error( RtAudioError::WARNING );
  2990. return;
  2991. }
  2992. // The following lines were commented-out because some behavior was
  2993. // noted where the device buffers need to be zeroed to avoid
  2994. // continuing sound, even when the device buffers are completely
  2995. // disposed. So now, calling abort is the same as calling stop.
  2996. // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2997. // handle->drainCounter = 2;
  2998. stopStream();
  2999. }
  3000. // This function will be called by a spawned thread when the user
  3001. // callback function signals that the stream should be stopped or
  3002. // aborted. It is necessary to handle it this way because the
  3003. // callbackEvent() function must return before the ASIOStop()
  3004. // function will return.
  3005. static unsigned __stdcall asioStopStream( void *ptr )
  3006. {
  3007. CallbackInfo *info = (CallbackInfo *) ptr;
  3008. RtApiAsio *object = (RtApiAsio *) info->object;
  3009. object->stopStream();
  3010. _endthreadex( 0 );
  3011. return 0;
  3012. }
  3013. bool RtApiAsio :: callbackEvent( long bufferIndex )
  3014. {
  3015. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  3016. if ( stream_.state == STREAM_CLOSED ) {
  3017. errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
  3018. error( RtAudioError::WARNING );
  3019. return FAILURE;
  3020. }
  3021. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  3022. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  3023. // Check if we were draining the stream and signal if finished.
  3024. if ( handle->drainCounter > 3 ) {
  3025. stream_.state = STREAM_STOPPING;
  3026. if ( handle->internalDrain == false )
  3027. SetEvent( handle->condition );
  3028. else { // spawn a thread to stop the stream
  3029. unsigned threadId;
  3030. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  3031. &stream_.callbackInfo, 0, &threadId );
  3032. }
  3033. return SUCCESS;
  3034. }
  3035. // Invoke user callback to get fresh output data UNLESS we are
  3036. // draining stream.
  3037. if ( handle->drainCounter == 0 ) {
  3038. RtAudioCallback callback = (RtAudioCallback) info->callback;
  3039. double streamTime = getStreamTime();
  3040. RtAudioStreamStatus status = 0;
  3041. if ( stream_.mode != INPUT && asioXRun == true ) {
  3042. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  3043. asioXRun = false;
  3044. }
  3045. if ( stream_.mode != OUTPUT && asioXRun == true ) {
  3046. status |= RTAUDIO_INPUT_OVERFLOW;
  3047. asioXRun = false;
  3048. }
  3049. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  3050. stream_.bufferSize, streamTime, status, info->userData );
  3051. if ( cbReturnValue == 2 ) {
  3052. stream_.state = STREAM_STOPPING;
  3053. handle->drainCounter = 2;
  3054. unsigned threadId;
  3055. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  3056. &stream_.callbackInfo, 0, &threadId );
  3057. return SUCCESS;
  3058. }
  3059. else if ( cbReturnValue == 1 ) {
  3060. handle->drainCounter = 1;
  3061. handle->internalDrain = true;
  3062. }
  3063. }
  3064. unsigned int nChannels, bufferBytes, i, j;
  3065. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  3066. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  3067. bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
  3068. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  3069. for ( i=0, j=0; i<nChannels; i++ ) {
  3070. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3071. memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
  3072. }
  3073. }
  3074. else if ( stream_.doConvertBuffer[0] ) {
  3075. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  3076. if ( stream_.doByteSwap[0] )
  3077. byteSwapBuffer( stream_.deviceBuffer,
  3078. stream_.bufferSize * stream_.nDeviceChannels[0],
  3079. stream_.deviceFormat[0] );
  3080. for ( i=0, j=0; i<nChannels; i++ ) {
  3081. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3082. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  3083. &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
  3084. }
  3085. }
  3086. else {
  3087. if ( stream_.doByteSwap[0] )
  3088. byteSwapBuffer( stream_.userBuffer[0],
  3089. stream_.bufferSize * stream_.nUserChannels[0],
  3090. stream_.userFormat );
  3091. for ( i=0, j=0; i<nChannels; i++ ) {
  3092. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3093. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  3094. &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
  3095. }
  3096. }
  3097. }
  3098. // Don't bother draining input
  3099. if ( handle->drainCounter ) {
  3100. handle->drainCounter++;
  3101. goto unlock;
  3102. }
  3103. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  3104. bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
  3105. if (stream_.doConvertBuffer[1]) {
  3106. // Always interleave ASIO input data.
  3107. for ( i=0, j=0; i<nChannels; i++ ) {
  3108. if ( handle->bufferInfos[i].isInput == ASIOTrue )
  3109. memcpy( &stream_.deviceBuffer[j++*bufferBytes],
  3110. handle->bufferInfos[i].buffers[bufferIndex],
  3111. bufferBytes );
  3112. }
  3113. if ( stream_.doByteSwap[1] )
  3114. byteSwapBuffer( stream_.deviceBuffer,
  3115. stream_.bufferSize * stream_.nDeviceChannels[1],
  3116. stream_.deviceFormat[1] );
  3117. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  3118. }
  3119. else {
  3120. for ( i=0, j=0; i<nChannels; i++ ) {
  3121. if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
  3122. memcpy( &stream_.userBuffer[1][bufferBytes*j++],
  3123. handle->bufferInfos[i].buffers[bufferIndex],
  3124. bufferBytes );
  3125. }
  3126. }
  3127. if ( stream_.doByteSwap[1] )
  3128. byteSwapBuffer( stream_.userBuffer[1],
  3129. stream_.bufferSize * stream_.nUserChannels[1],
  3130. stream_.userFormat );
  3131. }
  3132. }
  3133. unlock:
  3134. // The following call was suggested by Malte Clasen. While the API
  3135. // documentation indicates it should not be required, some device
  3136. // drivers apparently do not function correctly without it.
  3137. ASIOOutputReady();
  3138. RtApi::tickStreamTime();
  3139. return SUCCESS;
  3140. }
  3141. static void sampleRateChanged( ASIOSampleRate sRate )
  3142. {
  3143. // The ASIO documentation says that this usually only happens during
  3144. // external sync. Audio processing is not stopped by the driver,
  3145. // actual sample rate might not have even changed, maybe only the
  3146. // sample rate status of an AES/EBU or S/PDIF digital input at the
  3147. // audio device.
  3148. RtApi *object = (RtApi *) asioCallbackInfo->object;
  3149. try {
  3150. object->stopStream();
  3151. }
  3152. catch ( RtAudioError &exception ) {
  3153. std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
  3154. return;
  3155. }
  3156. std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
  3157. }
  3158. static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )
  3159. {
  3160. long ret = 0;
  3161. switch( selector ) {
  3162. case kAsioSelectorSupported:
  3163. if ( value == kAsioResetRequest
  3164. || value == kAsioEngineVersion
  3165. || value == kAsioResyncRequest
  3166. || value == kAsioLatenciesChanged
  3167. // The following three were added for ASIO 2.0, you don't
  3168. // necessarily have to support them.
  3169. || value == kAsioSupportsTimeInfo
  3170. || value == kAsioSupportsTimeCode
  3171. || value == kAsioSupportsInputMonitor)
  3172. ret = 1L;
  3173. break;
  3174. case kAsioResetRequest:
  3175. // Defer the task and perform the reset of the driver during the
  3176. // next "safe" situation. You cannot reset the driver right now,
  3177. // as this code is called from the driver. Reset the driver is
  3178. // done by completely destruct is. I.e. ASIOStop(),
  3179. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  3180. // driver again.
  3181. std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
  3182. ret = 1L;
  3183. break;
  3184. case kAsioResyncRequest:
  3185. // This informs the application that the driver encountered some
  3186. // non-fatal data loss. It is used for synchronization purposes
  3187. // of different media. Added mainly to work around the Win16Mutex
  3188. // problems in Windows 95/98 with the Windows Multimedia system,
  3189. // which could lose data because the Mutex was held too long by
  3190. // another thread. However a driver can issue it in other
  3191. // situations, too.
  3192. // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
  3193. asioXRun = true;
  3194. ret = 1L;
  3195. break;
  3196. case kAsioLatenciesChanged:
  3197. // This will inform the host application that the drivers were
  3198. // latencies changed. Beware, it this does not mean that the
  3199. // buffer sizes have changed! You might need to update internal
  3200. // delay data.
  3201. std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
  3202. ret = 1L;
  3203. break;
  3204. case kAsioEngineVersion:
  3205. // Return the supported ASIO version of the host application. If
  3206. // a host application does not implement this selector, ASIO 1.0
  3207. // is assumed by the driver.
  3208. ret = 2L;
  3209. break;
  3210. case kAsioSupportsTimeInfo:
  3211. // Informs the driver whether the
  3212. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  3213. // For compatibility with ASIO 1.0 drivers the host application
  3214. // should always support the "old" bufferSwitch method, too.
  3215. ret = 0;
  3216. break;
  3217. case kAsioSupportsTimeCode:
  3218. // Informs the driver whether application is interested in time
  3219. // code info. If an application does not need to know about time
  3220. // code, the driver has less work to do.
  3221. ret = 0;
  3222. break;
  3223. }
  3224. return ret;
  3225. }
  3226. static const char* getAsioErrorString( ASIOError result )
  3227. {
  3228. struct Messages
  3229. {
  3230. ASIOError value;
  3231. const char*message;
  3232. };
  3233. static const Messages m[] =
  3234. {
  3235. { ASE_NotPresent, "Hardware input or output is not present or available." },
  3236. { ASE_HWMalfunction, "Hardware is malfunctioning." },
  3237. { ASE_InvalidParameter, "Invalid input parameter." },
  3238. { ASE_InvalidMode, "Invalid mode." },
  3239. { ASE_SPNotAdvancing, "Sample position not advancing." },
  3240. { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
  3241. { ASE_NoMemory, "Not enough memory to complete the request." }
  3242. };
  3243. for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
  3244. if ( m[i].value == result ) return m[i].message;
  3245. return "Unknown error.";
  3246. }
  3247. //******************** End of __WINDOWS_ASIO__ *********************//
  3248. #endif
  3249. #if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
  3250. // Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014
  3251. // - Introduces support for the Windows WASAPI API
  3252. // - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required
  3253. // - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface
  3254. // - Includes automatic internal conversion of sample rate and buffer size between hardware and the user
  3255. #ifndef INITGUID
  3256. #define INITGUID
  3257. #endif
  3258. #include <mfapi.h>
  3259. #include <mferror.h>
  3260. #include <mfplay.h>
  3261. #include <mftransform.h>
  3262. #include <wmcodecdsp.h>
  3263. #include <audioclient.h>
  3264. #include <avrt.h>
  3265. #include <mmdeviceapi.h>
  3266. #include <functiondiscoverykeys_devpkey.h>
  3267. #ifndef MF_E_TRANSFORM_NEED_MORE_INPUT
  3268. #define MF_E_TRANSFORM_NEED_MORE_INPUT _HRESULT_TYPEDEF_(0xc00d6d72)
  3269. #endif
  3270. #ifndef MFSTARTUP_NOSOCKET
  3271. #define MFSTARTUP_NOSOCKET 0x1
  3272. #endif
  3273. #ifdef _MSC_VER
  3274. #pragma comment( lib, "ksuser" )
  3275. #pragma comment( lib, "mfplat.lib" )
  3276. #pragma comment( lib, "mfuuid.lib" )
  3277. #pragma comment( lib, "wmcodecdspuuid" )
  3278. #endif
  3279. //=============================================================================
  3280. #define SAFE_RELEASE( objectPtr )\
  3281. if ( objectPtr )\
  3282. {\
  3283. objectPtr->Release();\
  3284. objectPtr = NULL;\
  3285. }
  3286. typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );
  3287. //-----------------------------------------------------------------------------
  3288. // WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
  3289. // Therefore we must perform all necessary conversions to user buffers in order to satisfy these
  3290. // requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
  3291. // provide intermediate storage for read / write synchronization.
  3292. class WasapiBuffer
  3293. {
  3294. public:
  3295. WasapiBuffer()
  3296. : buffer_( NULL ),
  3297. bufferSize_( 0 ),
  3298. inIndex_( 0 ),
  3299. outIndex_( 0 ) {}
  3300. ~WasapiBuffer() {
  3301. free( buffer_ );
  3302. }
  3303. // sets the length of the internal ring buffer
  3304. void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {
  3305. free( buffer_ );
  3306. buffer_ = ( char* ) calloc( bufferSize, formatBytes );
  3307. bufferSize_ = bufferSize;
  3308. inIndex_ = 0;
  3309. outIndex_ = 0;
  3310. }
  3311. // attempt to push a buffer into the ring buffer at the current "in" index
  3312. bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3313. {
  3314. if ( !buffer || // incoming buffer is NULL
  3315. bufferSize == 0 || // incoming buffer has no data
  3316. bufferSize > bufferSize_ ) // incoming buffer too large
  3317. {
  3318. return false;
  3319. }
  3320. unsigned int relOutIndex = outIndex_;
  3321. unsigned int inIndexEnd = inIndex_ + bufferSize;
  3322. if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {
  3323. relOutIndex += bufferSize_;
  3324. }
  3325. // the "IN" index CAN BEGIN at the "OUT" index
  3326. // the "IN" index CANNOT END at the "OUT" index
  3327. if ( inIndex_ < relOutIndex && inIndexEnd >= relOutIndex ) {
  3328. return false; // not enough space between "in" index and "out" index
  3329. }
  3330. // copy buffer from external to internal
  3331. int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
  3332. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3333. int fromInSize = bufferSize - fromZeroSize;
  3334. switch( format )
  3335. {
  3336. case RTAUDIO_SINT8:
  3337. memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );
  3338. memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );
  3339. break;
  3340. case RTAUDIO_SINT16:
  3341. memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );
  3342. memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );
  3343. break;
  3344. case RTAUDIO_SINT24:
  3345. memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );
  3346. memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );
  3347. break;
  3348. case RTAUDIO_SINT32:
  3349. memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );
  3350. memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );
  3351. break;
  3352. case RTAUDIO_FLOAT32:
  3353. memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );
  3354. memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );
  3355. break;
  3356. case RTAUDIO_FLOAT64:
  3357. memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );
  3358. memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );
  3359. break;
  3360. }
  3361. // update "in" index
  3362. inIndex_ += bufferSize;
  3363. inIndex_ %= bufferSize_;
  3364. return true;
  3365. }
  3366. // attempt to pull a buffer from the ring buffer from the current "out" index
  3367. bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3368. {
  3369. if ( !buffer || // incoming buffer is NULL
  3370. bufferSize == 0 || // incoming buffer has no data
  3371. bufferSize > bufferSize_ ) // incoming buffer too large
  3372. {
  3373. return false;
  3374. }
  3375. unsigned int relInIndex = inIndex_;
  3376. unsigned int outIndexEnd = outIndex_ + bufferSize;
  3377. if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {
  3378. relInIndex += bufferSize_;
  3379. }
  3380. // the "OUT" index CANNOT BEGIN at the "IN" index
  3381. // the "OUT" index CAN END at the "IN" index
  3382. if ( outIndex_ <= relInIndex && outIndexEnd > relInIndex ) {
  3383. return false; // not enough space between "out" index and "in" index
  3384. }
  3385. // copy buffer from internal to external
  3386. int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
  3387. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3388. int fromOutSize = bufferSize - fromZeroSize;
  3389. switch( format )
  3390. {
  3391. case RTAUDIO_SINT8:
  3392. memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );
  3393. memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );
  3394. break;
  3395. case RTAUDIO_SINT16:
  3396. memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );
  3397. memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );
  3398. break;
  3399. case RTAUDIO_SINT24:
  3400. memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );
  3401. memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );
  3402. break;
  3403. case RTAUDIO_SINT32:
  3404. memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );
  3405. memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );
  3406. break;
  3407. case RTAUDIO_FLOAT32:
  3408. memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );
  3409. memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );
  3410. break;
  3411. case RTAUDIO_FLOAT64:
  3412. memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );
  3413. memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );
  3414. break;
  3415. }
  3416. // update "out" index
  3417. outIndex_ += bufferSize;
  3418. outIndex_ %= bufferSize_;
  3419. return true;
  3420. }
  3421. private:
  3422. char* buffer_;
  3423. unsigned int bufferSize_;
  3424. unsigned int inIndex_;
  3425. unsigned int outIndex_;
  3426. };
  3427. //-----------------------------------------------------------------------------
  3428. // In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate
  3429. // between HW and the user. The WasapiResampler class is used to perform this conversion between
  3430. // HwIn->UserIn and UserOut->HwOut during the stream callback loop.
  3431. class WasapiResampler
  3432. {
  3433. public:
  3434. WasapiResampler( bool isFloat, unsigned int bitsPerSample, unsigned int channelCount,
  3435. unsigned int inSampleRate, unsigned int outSampleRate )
  3436. : _bytesPerSample( bitsPerSample / 8 )
  3437. , _channelCount( channelCount )
  3438. , _sampleRatio( ( float ) outSampleRate / inSampleRate )
  3439. , _transformUnk( NULL )
  3440. , _transform( NULL )
  3441. , _mediaType( NULL )
  3442. , _inputMediaType( NULL )
  3443. , _outputMediaType( NULL )
  3444. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3445. , _resamplerProps( NULL )
  3446. #endif
  3447. {
  3448. // 1. Initialization
  3449. MFStartup( MF_VERSION, MFSTARTUP_NOSOCKET );
  3450. // 2. Create Resampler Transform Object
  3451. CoCreateInstance( CLSID_CResamplerMediaObject, NULL, CLSCTX_INPROC_SERVER,
  3452. IID_IUnknown, ( void** ) &_transformUnk );
  3453. _transformUnk->QueryInterface( IID_PPV_ARGS( &_transform ) );
  3454. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3455. _transformUnk->QueryInterface( IID_PPV_ARGS( &_resamplerProps ) );
  3456. _resamplerProps->SetHalfFilterLength( 60 ); // best conversion quality
  3457. #endif
  3458. // 3. Specify input / output format
  3459. MFCreateMediaType( &_mediaType );
  3460. _mediaType->SetGUID( MF_MT_MAJOR_TYPE, MFMediaType_Audio );
  3461. _mediaType->SetGUID( MF_MT_SUBTYPE, isFloat ? MFAudioFormat_Float : MFAudioFormat_PCM );
  3462. _mediaType->SetUINT32( MF_MT_AUDIO_NUM_CHANNELS, channelCount );
  3463. _mediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, inSampleRate );
  3464. _mediaType->SetUINT32( MF_MT_AUDIO_BLOCK_ALIGNMENT, _bytesPerSample * channelCount );
  3465. _mediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * inSampleRate );
  3466. _mediaType->SetUINT32( MF_MT_AUDIO_BITS_PER_SAMPLE, bitsPerSample );
  3467. _mediaType->SetUINT32( MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE );
  3468. MFCreateMediaType( &_inputMediaType );
  3469. _mediaType->CopyAllItems( _inputMediaType );
  3470. _transform->SetInputType( 0, _inputMediaType, 0 );
  3471. MFCreateMediaType( &_outputMediaType );
  3472. _mediaType->CopyAllItems( _outputMediaType );
  3473. _outputMediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, outSampleRate );
  3474. _outputMediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * outSampleRate );
  3475. _transform->SetOutputType( 0, _outputMediaType, 0 );
  3476. // 4. Send stream start messages to Resampler
  3477. _transform->ProcessMessage( MFT_MESSAGE_COMMAND_FLUSH, 0 );
  3478. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0 );
  3479. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0 );
  3480. }
  3481. ~WasapiResampler()
  3482. {
  3483. // 8. Send stream stop messages to Resampler
  3484. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0 );
  3485. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_STREAMING, 0 );
  3486. // 9. Cleanup
  3487. MFShutdown();
  3488. SAFE_RELEASE( _transformUnk );
  3489. SAFE_RELEASE( _transform );
  3490. SAFE_RELEASE( _mediaType );
  3491. SAFE_RELEASE( _inputMediaType );
  3492. SAFE_RELEASE( _outputMediaType );
  3493. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3494. SAFE_RELEASE( _resamplerProps );
  3495. #endif
  3496. }
  3497. void Convert( char* outBuffer, const char* inBuffer, unsigned int inSampleCount, unsigned int& outSampleCount, int maxOutSampleCount = -1 )
  3498. {
  3499. unsigned int inputBufferSize = _bytesPerSample * _channelCount * inSampleCount;
  3500. if ( _sampleRatio == 1 )
  3501. {
  3502. // no sample rate conversion required
  3503. memcpy( outBuffer, inBuffer, inputBufferSize );
  3504. outSampleCount = inSampleCount;
  3505. return;
  3506. }
  3507. unsigned int outputBufferSize = 0;
  3508. if ( maxOutSampleCount != -1 )
  3509. {
  3510. outputBufferSize = _bytesPerSample * _channelCount * maxOutSampleCount;
  3511. }
  3512. else
  3513. {
  3514. outputBufferSize = ( unsigned int ) ceilf( inputBufferSize * _sampleRatio ) + ( _bytesPerSample * _channelCount );
  3515. }
  3516. IMFMediaBuffer* rInBuffer;
  3517. IMFSample* rInSample;
  3518. BYTE* rInByteBuffer = NULL;
  3519. // 5. Create Sample object from input data
  3520. MFCreateMemoryBuffer( inputBufferSize, &rInBuffer );
  3521. rInBuffer->Lock( &rInByteBuffer, NULL, NULL );
  3522. memcpy( rInByteBuffer, inBuffer, inputBufferSize );
  3523. rInBuffer->Unlock();
  3524. rInByteBuffer = NULL;
  3525. rInBuffer->SetCurrentLength( inputBufferSize );
  3526. MFCreateSample( &rInSample );
  3527. rInSample->AddBuffer( rInBuffer );
  3528. // 6. Pass input data to Resampler
  3529. _transform->ProcessInput( 0, rInSample, 0 );
  3530. SAFE_RELEASE( rInBuffer );
  3531. SAFE_RELEASE( rInSample );
  3532. // 7. Perform sample rate conversion
  3533. IMFMediaBuffer* rOutBuffer = NULL;
  3534. BYTE* rOutByteBuffer = NULL;
  3535. MFT_OUTPUT_DATA_BUFFER rOutDataBuffer;
  3536. DWORD rStatus;
  3537. DWORD rBytes = outputBufferSize; // maximum bytes accepted per ProcessOutput
  3538. // 7.1 Create Sample object for output data
  3539. memset( &rOutDataBuffer, 0, sizeof rOutDataBuffer );
  3540. MFCreateSample( &( rOutDataBuffer.pSample ) );
  3541. MFCreateMemoryBuffer( rBytes, &rOutBuffer );
  3542. rOutDataBuffer.pSample->AddBuffer( rOutBuffer );
  3543. rOutDataBuffer.dwStreamID = 0;
  3544. rOutDataBuffer.dwStatus = 0;
  3545. rOutDataBuffer.pEvents = NULL;
  3546. // 7.2 Get output data from Resampler
  3547. if ( _transform->ProcessOutput( 0, 1, &rOutDataBuffer, &rStatus ) == MF_E_TRANSFORM_NEED_MORE_INPUT )
  3548. {
  3549. outSampleCount = 0;
  3550. SAFE_RELEASE( rOutBuffer );
  3551. SAFE_RELEASE( rOutDataBuffer.pSample );
  3552. return;
  3553. }
  3554. // 7.3 Write output data to outBuffer
  3555. SAFE_RELEASE( rOutBuffer );
  3556. rOutDataBuffer.pSample->ConvertToContiguousBuffer( &rOutBuffer );
  3557. rOutBuffer->GetCurrentLength( &rBytes );
  3558. rOutBuffer->Lock( &rOutByteBuffer, NULL, NULL );
  3559. memcpy( outBuffer, rOutByteBuffer, rBytes );
  3560. rOutBuffer->Unlock();
  3561. rOutByteBuffer = NULL;
  3562. outSampleCount = rBytes / _bytesPerSample / _channelCount;
  3563. SAFE_RELEASE( rOutBuffer );
  3564. SAFE_RELEASE( rOutDataBuffer.pSample );
  3565. }
  3566. private:
  3567. unsigned int _bytesPerSample;
  3568. unsigned int _channelCount;
  3569. float _sampleRatio;
  3570. IUnknown* _transformUnk;
  3571. IMFTransform* _transform;
  3572. IMFMediaType* _mediaType;
  3573. IMFMediaType* _inputMediaType;
  3574. IMFMediaType* _outputMediaType;
  3575. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3576. IWMResamplerProps* _resamplerProps;
  3577. #endif
  3578. };
  3579. //-----------------------------------------------------------------------------
  3580. // A structure to hold various information related to the WASAPI implementation.
  3581. struct WasapiHandle
  3582. {
  3583. IAudioClient* captureAudioClient;
  3584. IAudioClient* renderAudioClient;
  3585. IAudioCaptureClient* captureClient;
  3586. IAudioRenderClient* renderClient;
  3587. HANDLE captureEvent;
  3588. HANDLE renderEvent;
  3589. WasapiHandle()
  3590. : captureAudioClient( NULL ),
  3591. renderAudioClient( NULL ),
  3592. captureClient( NULL ),
  3593. renderClient( NULL ),
  3594. captureEvent( NULL ),
  3595. renderEvent( NULL ) {}
  3596. };
  3597. //=============================================================================
  3598. RtApiWasapi::RtApiWasapi()
  3599. : coInitialized_( false ), deviceEnumerator_( NULL )
  3600. {
  3601. // WASAPI can run either apartment or multi-threaded
  3602. HRESULT hr = CoInitialize( NULL );
  3603. if ( !FAILED( hr ) )
  3604. coInitialized_ = true;
  3605. // Instantiate device enumerator
  3606. hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
  3607. CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
  3608. ( void** ) &deviceEnumerator_ );
  3609. // If this runs on an old Windows, it will fail. Ignore and proceed.
  3610. if ( FAILED( hr ) )
  3611. deviceEnumerator_ = NULL;
  3612. }
  3613. //-----------------------------------------------------------------------------
  3614. RtApiWasapi::~RtApiWasapi()
  3615. {
  3616. if ( stream_.state != STREAM_CLOSED )
  3617. closeStream();
  3618. SAFE_RELEASE( deviceEnumerator_ );
  3619. // If this object previously called CoInitialize()
  3620. if ( coInitialized_ )
  3621. CoUninitialize();
  3622. }
  3623. //=============================================================================
  3624. unsigned int RtApiWasapi::getDeviceCount( void )
  3625. {
  3626. unsigned int captureDeviceCount = 0;
  3627. unsigned int renderDeviceCount = 0;
  3628. IMMDeviceCollection* captureDevices = NULL;
  3629. IMMDeviceCollection* renderDevices = NULL;
  3630. if ( !deviceEnumerator_ )
  3631. return 0;
  3632. // Count capture devices
  3633. errorText_.clear();
  3634. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3635. if ( FAILED( hr ) ) {
  3636. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
  3637. goto Exit;
  3638. }
  3639. hr = captureDevices->GetCount( &captureDeviceCount );
  3640. if ( FAILED( hr ) ) {
  3641. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
  3642. goto Exit;
  3643. }
  3644. // Count render devices
  3645. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3646. if ( FAILED( hr ) ) {
  3647. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
  3648. goto Exit;
  3649. }
  3650. hr = renderDevices->GetCount( &renderDeviceCount );
  3651. if ( FAILED( hr ) ) {
  3652. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
  3653. goto Exit;
  3654. }
  3655. Exit:
  3656. // release all references
  3657. SAFE_RELEASE( captureDevices );
  3658. SAFE_RELEASE( renderDevices );
  3659. if ( errorText_.empty() )
  3660. return captureDeviceCount + renderDeviceCount;
  3661. error( RtAudioError::DRIVER_ERROR );
  3662. return 0;
  3663. }
  3664. //-----------------------------------------------------------------------------
  3665. RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
  3666. {
  3667. RtAudio::DeviceInfo info;
  3668. unsigned int captureDeviceCount = 0;
  3669. unsigned int renderDeviceCount = 0;
  3670. std::string defaultDeviceName;
  3671. bool isCaptureDevice = false;
  3672. PROPVARIANT deviceNameProp;
  3673. PROPVARIANT defaultDeviceNameProp;
  3674. IMMDeviceCollection* captureDevices = NULL;
  3675. IMMDeviceCollection* renderDevices = NULL;
  3676. IMMDevice* devicePtr = NULL;
  3677. IMMDevice* defaultDevicePtr = NULL;
  3678. IAudioClient* audioClient = NULL;
  3679. IPropertyStore* devicePropStore = NULL;
  3680. IPropertyStore* defaultDevicePropStore = NULL;
  3681. WAVEFORMATEX* deviceFormat = NULL;
  3682. WAVEFORMATEX* closestMatchFormat = NULL;
  3683. // probed
  3684. info.probed = false;
  3685. // Count capture devices
  3686. errorText_.clear();
  3687. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3688. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3689. if ( FAILED( hr ) ) {
  3690. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
  3691. goto Exit;
  3692. }
  3693. hr = captureDevices->GetCount( &captureDeviceCount );
  3694. if ( FAILED( hr ) ) {
  3695. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
  3696. goto Exit;
  3697. }
  3698. // Count render devices
  3699. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3700. if ( FAILED( hr ) ) {
  3701. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
  3702. goto Exit;
  3703. }
  3704. hr = renderDevices->GetCount( &renderDeviceCount );
  3705. if ( FAILED( hr ) ) {
  3706. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
  3707. goto Exit;
  3708. }
  3709. // validate device index
  3710. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3711. errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
  3712. errorType = RtAudioError::INVALID_USE;
  3713. goto Exit;
  3714. }
  3715. // determine whether index falls within capture or render devices
  3716. if ( device >= renderDeviceCount ) {
  3717. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3718. if ( FAILED( hr ) ) {
  3719. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
  3720. goto Exit;
  3721. }
  3722. isCaptureDevice = true;
  3723. }
  3724. else {
  3725. hr = renderDevices->Item( device, &devicePtr );
  3726. if ( FAILED( hr ) ) {
  3727. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
  3728. goto Exit;
  3729. }
  3730. isCaptureDevice = false;
  3731. }
  3732. // get default device name
  3733. if ( isCaptureDevice ) {
  3734. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );
  3735. if ( FAILED( hr ) ) {
  3736. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
  3737. goto Exit;
  3738. }
  3739. }
  3740. else {
  3741. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );
  3742. if ( FAILED( hr ) ) {
  3743. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
  3744. goto Exit;
  3745. }
  3746. }
  3747. hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );
  3748. if ( FAILED( hr ) ) {
  3749. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
  3750. goto Exit;
  3751. }
  3752. PropVariantInit( &defaultDeviceNameProp );
  3753. hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );
  3754. if ( FAILED( hr ) ) {
  3755. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
  3756. goto Exit;
  3757. }
  3758. defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);
  3759. // name
  3760. hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
  3761. if ( FAILED( hr ) ) {
  3762. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
  3763. goto Exit;
  3764. }
  3765. PropVariantInit( &deviceNameProp );
  3766. hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
  3767. if ( FAILED( hr ) ) {
  3768. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
  3769. goto Exit;
  3770. }
  3771. info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);
  3772. // is default
  3773. if ( isCaptureDevice ) {
  3774. info.isDefaultInput = info.name == defaultDeviceName;
  3775. info.isDefaultOutput = false;
  3776. }
  3777. else {
  3778. info.isDefaultInput = false;
  3779. info.isDefaultOutput = info.name == defaultDeviceName;
  3780. }
  3781. // channel count
  3782. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
  3783. if ( FAILED( hr ) ) {
  3784. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
  3785. goto Exit;
  3786. }
  3787. hr = audioClient->GetMixFormat( &deviceFormat );
  3788. if ( FAILED( hr ) ) {
  3789. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
  3790. goto Exit;
  3791. }
  3792. if ( isCaptureDevice ) {
  3793. info.inputChannels = deviceFormat->nChannels;
  3794. info.outputChannels = 0;
  3795. info.duplexChannels = 0;
  3796. }
  3797. else {
  3798. info.inputChannels = 0;
  3799. info.outputChannels = deviceFormat->nChannels;
  3800. info.duplexChannels = 0;
  3801. }
  3802. // sample rates
  3803. info.sampleRates.clear();
  3804. // allow support for all sample rates as we have a built-in sample rate converter
  3805. for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {
  3806. info.sampleRates.push_back( SAMPLE_RATES[i] );
  3807. }
  3808. info.preferredSampleRate = deviceFormat->nSamplesPerSec;
  3809. // native format
  3810. info.nativeFormats = 0;
  3811. if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
  3812. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3813. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
  3814. {
  3815. if ( deviceFormat->wBitsPerSample == 32 ) {
  3816. info.nativeFormats |= RTAUDIO_FLOAT32;
  3817. }
  3818. else if ( deviceFormat->wBitsPerSample == 64 ) {
  3819. info.nativeFormats |= RTAUDIO_FLOAT64;
  3820. }
  3821. }
  3822. else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
  3823. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3824. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
  3825. {
  3826. if ( deviceFormat->wBitsPerSample == 8 ) {
  3827. info.nativeFormats |= RTAUDIO_SINT8;
  3828. }
  3829. else if ( deviceFormat->wBitsPerSample == 16 ) {
  3830. info.nativeFormats |= RTAUDIO_SINT16;
  3831. }
  3832. else if ( deviceFormat->wBitsPerSample == 24 ) {
  3833. info.nativeFormats |= RTAUDIO_SINT24;
  3834. }
  3835. else if ( deviceFormat->wBitsPerSample == 32 ) {
  3836. info.nativeFormats |= RTAUDIO_SINT32;
  3837. }
  3838. }
  3839. // probed
  3840. info.probed = true;
  3841. Exit:
  3842. // release all references
  3843. PropVariantClear( &deviceNameProp );
  3844. PropVariantClear( &defaultDeviceNameProp );
  3845. SAFE_RELEASE( captureDevices );
  3846. SAFE_RELEASE( renderDevices );
  3847. SAFE_RELEASE( devicePtr );
  3848. SAFE_RELEASE( defaultDevicePtr );
  3849. SAFE_RELEASE( audioClient );
  3850. SAFE_RELEASE( devicePropStore );
  3851. SAFE_RELEASE( defaultDevicePropStore );
  3852. CoTaskMemFree( deviceFormat );
  3853. CoTaskMemFree( closestMatchFormat );
  3854. if ( !errorText_.empty() )
  3855. error( errorType );
  3856. return info;
  3857. }
  3858. //-----------------------------------------------------------------------------
  3859. unsigned int RtApiWasapi::getDefaultOutputDevice( void )
  3860. {
  3861. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3862. if ( getDeviceInfo( i ).isDefaultOutput ) {
  3863. return i;
  3864. }
  3865. }
  3866. return 0;
  3867. }
  3868. //-----------------------------------------------------------------------------
  3869. unsigned int RtApiWasapi::getDefaultInputDevice( void )
  3870. {
  3871. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3872. if ( getDeviceInfo( i ).isDefaultInput ) {
  3873. return i;
  3874. }
  3875. }
  3876. return 0;
  3877. }
  3878. //-----------------------------------------------------------------------------
  3879. void RtApiWasapi::closeStream( void )
  3880. {
  3881. if ( stream_.state == STREAM_CLOSED ) {
  3882. errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
  3883. error( RtAudioError::WARNING );
  3884. return;
  3885. }
  3886. if ( stream_.state != STREAM_STOPPED )
  3887. stopStream();
  3888. // clean up stream memory
  3889. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
  3890. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
  3891. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )
  3892. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )
  3893. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
  3894. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
  3895. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
  3896. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
  3897. delete ( WasapiHandle* ) stream_.apiHandle;
  3898. stream_.apiHandle = NULL;
  3899. for ( int i = 0; i < 2; i++ ) {
  3900. if ( stream_.userBuffer[i] ) {
  3901. free( stream_.userBuffer[i] );
  3902. stream_.userBuffer[i] = 0;
  3903. }
  3904. }
  3905. if ( stream_.deviceBuffer ) {
  3906. free( stream_.deviceBuffer );
  3907. stream_.deviceBuffer = 0;
  3908. }
  3909. // update stream state
  3910. stream_.state = STREAM_CLOSED;
  3911. }
  3912. //-----------------------------------------------------------------------------
  3913. void RtApiWasapi::startStream( void )
  3914. {
  3915. verifyStream();
  3916. if ( stream_.state == STREAM_RUNNING ) {
  3917. errorText_ = "RtApiWasapi::startStream: The stream is already running.";
  3918. error( RtAudioError::WARNING );
  3919. return;
  3920. }
  3921. #if defined( HAVE_GETTIMEOFDAY )
  3922. gettimeofday( &stream_.lastTickTimestamp, NULL );
  3923. #endif
  3924. // update stream state
  3925. stream_.state = STREAM_RUNNING;
  3926. // create WASAPI stream thread
  3927. stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
  3928. if ( !stream_.callbackInfo.thread ) {
  3929. errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
  3930. error( RtAudioError::THREAD_ERROR );
  3931. }
  3932. else {
  3933. SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
  3934. ResumeThread( ( void* ) stream_.callbackInfo.thread );
  3935. }
  3936. }
  3937. //-----------------------------------------------------------------------------
  3938. void RtApiWasapi::stopStream( void )
  3939. {
  3940. verifyStream();
  3941. if ( stream_.state == STREAM_STOPPED ) {
  3942. errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
  3943. error( RtAudioError::WARNING );
  3944. return;
  3945. }
  3946. // inform stream thread by setting stream state to STREAM_STOPPING
  3947. stream_.state = STREAM_STOPPING;
  3948. // wait until stream thread is stopped
  3949. while( stream_.state != STREAM_STOPPED ) {
  3950. Sleep( 1 );
  3951. }
  3952. // Wait for the last buffer to play before stopping.
  3953. Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );
  3954. // close thread handle
  3955. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3956. errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
  3957. error( RtAudioError::THREAD_ERROR );
  3958. return;
  3959. }
  3960. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3961. }
  3962. //-----------------------------------------------------------------------------
  3963. void RtApiWasapi::abortStream( void )
  3964. {
  3965. verifyStream();
  3966. if ( stream_.state == STREAM_STOPPED ) {
  3967. errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
  3968. error( RtAudioError::WARNING );
  3969. return;
  3970. }
  3971. // inform stream thread by setting stream state to STREAM_STOPPING
  3972. stream_.state = STREAM_STOPPING;
  3973. // wait until stream thread is stopped
  3974. while ( stream_.state != STREAM_STOPPED ) {
  3975. Sleep( 1 );
  3976. }
  3977. // close thread handle
  3978. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3979. errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
  3980. error( RtAudioError::THREAD_ERROR );
  3981. return;
  3982. }
  3983. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3984. }
  3985. //-----------------------------------------------------------------------------
  3986. bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3987. unsigned int firstChannel, unsigned int sampleRate,
  3988. RtAudioFormat format, unsigned int* bufferSize,
  3989. RtAudio::StreamOptions* options )
  3990. {
  3991. bool methodResult = FAILURE;
  3992. unsigned int captureDeviceCount = 0;
  3993. unsigned int renderDeviceCount = 0;
  3994. IMMDeviceCollection* captureDevices = NULL;
  3995. IMMDeviceCollection* renderDevices = NULL;
  3996. IMMDevice* devicePtr = NULL;
  3997. WAVEFORMATEX* deviceFormat = NULL;
  3998. unsigned int bufferBytes;
  3999. stream_.state = STREAM_STOPPED;
  4000. // create API Handle if not already created
  4001. if ( !stream_.apiHandle )
  4002. stream_.apiHandle = ( void* ) new WasapiHandle();
  4003. // Count capture devices
  4004. errorText_.clear();
  4005. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  4006. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  4007. if ( FAILED( hr ) ) {
  4008. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
  4009. goto Exit;
  4010. }
  4011. hr = captureDevices->GetCount( &captureDeviceCount );
  4012. if ( FAILED( hr ) ) {
  4013. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
  4014. goto Exit;
  4015. }
  4016. // Count render devices
  4017. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  4018. if ( FAILED( hr ) ) {
  4019. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
  4020. goto Exit;
  4021. }
  4022. hr = renderDevices->GetCount( &renderDeviceCount );
  4023. if ( FAILED( hr ) ) {
  4024. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
  4025. goto Exit;
  4026. }
  4027. // validate device index
  4028. if ( device >= captureDeviceCount + renderDeviceCount ) {
  4029. errorType = RtAudioError::INVALID_USE;
  4030. errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
  4031. goto Exit;
  4032. }
  4033. // if device index falls within capture devices
  4034. if ( device >= renderDeviceCount ) {
  4035. if ( mode != INPUT ) {
  4036. errorType = RtAudioError::INVALID_USE;
  4037. errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
  4038. goto Exit;
  4039. }
  4040. // retrieve captureAudioClient from devicePtr
  4041. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4042. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  4043. if ( FAILED( hr ) ) {
  4044. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
  4045. goto Exit;
  4046. }
  4047. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4048. NULL, ( void** ) &captureAudioClient );
  4049. if ( FAILED( hr ) ) {
  4050. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device audio client.";
  4051. goto Exit;
  4052. }
  4053. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  4054. if ( FAILED( hr ) ) {
  4055. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device mix format.";
  4056. goto Exit;
  4057. }
  4058. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4059. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4060. }
  4061. // if device index falls within render devices and is configured for loopback
  4062. if ( device < renderDeviceCount && mode == INPUT )
  4063. {
  4064. // if renderAudioClient is not initialised, initialise it now
  4065. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4066. if ( !renderAudioClient )
  4067. {
  4068. probeDeviceOpen( device, OUTPUT, channels, firstChannel, sampleRate, format, bufferSize, options );
  4069. }
  4070. // retrieve captureAudioClient from devicePtr
  4071. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4072. hr = renderDevices->Item( device, &devicePtr );
  4073. if ( FAILED( hr ) ) {
  4074. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  4075. goto Exit;
  4076. }
  4077. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4078. NULL, ( void** ) &captureAudioClient );
  4079. if ( FAILED( hr ) ) {
  4080. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
  4081. goto Exit;
  4082. }
  4083. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  4084. if ( FAILED( hr ) ) {
  4085. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
  4086. goto Exit;
  4087. }
  4088. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4089. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4090. }
  4091. // if device index falls within render devices and is configured for output
  4092. if ( device < renderDeviceCount && mode == OUTPUT )
  4093. {
  4094. // if renderAudioClient is already initialised, don't initialise it again
  4095. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4096. if ( renderAudioClient )
  4097. {
  4098. methodResult = SUCCESS;
  4099. goto Exit;
  4100. }
  4101. hr = renderDevices->Item( device, &devicePtr );
  4102. if ( FAILED( hr ) ) {
  4103. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  4104. goto Exit;
  4105. }
  4106. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4107. NULL, ( void** ) &renderAudioClient );
  4108. if ( FAILED( hr ) ) {
  4109. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
  4110. goto Exit;
  4111. }
  4112. hr = renderAudioClient->GetMixFormat( &deviceFormat );
  4113. if ( FAILED( hr ) ) {
  4114. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
  4115. goto Exit;
  4116. }
  4117. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4118. renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4119. }
  4120. // fill stream data
  4121. if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
  4122. ( stream_.mode == INPUT && mode == OUTPUT ) ) {
  4123. stream_.mode = DUPLEX;
  4124. }
  4125. else {
  4126. stream_.mode = mode;
  4127. }
  4128. stream_.device[mode] = device;
  4129. stream_.doByteSwap[mode] = false;
  4130. stream_.sampleRate = sampleRate;
  4131. stream_.bufferSize = *bufferSize;
  4132. stream_.nBuffers = 1;
  4133. stream_.nUserChannels[mode] = channels;
  4134. stream_.channelOffset[mode] = firstChannel;
  4135. stream_.userFormat = format;
  4136. stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats;
  4137. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  4138. stream_.userInterleaved = false;
  4139. else
  4140. stream_.userInterleaved = true;
  4141. stream_.deviceInterleaved[mode] = true;
  4142. // Set flags for buffer conversion.
  4143. stream_.doConvertBuffer[mode] = false;
  4144. if ( stream_.userFormat != stream_.deviceFormat[mode] ||
  4145. stream_.nUserChannels[0] != stream_.nDeviceChannels[0] ||
  4146. stream_.nUserChannels[1] != stream_.nDeviceChannels[1] )
  4147. stream_.doConvertBuffer[mode] = true;
  4148. else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4149. stream_.nUserChannels[mode] > 1 )
  4150. stream_.doConvertBuffer[mode] = true;
  4151. if ( stream_.doConvertBuffer[mode] )
  4152. setConvertInfo( mode, firstChannel );
  4153. // Allocate necessary internal buffers
  4154. bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
  4155. stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
  4156. if ( !stream_.userBuffer[mode] ) {
  4157. errorType = RtAudioError::MEMORY_ERROR;
  4158. errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
  4159. goto Exit;
  4160. }
  4161. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
  4162. stream_.callbackInfo.priority = 15;
  4163. else
  4164. stream_.callbackInfo.priority = 0;
  4165. ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
  4166. ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
  4167. methodResult = SUCCESS;
  4168. Exit:
  4169. //clean up
  4170. SAFE_RELEASE( captureDevices );
  4171. SAFE_RELEASE( renderDevices );
  4172. SAFE_RELEASE( devicePtr );
  4173. CoTaskMemFree( deviceFormat );
  4174. // if method failed, close the stream
  4175. if ( methodResult == FAILURE )
  4176. closeStream();
  4177. if ( !errorText_.empty() )
  4178. error( errorType );
  4179. return methodResult;
  4180. }
  4181. //=============================================================================
  4182. DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
  4183. {
  4184. if ( wasapiPtr )
  4185. ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
  4186. return 0;
  4187. }
  4188. DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
  4189. {
  4190. if ( wasapiPtr )
  4191. ( ( RtApiWasapi* ) wasapiPtr )->stopStream();
  4192. return 0;
  4193. }
  4194. DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
  4195. {
  4196. if ( wasapiPtr )
  4197. ( ( RtApiWasapi* ) wasapiPtr )->abortStream();
  4198. return 0;
  4199. }
  4200. //-----------------------------------------------------------------------------
  4201. void RtApiWasapi::wasapiThread()
  4202. {
  4203. // as this is a new thread, we must CoInitialize it
  4204. CoInitialize( NULL );
  4205. HRESULT hr;
  4206. IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4207. IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4208. IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
  4209. IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
  4210. HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
  4211. HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
  4212. WAVEFORMATEX* captureFormat = NULL;
  4213. WAVEFORMATEX* renderFormat = NULL;
  4214. float captureSrRatio = 0.0f;
  4215. float renderSrRatio = 0.0f;
  4216. WasapiBuffer captureBuffer;
  4217. WasapiBuffer renderBuffer;
  4218. WasapiResampler* captureResampler = NULL;
  4219. WasapiResampler* renderResampler = NULL;
  4220. // declare local stream variables
  4221. RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
  4222. BYTE* streamBuffer = NULL;
  4223. DWORD captureFlags = 0;
  4224. unsigned int bufferFrameCount = 0;
  4225. unsigned int numFramesPadding = 0;
  4226. unsigned int convBufferSize = 0;
  4227. bool loopbackEnabled = stream_.device[INPUT] == stream_.device[OUTPUT];
  4228. bool callbackPushed = true;
  4229. bool callbackPulled = false;
  4230. bool callbackStopped = false;
  4231. int callbackResult = 0;
  4232. // convBuffer is used to store converted buffers between WASAPI and the user
  4233. char* convBuffer = NULL;
  4234. unsigned int convBuffSize = 0;
  4235. unsigned int deviceBuffSize = 0;
  4236. std::string errorText;
  4237. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  4238. // Attempt to assign "Pro Audio" characteristic to thread
  4239. HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );
  4240. if ( AvrtDll ) {
  4241. DWORD taskIndex = 0;
  4242. TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr =
  4243. ( TAvSetMmThreadCharacteristicsPtr ) (void(*)()) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
  4244. AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
  4245. FreeLibrary( AvrtDll );
  4246. }
  4247. // start capture stream if applicable
  4248. if ( captureAudioClient ) {
  4249. hr = captureAudioClient->GetMixFormat( &captureFormat );
  4250. if ( FAILED( hr ) ) {
  4251. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4252. goto Exit;
  4253. }
  4254. // init captureResampler
  4255. captureResampler = new WasapiResampler( stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT64,
  4256. formatBytes( stream_.deviceFormat[INPUT] ) * 8, stream_.nDeviceChannels[INPUT],
  4257. captureFormat->nSamplesPerSec, stream_.sampleRate );
  4258. captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );
  4259. if ( !captureClient ) {
  4260. hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4261. loopbackEnabled ? AUDCLNT_STREAMFLAGS_LOOPBACK : AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4262. 0,
  4263. 0,
  4264. captureFormat,
  4265. NULL );
  4266. if ( FAILED( hr ) ) {
  4267. errorText = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
  4268. goto Exit;
  4269. }
  4270. hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
  4271. ( void** ) &captureClient );
  4272. if ( FAILED( hr ) ) {
  4273. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
  4274. goto Exit;
  4275. }
  4276. // don't configure captureEvent if in loopback mode
  4277. if ( !loopbackEnabled )
  4278. {
  4279. // configure captureEvent to trigger on every available capture buffer
  4280. captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4281. if ( !captureEvent ) {
  4282. errorType = RtAudioError::SYSTEM_ERROR;
  4283. errorText = "RtApiWasapi::wasapiThread: Unable to create capture event.";
  4284. goto Exit;
  4285. }
  4286. hr = captureAudioClient->SetEventHandle( captureEvent );
  4287. if ( FAILED( hr ) ) {
  4288. errorText = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
  4289. goto Exit;
  4290. }
  4291. ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
  4292. }
  4293. ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
  4294. // reset the capture stream
  4295. hr = captureAudioClient->Reset();
  4296. if ( FAILED( hr ) ) {
  4297. errorText = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
  4298. goto Exit;
  4299. }
  4300. // start the capture stream
  4301. hr = captureAudioClient->Start();
  4302. if ( FAILED( hr ) ) {
  4303. errorText = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
  4304. goto Exit;
  4305. }
  4306. }
  4307. unsigned int inBufferSize = 0;
  4308. hr = captureAudioClient->GetBufferSize( &inBufferSize );
  4309. if ( FAILED( hr ) ) {
  4310. errorText = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
  4311. goto Exit;
  4312. }
  4313. // scale outBufferSize according to stream->user sample rate ratio
  4314. unsigned int outBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];
  4315. inBufferSize *= stream_.nDeviceChannels[INPUT];
  4316. // set captureBuffer size
  4317. captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
  4318. }
  4319. // start render stream if applicable
  4320. if ( renderAudioClient ) {
  4321. hr = renderAudioClient->GetMixFormat( &renderFormat );
  4322. if ( FAILED( hr ) ) {
  4323. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4324. goto Exit;
  4325. }
  4326. // init renderResampler
  4327. renderResampler = new WasapiResampler( stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT64,
  4328. formatBytes( stream_.deviceFormat[OUTPUT] ) * 8, stream_.nDeviceChannels[OUTPUT],
  4329. stream_.sampleRate, renderFormat->nSamplesPerSec );
  4330. renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );
  4331. if ( !renderClient ) {
  4332. hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4333. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4334. 0,
  4335. 0,
  4336. renderFormat,
  4337. NULL );
  4338. if ( FAILED( hr ) ) {
  4339. errorText = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
  4340. goto Exit;
  4341. }
  4342. hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
  4343. ( void** ) &renderClient );
  4344. if ( FAILED( hr ) ) {
  4345. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
  4346. goto Exit;
  4347. }
  4348. // configure renderEvent to trigger on every available render buffer
  4349. renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4350. if ( !renderEvent ) {
  4351. errorType = RtAudioError::SYSTEM_ERROR;
  4352. errorText = "RtApiWasapi::wasapiThread: Unable to create render event.";
  4353. goto Exit;
  4354. }
  4355. hr = renderAudioClient->SetEventHandle( renderEvent );
  4356. if ( FAILED( hr ) ) {
  4357. errorText = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
  4358. goto Exit;
  4359. }
  4360. ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
  4361. ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
  4362. // reset the render stream
  4363. hr = renderAudioClient->Reset();
  4364. if ( FAILED( hr ) ) {
  4365. errorText = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
  4366. goto Exit;
  4367. }
  4368. // start the render stream
  4369. hr = renderAudioClient->Start();
  4370. if ( FAILED( hr ) ) {
  4371. errorText = "RtApiWasapi::wasapiThread: Unable to start render stream.";
  4372. goto Exit;
  4373. }
  4374. }
  4375. unsigned int outBufferSize = 0;
  4376. hr = renderAudioClient->GetBufferSize( &outBufferSize );
  4377. if ( FAILED( hr ) ) {
  4378. errorText = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
  4379. goto Exit;
  4380. }
  4381. // scale inBufferSize according to user->stream sample rate ratio
  4382. unsigned int inBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];
  4383. outBufferSize *= stream_.nDeviceChannels[OUTPUT];
  4384. // set renderBuffer size
  4385. renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4386. }
  4387. // malloc buffer memory
  4388. if ( stream_.mode == INPUT )
  4389. {
  4390. using namespace std; // for ceilf
  4391. convBuffSize = ( size_t ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4392. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4393. }
  4394. else if ( stream_.mode == OUTPUT )
  4395. {
  4396. convBuffSize = ( size_t ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4397. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4398. }
  4399. else if ( stream_.mode == DUPLEX )
  4400. {
  4401. convBuffSize = std::max( ( size_t ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4402. ( size_t ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4403. deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4404. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4405. }
  4406. convBuffSize *= 2; // allow overflow for *SrRatio remainders
  4407. convBuffer = ( char* ) calloc( convBuffSize, 1 );
  4408. stream_.deviceBuffer = ( char* ) calloc( deviceBuffSize, 1 );
  4409. if ( !convBuffer || !stream_.deviceBuffer ) {
  4410. errorType = RtAudioError::MEMORY_ERROR;
  4411. errorText = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
  4412. goto Exit;
  4413. }
  4414. // stream process loop
  4415. while ( stream_.state != STREAM_STOPPING ) {
  4416. if ( !callbackPulled ) {
  4417. // Callback Input
  4418. // ==============
  4419. // 1. Pull callback buffer from inputBuffer
  4420. // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count
  4421. // Convert callback buffer to user format
  4422. if ( captureAudioClient )
  4423. {
  4424. int samplesToPull = ( unsigned int ) floorf( stream_.bufferSize * captureSrRatio );
  4425. convBufferSize = 0;
  4426. while ( convBufferSize < stream_.bufferSize )
  4427. {
  4428. // Pull callback buffer from inputBuffer
  4429. callbackPulled = captureBuffer.pullBuffer( convBuffer,
  4430. samplesToPull * stream_.nDeviceChannels[INPUT],
  4431. stream_.deviceFormat[INPUT] );
  4432. if ( !callbackPulled )
  4433. {
  4434. break;
  4435. }
  4436. // Convert callback buffer to user sample rate
  4437. unsigned int deviceBufferOffset = convBufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4438. unsigned int convSamples = 0;
  4439. captureResampler->Convert( stream_.deviceBuffer + deviceBufferOffset,
  4440. convBuffer,
  4441. samplesToPull,
  4442. convSamples,
  4443. convBufferSize == 0 ? -1 : stream_.bufferSize - convBufferSize );
  4444. convBufferSize += convSamples;
  4445. samplesToPull = 1; // now pull one sample at a time until we have stream_.bufferSize samples
  4446. }
  4447. if ( callbackPulled )
  4448. {
  4449. if ( stream_.doConvertBuffer[INPUT] ) {
  4450. // Convert callback buffer to user format
  4451. convertBuffer( stream_.userBuffer[INPUT],
  4452. stream_.deviceBuffer,
  4453. stream_.convertInfo[INPUT] );
  4454. }
  4455. else {
  4456. // no further conversion, simple copy deviceBuffer to userBuffer
  4457. memcpy( stream_.userBuffer[INPUT],
  4458. stream_.deviceBuffer,
  4459. stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
  4460. }
  4461. }
  4462. }
  4463. else {
  4464. // if there is no capture stream, set callbackPulled flag
  4465. callbackPulled = true;
  4466. }
  4467. // Execute Callback
  4468. // ================
  4469. // 1. Execute user callback method
  4470. // 2. Handle return value from callback
  4471. // if callback has not requested the stream to stop
  4472. if ( callbackPulled && !callbackStopped ) {
  4473. // Execute user callback method
  4474. callbackResult = callback( stream_.userBuffer[OUTPUT],
  4475. stream_.userBuffer[INPUT],
  4476. stream_.bufferSize,
  4477. getStreamTime(),
  4478. captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
  4479. stream_.callbackInfo.userData );
  4480. // tick stream time
  4481. RtApi::tickStreamTime();
  4482. // Handle return value from callback
  4483. if ( callbackResult == 1 ) {
  4484. // instantiate a thread to stop this thread
  4485. HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
  4486. if ( !threadHandle ) {
  4487. errorType = RtAudioError::THREAD_ERROR;
  4488. errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
  4489. goto Exit;
  4490. }
  4491. else if ( !CloseHandle( threadHandle ) ) {
  4492. errorType = RtAudioError::THREAD_ERROR;
  4493. errorText = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
  4494. goto Exit;
  4495. }
  4496. callbackStopped = true;
  4497. }
  4498. else if ( callbackResult == 2 ) {
  4499. // instantiate a thread to stop this thread
  4500. HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
  4501. if ( !threadHandle ) {
  4502. errorType = RtAudioError::THREAD_ERROR;
  4503. errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
  4504. goto Exit;
  4505. }
  4506. else if ( !CloseHandle( threadHandle ) ) {
  4507. errorType = RtAudioError::THREAD_ERROR;
  4508. errorText = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
  4509. goto Exit;
  4510. }
  4511. callbackStopped = true;
  4512. }
  4513. }
  4514. }
  4515. // Callback Output
  4516. // ===============
  4517. // 1. Convert callback buffer to stream format
  4518. // 2. Convert callback buffer to stream sample rate and channel count
  4519. // 3. Push callback buffer into outputBuffer
  4520. if ( renderAudioClient && callbackPulled )
  4521. {
  4522. // if the last call to renderBuffer.PushBuffer() was successful
  4523. if ( callbackPushed || convBufferSize == 0 )
  4524. {
  4525. if ( stream_.doConvertBuffer[OUTPUT] )
  4526. {
  4527. // Convert callback buffer to stream format
  4528. convertBuffer( stream_.deviceBuffer,
  4529. stream_.userBuffer[OUTPUT],
  4530. stream_.convertInfo[OUTPUT] );
  4531. }
  4532. else {
  4533. // no further conversion, simple copy userBuffer to deviceBuffer
  4534. memcpy( stream_.deviceBuffer,
  4535. stream_.userBuffer[OUTPUT],
  4536. stream_.bufferSize * stream_.nUserChannels[OUTPUT] * formatBytes( stream_.userFormat ) );
  4537. }
  4538. // Convert callback buffer to stream sample rate
  4539. renderResampler->Convert( convBuffer,
  4540. stream_.deviceBuffer,
  4541. stream_.bufferSize,
  4542. convBufferSize );
  4543. }
  4544. // Push callback buffer into outputBuffer
  4545. callbackPushed = renderBuffer.pushBuffer( convBuffer,
  4546. convBufferSize * stream_.nDeviceChannels[OUTPUT],
  4547. stream_.deviceFormat[OUTPUT] );
  4548. }
  4549. else {
  4550. // if there is no render stream, set callbackPushed flag
  4551. callbackPushed = true;
  4552. }
  4553. // Stream Capture
  4554. // ==============
  4555. // 1. Get capture buffer from stream
  4556. // 2. Push capture buffer into inputBuffer
  4557. // 3. If 2. was successful: Release capture buffer
  4558. if ( captureAudioClient ) {
  4559. // if the callback input buffer was not pulled from captureBuffer, wait for next capture event
  4560. if ( !callbackPulled ) {
  4561. WaitForSingleObject( loopbackEnabled ? renderEvent : captureEvent, INFINITE );
  4562. }
  4563. // Get capture buffer from stream
  4564. hr = captureClient->GetBuffer( &streamBuffer,
  4565. &bufferFrameCount,
  4566. &captureFlags, NULL, NULL );
  4567. if ( FAILED( hr ) ) {
  4568. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
  4569. goto Exit;
  4570. }
  4571. if ( bufferFrameCount != 0 ) {
  4572. // Push capture buffer into inputBuffer
  4573. if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
  4574. bufferFrameCount * stream_.nDeviceChannels[INPUT],
  4575. stream_.deviceFormat[INPUT] ) )
  4576. {
  4577. // Release capture buffer
  4578. hr = captureClient->ReleaseBuffer( bufferFrameCount );
  4579. if ( FAILED( hr ) ) {
  4580. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4581. goto Exit;
  4582. }
  4583. }
  4584. else
  4585. {
  4586. // Inform WASAPI that capture was unsuccessful
  4587. hr = captureClient->ReleaseBuffer( 0 );
  4588. if ( FAILED( hr ) ) {
  4589. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4590. goto Exit;
  4591. }
  4592. }
  4593. }
  4594. else
  4595. {
  4596. // Inform WASAPI that capture was unsuccessful
  4597. hr = captureClient->ReleaseBuffer( 0 );
  4598. if ( FAILED( hr ) ) {
  4599. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4600. goto Exit;
  4601. }
  4602. }
  4603. }
  4604. // Stream Render
  4605. // =============
  4606. // 1. Get render buffer from stream
  4607. // 2. Pull next buffer from outputBuffer
  4608. // 3. If 2. was successful: Fill render buffer with next buffer
  4609. // Release render buffer
  4610. if ( renderAudioClient ) {
  4611. // if the callback output buffer was not pushed to renderBuffer, wait for next render event
  4612. if ( callbackPulled && !callbackPushed ) {
  4613. WaitForSingleObject( renderEvent, INFINITE );
  4614. }
  4615. // Get render buffer from stream
  4616. hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
  4617. if ( FAILED( hr ) ) {
  4618. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
  4619. goto Exit;
  4620. }
  4621. hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
  4622. if ( FAILED( hr ) ) {
  4623. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
  4624. goto Exit;
  4625. }
  4626. bufferFrameCount -= numFramesPadding;
  4627. if ( bufferFrameCount != 0 ) {
  4628. hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
  4629. if ( FAILED( hr ) ) {
  4630. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
  4631. goto Exit;
  4632. }
  4633. // Pull next buffer from outputBuffer
  4634. // Fill render buffer with next buffer
  4635. if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
  4636. bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
  4637. stream_.deviceFormat[OUTPUT] ) )
  4638. {
  4639. // Release render buffer
  4640. hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
  4641. if ( FAILED( hr ) ) {
  4642. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4643. goto Exit;
  4644. }
  4645. }
  4646. else
  4647. {
  4648. // Inform WASAPI that render was unsuccessful
  4649. hr = renderClient->ReleaseBuffer( 0, 0 );
  4650. if ( FAILED( hr ) ) {
  4651. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4652. goto Exit;
  4653. }
  4654. }
  4655. }
  4656. else
  4657. {
  4658. // Inform WASAPI that render was unsuccessful
  4659. hr = renderClient->ReleaseBuffer( 0, 0 );
  4660. if ( FAILED( hr ) ) {
  4661. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4662. goto Exit;
  4663. }
  4664. }
  4665. }
  4666. // if the callback buffer was pushed renderBuffer reset callbackPulled flag
  4667. if ( callbackPushed ) {
  4668. // unsetting the callbackPulled flag lets the stream know that
  4669. // the audio device is ready for another callback output buffer.
  4670. callbackPulled = false;
  4671. }
  4672. }
  4673. Exit:
  4674. // clean up
  4675. CoTaskMemFree( captureFormat );
  4676. CoTaskMemFree( renderFormat );
  4677. free ( convBuffer );
  4678. delete renderResampler;
  4679. delete captureResampler;
  4680. CoUninitialize();
  4681. // update stream state
  4682. stream_.state = STREAM_STOPPED;
  4683. if ( !errorText.empty() )
  4684. {
  4685. errorText_ = errorText;
  4686. error( errorType );
  4687. }
  4688. }
  4689. //******************** End of __WINDOWS_WASAPI__ *********************//
  4690. #endif
  4691. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  4692. // Modified by Robin Davies, October 2005
  4693. // - Improvements to DirectX pointer chasing.
  4694. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  4695. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  4696. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  4697. // Changed device query structure for RtAudio 4.0.7, January 2010
  4698. #include <windows.h>
  4699. #include <process.h>
  4700. #include <mmsystem.h>
  4701. #include <mmreg.h>
  4702. #include <dsound.h>
  4703. #include <assert.h>
  4704. #include <algorithm>
  4705. #if defined(__MINGW32__)
  4706. // missing from latest mingw winapi
  4707. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  4708. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  4709. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  4710. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  4711. #endif
  4712. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  4713. #ifdef _MSC_VER // if Microsoft Visual C++
  4714. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  4715. #endif
  4716. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  4717. {
  4718. if ( pointer > bufferSize ) pointer -= bufferSize;
  4719. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  4720. if ( pointer < earlierPointer ) pointer += bufferSize;
  4721. return pointer >= earlierPointer && pointer < laterPointer;
  4722. }
  4723. // A structure to hold various information related to the DirectSound
  4724. // API implementation.
  4725. struct DsHandle {
  4726. unsigned int drainCounter; // Tracks callback counts when draining
  4727. bool internalDrain; // Indicates if stop is initiated from callback or not.
  4728. void *id[2];
  4729. void *buffer[2];
  4730. bool xrun[2];
  4731. UINT bufferPointer[2];
  4732. DWORD dsBufferSize[2];
  4733. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  4734. HANDLE condition;
  4735. DsHandle()
  4736. :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; }
  4737. };
  4738. // Declarations for utility functions, callbacks, and structures
  4739. // specific to the DirectSound implementation.
  4740. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4741. LPCTSTR description,
  4742. LPCTSTR module,
  4743. LPVOID lpContext );
  4744. static const char* getErrorString( int code );
  4745. static unsigned __stdcall callbackHandler( void *ptr );
  4746. struct DsDevice {
  4747. LPGUID id[2];
  4748. bool validId[2];
  4749. bool found;
  4750. std::string name;
  4751. DsDevice()
  4752. : found(false) { validId[0] = false; validId[1] = false; }
  4753. };
  4754. struct DsProbeData {
  4755. bool isInput;
  4756. std::vector<struct DsDevice>* dsDevices;
  4757. };
  4758. RtApiDs :: RtApiDs()
  4759. {
  4760. // Dsound will run both-threaded. If CoInitialize fails, then just
  4761. // accept whatever the mainline chose for a threading model.
  4762. coInitialized_ = false;
  4763. HRESULT hr = CoInitialize( NULL );
  4764. if ( !FAILED( hr ) ) coInitialized_ = true;
  4765. }
  4766. RtApiDs :: ~RtApiDs()
  4767. {
  4768. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4769. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  4770. }
  4771. // The DirectSound default output is always the first device.
  4772. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  4773. {
  4774. return 0;
  4775. }
  4776. // The DirectSound default input is always the first input device,
  4777. // which is the first capture device enumerated.
  4778. unsigned int RtApiDs :: getDefaultInputDevice( void )
  4779. {
  4780. return 0;
  4781. }
  4782. unsigned int RtApiDs :: getDeviceCount( void )
  4783. {
  4784. // Set query flag for previously found devices to false, so that we
  4785. // can check for any devices that have disappeared.
  4786. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4787. dsDevices[i].found = false;
  4788. // Query DirectSound devices.
  4789. struct DsProbeData probeInfo;
  4790. probeInfo.isInput = false;
  4791. probeInfo.dsDevices = &dsDevices;
  4792. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4793. if ( FAILED( result ) ) {
  4794. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  4795. errorText_ = errorStream_.str();
  4796. error( RtAudioError::WARNING );
  4797. }
  4798. // Query DirectSoundCapture devices.
  4799. probeInfo.isInput = true;
  4800. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4801. if ( FAILED( result ) ) {
  4802. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  4803. errorText_ = errorStream_.str();
  4804. error( RtAudioError::WARNING );
  4805. }
  4806. // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).
  4807. for ( unsigned int i=0; i<dsDevices.size(); ) {
  4808. if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );
  4809. else i++;
  4810. }
  4811. return static_cast<unsigned int>(dsDevices.size());
  4812. }
  4813. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  4814. {
  4815. RtAudio::DeviceInfo info;
  4816. info.probed = false;
  4817. if ( dsDevices.size() == 0 ) {
  4818. // Force a query of all devices
  4819. getDeviceCount();
  4820. if ( dsDevices.size() == 0 ) {
  4821. errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
  4822. error( RtAudioError::INVALID_USE );
  4823. return info;
  4824. }
  4825. }
  4826. if ( device >= dsDevices.size() ) {
  4827. errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
  4828. error( RtAudioError::INVALID_USE );
  4829. return info;
  4830. }
  4831. HRESULT result;
  4832. if ( dsDevices[ device ].validId[0] == false ) goto probeInput;
  4833. LPDIRECTSOUND output;
  4834. DSCAPS outCaps;
  4835. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4836. if ( FAILED( result ) ) {
  4837. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4838. errorText_ = errorStream_.str();
  4839. error( RtAudioError::WARNING );
  4840. goto probeInput;
  4841. }
  4842. outCaps.dwSize = sizeof( outCaps );
  4843. result = output->GetCaps( &outCaps );
  4844. if ( FAILED( result ) ) {
  4845. output->Release();
  4846. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  4847. errorText_ = errorStream_.str();
  4848. error( RtAudioError::WARNING );
  4849. goto probeInput;
  4850. }
  4851. // Get output channel information.
  4852. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  4853. // Get sample rate information.
  4854. info.sampleRates.clear();
  4855. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  4856. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  4857. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {
  4858. info.sampleRates.push_back( SAMPLE_RATES[k] );
  4859. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  4860. info.preferredSampleRate = SAMPLE_RATES[k];
  4861. }
  4862. }
  4863. // Get format information.
  4864. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  4865. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  4866. output->Release();
  4867. if ( getDefaultOutputDevice() == device )
  4868. info.isDefaultOutput = true;
  4869. if ( dsDevices[ device ].validId[1] == false ) {
  4870. info.name = dsDevices[ device ].name;
  4871. info.probed = true;
  4872. return info;
  4873. }
  4874. probeInput:
  4875. LPDIRECTSOUNDCAPTURE input;
  4876. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4877. if ( FAILED( result ) ) {
  4878. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4879. errorText_ = errorStream_.str();
  4880. error( RtAudioError::WARNING );
  4881. return info;
  4882. }
  4883. DSCCAPS inCaps;
  4884. inCaps.dwSize = sizeof( inCaps );
  4885. result = input->GetCaps( &inCaps );
  4886. if ( FAILED( result ) ) {
  4887. input->Release();
  4888. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";
  4889. errorText_ = errorStream_.str();
  4890. error( RtAudioError::WARNING );
  4891. return info;
  4892. }
  4893. // Get input channel information.
  4894. info.inputChannels = inCaps.dwChannels;
  4895. // Get sample rate and format information.
  4896. std::vector<unsigned int> rates;
  4897. if ( inCaps.dwChannels >= 2 ) {
  4898. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4899. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4900. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4901. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4902. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4903. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4904. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4905. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4906. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4907. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
  4908. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
  4909. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
  4910. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
  4911. }
  4912. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4913. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
  4914. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
  4915. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
  4916. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
  4917. }
  4918. }
  4919. else if ( inCaps.dwChannels == 1 ) {
  4920. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4921. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4922. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4923. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4924. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4925. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4926. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4927. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4928. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4929. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
  4930. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
  4931. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
  4932. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
  4933. }
  4934. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4935. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
  4936. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
  4937. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
  4938. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
  4939. }
  4940. }
  4941. else info.inputChannels = 0; // technically, this would be an error
  4942. input->Release();
  4943. if ( info.inputChannels == 0 ) return info;
  4944. // Copy the supported rates to the info structure but avoid duplication.
  4945. bool found;
  4946. for ( unsigned int i=0; i<rates.size(); i++ ) {
  4947. found = false;
  4948. for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
  4949. if ( rates[i] == info.sampleRates[j] ) {
  4950. found = true;
  4951. break;
  4952. }
  4953. }
  4954. if ( found == false ) info.sampleRates.push_back( rates[i] );
  4955. }
  4956. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  4957. // If device opens for both playback and capture, we determine the channels.
  4958. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4959. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4960. if ( device == 0 ) info.isDefaultInput = true;
  4961. // Copy name and return.
  4962. info.name = dsDevices[ device ].name;
  4963. info.probed = true;
  4964. return info;
  4965. }
  4966. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4967. unsigned int firstChannel, unsigned int sampleRate,
  4968. RtAudioFormat format, unsigned int *bufferSize,
  4969. RtAudio::StreamOptions *options )
  4970. {
  4971. if ( channels + firstChannel > 2 ) {
  4972. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  4973. return FAILURE;
  4974. }
  4975. size_t nDevices = dsDevices.size();
  4976. if ( nDevices == 0 ) {
  4977. // This should not happen because a check is made before this function is called.
  4978. errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
  4979. return FAILURE;
  4980. }
  4981. if ( device >= nDevices ) {
  4982. // This should not happen because a check is made before this function is called.
  4983. errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
  4984. return FAILURE;
  4985. }
  4986. if ( mode == OUTPUT ) {
  4987. if ( dsDevices[ device ].validId[0] == false ) {
  4988. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  4989. errorText_ = errorStream_.str();
  4990. return FAILURE;
  4991. }
  4992. }
  4993. else { // mode == INPUT
  4994. if ( dsDevices[ device ].validId[1] == false ) {
  4995. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  4996. errorText_ = errorStream_.str();
  4997. return FAILURE;
  4998. }
  4999. }
  5000. // According to a note in PortAudio, using GetDesktopWindow()
  5001. // instead of GetForegroundWindow() is supposed to avoid problems
  5002. // that occur when the application's window is not the foreground
  5003. // window. Also, if the application window closes before the
  5004. // DirectSound buffer, DirectSound can crash. In the past, I had
  5005. // problems when using GetDesktopWindow() but it seems fine now
  5006. // (January 2010). I'll leave it commented here.
  5007. // HWND hWnd = GetForegroundWindow();
  5008. HWND hWnd = GetDesktopWindow();
  5009. // Check the numberOfBuffers parameter and limit the lowest value to
  5010. // two. This is a judgement call and a value of two is probably too
  5011. // low for capture, but it should work for playback.
  5012. int nBuffers = 0;
  5013. if ( options ) nBuffers = options->numberOfBuffers;
  5014. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  5015. if ( nBuffers < 2 ) nBuffers = 3;
  5016. // Check the lower range of the user-specified buffer size and set
  5017. // (arbitrarily) to a lower bound of 32.
  5018. if ( *bufferSize < 32 ) *bufferSize = 32;
  5019. // Create the wave format structure. The data format setting will
  5020. // be determined later.
  5021. WAVEFORMATEX waveFormat;
  5022. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  5023. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  5024. waveFormat.nChannels = channels + firstChannel;
  5025. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  5026. // Determine the device buffer size. By default, we'll use the value
  5027. // defined above (32K), but we will grow it to make allowances for
  5028. // very large software buffer sizes.
  5029. DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
  5030. DWORD dsPointerLeadTime = 0;
  5031. void *ohandle = 0, *bhandle = 0;
  5032. HRESULT result;
  5033. if ( mode == OUTPUT ) {
  5034. LPDIRECTSOUND output;
  5035. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  5036. if ( FAILED( result ) ) {
  5037. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  5038. errorText_ = errorStream_.str();
  5039. return FAILURE;
  5040. }
  5041. DSCAPS outCaps;
  5042. outCaps.dwSize = sizeof( outCaps );
  5043. result = output->GetCaps( &outCaps );
  5044. if ( FAILED( result ) ) {
  5045. output->Release();
  5046. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";
  5047. errorText_ = errorStream_.str();
  5048. return FAILURE;
  5049. }
  5050. // Check channel information.
  5051. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  5052. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";
  5053. errorText_ = errorStream_.str();
  5054. return FAILURE;
  5055. }
  5056. // Check format information. Use 16-bit format unless not
  5057. // supported or user requests 8-bit.
  5058. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  5059. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  5060. waveFormat.wBitsPerSample = 16;
  5061. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5062. }
  5063. else {
  5064. waveFormat.wBitsPerSample = 8;
  5065. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5066. }
  5067. stream_.userFormat = format;
  5068. // Update wave format structure and buffer information.
  5069. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  5070. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  5071. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  5072. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  5073. while ( dsPointerLeadTime * 2U > dsBufferSize )
  5074. dsBufferSize *= 2;
  5075. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  5076. // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  5077. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  5078. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  5079. if ( FAILED( result ) ) {
  5080. output->Release();
  5081. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";
  5082. errorText_ = errorStream_.str();
  5083. return FAILURE;
  5084. }
  5085. // Even though we will write to the secondary buffer, we need to
  5086. // access the primary buffer to set the correct output format
  5087. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  5088. // buffer description.
  5089. DSBUFFERDESC bufferDescription;
  5090. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  5091. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  5092. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  5093. // Obtain the primary buffer
  5094. LPDIRECTSOUNDBUFFER buffer;
  5095. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5096. if ( FAILED( result ) ) {
  5097. output->Release();
  5098. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";
  5099. errorText_ = errorStream_.str();
  5100. return FAILURE;
  5101. }
  5102. // Set the primary DS buffer sound format.
  5103. result = buffer->SetFormat( &waveFormat );
  5104. if ( FAILED( result ) ) {
  5105. output->Release();
  5106. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";
  5107. errorText_ = errorStream_.str();
  5108. return FAILURE;
  5109. }
  5110. // Setup the secondary DS buffer description.
  5111. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  5112. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  5113. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  5114. DSBCAPS_GLOBALFOCUS |
  5115. DSBCAPS_GETCURRENTPOSITION2 |
  5116. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  5117. bufferDescription.dwBufferBytes = dsBufferSize;
  5118. bufferDescription.lpwfxFormat = &waveFormat;
  5119. // Try to create the secondary DS buffer. If that doesn't work,
  5120. // try to use software mixing. Otherwise, there's a problem.
  5121. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5122. if ( FAILED( result ) ) {
  5123. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  5124. DSBCAPS_GLOBALFOCUS |
  5125. DSBCAPS_GETCURRENTPOSITION2 |
  5126. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  5127. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5128. if ( FAILED( result ) ) {
  5129. output->Release();
  5130. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";
  5131. errorText_ = errorStream_.str();
  5132. return FAILURE;
  5133. }
  5134. }
  5135. // Get the buffer size ... might be different from what we specified.
  5136. DSBCAPS dsbcaps;
  5137. dsbcaps.dwSize = sizeof( DSBCAPS );
  5138. result = buffer->GetCaps( &dsbcaps );
  5139. if ( FAILED( result ) ) {
  5140. output->Release();
  5141. buffer->Release();
  5142. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  5143. errorText_ = errorStream_.str();
  5144. return FAILURE;
  5145. }
  5146. dsBufferSize = dsbcaps.dwBufferBytes;
  5147. // Lock the DS buffer
  5148. LPVOID audioPtr;
  5149. DWORD dataLen;
  5150. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  5151. if ( FAILED( result ) ) {
  5152. output->Release();
  5153. buffer->Release();
  5154. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";
  5155. errorText_ = errorStream_.str();
  5156. return FAILURE;
  5157. }
  5158. // Zero the DS buffer
  5159. ZeroMemory( audioPtr, dataLen );
  5160. // Unlock the DS buffer
  5161. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5162. if ( FAILED( result ) ) {
  5163. output->Release();
  5164. buffer->Release();
  5165. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";
  5166. errorText_ = errorStream_.str();
  5167. return FAILURE;
  5168. }
  5169. ohandle = (void *) output;
  5170. bhandle = (void *) buffer;
  5171. }
  5172. if ( mode == INPUT ) {
  5173. LPDIRECTSOUNDCAPTURE input;
  5174. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  5175. if ( FAILED( result ) ) {
  5176. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  5177. errorText_ = errorStream_.str();
  5178. return FAILURE;
  5179. }
  5180. DSCCAPS inCaps;
  5181. inCaps.dwSize = sizeof( inCaps );
  5182. result = input->GetCaps( &inCaps );
  5183. if ( FAILED( result ) ) {
  5184. input->Release();
  5185. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";
  5186. errorText_ = errorStream_.str();
  5187. return FAILURE;
  5188. }
  5189. // Check channel information.
  5190. if ( inCaps.dwChannels < channels + firstChannel ) {
  5191. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  5192. return FAILURE;
  5193. }
  5194. // Check format information. Use 16-bit format unless user
  5195. // requests 8-bit.
  5196. DWORD deviceFormats;
  5197. if ( channels + firstChannel == 2 ) {
  5198. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  5199. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5200. waveFormat.wBitsPerSample = 8;
  5201. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5202. }
  5203. else { // assume 16-bit is supported
  5204. waveFormat.wBitsPerSample = 16;
  5205. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5206. }
  5207. }
  5208. else { // channel == 1
  5209. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  5210. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5211. waveFormat.wBitsPerSample = 8;
  5212. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5213. }
  5214. else { // assume 16-bit is supported
  5215. waveFormat.wBitsPerSample = 16;
  5216. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5217. }
  5218. }
  5219. stream_.userFormat = format;
  5220. // Update wave format structure and buffer information.
  5221. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  5222. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  5223. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  5224. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  5225. while ( dsPointerLeadTime * 2U > dsBufferSize )
  5226. dsBufferSize *= 2;
  5227. // Setup the secondary DS buffer description.
  5228. DSCBUFFERDESC bufferDescription;
  5229. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  5230. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  5231. bufferDescription.dwFlags = 0;
  5232. bufferDescription.dwReserved = 0;
  5233. bufferDescription.dwBufferBytes = dsBufferSize;
  5234. bufferDescription.lpwfxFormat = &waveFormat;
  5235. // Create the capture buffer.
  5236. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  5237. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  5238. if ( FAILED( result ) ) {
  5239. input->Release();
  5240. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";
  5241. errorText_ = errorStream_.str();
  5242. return FAILURE;
  5243. }
  5244. // Get the buffer size ... might be different from what we specified.
  5245. DSCBCAPS dscbcaps;
  5246. dscbcaps.dwSize = sizeof( DSCBCAPS );
  5247. result = buffer->GetCaps( &dscbcaps );
  5248. if ( FAILED( result ) ) {
  5249. input->Release();
  5250. buffer->Release();
  5251. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  5252. errorText_ = errorStream_.str();
  5253. return FAILURE;
  5254. }
  5255. dsBufferSize = dscbcaps.dwBufferBytes;
  5256. // NOTE: We could have a problem here if this is a duplex stream
  5257. // and the play and capture hardware buffer sizes are different
  5258. // (I'm actually not sure if that is a problem or not).
  5259. // Currently, we are not verifying that.
  5260. // Lock the capture buffer
  5261. LPVOID audioPtr;
  5262. DWORD dataLen;
  5263. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  5264. if ( FAILED( result ) ) {
  5265. input->Release();
  5266. buffer->Release();
  5267. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";
  5268. errorText_ = errorStream_.str();
  5269. return FAILURE;
  5270. }
  5271. // Zero the buffer
  5272. ZeroMemory( audioPtr, dataLen );
  5273. // Unlock the buffer
  5274. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5275. if ( FAILED( result ) ) {
  5276. input->Release();
  5277. buffer->Release();
  5278. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";
  5279. errorText_ = errorStream_.str();
  5280. return FAILURE;
  5281. }
  5282. ohandle = (void *) input;
  5283. bhandle = (void *) buffer;
  5284. }
  5285. // Set various stream parameters
  5286. DsHandle *handle = 0;
  5287. stream_.nDeviceChannels[mode] = channels + firstChannel;
  5288. stream_.nUserChannels[mode] = channels;
  5289. stream_.bufferSize = *bufferSize;
  5290. stream_.channelOffset[mode] = firstChannel;
  5291. stream_.deviceInterleaved[mode] = true;
  5292. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  5293. else stream_.userInterleaved = true;
  5294. // Set flag for buffer conversion
  5295. stream_.doConvertBuffer[mode] = false;
  5296. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  5297. stream_.doConvertBuffer[mode] = true;
  5298. if (stream_.userFormat != stream_.deviceFormat[mode])
  5299. stream_.doConvertBuffer[mode] = true;
  5300. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  5301. stream_.nUserChannels[mode] > 1 )
  5302. stream_.doConvertBuffer[mode] = true;
  5303. // Allocate necessary internal buffers
  5304. long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  5305. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  5306. if ( stream_.userBuffer[mode] == NULL ) {
  5307. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  5308. goto error;
  5309. }
  5310. if ( stream_.doConvertBuffer[mode] ) {
  5311. bool makeBuffer = true;
  5312. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  5313. if ( mode == INPUT ) {
  5314. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  5315. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  5316. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  5317. }
  5318. }
  5319. if ( makeBuffer ) {
  5320. bufferBytes *= *bufferSize;
  5321. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  5322. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  5323. if ( stream_.deviceBuffer == NULL ) {
  5324. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  5325. goto error;
  5326. }
  5327. }
  5328. }
  5329. // Allocate our DsHandle structures for the stream.
  5330. if ( stream_.apiHandle == 0 ) {
  5331. try {
  5332. handle = new DsHandle;
  5333. }
  5334. catch ( std::bad_alloc& ) {
  5335. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  5336. goto error;
  5337. }
  5338. // Create a manual-reset event.
  5339. handle->condition = CreateEvent( NULL, // no security
  5340. TRUE, // manual-reset
  5341. FALSE, // non-signaled initially
  5342. NULL ); // unnamed
  5343. stream_.apiHandle = (void *) handle;
  5344. }
  5345. else
  5346. handle = (DsHandle *) stream_.apiHandle;
  5347. handle->id[mode] = ohandle;
  5348. handle->buffer[mode] = bhandle;
  5349. handle->dsBufferSize[mode] = dsBufferSize;
  5350. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  5351. stream_.device[mode] = device;
  5352. stream_.state = STREAM_STOPPED;
  5353. if ( stream_.mode == OUTPUT && mode == INPUT )
  5354. // We had already set up an output stream.
  5355. stream_.mode = DUPLEX;
  5356. else
  5357. stream_.mode = mode;
  5358. stream_.nBuffers = nBuffers;
  5359. stream_.sampleRate = sampleRate;
  5360. // Setup the buffer conversion information structure.
  5361. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  5362. // Setup the callback thread.
  5363. if ( stream_.callbackInfo.isRunning == false ) {
  5364. unsigned threadId;
  5365. stream_.callbackInfo.isRunning = true;
  5366. stream_.callbackInfo.object = (void *) this;
  5367. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  5368. &stream_.callbackInfo, 0, &threadId );
  5369. if ( stream_.callbackInfo.thread == 0 ) {
  5370. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  5371. goto error;
  5372. }
  5373. // Boost DS thread priority
  5374. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  5375. }
  5376. return SUCCESS;
  5377. error:
  5378. if ( handle ) {
  5379. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5380. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5381. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5382. if ( buffer ) buffer->Release();
  5383. object->Release();
  5384. }
  5385. if ( handle->buffer[1] ) {
  5386. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5387. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5388. if ( buffer ) buffer->Release();
  5389. object->Release();
  5390. }
  5391. CloseHandle( handle->condition );
  5392. delete handle;
  5393. stream_.apiHandle = 0;
  5394. }
  5395. for ( int i=0; i<2; i++ ) {
  5396. if ( stream_.userBuffer[i] ) {
  5397. free( stream_.userBuffer[i] );
  5398. stream_.userBuffer[i] = 0;
  5399. }
  5400. }
  5401. if ( stream_.deviceBuffer ) {
  5402. free( stream_.deviceBuffer );
  5403. stream_.deviceBuffer = 0;
  5404. }
  5405. stream_.state = STREAM_CLOSED;
  5406. return FAILURE;
  5407. }
  5408. void RtApiDs :: closeStream()
  5409. {
  5410. if ( stream_.state == STREAM_CLOSED ) {
  5411. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  5412. error( RtAudioError::WARNING );
  5413. return;
  5414. }
  5415. // Stop the callback thread.
  5416. stream_.callbackInfo.isRunning = false;
  5417. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  5418. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  5419. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5420. if ( handle ) {
  5421. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5422. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5423. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5424. if ( buffer ) {
  5425. buffer->Stop();
  5426. buffer->Release();
  5427. }
  5428. object->Release();
  5429. }
  5430. if ( handle->buffer[1] ) {
  5431. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5432. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5433. if ( buffer ) {
  5434. buffer->Stop();
  5435. buffer->Release();
  5436. }
  5437. object->Release();
  5438. }
  5439. CloseHandle( handle->condition );
  5440. delete handle;
  5441. stream_.apiHandle = 0;
  5442. }
  5443. for ( int i=0; i<2; i++ ) {
  5444. if ( stream_.userBuffer[i] ) {
  5445. free( stream_.userBuffer[i] );
  5446. stream_.userBuffer[i] = 0;
  5447. }
  5448. }
  5449. if ( stream_.deviceBuffer ) {
  5450. free( stream_.deviceBuffer );
  5451. stream_.deviceBuffer = 0;
  5452. }
  5453. stream_.mode = UNINITIALIZED;
  5454. stream_.state = STREAM_CLOSED;
  5455. }
  5456. void RtApiDs :: startStream()
  5457. {
  5458. verifyStream();
  5459. if ( stream_.state == STREAM_RUNNING ) {
  5460. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  5461. error( RtAudioError::WARNING );
  5462. return;
  5463. }
  5464. #if defined( HAVE_GETTIMEOFDAY )
  5465. gettimeofday( &stream_.lastTickTimestamp, NULL );
  5466. #endif
  5467. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5468. // Increase scheduler frequency on lesser windows (a side-effect of
  5469. // increasing timer accuracy). On greater windows (Win2K or later),
  5470. // this is already in effect.
  5471. timeBeginPeriod( 1 );
  5472. buffersRolling = false;
  5473. duplexPrerollBytes = 0;
  5474. if ( stream_.mode == DUPLEX ) {
  5475. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  5476. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  5477. }
  5478. HRESULT result = 0;
  5479. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5480. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5481. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  5482. if ( FAILED( result ) ) {
  5483. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  5484. errorText_ = errorStream_.str();
  5485. goto unlock;
  5486. }
  5487. }
  5488. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5489. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5490. result = buffer->Start( DSCBSTART_LOOPING );
  5491. if ( FAILED( result ) ) {
  5492. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  5493. errorText_ = errorStream_.str();
  5494. goto unlock;
  5495. }
  5496. }
  5497. handle->drainCounter = 0;
  5498. handle->internalDrain = false;
  5499. ResetEvent( handle->condition );
  5500. stream_.state = STREAM_RUNNING;
  5501. unlock:
  5502. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5503. }
  5504. void RtApiDs :: stopStream()
  5505. {
  5506. verifyStream();
  5507. if ( stream_.state == STREAM_STOPPED ) {
  5508. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  5509. error( RtAudioError::WARNING );
  5510. return;
  5511. }
  5512. HRESULT result = 0;
  5513. LPVOID audioPtr;
  5514. DWORD dataLen;
  5515. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5516. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5517. if ( handle->drainCounter == 0 ) {
  5518. handle->drainCounter = 2;
  5519. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  5520. }
  5521. stream_.state = STREAM_STOPPED;
  5522. MUTEX_LOCK( &stream_.mutex );
  5523. // Stop the buffer and clear memory
  5524. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5525. result = buffer->Stop();
  5526. if ( FAILED( result ) ) {
  5527. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  5528. errorText_ = errorStream_.str();
  5529. goto unlock;
  5530. }
  5531. // Lock the buffer and clear it so that if we start to play again,
  5532. // we won't have old data playing.
  5533. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  5534. if ( FAILED( result ) ) {
  5535. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
  5536. errorText_ = errorStream_.str();
  5537. goto unlock;
  5538. }
  5539. // Zero the DS buffer
  5540. ZeroMemory( audioPtr, dataLen );
  5541. // Unlock the DS buffer
  5542. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5543. if ( FAILED( result ) ) {
  5544. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  5545. errorText_ = errorStream_.str();
  5546. goto unlock;
  5547. }
  5548. // If we start playing again, we must begin at beginning of buffer.
  5549. handle->bufferPointer[0] = 0;
  5550. }
  5551. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5552. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5553. audioPtr = NULL;
  5554. dataLen = 0;
  5555. stream_.state = STREAM_STOPPED;
  5556. if ( stream_.mode != DUPLEX )
  5557. MUTEX_LOCK( &stream_.mutex );
  5558. result = buffer->Stop();
  5559. if ( FAILED( result ) ) {
  5560. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  5561. errorText_ = errorStream_.str();
  5562. goto unlock;
  5563. }
  5564. // Lock the buffer and clear it so that if we start to play again,
  5565. // we won't have old data playing.
  5566. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  5567. if ( FAILED( result ) ) {
  5568. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
  5569. errorText_ = errorStream_.str();
  5570. goto unlock;
  5571. }
  5572. // Zero the DS buffer
  5573. ZeroMemory( audioPtr, dataLen );
  5574. // Unlock the DS buffer
  5575. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5576. if ( FAILED( result ) ) {
  5577. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  5578. errorText_ = errorStream_.str();
  5579. goto unlock;
  5580. }
  5581. // If we start recording again, we must begin at beginning of buffer.
  5582. handle->bufferPointer[1] = 0;
  5583. }
  5584. unlock:
  5585. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  5586. MUTEX_UNLOCK( &stream_.mutex );
  5587. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5588. }
  5589. void RtApiDs :: abortStream()
  5590. {
  5591. verifyStream();
  5592. if ( stream_.state == STREAM_STOPPED ) {
  5593. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  5594. error( RtAudioError::WARNING );
  5595. return;
  5596. }
  5597. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5598. handle->drainCounter = 2;
  5599. stopStream();
  5600. }
  5601. void RtApiDs :: callbackEvent()
  5602. {
  5603. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
  5604. Sleep( 50 ); // sleep 50 milliseconds
  5605. return;
  5606. }
  5607. if ( stream_.state == STREAM_CLOSED ) {
  5608. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5609. error( RtAudioError::WARNING );
  5610. return;
  5611. }
  5612. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  5613. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5614. // Check if we were draining the stream and signal is finished.
  5615. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  5616. stream_.state = STREAM_STOPPING;
  5617. if ( handle->internalDrain == false )
  5618. SetEvent( handle->condition );
  5619. else
  5620. stopStream();
  5621. return;
  5622. }
  5623. // Invoke user callback to get fresh output data UNLESS we are
  5624. // draining stream.
  5625. if ( handle->drainCounter == 0 ) {
  5626. RtAudioCallback callback = (RtAudioCallback) info->callback;
  5627. double streamTime = getStreamTime();
  5628. RtAudioStreamStatus status = 0;
  5629. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  5630. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5631. handle->xrun[0] = false;
  5632. }
  5633. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  5634. status |= RTAUDIO_INPUT_OVERFLOW;
  5635. handle->xrun[1] = false;
  5636. }
  5637. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5638. stream_.bufferSize, streamTime, status, info->userData );
  5639. if ( cbReturnValue == 2 ) {
  5640. stream_.state = STREAM_STOPPING;
  5641. handle->drainCounter = 2;
  5642. abortStream();
  5643. return;
  5644. }
  5645. else if ( cbReturnValue == 1 ) {
  5646. handle->drainCounter = 1;
  5647. handle->internalDrain = true;
  5648. }
  5649. }
  5650. HRESULT result;
  5651. DWORD currentWritePointer, safeWritePointer;
  5652. DWORD currentReadPointer, safeReadPointer;
  5653. UINT nextWritePointer;
  5654. LPVOID buffer1 = NULL;
  5655. LPVOID buffer2 = NULL;
  5656. DWORD bufferSize1 = 0;
  5657. DWORD bufferSize2 = 0;
  5658. char *buffer;
  5659. long bufferBytes;
  5660. MUTEX_LOCK( &stream_.mutex );
  5661. if ( stream_.state == STREAM_STOPPED ) {
  5662. MUTEX_UNLOCK( &stream_.mutex );
  5663. return;
  5664. }
  5665. if ( buffersRolling == false ) {
  5666. if ( stream_.mode == DUPLEX ) {
  5667. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5668. // It takes a while for the devices to get rolling. As a result,
  5669. // there's no guarantee that the capture and write device pointers
  5670. // will move in lockstep. Wait here for both devices to start
  5671. // rolling, and then set our buffer pointers accordingly.
  5672. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  5673. // bytes later than the write buffer.
  5674. // Stub: a serious risk of having a pre-emptive scheduling round
  5675. // take place between the two GetCurrentPosition calls... but I'm
  5676. // really not sure how to solve the problem. Temporarily boost to
  5677. // Realtime priority, maybe; but I'm not sure what priority the
  5678. // DirectSound service threads run at. We *should* be roughly
  5679. // within a ms or so of correct.
  5680. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5681. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5682. DWORD startSafeWritePointer, startSafeReadPointer;
  5683. result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
  5684. if ( FAILED( result ) ) {
  5685. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5686. errorText_ = errorStream_.str();
  5687. MUTEX_UNLOCK( &stream_.mutex );
  5688. error( RtAudioError::SYSTEM_ERROR );
  5689. return;
  5690. }
  5691. result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
  5692. if ( FAILED( result ) ) {
  5693. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5694. errorText_ = errorStream_.str();
  5695. MUTEX_UNLOCK( &stream_.mutex );
  5696. error( RtAudioError::SYSTEM_ERROR );
  5697. return;
  5698. }
  5699. while ( true ) {
  5700. result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
  5701. if ( FAILED( result ) ) {
  5702. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5703. errorText_ = errorStream_.str();
  5704. MUTEX_UNLOCK( &stream_.mutex );
  5705. error( RtAudioError::SYSTEM_ERROR );
  5706. return;
  5707. }
  5708. result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
  5709. if ( FAILED( result ) ) {
  5710. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5711. errorText_ = errorStream_.str();
  5712. MUTEX_UNLOCK( &stream_.mutex );
  5713. error( RtAudioError::SYSTEM_ERROR );
  5714. return;
  5715. }
  5716. if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
  5717. Sleep( 1 );
  5718. }
  5719. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5720. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5721. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5722. handle->bufferPointer[1] = safeReadPointer;
  5723. }
  5724. else if ( stream_.mode == OUTPUT ) {
  5725. // Set the proper nextWritePosition after initial startup.
  5726. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5727. result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5728. if ( FAILED( result ) ) {
  5729. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5730. errorText_ = errorStream_.str();
  5731. MUTEX_UNLOCK( &stream_.mutex );
  5732. error( RtAudioError::SYSTEM_ERROR );
  5733. return;
  5734. }
  5735. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5736. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5737. }
  5738. buffersRolling = true;
  5739. }
  5740. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5741. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5742. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  5743. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5744. bufferBytes *= formatBytes( stream_.userFormat );
  5745. memset( stream_.userBuffer[0], 0, bufferBytes );
  5746. }
  5747. // Setup parameters and do buffer conversion if necessary.
  5748. if ( stream_.doConvertBuffer[0] ) {
  5749. buffer = stream_.deviceBuffer;
  5750. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5751. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  5752. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  5753. }
  5754. else {
  5755. buffer = stream_.userBuffer[0];
  5756. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5757. bufferBytes *= formatBytes( stream_.userFormat );
  5758. }
  5759. // No byte swapping necessary in DirectSound implementation.
  5760. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  5761. // unsigned. So, we need to convert our signed 8-bit data here to
  5762. // unsigned.
  5763. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  5764. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  5765. DWORD dsBufferSize = handle->dsBufferSize[0];
  5766. nextWritePointer = handle->bufferPointer[0];
  5767. DWORD endWrite, leadPointer;
  5768. while ( true ) {
  5769. // Find out where the read and "safe write" pointers are.
  5770. result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5771. if ( FAILED( result ) ) {
  5772. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5773. errorText_ = errorStream_.str();
  5774. MUTEX_UNLOCK( &stream_.mutex );
  5775. error( RtAudioError::SYSTEM_ERROR );
  5776. return;
  5777. }
  5778. // We will copy our output buffer into the region between
  5779. // safeWritePointer and leadPointer. If leadPointer is not
  5780. // beyond the next endWrite position, wait until it is.
  5781. leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
  5782. //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
  5783. if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
  5784. if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
  5785. endWrite = nextWritePointer + bufferBytes;
  5786. // Check whether the entire write region is behind the play pointer.
  5787. if ( leadPointer >= endWrite ) break;
  5788. // If we are here, then we must wait until the leadPointer advances
  5789. // beyond the end of our next write region. We use the
  5790. // Sleep() function to suspend operation until that happens.
  5791. double millis = ( endWrite - leadPointer ) * 1000.0;
  5792. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  5793. if ( millis < 1.0 ) millis = 1.0;
  5794. Sleep( (DWORD) millis );
  5795. }
  5796. if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
  5797. || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
  5798. // We've strayed into the forbidden zone ... resync the read pointer.
  5799. handle->xrun[0] = true;
  5800. nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
  5801. if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
  5802. handle->bufferPointer[0] = nextWritePointer;
  5803. endWrite = nextWritePointer + bufferBytes;
  5804. }
  5805. // Lock free space in the buffer
  5806. result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
  5807. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5808. if ( FAILED( result ) ) {
  5809. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  5810. errorText_ = errorStream_.str();
  5811. MUTEX_UNLOCK( &stream_.mutex );
  5812. error( RtAudioError::SYSTEM_ERROR );
  5813. return;
  5814. }
  5815. // Copy our buffer into the DS buffer
  5816. CopyMemory( buffer1, buffer, bufferSize1 );
  5817. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  5818. // Update our buffer offset and unlock sound buffer
  5819. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5820. if ( FAILED( result ) ) {
  5821. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  5822. errorText_ = errorStream_.str();
  5823. MUTEX_UNLOCK( &stream_.mutex );
  5824. error( RtAudioError::SYSTEM_ERROR );
  5825. return;
  5826. }
  5827. nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5828. handle->bufferPointer[0] = nextWritePointer;
  5829. }
  5830. // Don't bother draining input
  5831. if ( handle->drainCounter ) {
  5832. handle->drainCounter++;
  5833. goto unlock;
  5834. }
  5835. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5836. // Setup parameters.
  5837. if ( stream_.doConvertBuffer[1] ) {
  5838. buffer = stream_.deviceBuffer;
  5839. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  5840. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  5841. }
  5842. else {
  5843. buffer = stream_.userBuffer[1];
  5844. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  5845. bufferBytes *= formatBytes( stream_.userFormat );
  5846. }
  5847. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5848. long nextReadPointer = handle->bufferPointer[1];
  5849. DWORD dsBufferSize = handle->dsBufferSize[1];
  5850. // Find out where the write and "safe read" pointers are.
  5851. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5852. if ( FAILED( result ) ) {
  5853. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5854. errorText_ = errorStream_.str();
  5855. MUTEX_UNLOCK( &stream_.mutex );
  5856. error( RtAudioError::SYSTEM_ERROR );
  5857. return;
  5858. }
  5859. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5860. DWORD endRead = nextReadPointer + bufferBytes;
  5861. // Handling depends on whether we are INPUT or DUPLEX.
  5862. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  5863. // then a wait here will drag the write pointers into the forbidden zone.
  5864. //
  5865. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  5866. // it's in a safe position. This causes dropouts, but it seems to be the only
  5867. // practical way to sync up the read and write pointers reliably, given the
  5868. // the very complex relationship between phase and increment of the read and write
  5869. // pointers.
  5870. //
  5871. // In order to minimize audible dropouts in DUPLEX mode, we will
  5872. // provide a pre-roll period of 0.5 seconds in which we return
  5873. // zeros from the read buffer while the pointers sync up.
  5874. if ( stream_.mode == DUPLEX ) {
  5875. if ( safeReadPointer < endRead ) {
  5876. if ( duplexPrerollBytes <= 0 ) {
  5877. // Pre-roll time over. Be more agressive.
  5878. int adjustment = endRead-safeReadPointer;
  5879. handle->xrun[1] = true;
  5880. // Two cases:
  5881. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  5882. // and perform fine adjustments later.
  5883. // - small adjustments: back off by twice as much.
  5884. if ( adjustment >= 2*bufferBytes )
  5885. nextReadPointer = safeReadPointer-2*bufferBytes;
  5886. else
  5887. nextReadPointer = safeReadPointer-bufferBytes-adjustment;
  5888. if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5889. }
  5890. else {
  5891. // In pre=roll time. Just do it.
  5892. nextReadPointer = safeReadPointer - bufferBytes;
  5893. while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5894. }
  5895. endRead = nextReadPointer + bufferBytes;
  5896. }
  5897. }
  5898. else { // mode == INPUT
  5899. while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
  5900. // See comments for playback.
  5901. double millis = (endRead - safeReadPointer) * 1000.0;
  5902. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  5903. if ( millis < 1.0 ) millis = 1.0;
  5904. Sleep( (DWORD) millis );
  5905. // Wake up and find out where we are now.
  5906. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5907. if ( FAILED( result ) ) {
  5908. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5909. errorText_ = errorStream_.str();
  5910. MUTEX_UNLOCK( &stream_.mutex );
  5911. error( RtAudioError::SYSTEM_ERROR );
  5912. return;
  5913. }
  5914. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5915. }
  5916. }
  5917. // Lock free space in the buffer
  5918. result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
  5919. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5920. if ( FAILED( result ) ) {
  5921. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  5922. errorText_ = errorStream_.str();
  5923. MUTEX_UNLOCK( &stream_.mutex );
  5924. error( RtAudioError::SYSTEM_ERROR );
  5925. return;
  5926. }
  5927. if ( duplexPrerollBytes <= 0 ) {
  5928. // Copy our buffer into the DS buffer
  5929. CopyMemory( buffer, buffer1, bufferSize1 );
  5930. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  5931. }
  5932. else {
  5933. memset( buffer, 0, bufferSize1 );
  5934. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  5935. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  5936. }
  5937. // Update our buffer offset and unlock sound buffer
  5938. nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5939. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5940. if ( FAILED( result ) ) {
  5941. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  5942. errorText_ = errorStream_.str();
  5943. MUTEX_UNLOCK( &stream_.mutex );
  5944. error( RtAudioError::SYSTEM_ERROR );
  5945. return;
  5946. }
  5947. handle->bufferPointer[1] = nextReadPointer;
  5948. // No byte swapping necessary in DirectSound implementation.
  5949. // If necessary, convert 8-bit data from unsigned to signed.
  5950. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  5951. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  5952. // Do buffer conversion if necessary.
  5953. if ( stream_.doConvertBuffer[1] )
  5954. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5955. }
  5956. unlock:
  5957. MUTEX_UNLOCK( &stream_.mutex );
  5958. RtApi::tickStreamTime();
  5959. }
  5960. // Definitions for utility functions and callbacks
  5961. // specific to the DirectSound implementation.
  5962. static unsigned __stdcall callbackHandler( void *ptr )
  5963. {
  5964. CallbackInfo *info = (CallbackInfo *) ptr;
  5965. RtApiDs *object = (RtApiDs *) info->object;
  5966. bool* isRunning = &info->isRunning;
  5967. while ( *isRunning == true ) {
  5968. object->callbackEvent();
  5969. }
  5970. _endthreadex( 0 );
  5971. return 0;
  5972. }
  5973. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  5974. LPCTSTR description,
  5975. LPCTSTR /*module*/,
  5976. LPVOID lpContext )
  5977. {
  5978. struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
  5979. std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
  5980. HRESULT hr;
  5981. bool validDevice = false;
  5982. if ( probeInfo.isInput == true ) {
  5983. DSCCAPS caps;
  5984. LPDIRECTSOUNDCAPTURE object;
  5985. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  5986. if ( hr != DS_OK ) return TRUE;
  5987. caps.dwSize = sizeof(caps);
  5988. hr = object->GetCaps( &caps );
  5989. if ( hr == DS_OK ) {
  5990. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  5991. validDevice = true;
  5992. }
  5993. object->Release();
  5994. }
  5995. else {
  5996. DSCAPS caps;
  5997. LPDIRECTSOUND object;
  5998. hr = DirectSoundCreate( lpguid, &object, NULL );
  5999. if ( hr != DS_OK ) return TRUE;
  6000. caps.dwSize = sizeof(caps);
  6001. hr = object->GetCaps( &caps );
  6002. if ( hr == DS_OK ) {
  6003. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  6004. validDevice = true;
  6005. }
  6006. object->Release();
  6007. }
  6008. // If good device, then save its name and guid.
  6009. std::string name = convertCharPointerToStdString( description );
  6010. //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
  6011. if ( lpguid == NULL )
  6012. name = "Default Device";
  6013. if ( validDevice ) {
  6014. for ( unsigned int i=0; i<dsDevices.size(); i++ ) {
  6015. if ( dsDevices[i].name == name ) {
  6016. dsDevices[i].found = true;
  6017. if ( probeInfo.isInput ) {
  6018. dsDevices[i].id[1] = lpguid;
  6019. dsDevices[i].validId[1] = true;
  6020. }
  6021. else {
  6022. dsDevices[i].id[0] = lpguid;
  6023. dsDevices[i].validId[0] = true;
  6024. }
  6025. return TRUE;
  6026. }
  6027. }
  6028. DsDevice device;
  6029. device.name = name;
  6030. device.found = true;
  6031. if ( probeInfo.isInput ) {
  6032. device.id[1] = lpguid;
  6033. device.validId[1] = true;
  6034. }
  6035. else {
  6036. device.id[0] = lpguid;
  6037. device.validId[0] = true;
  6038. }
  6039. dsDevices.push_back( device );
  6040. }
  6041. return TRUE;
  6042. }
  6043. static const char* getErrorString( int code )
  6044. {
  6045. switch ( code ) {
  6046. case DSERR_ALLOCATED:
  6047. return "Already allocated";
  6048. case DSERR_CONTROLUNAVAIL:
  6049. return "Control unavailable";
  6050. case DSERR_INVALIDPARAM:
  6051. return "Invalid parameter";
  6052. case DSERR_INVALIDCALL:
  6053. return "Invalid call";
  6054. case DSERR_GENERIC:
  6055. return "Generic error";
  6056. case DSERR_PRIOLEVELNEEDED:
  6057. return "Priority level needed";
  6058. case DSERR_OUTOFMEMORY:
  6059. return "Out of memory";
  6060. case DSERR_BADFORMAT:
  6061. return "The sample rate or the channel format is not supported";
  6062. case DSERR_UNSUPPORTED:
  6063. return "Not supported";
  6064. case DSERR_NODRIVER:
  6065. return "No driver";
  6066. case DSERR_ALREADYINITIALIZED:
  6067. return "Already initialized";
  6068. case DSERR_NOAGGREGATION:
  6069. return "No aggregation";
  6070. case DSERR_BUFFERLOST:
  6071. return "Buffer lost";
  6072. case DSERR_OTHERAPPHASPRIO:
  6073. return "Another application already has priority";
  6074. case DSERR_UNINITIALIZED:
  6075. return "Uninitialized";
  6076. default:
  6077. return "DirectSound unknown error";
  6078. }
  6079. }
  6080. //******************** End of __WINDOWS_DS__ *********************//
  6081. #endif
  6082. #if defined(__LINUX_ALSA__)
  6083. #include <alsa/asoundlib.h>
  6084. #include <unistd.h>
  6085. // A structure to hold various information related to the ALSA API
  6086. // implementation.
  6087. struct AlsaHandle {
  6088. snd_pcm_t *handles[2];
  6089. bool synchronized;
  6090. bool xrun[2];
  6091. pthread_cond_t runnable_cv;
  6092. bool runnable;
  6093. AlsaHandle()
  6094. :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
  6095. };
  6096. static void *alsaCallbackHandler( void * ptr );
  6097. RtApiAlsa :: RtApiAlsa()
  6098. {
  6099. // Nothing to do here.
  6100. }
  6101. RtApiAlsa :: ~RtApiAlsa()
  6102. {
  6103. if ( stream_.state != STREAM_CLOSED ) closeStream();
  6104. }
  6105. unsigned int RtApiAlsa :: getDeviceCount( void )
  6106. {
  6107. unsigned nDevices = 0;
  6108. int result, subdevice, card;
  6109. char name[64];
  6110. snd_ctl_t *handle = 0;
  6111. // Count cards and devices
  6112. card = -1;
  6113. snd_card_next( &card );