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.

10613 lines
363KB

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