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.

10637 lines
364KB

  1. /************************************************************************/
  2. /*! \class RtAudio
  3. \brief Realtime audio i/o C++ classes.
  4. RtAudio provides a common API (Application Programming Interface)
  5. for realtime audio input/output across Linux (native ALSA, Jack,
  6. and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
  7. (DirectSound, ASIO and WASAPI) operating systems.
  8. RtAudio GitHub site: https://github.com/thestk/rtaudio
  9. RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
  10. RtAudio: realtime audio i/o C++ classes
  11. Copyright (c) 2001-2019 Gary P. Scavone
  12. Permission is hereby granted, free of charge, to any person
  13. obtaining a copy of this software and associated documentation files
  14. (the "Software"), to deal in the Software without restriction,
  15. including without limitation the rights to use, copy, modify, merge,
  16. publish, distribute, sublicense, and/or sell copies of the Software,
  17. and to permit persons to whom the Software is furnished to do so,
  18. subject to the following conditions:
  19. The above copyright notice and this permission notice shall be
  20. included in all copies or substantial portions of the Software.
  21. Any person wishing to distribute modifications to the Software is
  22. asked to send the modifications to the original developer so that
  23. they can be incorporated into the canonical version. This is,
  24. however, not a binding provision of this license.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  28. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  29. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  30. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. /************************************************************************/
  34. // RtAudio: Version 5.1.0
  35. #include "RtAudio.h"
  36. #include <iostream>
  37. #include <cstdlib>
  38. #include <cstring>
  39. #include <climits>
  40. #include <cmath>
  41. #include <algorithm>
  42. // Static variable definitions.
  43. const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
  44. const unsigned int RtApi::SAMPLE_RATES[] = {
  45. 4000, 5512, 8000, 9600, 11025, 16000, 22050,
  46. 32000, 44100, 48000, 88200, 96000, 176400, 192000
  47. };
  48. #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
  49. #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
  50. #define MUTEX_DESTROY(A) DeleteCriticalSection(A)
  51. #define MUTEX_LOCK(A) EnterCriticalSection(A)
  52. #define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
  53. #include "tchar.h"
  54. static std::string convertCharPointerToStdString(const char *text)
  55. {
  56. return std::string(text);
  57. }
  58. static std::string convertCharPointerToStdString(const wchar_t *text)
  59. {
  60. int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);
  61. std::string s( length-1, '\0' );
  62. WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);
  63. return s;
  64. }
  65. #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
  66. // pthread API
  67. #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
  68. #define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
  69. #define MUTEX_LOCK(A) pthread_mutex_lock(A)
  70. #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
  71. #else
  72. #define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions
  73. #define MUTEX_DESTROY(A) abs(*A) // dummy definitions
  74. #endif
  75. // *************************************************** //
  76. //
  77. // RtAudio definitions.
  78. //
  79. // *************************************************** //
  80. std::string RtAudio :: getVersion( void )
  81. {
  82. return RTAUDIO_VERSION;
  83. }
  84. // Define API names and display names.
  85. // Must be in same order as API enum.
  86. extern "C" {
  87. const char* rtaudio_api_names[][2] = {
  88. { "unspecified" , "Unknown" },
  89. { "alsa" , "ALSA" },
  90. { "pulse" , "Pulse" },
  91. { "oss" , "OpenSoundSystem" },
  92. { "jack" , "Jack" },
  93. { "core" , "CoreAudio" },
  94. { "wasapi" , "WASAPI" },
  95. { "asio" , "ASIO" },
  96. { "ds" , "DirectSound" },
  97. { "dummy" , "Dummy" },
  98. };
  99. const unsigned int rtaudio_num_api_names =
  100. sizeof(rtaudio_api_names)/sizeof(rtaudio_api_names[0]);
  101. // The order here will control the order of RtAudio's API search in
  102. // the constructor.
  103. extern "C" const RtAudio::Api rtaudio_compiled_apis[] = {
  104. #if defined(__UNIX_JACK__)
  105. RtAudio::UNIX_JACK,
  106. #endif
  107. #if defined(__LINUX_PULSE__)
  108. RtAudio::LINUX_PULSE,
  109. #endif
  110. #if defined(__LINUX_ALSA__)
  111. RtAudio::LINUX_ALSA,
  112. #endif
  113. #if defined(__LINUX_OSS__)
  114. RtAudio::LINUX_OSS,
  115. #endif
  116. #if defined(__WINDOWS_ASIO__)
  117. RtAudio::WINDOWS_ASIO,
  118. #endif
  119. #if defined(__WINDOWS_WASAPI__)
  120. RtAudio::WINDOWS_WASAPI,
  121. #endif
  122. #if defined(__WINDOWS_DS__)
  123. RtAudio::WINDOWS_DS,
  124. #endif
  125. #if defined(__MACOSX_CORE__)
  126. RtAudio::MACOSX_CORE,
  127. #endif
  128. #if defined(__RTAUDIO_DUMMY__)
  129. RtAudio::RTAUDIO_DUMMY,
  130. #endif
  131. RtAudio::UNSPECIFIED,
  132. };
  133. extern "C" const unsigned int rtaudio_num_compiled_apis =
  134. sizeof(rtaudio_compiled_apis)/sizeof(rtaudio_compiled_apis[0])-1;
  135. }
  136. // This is a compile-time check that rtaudio_num_api_names == RtAudio::NUM_APIS.
  137. // If the build breaks here, check that they match.
  138. template<bool b> class StaticAssert { private: StaticAssert() {} };
  139. template<> class StaticAssert<true>{ public: StaticAssert() {} };
  140. class StaticAssertions { StaticAssertions() {
  141. StaticAssert<rtaudio_num_api_names == RtAudio::NUM_APIS>();
  142. }};
  143. void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis )
  144. {
  145. apis = std::vector<RtAudio::Api>(rtaudio_compiled_apis,
  146. rtaudio_compiled_apis + rtaudio_num_compiled_apis);
  147. }
  148. std::string RtAudio :: getApiName( RtAudio::Api api )
  149. {
  150. if (api < 0 || api >= RtAudio::NUM_APIS)
  151. return "";
  152. return rtaudio_api_names[api][0];
  153. }
  154. std::string RtAudio :: getApiDisplayName( RtAudio::Api api )
  155. {
  156. if (api < 0 || api >= RtAudio::NUM_APIS)
  157. return "Unknown";
  158. return rtaudio_api_names[api][1];
  159. }
  160. RtAudio::Api RtAudio :: getCompiledApiByName( const std::string &name )
  161. {
  162. unsigned int i=0;
  163. for (i = 0; i < rtaudio_num_compiled_apis; ++i)
  164. if (name == rtaudio_api_names[rtaudio_compiled_apis[i]][0])
  165. return rtaudio_compiled_apis[i];
  166. return RtAudio::UNSPECIFIED;
  167. }
  168. void RtAudio :: openRtApi( RtAudio::Api api )
  169. {
  170. if ( rtapi_ )
  171. delete rtapi_;
  172. rtapi_ = 0;
  173. #if defined(__UNIX_JACK__)
  174. if ( api == UNIX_JACK )
  175. rtapi_ = new RtApiJack();
  176. #endif
  177. #if defined(__LINUX_ALSA__)
  178. if ( api == LINUX_ALSA )
  179. rtapi_ = new RtApiAlsa();
  180. #endif
  181. #if defined(__LINUX_PULSE__)
  182. if ( api == LINUX_PULSE )
  183. rtapi_ = new RtApiPulse();
  184. #endif
  185. #if defined(__LINUX_OSS__)
  186. if ( api == LINUX_OSS )
  187. rtapi_ = new RtApiOss();
  188. #endif
  189. #if defined(__WINDOWS_ASIO__)
  190. if ( api == WINDOWS_ASIO )
  191. rtapi_ = new RtApiAsio();
  192. #endif
  193. #if defined(__WINDOWS_WASAPI__)
  194. if ( api == WINDOWS_WASAPI )
  195. rtapi_ = new RtApiWasapi();
  196. #endif
  197. #if defined(__WINDOWS_DS__)
  198. if ( api == WINDOWS_DS )
  199. rtapi_ = new RtApiDs();
  200. #endif
  201. #if defined(__MACOSX_CORE__)
  202. if ( api == MACOSX_CORE )
  203. rtapi_ = new RtApiCore();
  204. #endif
  205. #if defined(__RTAUDIO_DUMMY__)
  206. if ( api == RTAUDIO_DUMMY )
  207. rtapi_ = new RtApiDummy();
  208. #endif
  209. }
  210. RtAudio :: RtAudio( RtAudio::Api api )
  211. {
  212. rtapi_ = 0;
  213. if ( api != UNSPECIFIED ) {
  214. // Attempt to open the specified API.
  215. openRtApi( api );
  216. if ( rtapi_ ) return;
  217. // No compiled support for specified API value. Issue a debug
  218. // warning and continue as if no API was specified.
  219. std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;
  220. }
  221. // Iterate through the compiled APIs and return as soon as we find
  222. // one with at least one device or we reach the end of the list.
  223. std::vector< RtAudio::Api > apis;
  224. getCompiledApi( apis );
  225. for ( unsigned int i=0; i<apis.size(); i++ ) {
  226. openRtApi( apis[i] );
  227. if ( rtapi_ && rtapi_->getDeviceCount() ) break;
  228. }
  229. if ( rtapi_ ) return;
  230. // It should not be possible to get here because the preprocessor
  231. // definition __RTAUDIO_DUMMY__ is automatically defined if no
  232. // API-specific definitions are passed to the compiler. But just in
  233. // case something weird happens, we'll thow an error.
  234. std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";
  235. throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );
  236. }
  237. RtAudio :: ~RtAudio()
  238. {
  239. if ( rtapi_ )
  240. delete rtapi_;
  241. }
  242. void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
  243. RtAudio::StreamParameters *inputParameters,
  244. RtAudioFormat format, unsigned int sampleRate,
  245. unsigned int *bufferFrames,
  246. RtAudioCallback callback, void *userData,
  247. RtAudio::StreamOptions *options,
  248. RtAudioErrorCallback errorCallback )
  249. {
  250. return rtapi_->openStream( outputParameters, inputParameters, format,
  251. sampleRate, bufferFrames, callback,
  252. userData, options, errorCallback );
  253. }
  254. // *************************************************** //
  255. //
  256. // Public RtApi definitions (see end of file for
  257. // private or protected utility functions).
  258. //
  259. // *************************************************** //
  260. RtApi :: RtApi()
  261. {
  262. stream_.state = STREAM_CLOSED;
  263. stream_.mode = UNINITIALIZED;
  264. stream_.apiHandle = 0;
  265. stream_.userBuffer[0] = 0;
  266. stream_.userBuffer[1] = 0;
  267. MUTEX_INITIALIZE( &stream_.mutex );
  268. showWarnings_ = true;
  269. firstErrorOccurred_ = false;
  270. }
  271. RtApi :: ~RtApi()
  272. {
  273. MUTEX_DESTROY( &stream_.mutex );
  274. }
  275. void RtApi :: openStream( RtAudio::StreamParameters *oParams,
  276. RtAudio::StreamParameters *iParams,
  277. RtAudioFormat format, unsigned int sampleRate,
  278. unsigned int *bufferFrames,
  279. RtAudioCallback callback, void *userData,
  280. RtAudio::StreamOptions *options,
  281. RtAudioErrorCallback errorCallback )
  282. {
  283. if ( stream_.state != STREAM_CLOSED ) {
  284. errorText_ = "RtApi::openStream: a stream is already open!";
  285. error( RtAudioError::INVALID_USE );
  286. return;
  287. }
  288. // Clear stream information potentially left from a previously open stream.
  289. clearStreamInfo();
  290. if ( oParams && oParams->nChannels < 1 ) {
  291. errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
  292. error( RtAudioError::INVALID_USE );
  293. return;
  294. }
  295. if ( iParams && iParams->nChannels < 1 ) {
  296. errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
  297. error( RtAudioError::INVALID_USE );
  298. return;
  299. }
  300. if ( oParams == NULL && iParams == NULL ) {
  301. errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
  302. error( RtAudioError::INVALID_USE );
  303. return;
  304. }
  305. if ( formatBytes(format) == 0 ) {
  306. errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
  307. error( RtAudioError::INVALID_USE );
  308. return;
  309. }
  310. unsigned int nDevices = getDeviceCount();
  311. unsigned int oChannels = 0;
  312. if ( oParams ) {
  313. oChannels = oParams->nChannels;
  314. if ( oParams->deviceId >= nDevices ) {
  315. errorText_ = "RtApi::openStream: output device parameter value is invalid.";
  316. error( RtAudioError::INVALID_USE );
  317. return;
  318. }
  319. }
  320. unsigned int iChannels = 0;
  321. if ( iParams ) {
  322. iChannels = iParams->nChannels;
  323. if ( iParams->deviceId >= nDevices ) {
  324. errorText_ = "RtApi::openStream: input device parameter value is invalid.";
  325. error( RtAudioError::INVALID_USE );
  326. return;
  327. }
  328. }
  329. bool result;
  330. if ( oChannels > 0 ) {
  331. result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
  332. sampleRate, format, bufferFrames, options );
  333. if ( result == false ) {
  334. error( RtAudioError::SYSTEM_ERROR );
  335. return;
  336. }
  337. }
  338. if ( iChannels > 0 ) {
  339. result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
  340. sampleRate, format, bufferFrames, options );
  341. if ( result == false ) {
  342. if ( oChannels > 0 ) closeStream();
  343. error( RtAudioError::SYSTEM_ERROR );
  344. return;
  345. }
  346. }
  347. stream_.callbackInfo.callback = (void *) callback;
  348. stream_.callbackInfo.userData = userData;
  349. stream_.callbackInfo.errorCallback = (void *) errorCallback;
  350. if ( options ) options->numberOfBuffers = stream_.nBuffers;
  351. stream_.state = STREAM_STOPPED;
  352. }
  353. unsigned int RtApi :: getDefaultInputDevice( void )
  354. {
  355. // Should be implemented in subclasses if possible.
  356. return 0;
  357. }
  358. unsigned int RtApi :: getDefaultOutputDevice( void )
  359. {
  360. // Should be implemented in subclasses if possible.
  361. return 0;
  362. }
  363. void RtApi :: closeStream( void )
  364. {
  365. // MUST be implemented in subclasses!
  366. return;
  367. }
  368. bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
  369. unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
  370. RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
  371. RtAudio::StreamOptions * /*options*/ )
  372. {
  373. // MUST be implemented in subclasses!
  374. return FAILURE;
  375. }
  376. void RtApi :: tickStreamTime( void )
  377. {
  378. // Subclasses that do not provide their own implementation of
  379. // getStreamTime should call this function once per buffer I/O to
  380. // provide basic stream time support.
  381. stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
  382. #if defined( HAVE_GETTIMEOFDAY )
  383. gettimeofday( &stream_.lastTickTimestamp, NULL );
  384. #endif
  385. }
  386. long RtApi :: getStreamLatency( void )
  387. {
  388. verifyStream();
  389. long totalLatency = 0;
  390. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  391. totalLatency = stream_.latency[0];
  392. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  393. totalLatency += stream_.latency[1];
  394. return totalLatency;
  395. }
  396. double RtApi :: getStreamTime( void )
  397. {
  398. verifyStream();
  399. #if defined( HAVE_GETTIMEOFDAY )
  400. // Return a very accurate estimate of the stream time by
  401. // adding in the elapsed time since the last tick.
  402. struct timeval then;
  403. struct timeval now;
  404. if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
  405. return stream_.streamTime;
  406. gettimeofday( &now, NULL );
  407. then = stream_.lastTickTimestamp;
  408. return stream_.streamTime +
  409. ((now.tv_sec + 0.000001 * now.tv_usec) -
  410. (then.tv_sec + 0.000001 * then.tv_usec));
  411. #else
  412. return stream_.streamTime;
  413. #endif
  414. }
  415. void RtApi :: setStreamTime( double time )
  416. {
  417. verifyStream();
  418. if ( time >= 0.0 )
  419. stream_.streamTime = time;
  420. #if defined( HAVE_GETTIMEOFDAY )
  421. gettimeofday( &stream_.lastTickTimestamp, NULL );
  422. #endif
  423. }
  424. unsigned int RtApi :: getStreamSampleRate( void )
  425. {
  426. verifyStream();
  427. return stream_.sampleRate;
  428. }
  429. // *************************************************** //
  430. //
  431. // OS/API-specific methods.
  432. //
  433. // *************************************************** //
  434. #if defined(__MACOSX_CORE__)
  435. // The OS X CoreAudio API is designed to use a separate callback
  436. // procedure for each of its audio devices. A single RtAudio duplex
  437. // stream using two different devices is supported here, though it
  438. // cannot be guaranteed to always behave correctly because we cannot
  439. // synchronize these two callbacks.
  440. //
  441. // A property listener is installed for over/underrun information.
  442. // However, no functionality is currently provided to allow property
  443. // listeners to trigger user handlers because it is unclear what could
  444. // be done if a critical stream parameter (buffer size, sample rate,
  445. // device disconnect) notification arrived. The listeners entail
  446. // quite a bit of extra code and most likely, a user program wouldn't
  447. // be prepared for the result anyway. However, we do provide a flag
  448. // to the client callback function to inform of an over/underrun.
  449. // A structure to hold various information related to the CoreAudio API
  450. // implementation.
  451. struct CoreHandle {
  452. AudioDeviceID id[2]; // device ids
  453. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  454. AudioDeviceIOProcID procId[2];
  455. #endif
  456. UInt32 iStream[2]; // device stream index (or first if using multiple)
  457. UInt32 nStreams[2]; // number of streams to use
  458. bool xrun[2];
  459. char *deviceBuffer;
  460. pthread_cond_t condition;
  461. int drainCounter; // Tracks callback counts when draining
  462. bool internalDrain; // Indicates if stop is initiated from callback or not.
  463. CoreHandle()
  464. :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  465. };
  466. RtApiCore:: RtApiCore()
  467. {
  468. #if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )
  469. // This is a largely undocumented but absolutely necessary
  470. // requirement starting with OS-X 10.6. If not called, queries and
  471. // updates to various audio device properties are not handled
  472. // correctly.
  473. CFRunLoopRef theRunLoop = NULL;
  474. AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,
  475. kAudioObjectPropertyScopeGlobal,
  476. kAudioObjectPropertyElementMaster };
  477. OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  478. if ( result != noErr ) {
  479. errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
  480. error( RtAudioError::WARNING );
  481. }
  482. #endif
  483. }
  484. RtApiCore :: ~RtApiCore()
  485. {
  486. // The subclass destructor gets called before the base class
  487. // destructor, so close an existing stream before deallocating
  488. // apiDeviceId memory.
  489. if ( stream_.state != STREAM_CLOSED ) closeStream();
  490. }
  491. unsigned int RtApiCore :: getDeviceCount( void )
  492. {
  493. // Find out how many audio devices there are, if any.
  494. UInt32 dataSize;
  495. AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  496. OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );
  497. if ( result != noErr ) {
  498. errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
  499. error( RtAudioError::WARNING );
  500. return 0;
  501. }
  502. return dataSize / sizeof( AudioDeviceID );
  503. }
  504. unsigned int RtApiCore :: getDefaultInputDevice( void )
  505. {
  506. unsigned int nDevices = getDeviceCount();
  507. if ( nDevices <= 1 ) return 0;
  508. AudioDeviceID id;
  509. UInt32 dataSize = sizeof( AudioDeviceID );
  510. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  511. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  512. if ( result != noErr ) {
  513. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
  514. error( RtAudioError::WARNING );
  515. return 0;
  516. }
  517. dataSize *= nDevices;
  518. AudioDeviceID deviceList[ nDevices ];
  519. property.mSelector = kAudioHardwarePropertyDevices;
  520. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  521. if ( result != noErr ) {
  522. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
  523. error( RtAudioError::WARNING );
  524. return 0;
  525. }
  526. for ( unsigned int i=0; i<nDevices; i++ )
  527. if ( id == deviceList[i] ) return i;
  528. errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
  529. error( RtAudioError::WARNING );
  530. return 0;
  531. }
  532. unsigned int RtApiCore :: getDefaultOutputDevice( void )
  533. {
  534. unsigned int nDevices = getDeviceCount();
  535. if ( nDevices <= 1 ) return 0;
  536. AudioDeviceID id;
  537. UInt32 dataSize = sizeof( AudioDeviceID );
  538. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  539. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  540. if ( result != noErr ) {
  541. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
  542. error( RtAudioError::WARNING );
  543. return 0;
  544. }
  545. dataSize = sizeof( AudioDeviceID ) * nDevices;
  546. AudioDeviceID deviceList[ nDevices ];
  547. property.mSelector = kAudioHardwarePropertyDevices;
  548. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  549. if ( result != noErr ) {
  550. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
  551. error( RtAudioError::WARNING );
  552. return 0;
  553. }
  554. for ( unsigned int i=0; i<nDevices; i++ )
  555. if ( id == deviceList[i] ) return i;
  556. errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
  557. error( RtAudioError::WARNING );
  558. return 0;
  559. }
  560. RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
  561. {
  562. RtAudio::DeviceInfo info;
  563. info.probed = false;
  564. // Get device ID
  565. unsigned int nDevices = getDeviceCount();
  566. if ( nDevices == 0 ) {
  567. errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
  568. error( RtAudioError::INVALID_USE );
  569. return info;
  570. }
  571. if ( device >= nDevices ) {
  572. errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
  573. error( RtAudioError::INVALID_USE );
  574. return info;
  575. }
  576. AudioDeviceID deviceList[ nDevices ];
  577. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  578. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  579. kAudioObjectPropertyScopeGlobal,
  580. kAudioObjectPropertyElementMaster };
  581. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  582. 0, NULL, &dataSize, (void *) &deviceList );
  583. if ( result != noErr ) {
  584. errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
  585. error( RtAudioError::WARNING );
  586. return info;
  587. }
  588. AudioDeviceID id = deviceList[ device ];
  589. // Get the device name.
  590. info.name.erase();
  591. CFStringRef cfname;
  592. dataSize = sizeof( CFStringRef );
  593. property.mSelector = kAudioObjectPropertyManufacturer;
  594. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  595. if ( result != noErr ) {
  596. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
  597. errorText_ = errorStream_.str();
  598. error( RtAudioError::WARNING );
  599. return info;
  600. }
  601. //const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  602. int length = CFStringGetLength(cfname);
  603. char *mname = (char *)malloc(length * 3 + 1);
  604. #if defined( UNICODE ) || defined( _UNICODE )
  605. CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
  606. #else
  607. CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
  608. #endif
  609. info.name.append( (const char *)mname, strlen(mname) );
  610. info.name.append( ": " );
  611. CFRelease( cfname );
  612. free(mname);
  613. property.mSelector = kAudioObjectPropertyName;
  614. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  615. if ( result != noErr ) {
  616. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
  617. errorText_ = errorStream_.str();
  618. error( RtAudioError::WARNING );
  619. return info;
  620. }
  621. //const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  622. length = CFStringGetLength(cfname);
  623. char *name = (char *)malloc(length * 3 + 1);
  624. #if defined( UNICODE ) || defined( _UNICODE )
  625. CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
  626. #else
  627. CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
  628. #endif
  629. info.name.append( (const char *)name, strlen(name) );
  630. CFRelease( cfname );
  631. free(name);
  632. // Get the output stream "configuration".
  633. AudioBufferList *bufferList = nil;
  634. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  635. property.mScope = kAudioDevicePropertyScopeOutput;
  636. // property.mElement = kAudioObjectPropertyElementWildcard;
  637. dataSize = 0;
  638. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  639. if ( result != noErr || dataSize == 0 ) {
  640. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";
  641. errorText_ = errorStream_.str();
  642. error( RtAudioError::WARNING );
  643. return info;
  644. }
  645. // Allocate the AudioBufferList.
  646. bufferList = (AudioBufferList *) malloc( dataSize );
  647. if ( bufferList == NULL ) {
  648. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
  649. error( RtAudioError::WARNING );
  650. return info;
  651. }
  652. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  653. if ( result != noErr || dataSize == 0 ) {
  654. free( bufferList );
  655. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";
  656. errorText_ = errorStream_.str();
  657. error( RtAudioError::WARNING );
  658. return info;
  659. }
  660. // Get output channel information.
  661. unsigned int i, nStreams = bufferList->mNumberBuffers;
  662. for ( i=0; i<nStreams; i++ )
  663. info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
  664. free( bufferList );
  665. // Get the input stream "configuration".
  666. property.mScope = kAudioDevicePropertyScopeInput;
  667. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  668. if ( result != noErr || dataSize == 0 ) {
  669. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";
  670. errorText_ = errorStream_.str();
  671. error( RtAudioError::WARNING );
  672. return info;
  673. }
  674. // Allocate the AudioBufferList.
  675. bufferList = (AudioBufferList *) malloc( dataSize );
  676. if ( bufferList == NULL ) {
  677. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
  678. error( RtAudioError::WARNING );
  679. return info;
  680. }
  681. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  682. if (result != noErr || dataSize == 0) {
  683. free( bufferList );
  684. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";
  685. errorText_ = errorStream_.str();
  686. error( RtAudioError::WARNING );
  687. return info;
  688. }
  689. // Get input channel information.
  690. nStreams = bufferList->mNumberBuffers;
  691. for ( i=0; i<nStreams; i++ )
  692. info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
  693. free( bufferList );
  694. // If device opens for both playback and capture, we determine the channels.
  695. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  696. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  697. // Probe the device sample rates.
  698. bool isInput = false;
  699. if ( info.outputChannels == 0 ) isInput = true;
  700. // Determine the supported sample rates.
  701. property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  702. if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;
  703. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  704. if ( result != kAudioHardwareNoError || dataSize == 0 ) {
  705. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
  706. errorText_ = errorStream_.str();
  707. error( RtAudioError::WARNING );
  708. return info;
  709. }
  710. UInt32 nRanges = dataSize / sizeof( AudioValueRange );
  711. AudioValueRange rangeList[ nRanges ];
  712. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );
  713. if ( result != kAudioHardwareNoError ) {
  714. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
  715. errorText_ = errorStream_.str();
  716. error( RtAudioError::WARNING );
  717. return info;
  718. }
  719. // The sample rate reporting mechanism is a bit of a mystery. It
  720. // seems that it can either return individual rates or a range of
  721. // rates. I assume that if the min / max range values are the same,
  722. // then that represents a single supported rate and if the min / max
  723. // range values are different, the device supports an arbitrary
  724. // range of values (though there might be multiple ranges, so we'll
  725. // use the most conservative range).
  726. Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
  727. bool haveValueRange = false;
  728. info.sampleRates.clear();
  729. for ( UInt32 i=0; i<nRanges; i++ ) {
  730. if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {
  731. unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;
  732. info.sampleRates.push_back( tmpSr );
  733. if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )
  734. info.preferredSampleRate = tmpSr;
  735. } else {
  736. haveValueRange = true;
  737. if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;
  738. if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;
  739. }
  740. }
  741. if ( haveValueRange ) {
  742. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  743. if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {
  744. info.sampleRates.push_back( SAMPLE_RATES[k] );
  745. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  746. info.preferredSampleRate = SAMPLE_RATES[k];
  747. }
  748. }
  749. }
  750. // Sort and remove any redundant values
  751. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  752. info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );
  753. if ( info.sampleRates.size() == 0 ) {
  754. errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
  755. errorText_ = errorStream_.str();
  756. error( RtAudioError::WARNING );
  757. return info;
  758. }
  759. // CoreAudio always uses 32-bit floating point data for PCM streams.
  760. // Thus, any other "physical" formats supported by the device are of
  761. // no interest to the client.
  762. info.nativeFormats = RTAUDIO_FLOAT32;
  763. if ( info.outputChannels > 0 )
  764. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  765. if ( info.inputChannels > 0 )
  766. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  767. info.probed = true;
  768. return info;
  769. }
  770. static OSStatus callbackHandler( AudioDeviceID inDevice,
  771. const AudioTimeStamp* /*inNow*/,
  772. const AudioBufferList* inInputData,
  773. const AudioTimeStamp* /*inInputTime*/,
  774. AudioBufferList* outOutputData,
  775. const AudioTimeStamp* /*inOutputTime*/,
  776. void* infoPointer )
  777. {
  778. CallbackInfo *info = (CallbackInfo *) infoPointer;
  779. RtApiCore *object = (RtApiCore *) info->object;
  780. if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
  781. return kAudioHardwareUnspecifiedError;
  782. else
  783. return kAudioHardwareNoError;
  784. }
  785. static OSStatus xrunListener( AudioObjectID /*inDevice*/,
  786. UInt32 nAddresses,
  787. const AudioObjectPropertyAddress properties[],
  788. void* handlePointer )
  789. {
  790. CoreHandle *handle = (CoreHandle *) handlePointer;
  791. for ( UInt32 i=0; i<nAddresses; i++ ) {
  792. if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {
  793. if ( properties[i].mScope == kAudioDevicePropertyScopeInput )
  794. handle->xrun[1] = true;
  795. else
  796. handle->xrun[0] = true;
  797. }
  798. }
  799. return kAudioHardwareNoError;
  800. }
  801. static OSStatus rateListener( AudioObjectID inDevice,
  802. UInt32 /*nAddresses*/,
  803. const AudioObjectPropertyAddress /*properties*/[],
  804. void* ratePointer )
  805. {
  806. Float64 *rate = (Float64 *) ratePointer;
  807. UInt32 dataSize = sizeof( Float64 );
  808. AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,
  809. kAudioObjectPropertyScopeGlobal,
  810. kAudioObjectPropertyElementMaster };
  811. AudioObjectGetPropertyData( inDevice, &property, 0, NULL, &dataSize, rate );
  812. return kAudioHardwareNoError;
  813. }
  814. bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  815. unsigned int firstChannel, unsigned int sampleRate,
  816. RtAudioFormat format, unsigned int *bufferSize,
  817. RtAudio::StreamOptions *options )
  818. {
  819. // Get device ID
  820. unsigned int nDevices = getDeviceCount();
  821. if ( nDevices == 0 ) {
  822. // This should not happen because a check is made before this function is called.
  823. errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
  824. return FAILURE;
  825. }
  826. if ( device >= nDevices ) {
  827. // This should not happen because a check is made before this function is called.
  828. errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
  829. return FAILURE;
  830. }
  831. AudioDeviceID deviceList[ nDevices ];
  832. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  833. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  834. kAudioObjectPropertyScopeGlobal,
  835. kAudioObjectPropertyElementMaster };
  836. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  837. 0, NULL, &dataSize, (void *) &deviceList );
  838. if ( result != noErr ) {
  839. errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
  840. return FAILURE;
  841. }
  842. AudioDeviceID id = deviceList[ device ];
  843. // Setup for stream mode.
  844. bool isInput = false;
  845. if ( mode == INPUT ) {
  846. isInput = true;
  847. property.mScope = kAudioDevicePropertyScopeInput;
  848. }
  849. else
  850. property.mScope = kAudioDevicePropertyScopeOutput;
  851. // Get the stream "configuration".
  852. AudioBufferList *bufferList = nil;
  853. dataSize = 0;
  854. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  855. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  856. if ( result != noErr || dataSize == 0 ) {
  857. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";
  858. errorText_ = errorStream_.str();
  859. return FAILURE;
  860. }
  861. // Allocate the AudioBufferList.
  862. bufferList = (AudioBufferList *) malloc( dataSize );
  863. if ( bufferList == NULL ) {
  864. errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
  865. return FAILURE;
  866. }
  867. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  868. if (result != noErr || dataSize == 0) {
  869. free( bufferList );
  870. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";
  871. errorText_ = errorStream_.str();
  872. return FAILURE;
  873. }
  874. // Search for one or more streams that contain the desired number of
  875. // channels. CoreAudio devices can have an arbitrary number of
  876. // streams and each stream can have an arbitrary number of channels.
  877. // For each stream, a single buffer of interleaved samples is
  878. // provided. RtAudio prefers the use of one stream of interleaved
  879. // data or multiple consecutive single-channel streams. However, we
  880. // now support multiple consecutive multi-channel streams of
  881. // interleaved data as well.
  882. UInt32 iStream, offsetCounter = firstChannel;
  883. UInt32 nStreams = bufferList->mNumberBuffers;
  884. bool monoMode = false;
  885. bool foundStream = false;
  886. // First check that the device supports the requested number of
  887. // channels.
  888. UInt32 deviceChannels = 0;
  889. for ( iStream=0; iStream<nStreams; iStream++ )
  890. deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
  891. if ( deviceChannels < ( channels + firstChannel ) ) {
  892. free( bufferList );
  893. errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";
  894. errorText_ = errorStream_.str();
  895. return FAILURE;
  896. }
  897. // Look for a single stream meeting our needs.
  898. UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;
  899. for ( iStream=0; iStream<nStreams; iStream++ ) {
  900. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  901. if ( streamChannels >= channels + offsetCounter ) {
  902. firstStream = iStream;
  903. channelOffset = offsetCounter;
  904. foundStream = true;
  905. break;
  906. }
  907. if ( streamChannels > offsetCounter ) break;
  908. offsetCounter -= streamChannels;
  909. }
  910. // If we didn't find a single stream above, then we should be able
  911. // to meet the channel specification with multiple streams.
  912. if ( foundStream == false ) {
  913. monoMode = true;
  914. offsetCounter = firstChannel;
  915. for ( iStream=0; iStream<nStreams; iStream++ ) {
  916. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  917. if ( streamChannels > offsetCounter ) break;
  918. offsetCounter -= streamChannels;
  919. }
  920. firstStream = iStream;
  921. channelOffset = offsetCounter;
  922. Int32 channelCounter = channels + offsetCounter - streamChannels;
  923. if ( streamChannels > 1 ) monoMode = false;
  924. while ( channelCounter > 0 ) {
  925. streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
  926. if ( streamChannels > 1 ) monoMode = false;
  927. channelCounter -= streamChannels;
  928. streamCount++;
  929. }
  930. }
  931. free( bufferList );
  932. // Determine the buffer size.
  933. AudioValueRange bufferRange;
  934. dataSize = sizeof( AudioValueRange );
  935. property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  936. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange );
  937. if ( result != noErr ) {
  938. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ").";
  939. errorText_ = errorStream_.str();
  940. return FAILURE;
  941. }
  942. if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  943. else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMaximum;
  944. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  945. // Set the buffer size. For multiple streams, I'm assuming we only
  946. // need to make this setting for the master channel.
  947. UInt32 theSize = (UInt32) *bufferSize;
  948. dataSize = sizeof( UInt32 );
  949. property.mSelector = kAudioDevicePropertyBufferFrameSize;
  950. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize );
  951. if ( result != noErr ) {
  952. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ").";
  953. errorText_ = errorStream_.str();
  954. return FAILURE;
  955. }
  956. // If attempting to setup a duplex stream, the bufferSize parameter
  957. // MUST be the same in both directions!
  958. *bufferSize = theSize;
  959. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  960. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";
  961. errorText_ = errorStream_.str();
  962. return FAILURE;
  963. }
  964. stream_.bufferSize = *bufferSize;
  965. stream_.nBuffers = 1;
  966. // Try to set "hog" mode ... it's not clear to me this is working.
  967. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) {
  968. pid_t hog_pid;
  969. dataSize = sizeof( hog_pid );
  970. property.mSelector = kAudioDevicePropertyHogMode;
  971. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid );
  972. if ( result != noErr ) {
  973. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!";
  974. errorText_ = errorStream_.str();
  975. return FAILURE;
  976. }
  977. if ( hog_pid != getpid() ) {
  978. hog_pid = getpid();
  979. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid );
  980. if ( result != noErr ) {
  981. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";
  982. errorText_ = errorStream_.str();
  983. return FAILURE;
  984. }
  985. }
  986. }
  987. // Check and if necessary, change the sample rate for the device.
  988. Float64 nominalRate;
  989. dataSize = sizeof( Float64 );
  990. property.mSelector = kAudioDevicePropertyNominalSampleRate;
  991. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );
  992. if ( result != noErr ) {
  993. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";
  994. errorText_ = errorStream_.str();
  995. return FAILURE;
  996. }
  997. // Only change the sample rate if off by more than 1 Hz.
  998. if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) {
  999. // Set a property listener for the sample rate change
  1000. Float64 reportedRate = 0.0;
  1001. AudioObjectPropertyAddress tmp = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  1002. result = AudioObjectAddPropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1003. if ( result != noErr ) {
  1004. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate property listener for device (" << device << ").";
  1005. errorText_ = errorStream_.str();
  1006. return FAILURE;
  1007. }
  1008. nominalRate = (Float64) sampleRate;
  1009. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );
  1010. if ( result != noErr ) {
  1011. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1012. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ").";
  1013. errorText_ = errorStream_.str();
  1014. return FAILURE;
  1015. }
  1016. // Now wait until the reported nominal rate is what we just set.
  1017. UInt32 microCounter = 0;
  1018. while ( reportedRate != nominalRate ) {
  1019. microCounter += 5000;
  1020. if ( microCounter > 5000000 ) break;
  1021. usleep( 5000 );
  1022. }
  1023. // Remove the property listener.
  1024. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1025. if ( microCounter > 5000000 ) {
  1026. errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ").";
  1027. errorText_ = errorStream_.str();
  1028. return FAILURE;
  1029. }
  1030. }
  1031. // Now set the stream format for all streams. Also, check the
  1032. // physical format of the device and change that if necessary.
  1033. AudioStreamBasicDescription description;
  1034. dataSize = sizeof( AudioStreamBasicDescription );
  1035. property.mSelector = kAudioStreamPropertyVirtualFormat;
  1036. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  1037. if ( result != noErr ) {
  1038. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ").";
  1039. errorText_ = errorStream_.str();
  1040. return FAILURE;
  1041. }
  1042. // Set the sample rate and data format id. However, only make the
  1043. // change if the sample rate is not within 1.0 of the desired
  1044. // rate and the format is not linear pcm.
  1045. bool updateFormat = false;
  1046. if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) {
  1047. description.mSampleRate = (Float64) sampleRate;
  1048. updateFormat = true;
  1049. }
  1050. if ( description.mFormatID != kAudioFormatLinearPCM ) {
  1051. description.mFormatID = kAudioFormatLinearPCM;
  1052. updateFormat = true;
  1053. }
  1054. if ( updateFormat ) {
  1055. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description );
  1056. if ( result != noErr ) {
  1057. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ").";
  1058. errorText_ = errorStream_.str();
  1059. return FAILURE;
  1060. }
  1061. }
  1062. // Now check the physical format.
  1063. property.mSelector = kAudioStreamPropertyPhysicalFormat;
  1064. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  1065. if ( result != noErr ) {
  1066. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ").";
  1067. errorText_ = errorStream_.str();
  1068. return FAILURE;
  1069. }
  1070. //std::cout << "Current physical stream format:" << std::endl;
  1071. //std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl;
  1072. //std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1073. //std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl;
  1074. //std::cout << " sample rate = " << description.mSampleRate << std::endl;
  1075. if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) {
  1076. description.mFormatID = kAudioFormatLinearPCM;
  1077. //description.mSampleRate = (Float64) sampleRate;
  1078. AudioStreamBasicDescription testDescription = description;
  1079. UInt32 formatFlags;
  1080. // We'll try higher bit rates first and then work our way down.
  1081. std::vector< std::pair<UInt32, UInt32> > physicalFormats;
  1082. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;
  1083. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1084. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1085. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1086. physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) ); // 24-bit packed
  1087. formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh );
  1088. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low
  1089. formatFlags |= kAudioFormatFlagIsAlignedHigh;
  1090. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high
  1091. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1092. physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) );
  1093. physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) );
  1094. bool setPhysicalFormat = false;
  1095. for( unsigned int i=0; i<physicalFormats.size(); i++ ) {
  1096. testDescription = description;
  1097. testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first;
  1098. testDescription.mFormatFlags = physicalFormats[i].second;
  1099. if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) )
  1100. testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame;
  1101. else
  1102. testDescription.mBytesPerFrame = testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame;
  1103. testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;
  1104. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription );
  1105. if ( result == noErr ) {
  1106. setPhysicalFormat = true;
  1107. //std::cout << "Updated physical stream format:" << std::endl;
  1108. //std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;
  1109. //std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1110. //std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;
  1111. //std::cout << " sample rate = " << testDescription.mSampleRate << std::endl;
  1112. break;
  1113. }
  1114. }
  1115. if ( !setPhysicalFormat ) {
  1116. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ").";
  1117. errorText_ = errorStream_.str();
  1118. return FAILURE;
  1119. }
  1120. } // done setting virtual/physical formats.
  1121. // Get the stream / device latency.
  1122. UInt32 latency;
  1123. dataSize = sizeof( UInt32 );
  1124. property.mSelector = kAudioDevicePropertyLatency;
  1125. if ( AudioObjectHasProperty( id, &property ) == true ) {
  1126. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency );
  1127. if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;
  1128. else {
  1129. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";
  1130. errorText_ = errorStream_.str();
  1131. error( RtAudioError::WARNING );
  1132. }
  1133. }
  1134. // Byte-swapping: According to AudioHardware.h, the stream data will
  1135. // always be presented in native-endian format, so we should never
  1136. // need to byte swap.
  1137. stream_.doByteSwap[mode] = false;
  1138. // From the CoreAudio documentation, PCM data must be supplied as
  1139. // 32-bit floats.
  1140. stream_.userFormat = format;
  1141. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1142. if ( streamCount == 1 )
  1143. stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
  1144. else // multiple streams
  1145. stream_.nDeviceChannels[mode] = channels;
  1146. stream_.nUserChannels[mode] = channels;
  1147. stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
  1148. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1149. else stream_.userInterleaved = true;
  1150. stream_.deviceInterleaved[mode] = true;
  1151. if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;
  1152. // Set flags for buffer conversion.
  1153. stream_.doConvertBuffer[mode] = false;
  1154. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1155. stream_.doConvertBuffer[mode] = true;
  1156. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  1157. stream_.doConvertBuffer[mode] = true;
  1158. if ( streamCount == 1 ) {
  1159. if ( stream_.nUserChannels[mode] > 1 &&
  1160. stream_.userInterleaved != stream_.deviceInterleaved[mode] )
  1161. stream_.doConvertBuffer[mode] = true;
  1162. }
  1163. else if ( monoMode && stream_.userInterleaved )
  1164. stream_.doConvertBuffer[mode] = true;
  1165. // Allocate our CoreHandle structure for the stream.
  1166. CoreHandle *handle = 0;
  1167. if ( stream_.apiHandle == 0 ) {
  1168. try {
  1169. handle = new CoreHandle;
  1170. }
  1171. catch ( std::bad_alloc& ) {
  1172. errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
  1173. goto error;
  1174. }
  1175. if ( pthread_cond_init( &handle->condition, NULL ) ) {
  1176. errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
  1177. goto error;
  1178. }
  1179. stream_.apiHandle = (void *) handle;
  1180. }
  1181. else
  1182. handle = (CoreHandle *) stream_.apiHandle;
  1183. handle->iStream[mode] = firstStream;
  1184. handle->nStreams[mode] = streamCount;
  1185. handle->id[mode] = id;
  1186. // Allocate necessary internal buffers.
  1187. unsigned long bufferBytes;
  1188. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  1189. // stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1190. stream_.userBuffer[mode] = (char *) malloc( bufferBytes * sizeof(char) );
  1191. memset( stream_.userBuffer[mode], 0, bufferBytes * sizeof(char) );
  1192. if ( stream_.userBuffer[mode] == NULL ) {
  1193. errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
  1194. goto error;
  1195. }
  1196. // If possible, we will make use of the CoreAudio stream buffers as
  1197. // "device buffers". However, we can't do this if using multiple
  1198. // streams.
  1199. if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {
  1200. bool makeBuffer = true;
  1201. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  1202. if ( mode == INPUT ) {
  1203. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1204. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1205. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  1206. }
  1207. }
  1208. if ( makeBuffer ) {
  1209. bufferBytes *= *bufferSize;
  1210. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1211. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1212. if ( stream_.deviceBuffer == NULL ) {
  1213. errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
  1214. goto error;
  1215. }
  1216. }
  1217. }
  1218. stream_.sampleRate = sampleRate;
  1219. stream_.device[mode] = device;
  1220. stream_.state = STREAM_STOPPED;
  1221. stream_.callbackInfo.object = (void *) this;
  1222. // Setup the buffer conversion information structure.
  1223. if ( stream_.doConvertBuffer[mode] ) {
  1224. if ( streamCount > 1 ) setConvertInfo( mode, 0 );
  1225. else setConvertInfo( mode, channelOffset );
  1226. }
  1227. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device )
  1228. // Only one callback procedure per device.
  1229. stream_.mode = DUPLEX;
  1230. else {
  1231. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1232. result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );
  1233. #else
  1234. // deprecated in favor of AudioDeviceCreateIOProcID()
  1235. result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
  1236. #endif
  1237. if ( result != noErr ) {
  1238. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";
  1239. errorText_ = errorStream_.str();
  1240. goto error;
  1241. }
  1242. if ( stream_.mode == OUTPUT && mode == INPUT )
  1243. stream_.mode = DUPLEX;
  1244. else
  1245. stream_.mode = mode;
  1246. }
  1247. // Setup the device property listener for over/underload.
  1248. property.mSelector = kAudioDeviceProcessorOverload;
  1249. property.mScope = kAudioObjectPropertyScopeGlobal;
  1250. result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );
  1251. return SUCCESS;
  1252. error:
  1253. if ( handle ) {
  1254. pthread_cond_destroy( &handle->condition );
  1255. delete handle;
  1256. stream_.apiHandle = 0;
  1257. }
  1258. for ( int i=0; i<2; i++ ) {
  1259. if ( stream_.userBuffer[i] ) {
  1260. free( stream_.userBuffer[i] );
  1261. stream_.userBuffer[i] = 0;
  1262. }
  1263. }
  1264. if ( stream_.deviceBuffer ) {
  1265. free( stream_.deviceBuffer );
  1266. stream_.deviceBuffer = 0;
  1267. }
  1268. stream_.state = STREAM_CLOSED;
  1269. return FAILURE;
  1270. }
  1271. void RtApiCore :: closeStream( void )
  1272. {
  1273. if ( stream_.state == STREAM_CLOSED ) {
  1274. errorText_ = "RtApiCore::closeStream(): no open stream to close!";
  1275. error( RtAudioError::WARNING );
  1276. return;
  1277. }
  1278. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1279. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1280. if (handle) {
  1281. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1282. kAudioObjectPropertyScopeGlobal,
  1283. kAudioObjectPropertyElementMaster };
  1284. property.mSelector = kAudioDeviceProcessorOverload;
  1285. property.mScope = kAudioObjectPropertyScopeGlobal;
  1286. if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {
  1287. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1288. error( RtAudioError::WARNING );
  1289. }
  1290. }
  1291. if ( stream_.state == STREAM_RUNNING )
  1292. AudioDeviceStop( handle->id[0], callbackHandler );
  1293. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1294. AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );
  1295. #else
  1296. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1297. AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );
  1298. #endif
  1299. }
  1300. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1301. if (handle) {
  1302. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1303. kAudioObjectPropertyScopeGlobal,
  1304. kAudioObjectPropertyElementMaster };
  1305. property.mSelector = kAudioDeviceProcessorOverload;
  1306. property.mScope = kAudioObjectPropertyScopeGlobal;
  1307. if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {
  1308. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1309. error( RtAudioError::WARNING );
  1310. }
  1311. }
  1312. if ( stream_.state == STREAM_RUNNING )
  1313. AudioDeviceStop( handle->id[1], callbackHandler );
  1314. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1315. AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );
  1316. #else
  1317. // deprecated in favor of AudioDeviceDestroyIOProcID()
  1318. AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );
  1319. #endif
  1320. }
  1321. for ( int i=0; i<2; i++ ) {
  1322. if ( stream_.userBuffer[i] ) {
  1323. free( stream_.userBuffer[i] );
  1324. stream_.userBuffer[i] = 0;
  1325. }
  1326. }
  1327. if ( stream_.deviceBuffer ) {
  1328. free( stream_.deviceBuffer );
  1329. stream_.deviceBuffer = 0;
  1330. }
  1331. // Destroy pthread condition variable.
  1332. pthread_cond_destroy( &handle->condition );
  1333. delete handle;
  1334. stream_.apiHandle = 0;
  1335. stream_.mode = UNINITIALIZED;
  1336. stream_.state = STREAM_CLOSED;
  1337. }
  1338. void RtApiCore :: startStream( void )
  1339. {
  1340. verifyStream();
  1341. if ( stream_.state == STREAM_RUNNING ) {
  1342. errorText_ = "RtApiCore::startStream(): the stream is already running!";
  1343. error( RtAudioError::WARNING );
  1344. return;
  1345. }
  1346. #if defined( HAVE_GETTIMEOFDAY )
  1347. gettimeofday( &stream_.lastTickTimestamp, NULL );
  1348. #endif
  1349. OSStatus result = noErr;
  1350. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1351. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1352. result = AudioDeviceStart( handle->id[0], callbackHandler );
  1353. if ( result != noErr ) {
  1354. errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ").";
  1355. errorText_ = errorStream_.str();
  1356. goto unlock;
  1357. }
  1358. }
  1359. if ( stream_.mode == INPUT ||
  1360. ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1361. result = AudioDeviceStart( handle->id[1], callbackHandler );
  1362. if ( result != noErr ) {
  1363. errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";
  1364. errorText_ = errorStream_.str();
  1365. goto unlock;
  1366. }
  1367. }
  1368. handle->drainCounter = 0;
  1369. handle->internalDrain = false;
  1370. stream_.state = STREAM_RUNNING;
  1371. unlock:
  1372. if ( result == noErr ) return;
  1373. error( RtAudioError::SYSTEM_ERROR );
  1374. }
  1375. void RtApiCore :: stopStream( void )
  1376. {
  1377. verifyStream();
  1378. if ( stream_.state == STREAM_STOPPED ) {
  1379. errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
  1380. error( RtAudioError::WARNING );
  1381. return;
  1382. }
  1383. OSStatus result = noErr;
  1384. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1385. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1386. if ( handle->drainCounter == 0 ) {
  1387. handle->drainCounter = 2;
  1388. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  1389. }
  1390. result = AudioDeviceStop( handle->id[0], callbackHandler );
  1391. if ( result != noErr ) {
  1392. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";
  1393. errorText_ = errorStream_.str();
  1394. goto unlock;
  1395. }
  1396. }
  1397. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1398. result = AudioDeviceStop( handle->id[1], callbackHandler );
  1399. if ( result != noErr ) {
  1400. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";
  1401. errorText_ = errorStream_.str();
  1402. goto unlock;
  1403. }
  1404. }
  1405. stream_.state = STREAM_STOPPED;
  1406. unlock:
  1407. if ( result == noErr ) return;
  1408. error( RtAudioError::SYSTEM_ERROR );
  1409. }
  1410. void RtApiCore :: abortStream( void )
  1411. {
  1412. verifyStream();
  1413. if ( stream_.state == STREAM_STOPPED ) {
  1414. errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
  1415. error( RtAudioError::WARNING );
  1416. return;
  1417. }
  1418. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1419. handle->drainCounter = 2;
  1420. stopStream();
  1421. }
  1422. // This function will be called by a spawned thread when the user
  1423. // callback function signals that the stream should be stopped or
  1424. // aborted. It is better to handle it this way because the
  1425. // callbackEvent() function probably should return before the AudioDeviceStop()
  1426. // function is called.
  1427. static void *coreStopStream( void *ptr )
  1428. {
  1429. CallbackInfo *info = (CallbackInfo *) ptr;
  1430. RtApiCore *object = (RtApiCore *) info->object;
  1431. object->stopStream();
  1432. pthread_exit( NULL );
  1433. }
  1434. bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
  1435. const AudioBufferList *inBufferList,
  1436. const AudioBufferList *outBufferList )
  1437. {
  1438. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  1439. if ( stream_.state == STREAM_CLOSED ) {
  1440. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  1441. error( RtAudioError::WARNING );
  1442. return FAILURE;
  1443. }
  1444. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  1445. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1446. // Check if we were draining the stream and signal is finished.
  1447. if ( handle->drainCounter > 3 ) {
  1448. ThreadHandle threadId;
  1449. stream_.state = STREAM_STOPPING;
  1450. if ( handle->internalDrain == true )
  1451. pthread_create( &threadId, NULL, coreStopStream, info );
  1452. else // external call to stopStream()
  1453. pthread_cond_signal( &handle->condition );
  1454. return SUCCESS;
  1455. }
  1456. AudioDeviceID outputDevice = handle->id[0];
  1457. // Invoke user callback to get fresh output data UNLESS we are
  1458. // draining stream or duplex mode AND the input/output devices are
  1459. // different AND this function is called for the input device.
  1460. if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {
  1461. RtAudioCallback callback = (RtAudioCallback) info->callback;
  1462. double streamTime = getStreamTime();
  1463. RtAudioStreamStatus status = 0;
  1464. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  1465. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  1466. handle->xrun[0] = false;
  1467. }
  1468. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  1469. status |= RTAUDIO_INPUT_OVERFLOW;
  1470. handle->xrun[1] = false;
  1471. }
  1472. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  1473. stream_.bufferSize, streamTime, status, info->userData );
  1474. if ( cbReturnValue == 2 ) {
  1475. stream_.state = STREAM_STOPPING;
  1476. handle->drainCounter = 2;
  1477. abortStream();
  1478. return SUCCESS;
  1479. }
  1480. else if ( cbReturnValue == 1 ) {
  1481. handle->drainCounter = 1;
  1482. handle->internalDrain = true;
  1483. }
  1484. }
  1485. if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {
  1486. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  1487. if ( handle->nStreams[0] == 1 ) {
  1488. memset( outBufferList->mBuffers[handle->iStream[0]].mData,
  1489. 0,
  1490. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1491. }
  1492. else { // fill multiple streams with zeros
  1493. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1494. memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1495. 0,
  1496. outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );
  1497. }
  1498. }
  1499. }
  1500. else if ( handle->nStreams[0] == 1 ) {
  1501. if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer
  1502. convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,
  1503. stream_.userBuffer[0], stream_.convertInfo[0] );
  1504. }
  1505. else { // copy from user buffer
  1506. memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,
  1507. stream_.userBuffer[0],
  1508. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1509. }
  1510. }
  1511. else { // fill multiple streams
  1512. Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];
  1513. if ( stream_.doConvertBuffer[0] ) {
  1514. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  1515. inBuffer = (Float32 *) stream_.deviceBuffer;
  1516. }
  1517. if ( stream_.deviceInterleaved[0] == false ) { // mono mode
  1518. UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
  1519. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1520. memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1521. (void *)&inBuffer[i*stream_.bufferSize], bufferBytes );
  1522. }
  1523. }
  1524. else { // fill multiple multi-channel streams with interleaved data
  1525. UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
  1526. Float32 *out, *in;
  1527. bool inInterleaved = ( stream_.userInterleaved ) ? true : false;
  1528. UInt32 inChannels = stream_.nUserChannels[0];
  1529. if ( stream_.doConvertBuffer[0] ) {
  1530. inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1531. inChannels = stream_.nDeviceChannels[0];
  1532. }
  1533. if ( inInterleaved ) inOffset = 1;
  1534. else inOffset = stream_.bufferSize;
  1535. channelsLeft = inChannels;
  1536. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1537. in = inBuffer;
  1538. out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;
  1539. streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;
  1540. outJump = 0;
  1541. // Account for possible channel offset in first stream
  1542. if ( i == 0 && stream_.channelOffset[0] > 0 ) {
  1543. streamChannels -= stream_.channelOffset[0];
  1544. outJump = stream_.channelOffset[0];
  1545. out += outJump;
  1546. }
  1547. // Account for possible unfilled channels at end of the last stream
  1548. if ( streamChannels > channelsLeft ) {
  1549. outJump = streamChannels - channelsLeft;
  1550. streamChannels = channelsLeft;
  1551. }
  1552. // Determine input buffer offsets and skips
  1553. if ( inInterleaved ) {
  1554. inJump = inChannels;
  1555. in += inChannels - channelsLeft;
  1556. }
  1557. else {
  1558. inJump = 1;
  1559. in += (inChannels - channelsLeft) * inOffset;
  1560. }
  1561. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1562. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1563. *out++ = in[j*inOffset];
  1564. }
  1565. out += outJump;
  1566. in += inJump;
  1567. }
  1568. channelsLeft -= streamChannels;
  1569. }
  1570. }
  1571. }
  1572. }
  1573. // Don't bother draining input
  1574. if ( handle->drainCounter ) {
  1575. handle->drainCounter++;
  1576. goto unlock;
  1577. }
  1578. AudioDeviceID inputDevice;
  1579. inputDevice = handle->id[1];
  1580. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {
  1581. if ( handle->nStreams[1] == 1 ) {
  1582. if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer
  1583. convertBuffer( stream_.userBuffer[1],
  1584. (char *) inBufferList->mBuffers[handle->iStream[1]].mData,
  1585. stream_.convertInfo[1] );
  1586. }
  1587. else { // copy to user buffer
  1588. memcpy( stream_.userBuffer[1],
  1589. inBufferList->mBuffers[handle->iStream[1]].mData,
  1590. inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );
  1591. }
  1592. }
  1593. else { // read from multiple streams
  1594. Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];
  1595. if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;
  1596. if ( stream_.deviceInterleaved[1] == false ) { // mono mode
  1597. UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
  1598. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1599. memcpy( (void *)&outBuffer[i*stream_.bufferSize],
  1600. inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );
  1601. }
  1602. }
  1603. else { // read from multiple multi-channel streams
  1604. UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
  1605. Float32 *out, *in;
  1606. bool outInterleaved = ( stream_.userInterleaved ) ? true : false;
  1607. UInt32 outChannels = stream_.nUserChannels[1];
  1608. if ( stream_.doConvertBuffer[1] ) {
  1609. outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1610. outChannels = stream_.nDeviceChannels[1];
  1611. }
  1612. if ( outInterleaved ) outOffset = 1;
  1613. else outOffset = stream_.bufferSize;
  1614. channelsLeft = outChannels;
  1615. for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {
  1616. out = outBuffer;
  1617. in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;
  1618. streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;
  1619. inJump = 0;
  1620. // Account for possible channel offset in first stream
  1621. if ( i == 0 && stream_.channelOffset[1] > 0 ) {
  1622. streamChannels -= stream_.channelOffset[1];
  1623. inJump = stream_.channelOffset[1];
  1624. in += inJump;
  1625. }
  1626. // Account for possible unread channels at end of the last stream
  1627. if ( streamChannels > channelsLeft ) {
  1628. inJump = streamChannels - channelsLeft;
  1629. streamChannels = channelsLeft;
  1630. }
  1631. // Determine output buffer offsets and skips
  1632. if ( outInterleaved ) {
  1633. outJump = outChannels;
  1634. out += outChannels - channelsLeft;
  1635. }
  1636. else {
  1637. outJump = 1;
  1638. out += (outChannels - channelsLeft) * outOffset;
  1639. }
  1640. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1641. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1642. out[j*outOffset] = *in++;
  1643. }
  1644. out += outJump;
  1645. in += inJump;
  1646. }
  1647. channelsLeft -= streamChannels;
  1648. }
  1649. }
  1650. if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer
  1651. convertBuffer( stream_.userBuffer[1],
  1652. stream_.deviceBuffer,
  1653. stream_.convertInfo[1] );
  1654. }
  1655. }
  1656. }
  1657. unlock:
  1658. //MUTEX_UNLOCK( &stream_.mutex );
  1659. // Make sure to only tick duplex stream time once if using two devices
  1660. if ( stream_.mode != DUPLEX || (stream_.mode == DUPLEX && handle->id[0] != handle->id[1] && deviceId == handle->id[0] ) )
  1661. RtApi::tickStreamTime();
  1662. return SUCCESS;
  1663. }
  1664. const char* RtApiCore :: getErrorCode( OSStatus code )
  1665. {
  1666. switch( code ) {
  1667. case kAudioHardwareNotRunningError:
  1668. return "kAudioHardwareNotRunningError";
  1669. case kAudioHardwareUnspecifiedError:
  1670. return "kAudioHardwareUnspecifiedError";
  1671. case kAudioHardwareUnknownPropertyError:
  1672. return "kAudioHardwareUnknownPropertyError";
  1673. case kAudioHardwareBadPropertySizeError:
  1674. return "kAudioHardwareBadPropertySizeError";
  1675. case kAudioHardwareIllegalOperationError:
  1676. return "kAudioHardwareIllegalOperationError";
  1677. case kAudioHardwareBadObjectError:
  1678. return "kAudioHardwareBadObjectError";
  1679. case kAudioHardwareBadDeviceError:
  1680. return "kAudioHardwareBadDeviceError";
  1681. case kAudioHardwareBadStreamError:
  1682. return "kAudioHardwareBadStreamError";
  1683. case kAudioHardwareUnsupportedOperationError:
  1684. return "kAudioHardwareUnsupportedOperationError";
  1685. case kAudioDeviceUnsupportedFormatError:
  1686. return "kAudioDeviceUnsupportedFormatError";
  1687. case kAudioDevicePermissionsError:
  1688. return "kAudioDevicePermissionsError";
  1689. default:
  1690. return "CoreAudio unknown error";
  1691. }
  1692. }
  1693. //******************** End of __MACOSX_CORE__ *********************//
  1694. #endif
  1695. #if defined(__UNIX_JACK__)
  1696. // JACK is a low-latency audio server, originally written for the
  1697. // GNU/Linux operating system and now also ported to OS-X. It can
  1698. // connect a number of different applications to an audio device, as
  1699. // well as allowing them to share audio between themselves.
  1700. //
  1701. // When using JACK with RtAudio, "devices" refer to JACK clients that
  1702. // have ports connected to the server. The JACK server is typically
  1703. // started in a terminal as follows:
  1704. //
  1705. // .jackd -d alsa -d hw:0
  1706. //
  1707. // or through an interface program such as qjackctl. Many of the
  1708. // parameters normally set for a stream are fixed by the JACK server
  1709. // and can be specified when the JACK server is started. In
  1710. // particular,
  1711. //
  1712. // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
  1713. //
  1714. // specifies a sample rate of 44100 Hz, a buffer size of 512 sample
  1715. // frames, and number of buffers = 4. Once the server is running, it
  1716. // is not possible to override these values. If the values are not
  1717. // specified in the command-line, the JACK server uses default values.
  1718. //
  1719. // The JACK server does not have to be running when an instance of
  1720. // RtApiJack is created, though the function getDeviceCount() will
  1721. // report 0 devices found until JACK has been started. When no
  1722. // devices are available (i.e., the JACK server is not running), a
  1723. // stream cannot be opened.
  1724. #include <jack/jack.h>
  1725. #include <unistd.h>
  1726. #include <cstdio>
  1727. // A structure to hold various information related to the Jack API
  1728. // implementation.
  1729. struct JackHandle {
  1730. jack_client_t *client;
  1731. jack_port_t **ports[2];
  1732. std::string deviceName[2];
  1733. bool xrun[2];
  1734. pthread_cond_t condition;
  1735. int drainCounter; // Tracks callback counts when draining
  1736. bool internalDrain; // Indicates if stop is initiated from callback or not.
  1737. JackHandle()
  1738. :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
  1739. };
  1740. #if !defined(__RTAUDIO_DEBUG__)
  1741. static void jackSilentError( const char * ) {};
  1742. #endif
  1743. RtApiJack :: RtApiJack()
  1744. :shouldAutoconnect_(true) {
  1745. // Nothing to do here.
  1746. #if !defined(__RTAUDIO_DEBUG__)
  1747. // Turn off Jack's internal error reporting.
  1748. jack_set_error_function( &jackSilentError );
  1749. #endif
  1750. }
  1751. RtApiJack :: ~RtApiJack()
  1752. {
  1753. if ( stream_.state != STREAM_CLOSED ) closeStream();
  1754. }
  1755. unsigned int RtApiJack :: getDeviceCount( void )
  1756. {
  1757. // See if we can become a jack client.
  1758. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1759. jack_status_t *status = NULL;
  1760. jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );
  1761. if ( client == 0 ) return 0;
  1762. const char **ports;
  1763. std::string port, previousPort;
  1764. unsigned int nChannels = 0, nDevices = 0;
  1765. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1766. if ( ports ) {
  1767. // Parse the port names up to the first colon (:).
  1768. size_t iColon = 0;
  1769. do {
  1770. port = (char *) ports[ nChannels ];
  1771. iColon = port.find(":");
  1772. if ( iColon != std::string::npos ) {
  1773. port = port.substr( 0, iColon + 1 );
  1774. if ( port != previousPort ) {
  1775. nDevices++;
  1776. previousPort = port;
  1777. }
  1778. }
  1779. } while ( ports[++nChannels] );
  1780. free( ports );
  1781. }
  1782. jack_client_close( client );
  1783. return nDevices;
  1784. }
  1785. RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
  1786. {
  1787. RtAudio::DeviceInfo info;
  1788. info.probed = false;
  1789. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption
  1790. jack_status_t *status = NULL;
  1791. jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );
  1792. if ( client == 0 ) {
  1793. errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
  1794. error( RtAudioError::WARNING );
  1795. return info;
  1796. }
  1797. const char **ports;
  1798. std::string port, previousPort;
  1799. unsigned int nPorts = 0, nDevices = 0;
  1800. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1801. if ( ports ) {
  1802. // Parse the port names up to the first colon (:).
  1803. size_t iColon = 0;
  1804. do {
  1805. port = (char *) ports[ nPorts ];
  1806. iColon = port.find(":");
  1807. if ( iColon != std::string::npos ) {
  1808. port = port.substr( 0, iColon );
  1809. if ( port != previousPort ) {
  1810. if ( nDevices == device ) info.name = port;
  1811. nDevices++;
  1812. previousPort = port;
  1813. }
  1814. }
  1815. } while ( ports[++nPorts] );
  1816. free( ports );
  1817. }
  1818. if ( device >= nDevices ) {
  1819. jack_client_close( client );
  1820. errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
  1821. error( RtAudioError::INVALID_USE );
  1822. return info;
  1823. }
  1824. // Get the current jack server sample rate.
  1825. info.sampleRates.clear();
  1826. info.preferredSampleRate = jack_get_sample_rate( client );
  1827. info.sampleRates.push_back( info.preferredSampleRate );
  1828. // Count the available ports containing the client name as device
  1829. // channels. Jack "input ports" equal RtAudio output channels.
  1830. unsigned int nChannels = 0;
  1831. ports = jack_get_ports( client, info.name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput );
  1832. if ( ports ) {
  1833. while ( ports[ nChannels ] ) nChannels++;
  1834. free( ports );
  1835. info.outputChannels = nChannels;
  1836. }
  1837. // Jack "output ports" equal RtAudio input channels.
  1838. nChannels = 0;
  1839. ports = jack_get_ports( client, info.name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
  1840. if ( ports ) {
  1841. while ( ports[ nChannels ] ) nChannels++;
  1842. free( ports );
  1843. info.inputChannels = nChannels;
  1844. }
  1845. if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
  1846. jack_client_close(client);
  1847. errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
  1848. error( RtAudioError::WARNING );
  1849. return info;
  1850. }
  1851. // If device opens for both playback and capture, we determine the channels.
  1852. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  1853. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  1854. // Jack always uses 32-bit floats.
  1855. info.nativeFormats = RTAUDIO_FLOAT32;
  1856. // Jack doesn't provide default devices so we'll use the first available one.
  1857. if ( device == 0 && info.outputChannels > 0 )
  1858. info.isDefaultOutput = true;
  1859. if ( device == 0 && info.inputChannels > 0 )
  1860. info.isDefaultInput = true;
  1861. jack_client_close(client);
  1862. info.probed = true;
  1863. return info;
  1864. }
  1865. static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
  1866. {
  1867. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1868. RtApiJack *object = (RtApiJack *) info->object;
  1869. if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
  1870. return 0;
  1871. }
  1872. // This function will be called by a spawned thread when the Jack
  1873. // server signals that it is shutting down. It is necessary to handle
  1874. // it this way because the jackShutdown() function must return before
  1875. // the jack_deactivate() function (in closeStream()) will return.
  1876. static void *jackCloseStream( void *ptr )
  1877. {
  1878. CallbackInfo *info = (CallbackInfo *) ptr;
  1879. RtApiJack *object = (RtApiJack *) info->object;
  1880. object->closeStream();
  1881. pthread_exit( NULL );
  1882. }
  1883. static void jackShutdown( void *infoPointer )
  1884. {
  1885. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1886. RtApiJack *object = (RtApiJack *) info->object;
  1887. // Check current stream state. If stopped, then we'll assume this
  1888. // was called as a result of a call to RtApiJack::stopStream (the
  1889. // deactivation of a client handle causes this function to be called).
  1890. // If not, we'll assume the Jack server is shutting down or some
  1891. // other problem occurred and we should close the stream.
  1892. if ( object->isStreamRunning() == false ) return;
  1893. ThreadHandle threadId;
  1894. pthread_create( &threadId, NULL, jackCloseStream, info );
  1895. std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
  1896. }
  1897. static int jackXrun( void *infoPointer )
  1898. {
  1899. JackHandle *handle = *((JackHandle **) infoPointer);
  1900. if ( handle->ports[0] ) handle->xrun[0] = true;
  1901. if ( handle->ports[1] ) handle->xrun[1] = true;
  1902. return 0;
  1903. }
  1904. bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  1905. unsigned int firstChannel, unsigned int sampleRate,
  1906. RtAudioFormat format, unsigned int *bufferSize,
  1907. RtAudio::StreamOptions *options )
  1908. {
  1909. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1910. // Look for jack server and try to become a client (only do once per stream).
  1911. jack_client_t *client = 0;
  1912. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
  1913. jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1914. jack_status_t *status = NULL;
  1915. if ( options && !options->streamName.empty() )
  1916. client = jack_client_open( options->streamName.c_str(), jackoptions, status );
  1917. else
  1918. client = jack_client_open( "RtApiJack", jackoptions, status );
  1919. if ( client == 0 ) {
  1920. errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
  1921. error( RtAudioError::WARNING );
  1922. return FAILURE;
  1923. }
  1924. }
  1925. else {
  1926. // The handle must have been created on an earlier pass.
  1927. client = handle->client;
  1928. }
  1929. const char **ports;
  1930. std::string port, previousPort, deviceName;
  1931. unsigned int nPorts = 0, nDevices = 0;
  1932. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1933. if ( ports ) {
  1934. // Parse the port names up to the first colon (:).
  1935. size_t iColon = 0;
  1936. do {
  1937. port = (char *) ports[ nPorts ];
  1938. iColon = port.find(":");
  1939. if ( iColon != std::string::npos ) {
  1940. port = port.substr( 0, iColon );
  1941. if ( port != previousPort ) {
  1942. if ( nDevices == device ) deviceName = port;
  1943. nDevices++;
  1944. previousPort = port;
  1945. }
  1946. }
  1947. } while ( ports[++nPorts] );
  1948. free( ports );
  1949. }
  1950. if ( device >= nDevices ) {
  1951. errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
  1952. return FAILURE;
  1953. }
  1954. unsigned long flag = JackPortIsInput;
  1955. if ( mode == INPUT ) flag = JackPortIsOutput;
  1956. if ( ! (options && (options->flags & RTAUDIO_JACK_DONT_CONNECT)) ) {
  1957. // Count the available ports containing the client name as device
  1958. // channels. Jack "input ports" equal RtAudio output channels.
  1959. unsigned int nChannels = 0;
  1960. ports = jack_get_ports( client, deviceName.c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
  1961. if ( ports ) {
  1962. while ( ports[ nChannels ] ) nChannels++;
  1963. free( ports );
  1964. }
  1965. // Compare the jack ports for specified client to the requested number of channels.
  1966. if ( nChannels < (channels + firstChannel) ) {
  1967. errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
  1968. errorText_ = errorStream_.str();
  1969. return FAILURE;
  1970. }
  1971. }
  1972. // Check the jack server sample rate.
  1973. unsigned int jackRate = jack_get_sample_rate( client );
  1974. if ( sampleRate != jackRate ) {
  1975. jack_client_close( client );
  1976. errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
  1977. errorText_ = errorStream_.str();
  1978. return FAILURE;
  1979. }
  1980. stream_.sampleRate = jackRate;
  1981. // Get the latency of the JACK port.
  1982. ports = jack_get_ports( client, deviceName.c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
  1983. if ( ports[ firstChannel ] ) {
  1984. // Added by Ge Wang
  1985. jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
  1986. // the range (usually the min and max are equal)
  1987. jack_latency_range_t latrange; latrange.min = latrange.max = 0;
  1988. // get the latency range
  1989. jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );
  1990. // be optimistic, use the min!
  1991. stream_.latency[mode] = latrange.min;
  1992. //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
  1993. }
  1994. free( ports );
  1995. // The jack server always uses 32-bit floating-point data.
  1996. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1997. stream_.userFormat = format;
  1998. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1999. else stream_.userInterleaved = true;
  2000. // Jack always uses non-interleaved buffers.
  2001. stream_.deviceInterleaved[mode] = false;
  2002. // Jack always provides host byte-ordered data.
  2003. stream_.doByteSwap[mode] = false;
  2004. // Get the buffer size. The buffer size and number of buffers
  2005. // (periods) is set when the jack server is started.
  2006. stream_.bufferSize = (int) jack_get_buffer_size( client );
  2007. *bufferSize = stream_.bufferSize;
  2008. stream_.nDeviceChannels[mode] = channels;
  2009. stream_.nUserChannels[mode] = channels;
  2010. // Set flags for buffer conversion.
  2011. stream_.doConvertBuffer[mode] = false;
  2012. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2013. stream_.doConvertBuffer[mode] = true;
  2014. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2015. stream_.nUserChannels[mode] > 1 )
  2016. stream_.doConvertBuffer[mode] = true;
  2017. // Allocate our JackHandle structure for the stream.
  2018. if ( handle == 0 ) {
  2019. try {
  2020. handle = new JackHandle;
  2021. }
  2022. catch ( std::bad_alloc& ) {
  2023. errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
  2024. goto error;
  2025. }
  2026. if ( pthread_cond_init(&handle->condition, NULL) ) {
  2027. errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
  2028. goto error;
  2029. }
  2030. stream_.apiHandle = (void *) handle;
  2031. handle->client = client;
  2032. }
  2033. handle->deviceName[mode] = deviceName;
  2034. // Allocate necessary internal buffers.
  2035. unsigned long bufferBytes;
  2036. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2037. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2038. if ( stream_.userBuffer[mode] == NULL ) {
  2039. errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
  2040. goto error;
  2041. }
  2042. if ( stream_.doConvertBuffer[mode] ) {
  2043. bool makeBuffer = true;
  2044. if ( mode == OUTPUT )
  2045. bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2046. else { // mode == INPUT
  2047. bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
  2048. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  2049. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
  2050. if ( bufferBytes < bytesOut ) makeBuffer = false;
  2051. }
  2052. }
  2053. if ( makeBuffer ) {
  2054. bufferBytes *= *bufferSize;
  2055. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2056. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2057. if ( stream_.deviceBuffer == NULL ) {
  2058. errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
  2059. goto error;
  2060. }
  2061. }
  2062. }
  2063. // Allocate memory for the Jack ports (channels) identifiers.
  2064. handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
  2065. if ( handle->ports[mode] == NULL ) {
  2066. errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
  2067. goto error;
  2068. }
  2069. stream_.device[mode] = device;
  2070. stream_.channelOffset[mode] = firstChannel;
  2071. stream_.state = STREAM_STOPPED;
  2072. stream_.callbackInfo.object = (void *) this;
  2073. if ( stream_.mode == OUTPUT && mode == INPUT )
  2074. // We had already set up the stream for output.
  2075. stream_.mode = DUPLEX;
  2076. else {
  2077. stream_.mode = mode;
  2078. jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
  2079. jack_set_xrun_callback( handle->client, jackXrun, (void *) &stream_.apiHandle );
  2080. jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
  2081. }
  2082. // Register our ports.
  2083. char label[64];
  2084. if ( mode == OUTPUT ) {
  2085. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2086. snprintf( label, 64, "outport %d", i );
  2087. handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
  2088. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
  2089. }
  2090. }
  2091. else {
  2092. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2093. snprintf( label, 64, "inport %d", i );
  2094. handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
  2095. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
  2096. }
  2097. }
  2098. // Setup the buffer conversion information structure. We don't use
  2099. // buffers to do channel offsets, so we override that parameter
  2100. // here.
  2101. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2102. if ( options && options->flags & RTAUDIO_JACK_DONT_CONNECT ) shouldAutoconnect_ = false;
  2103. return SUCCESS;
  2104. error:
  2105. if ( handle ) {
  2106. pthread_cond_destroy( &handle->condition );
  2107. jack_client_close( handle->client );
  2108. if ( handle->ports[0] ) free( handle->ports[0] );
  2109. if ( handle->ports[1] ) free( handle->ports[1] );
  2110. delete handle;
  2111. stream_.apiHandle = 0;
  2112. }
  2113. for ( int i=0; i<2; i++ ) {
  2114. if ( stream_.userBuffer[i] ) {
  2115. free( stream_.userBuffer[i] );
  2116. stream_.userBuffer[i] = 0;
  2117. }
  2118. }
  2119. if ( stream_.deviceBuffer ) {
  2120. free( stream_.deviceBuffer );
  2121. stream_.deviceBuffer = 0;
  2122. }
  2123. return FAILURE;
  2124. }
  2125. void RtApiJack :: closeStream( void )
  2126. {
  2127. if ( stream_.state == STREAM_CLOSED ) {
  2128. errorText_ = "RtApiJack::closeStream(): no open stream to close!";
  2129. error( RtAudioError::WARNING );
  2130. return;
  2131. }
  2132. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2133. if ( handle ) {
  2134. if ( stream_.state == STREAM_RUNNING )
  2135. jack_deactivate( handle->client );
  2136. jack_client_close( handle->client );
  2137. }
  2138. if ( handle ) {
  2139. if ( handle->ports[0] ) free( handle->ports[0] );
  2140. if ( handle->ports[1] ) free( handle->ports[1] );
  2141. pthread_cond_destroy( &handle->condition );
  2142. delete handle;
  2143. stream_.apiHandle = 0;
  2144. }
  2145. for ( int i=0; i<2; i++ ) {
  2146. if ( stream_.userBuffer[i] ) {
  2147. free( stream_.userBuffer[i] );
  2148. stream_.userBuffer[i] = 0;
  2149. }
  2150. }
  2151. if ( stream_.deviceBuffer ) {
  2152. free( stream_.deviceBuffer );
  2153. stream_.deviceBuffer = 0;
  2154. }
  2155. stream_.mode = UNINITIALIZED;
  2156. stream_.state = STREAM_CLOSED;
  2157. }
  2158. void RtApiJack :: startStream( void )
  2159. {
  2160. verifyStream();
  2161. if ( stream_.state == STREAM_RUNNING ) {
  2162. errorText_ = "RtApiJack::startStream(): the stream is already running!";
  2163. error( RtAudioError::WARNING );
  2164. return;
  2165. }
  2166. #if defined( HAVE_GETTIMEOFDAY )
  2167. gettimeofday( &stream_.lastTickTimestamp, NULL );
  2168. #endif
  2169. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2170. int result = jack_activate( handle->client );
  2171. if ( result ) {
  2172. errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
  2173. goto unlock;
  2174. }
  2175. const char **ports;
  2176. // Get the list of available ports.
  2177. if ( shouldAutoconnect_ && (stream_.mode == OUTPUT || stream_.mode == DUPLEX) ) {
  2178. result = 1;
  2179. ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput);
  2180. if ( ports == NULL) {
  2181. errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
  2182. goto unlock;
  2183. }
  2184. // Now make the port connections. Since RtAudio wasn't designed to
  2185. // allow the user to select particular channels of a device, we'll
  2186. // just open the first "nChannels" ports with offset.
  2187. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2188. result = 1;
  2189. if ( ports[ stream_.channelOffset[0] + i ] )
  2190. result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
  2191. if ( result ) {
  2192. free( ports );
  2193. errorText_ = "RtApiJack::startStream(): error connecting output ports!";
  2194. goto unlock;
  2195. }
  2196. }
  2197. free(ports);
  2198. }
  2199. if ( shouldAutoconnect_ && (stream_.mode == INPUT || stream_.mode == DUPLEX) ) {
  2200. result = 1;
  2201. ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
  2202. if ( ports == NULL) {
  2203. errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
  2204. goto unlock;
  2205. }
  2206. // Now make the port connections. See note above.
  2207. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2208. result = 1;
  2209. if ( ports[ stream_.channelOffset[1] + i ] )
  2210. result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
  2211. if ( result ) {
  2212. free( ports );
  2213. errorText_ = "RtApiJack::startStream(): error connecting input ports!";
  2214. goto unlock;
  2215. }
  2216. }
  2217. free(ports);
  2218. }
  2219. handle->drainCounter = 0;
  2220. handle->internalDrain = false;
  2221. stream_.state = STREAM_RUNNING;
  2222. unlock:
  2223. if ( result == 0 ) return;
  2224. error( RtAudioError::SYSTEM_ERROR );
  2225. }
  2226. void RtApiJack :: stopStream( void )
  2227. {
  2228. verifyStream();
  2229. if ( stream_.state == STREAM_STOPPED ) {
  2230. errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
  2231. error( RtAudioError::WARNING );
  2232. return;
  2233. }
  2234. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2235. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2236. if ( handle->drainCounter == 0 ) {
  2237. handle->drainCounter = 2;
  2238. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  2239. }
  2240. }
  2241. jack_deactivate( handle->client );
  2242. stream_.state = STREAM_STOPPED;
  2243. }
  2244. void RtApiJack :: abortStream( void )
  2245. {
  2246. verifyStream();
  2247. if ( stream_.state == STREAM_STOPPED ) {
  2248. errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
  2249. error( RtAudioError::WARNING );
  2250. return;
  2251. }
  2252. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2253. handle->drainCounter = 2;
  2254. stopStream();
  2255. }
  2256. // This function will be called by a spawned thread when the user
  2257. // callback function signals that the stream should be stopped or
  2258. // aborted. It is necessary to handle it this way because the
  2259. // callbackEvent() function must return before the jack_deactivate()
  2260. // function will return.
  2261. static void *jackStopStream( void *ptr )
  2262. {
  2263. CallbackInfo *info = (CallbackInfo *) ptr;
  2264. RtApiJack *object = (RtApiJack *) info->object;
  2265. object->stopStream();
  2266. pthread_exit( NULL );
  2267. }
  2268. bool RtApiJack :: callbackEvent( unsigned long nframes )
  2269. {
  2270. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2271. if ( stream_.state == STREAM_CLOSED ) {
  2272. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2273. error( RtAudioError::WARNING );
  2274. return FAILURE;
  2275. }
  2276. if ( stream_.bufferSize != nframes ) {
  2277. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
  2278. error( RtAudioError::WARNING );
  2279. return FAILURE;
  2280. }
  2281. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2282. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2283. // Check if we were draining the stream and signal is finished.
  2284. if ( handle->drainCounter > 3 ) {
  2285. ThreadHandle threadId;
  2286. stream_.state = STREAM_STOPPING;
  2287. if ( handle->internalDrain == true )
  2288. pthread_create( &threadId, NULL, jackStopStream, info );
  2289. else
  2290. pthread_cond_signal( &handle->condition );
  2291. return SUCCESS;
  2292. }
  2293. // Invoke user callback first, to get fresh output data.
  2294. if ( handle->drainCounter == 0 ) {
  2295. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2296. double streamTime = getStreamTime();
  2297. RtAudioStreamStatus status = 0;
  2298. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  2299. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2300. handle->xrun[0] = false;
  2301. }
  2302. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  2303. status |= RTAUDIO_INPUT_OVERFLOW;
  2304. handle->xrun[1] = false;
  2305. }
  2306. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2307. stream_.bufferSize, streamTime, status, info->userData );
  2308. if ( cbReturnValue == 2 ) {
  2309. stream_.state = STREAM_STOPPING;
  2310. handle->drainCounter = 2;
  2311. ThreadHandle id;
  2312. pthread_create( &id, NULL, jackStopStream, info );
  2313. return SUCCESS;
  2314. }
  2315. else if ( cbReturnValue == 1 ) {
  2316. handle->drainCounter = 1;
  2317. handle->internalDrain = true;
  2318. }
  2319. }
  2320. jack_default_audio_sample_t *jackbuffer;
  2321. unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
  2322. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2323. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2324. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2325. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2326. memset( jackbuffer, 0, bufferBytes );
  2327. }
  2328. }
  2329. else if ( stream_.doConvertBuffer[0] ) {
  2330. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2331. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2332. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2333. memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
  2334. }
  2335. }
  2336. else { // no buffer conversion
  2337. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2338. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2339. memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
  2340. }
  2341. }
  2342. }
  2343. // Don't bother draining input
  2344. if ( handle->drainCounter ) {
  2345. handle->drainCounter++;
  2346. goto unlock;
  2347. }
  2348. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2349. if ( stream_.doConvertBuffer[1] ) {
  2350. for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
  2351. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2352. memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
  2353. }
  2354. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2355. }
  2356. else { // no buffer conversion
  2357. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2358. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2359. memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
  2360. }
  2361. }
  2362. }
  2363. unlock:
  2364. RtApi::tickStreamTime();
  2365. return SUCCESS;
  2366. }
  2367. //******************** End of __UNIX_JACK__ *********************//
  2368. #endif
  2369. #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2370. // The ASIO API is designed around a callback scheme, so this
  2371. // implementation is similar to that used for OS-X CoreAudio and Linux
  2372. // Jack. The primary constraint with ASIO is that it only allows
  2373. // access to a single driver at a time. Thus, it is not possible to
  2374. // have more than one simultaneous RtAudio stream.
  2375. //
  2376. // This implementation also requires a number of external ASIO files
  2377. // and a few global variables. The ASIO callback scheme does not
  2378. // allow for the passing of user data, so we must create a global
  2379. // pointer to our callbackInfo structure.
  2380. //
  2381. // On unix systems, we make use of a pthread condition variable.
  2382. // Since there is no equivalent in Windows, I hacked something based
  2383. // on information found in
  2384. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
  2385. #include "asiosys.h"
  2386. #include "asio.h"
  2387. #include "iasiothiscallresolver.h"
  2388. #include "asiodrivers.h"
  2389. #include <cmath>
  2390. static AsioDrivers drivers;
  2391. static ASIOCallbacks asioCallbacks;
  2392. static ASIODriverInfo driverInfo;
  2393. static CallbackInfo *asioCallbackInfo;
  2394. static bool asioXRun;
  2395. struct AsioHandle {
  2396. int drainCounter; // Tracks callback counts when draining
  2397. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2398. ASIOBufferInfo *bufferInfos;
  2399. HANDLE condition;
  2400. AsioHandle()
  2401. :drainCounter(0), internalDrain(false), bufferInfos(0) {}
  2402. };
  2403. // Function declarations (definitions at end of section)
  2404. static const char* getAsioErrorString( ASIOError result );
  2405. static void sampleRateChanged( ASIOSampleRate sRate );
  2406. static long asioMessages( long selector, long value, void* message, double* opt );
  2407. RtApiAsio :: RtApiAsio()
  2408. {
  2409. // ASIO cannot run on a multi-threaded appartment. You can call
  2410. // CoInitialize beforehand, but it must be for appartment threading
  2411. // (in which case, CoInitilialize will return S_FALSE here).
  2412. coInitialized_ = false;
  2413. HRESULT hr = CoInitialize( NULL );
  2414. if ( FAILED(hr) ) {
  2415. errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
  2416. error( RtAudioError::WARNING );
  2417. }
  2418. coInitialized_ = true;
  2419. drivers.removeCurrentDriver();
  2420. driverInfo.asioVersion = 2;
  2421. // See note in DirectSound implementation about GetDesktopWindow().
  2422. driverInfo.sysRef = GetForegroundWindow();
  2423. }
  2424. RtApiAsio :: ~RtApiAsio()
  2425. {
  2426. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2427. if ( coInitialized_ ) CoUninitialize();
  2428. }
  2429. unsigned int RtApiAsio :: getDeviceCount( void )
  2430. {
  2431. return (unsigned int) drivers.asioGetNumDev();
  2432. }
  2433. RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
  2434. {
  2435. RtAudio::DeviceInfo info;
  2436. info.probed = false;
  2437. // Get device ID
  2438. unsigned int nDevices = getDeviceCount();
  2439. if ( nDevices == 0 ) {
  2440. errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
  2441. error( RtAudioError::INVALID_USE );
  2442. return info;
  2443. }
  2444. if ( device >= nDevices ) {
  2445. errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
  2446. error( RtAudioError::INVALID_USE );
  2447. return info;
  2448. }
  2449. // If a stream is already open, we cannot probe other devices. Thus, use the saved results.
  2450. if ( stream_.state != STREAM_CLOSED ) {
  2451. if ( device >= devices_.size() ) {
  2452. errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
  2453. error( RtAudioError::WARNING );
  2454. return info;
  2455. }
  2456. return devices_[ device ];
  2457. }
  2458. char driverName[32];
  2459. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2460. if ( result != ASE_OK ) {
  2461. errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2462. errorText_ = errorStream_.str();
  2463. error( RtAudioError::WARNING );
  2464. return info;
  2465. }
  2466. info.name = driverName;
  2467. if ( !drivers.loadDriver( driverName ) ) {
  2468. errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
  2469. errorText_ = errorStream_.str();
  2470. error( RtAudioError::WARNING );
  2471. return info;
  2472. }
  2473. result = ASIOInit( &driverInfo );
  2474. if ( result != ASE_OK ) {
  2475. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2476. errorText_ = errorStream_.str();
  2477. error( RtAudioError::WARNING );
  2478. return info;
  2479. }
  2480. // Determine the device channel information.
  2481. long inputChannels, outputChannels;
  2482. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2483. if ( result != ASE_OK ) {
  2484. drivers.removeCurrentDriver();
  2485. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2486. errorText_ = errorStream_.str();
  2487. error( RtAudioError::WARNING );
  2488. return info;
  2489. }
  2490. info.outputChannels = outputChannels;
  2491. info.inputChannels = inputChannels;
  2492. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  2493. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  2494. // Determine the supported sample rates.
  2495. info.sampleRates.clear();
  2496. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  2497. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  2498. if ( result == ASE_OK ) {
  2499. info.sampleRates.push_back( SAMPLE_RATES[i] );
  2500. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  2501. info.preferredSampleRate = SAMPLE_RATES[i];
  2502. }
  2503. }
  2504. // Determine supported data types ... just check first channel and assume rest are the same.
  2505. ASIOChannelInfo channelInfo;
  2506. channelInfo.channel = 0;
  2507. channelInfo.isInput = true;
  2508. if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
  2509. result = ASIOGetChannelInfo( &channelInfo );
  2510. if ( result != ASE_OK ) {
  2511. drivers.removeCurrentDriver();
  2512. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
  2513. errorText_ = errorStream_.str();
  2514. error( RtAudioError::WARNING );
  2515. return info;
  2516. }
  2517. info.nativeFormats = 0;
  2518. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  2519. info.nativeFormats |= RTAUDIO_SINT16;
  2520. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  2521. info.nativeFormats |= RTAUDIO_SINT32;
  2522. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  2523. info.nativeFormats |= RTAUDIO_FLOAT32;
  2524. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  2525. info.nativeFormats |= RTAUDIO_FLOAT64;
  2526. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )
  2527. info.nativeFormats |= RTAUDIO_SINT24;
  2528. if ( info.outputChannels > 0 )
  2529. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  2530. if ( info.inputChannels > 0 )
  2531. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  2532. info.probed = true;
  2533. drivers.removeCurrentDriver();
  2534. return info;
  2535. }
  2536. static void bufferSwitch( long index, ASIOBool /*processNow*/ )
  2537. {
  2538. RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
  2539. object->callbackEvent( index );
  2540. }
  2541. void RtApiAsio :: saveDeviceInfo( void )
  2542. {
  2543. devices_.clear();
  2544. unsigned int nDevices = getDeviceCount();
  2545. devices_.resize( nDevices );
  2546. for ( unsigned int i=0; i<nDevices; i++ )
  2547. devices_[i] = getDeviceInfo( i );
  2548. }
  2549. bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  2550. unsigned int firstChannel, unsigned int sampleRate,
  2551. RtAudioFormat format, unsigned int *bufferSize,
  2552. RtAudio::StreamOptions *options )
  2553. {////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2554. bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;
  2555. // For ASIO, a duplex stream MUST use the same driver.
  2556. if ( isDuplexInput && stream_.device[0] != device ) {
  2557. errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
  2558. return FAILURE;
  2559. }
  2560. char driverName[32];
  2561. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2562. if ( result != ASE_OK ) {
  2563. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2564. errorText_ = errorStream_.str();
  2565. return FAILURE;
  2566. }
  2567. // Only load the driver once for duplex stream.
  2568. if ( !isDuplexInput ) {
  2569. // The getDeviceInfo() function will not work when a stream is open
  2570. // because ASIO does not allow multiple devices to run at the same
  2571. // time. Thus, we'll probe the system before opening a stream and
  2572. // save the results for use by getDeviceInfo().
  2573. this->saveDeviceInfo();
  2574. if ( !drivers.loadDriver( driverName ) ) {
  2575. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
  2576. errorText_ = errorStream_.str();
  2577. return FAILURE;
  2578. }
  2579. result = ASIOInit( &driverInfo );
  2580. if ( result != ASE_OK ) {
  2581. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2582. errorText_ = errorStream_.str();
  2583. return FAILURE;
  2584. }
  2585. }
  2586. // keep them before any "goto error", they are used for error cleanup + goto device boundary checks
  2587. bool buffersAllocated = false;
  2588. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2589. unsigned int nChannels;
  2590. // Check the device channel count.
  2591. long inputChannels, outputChannels;
  2592. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2593. if ( result != ASE_OK ) {
  2594. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2595. errorText_ = errorStream_.str();
  2596. goto error;
  2597. }
  2598. if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
  2599. ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
  2600. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
  2601. errorText_ = errorStream_.str();
  2602. goto error;
  2603. }
  2604. stream_.nDeviceChannels[mode] = channels;
  2605. stream_.nUserChannels[mode] = channels;
  2606. stream_.channelOffset[mode] = firstChannel;
  2607. // Verify the sample rate is supported.
  2608. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  2609. if ( result != ASE_OK ) {
  2610. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
  2611. errorText_ = errorStream_.str();
  2612. goto error;
  2613. }
  2614. // Get the current sample rate
  2615. ASIOSampleRate currentRate;
  2616. result = ASIOGetSampleRate( &currentRate );
  2617. if ( result != ASE_OK ) {
  2618. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
  2619. errorText_ = errorStream_.str();
  2620. goto error;
  2621. }
  2622. // Set the sample rate only if necessary
  2623. if ( currentRate != sampleRate ) {
  2624. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  2625. if ( result != ASE_OK ) {
  2626. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
  2627. errorText_ = errorStream_.str();
  2628. goto error;
  2629. }
  2630. }
  2631. // Determine the driver data type.
  2632. ASIOChannelInfo channelInfo;
  2633. channelInfo.channel = 0;
  2634. if ( mode == OUTPUT ) channelInfo.isInput = false;
  2635. else channelInfo.isInput = true;
  2636. result = ASIOGetChannelInfo( &channelInfo );
  2637. if ( result != ASE_OK ) {
  2638. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
  2639. errorText_ = errorStream_.str();
  2640. goto error;
  2641. }
  2642. // Assuming WINDOWS host is always little-endian.
  2643. stream_.doByteSwap[mode] = false;
  2644. stream_.userFormat = format;
  2645. stream_.deviceFormat[mode] = 0;
  2646. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  2647. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  2648. if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
  2649. }
  2650. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  2651. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  2652. if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
  2653. }
  2654. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  2655. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2656. if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
  2657. }
  2658. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  2659. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  2660. if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
  2661. }
  2662. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {
  2663. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  2664. if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;
  2665. }
  2666. if ( stream_.deviceFormat[mode] == 0 ) {
  2667. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
  2668. errorText_ = errorStream_.str();
  2669. goto error;
  2670. }
  2671. // Set the buffer size. For a duplex stream, this will end up
  2672. // setting the buffer size based on the input constraints, which
  2673. // should be ok.
  2674. long minSize, maxSize, preferSize, granularity;
  2675. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  2676. if ( result != ASE_OK ) {
  2677. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
  2678. errorText_ = errorStream_.str();
  2679. goto error;
  2680. }
  2681. if ( isDuplexInput ) {
  2682. // When this is the duplex input (output was opened before), then we have to use the same
  2683. // buffersize as the output, because it might use the preferred buffer size, which most
  2684. // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,
  2685. // So instead of throwing an error, make them equal. The caller uses the reference
  2686. // to the "bufferSize" param as usual to set up processing buffers.
  2687. *bufferSize = stream_.bufferSize;
  2688. } else {
  2689. if ( *bufferSize == 0 ) *bufferSize = preferSize;
  2690. else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2691. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2692. else if ( granularity == -1 ) {
  2693. // Make sure bufferSize is a power of two.
  2694. int log2_of_min_size = 0;
  2695. int log2_of_max_size = 0;
  2696. for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
  2697. if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
  2698. if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
  2699. }
  2700. long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
  2701. int min_delta_num = log2_of_min_size;
  2702. for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
  2703. long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
  2704. if (current_delta < min_delta) {
  2705. min_delta = current_delta;
  2706. min_delta_num = i;
  2707. }
  2708. }
  2709. *bufferSize = ( (unsigned int)1 << min_delta_num );
  2710. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2711. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2712. }
  2713. else if ( granularity != 0 ) {
  2714. // Set to an even multiple of granularity, rounding up.
  2715. *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
  2716. }
  2717. }
  2718. /*
  2719. // we don't use it anymore, see above!
  2720. // Just left it here for the case...
  2721. if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {
  2722. errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
  2723. goto error;
  2724. }
  2725. */
  2726. stream_.bufferSize = *bufferSize;
  2727. stream_.nBuffers = 2;
  2728. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2729. else stream_.userInterleaved = true;
  2730. // ASIO always uses non-interleaved buffers.
  2731. stream_.deviceInterleaved[mode] = false;
  2732. // Allocate, if necessary, our AsioHandle structure for the stream.
  2733. if ( handle == 0 ) {
  2734. try {
  2735. handle = new AsioHandle;
  2736. }
  2737. catch ( std::bad_alloc& ) {
  2738. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
  2739. goto error;
  2740. }
  2741. handle->bufferInfos = 0;
  2742. // Create a manual-reset event.
  2743. handle->condition = CreateEvent( NULL, // no security
  2744. TRUE, // manual-reset
  2745. FALSE, // non-signaled initially
  2746. NULL ); // unnamed
  2747. stream_.apiHandle = (void *) handle;
  2748. }
  2749. // Create the ASIO internal buffers. Since RtAudio sets up input
  2750. // and output separately, we'll have to dispose of previously
  2751. // created output buffers for a duplex stream.
  2752. if ( mode == INPUT && stream_.mode == OUTPUT ) {
  2753. ASIODisposeBuffers();
  2754. if ( handle->bufferInfos ) free( handle->bufferInfos );
  2755. }
  2756. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  2757. unsigned int i;
  2758. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2759. handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  2760. if ( handle->bufferInfos == NULL ) {
  2761. errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
  2762. errorText_ = errorStream_.str();
  2763. goto error;
  2764. }
  2765. ASIOBufferInfo *infos;
  2766. infos = handle->bufferInfos;
  2767. for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
  2768. infos->isInput = ASIOFalse;
  2769. infos->channelNum = i + stream_.channelOffset[0];
  2770. infos->buffers[0] = infos->buffers[1] = 0;
  2771. }
  2772. for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
  2773. infos->isInput = ASIOTrue;
  2774. infos->channelNum = i + stream_.channelOffset[1];
  2775. infos->buffers[0] = infos->buffers[1] = 0;
  2776. }
  2777. // prepare for callbacks
  2778. stream_.sampleRate = sampleRate;
  2779. stream_.device[mode] = device;
  2780. stream_.mode = isDuplexInput ? DUPLEX : mode;
  2781. // store this class instance before registering callbacks, that are going to use it
  2782. asioCallbackInfo = &stream_.callbackInfo;
  2783. stream_.callbackInfo.object = (void *) this;
  2784. // Set up the ASIO callback structure and create the ASIO data buffers.
  2785. asioCallbacks.bufferSwitch = &bufferSwitch;
  2786. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  2787. asioCallbacks.asioMessage = &asioMessages;
  2788. asioCallbacks.bufferSwitchTimeInfo = NULL;
  2789. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2790. if ( result != ASE_OK ) {
  2791. // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges
  2792. // but only accept the preferred buffer size as parameter for ASIOCreateBuffers (e.g. Creative's ASIO driver).
  2793. // In that case, let's be naïve and try that instead.
  2794. *bufferSize = preferSize;
  2795. stream_.bufferSize = *bufferSize;
  2796. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2797. }
  2798. if ( result != ASE_OK ) {
  2799. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
  2800. errorText_ = errorStream_.str();
  2801. goto error;
  2802. }
  2803. buffersAllocated = true;
  2804. stream_.state = STREAM_STOPPED;
  2805. // Set flags for buffer conversion.
  2806. stream_.doConvertBuffer[mode] = false;
  2807. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2808. stream_.doConvertBuffer[mode] = true;
  2809. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2810. stream_.nUserChannels[mode] > 1 )
  2811. stream_.doConvertBuffer[mode] = true;
  2812. // Allocate necessary internal buffers
  2813. unsigned long bufferBytes;
  2814. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2815. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2816. if ( stream_.userBuffer[mode] == NULL ) {
  2817. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
  2818. goto error;
  2819. }
  2820. if ( stream_.doConvertBuffer[mode] ) {
  2821. bool makeBuffer = true;
  2822. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  2823. if ( isDuplexInput && stream_.deviceBuffer ) {
  2824. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2825. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  2826. }
  2827. if ( makeBuffer ) {
  2828. bufferBytes *= *bufferSize;
  2829. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2830. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2831. if ( stream_.deviceBuffer == NULL ) {
  2832. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
  2833. goto error;
  2834. }
  2835. }
  2836. }
  2837. // Determine device latencies
  2838. long inputLatency, outputLatency;
  2839. result = ASIOGetLatencies( &inputLatency, &outputLatency );
  2840. if ( result != ASE_OK ) {
  2841. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
  2842. errorText_ = errorStream_.str();
  2843. error( RtAudioError::WARNING); // warn but don't fail
  2844. }
  2845. else {
  2846. stream_.latency[0] = outputLatency;
  2847. stream_.latency[1] = inputLatency;
  2848. }
  2849. // Setup the buffer conversion information structure. We don't use
  2850. // buffers to do channel offsets, so we override that parameter
  2851. // here.
  2852. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2853. return SUCCESS;
  2854. error:
  2855. if ( !isDuplexInput ) {
  2856. // the cleanup for error in the duplex input, is done by RtApi::openStream
  2857. // So we clean up for single channel only
  2858. if ( buffersAllocated )
  2859. ASIODisposeBuffers();
  2860. drivers.removeCurrentDriver();
  2861. if ( handle ) {
  2862. CloseHandle( handle->condition );
  2863. if ( handle->bufferInfos )
  2864. free( handle->bufferInfos );
  2865. delete handle;
  2866. stream_.apiHandle = 0;
  2867. }
  2868. if ( stream_.userBuffer[mode] ) {
  2869. free( stream_.userBuffer[mode] );
  2870. stream_.userBuffer[mode] = 0;
  2871. }
  2872. if ( stream_.deviceBuffer ) {
  2873. free( stream_.deviceBuffer );
  2874. stream_.deviceBuffer = 0;
  2875. }
  2876. }
  2877. return FAILURE;
  2878. }////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2879. void RtApiAsio :: closeStream()
  2880. {
  2881. if ( stream_.state == STREAM_CLOSED ) {
  2882. errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
  2883. error( RtAudioError::WARNING );
  2884. return;
  2885. }
  2886. if ( stream_.state == STREAM_RUNNING ) {
  2887. stream_.state = STREAM_STOPPED;
  2888. ASIOStop();
  2889. }
  2890. ASIODisposeBuffers();
  2891. drivers.removeCurrentDriver();
  2892. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2893. if ( handle ) {
  2894. CloseHandle( handle->condition );
  2895. if ( handle->bufferInfos )
  2896. free( handle->bufferInfos );
  2897. delete handle;
  2898. stream_.apiHandle = 0;
  2899. }
  2900. for ( int i=0; i<2; i++ ) {
  2901. if ( stream_.userBuffer[i] ) {
  2902. free( stream_.userBuffer[i] );
  2903. stream_.userBuffer[i] = 0;
  2904. }
  2905. }
  2906. if ( stream_.deviceBuffer ) {
  2907. free( stream_.deviceBuffer );
  2908. stream_.deviceBuffer = 0;
  2909. }
  2910. stream_.mode = UNINITIALIZED;
  2911. stream_.state = STREAM_CLOSED;
  2912. }
  2913. bool stopThreadCalled = false;
  2914. void RtApiAsio :: startStream()
  2915. {
  2916. verifyStream();
  2917. if ( stream_.state == STREAM_RUNNING ) {
  2918. errorText_ = "RtApiAsio::startStream(): the stream is already running!";
  2919. error( RtAudioError::WARNING );
  2920. return;
  2921. }
  2922. #if defined( HAVE_GETTIMEOFDAY )
  2923. gettimeofday( &stream_.lastTickTimestamp, NULL );
  2924. #endif
  2925. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2926. ASIOError result = ASIOStart();
  2927. if ( result != ASE_OK ) {
  2928. errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
  2929. errorText_ = errorStream_.str();
  2930. goto unlock;
  2931. }
  2932. handle->drainCounter = 0;
  2933. handle->internalDrain = false;
  2934. ResetEvent( handle->condition );
  2935. stream_.state = STREAM_RUNNING;
  2936. asioXRun = false;
  2937. unlock:
  2938. stopThreadCalled = false;
  2939. if ( result == ASE_OK ) return;
  2940. error( RtAudioError::SYSTEM_ERROR );
  2941. }
  2942. void RtApiAsio :: stopStream()
  2943. {
  2944. verifyStream();
  2945. if ( stream_.state == STREAM_STOPPED ) {
  2946. errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
  2947. error( RtAudioError::WARNING );
  2948. return;
  2949. }
  2950. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2951. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2952. if ( handle->drainCounter == 0 ) {
  2953. handle->drainCounter = 2;
  2954. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  2955. }
  2956. }
  2957. stream_.state = STREAM_STOPPED;
  2958. ASIOError result = ASIOStop();
  2959. if ( result != ASE_OK ) {
  2960. errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
  2961. errorText_ = errorStream_.str();
  2962. }
  2963. if ( result == ASE_OK ) return;
  2964. error( RtAudioError::SYSTEM_ERROR );
  2965. }
  2966. void RtApiAsio :: abortStream()
  2967. {
  2968. verifyStream();
  2969. if ( stream_.state == STREAM_STOPPED ) {
  2970. errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
  2971. error( RtAudioError::WARNING );
  2972. return;
  2973. }
  2974. // The following lines were commented-out because some behavior was
  2975. // noted where the device buffers need to be zeroed to avoid
  2976. // continuing sound, even when the device buffers are completely
  2977. // disposed. So now, calling abort is the same as calling stop.
  2978. // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2979. // handle->drainCounter = 2;
  2980. stopStream();
  2981. }
  2982. // This function will be called by a spawned thread when the user
  2983. // callback function signals that the stream should be stopped or
  2984. // aborted. It is necessary to handle it this way because the
  2985. // callbackEvent() function must return before the ASIOStop()
  2986. // function will return.
  2987. static unsigned __stdcall asioStopStream( void *ptr )
  2988. {
  2989. CallbackInfo *info = (CallbackInfo *) ptr;
  2990. RtApiAsio *object = (RtApiAsio *) info->object;
  2991. object->stopStream();
  2992. _endthreadex( 0 );
  2993. return 0;
  2994. }
  2995. bool RtApiAsio :: callbackEvent( long bufferIndex )
  2996. {
  2997. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2998. if ( stream_.state == STREAM_CLOSED ) {
  2999. errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
  3000. error( RtAudioError::WARNING );
  3001. return FAILURE;
  3002. }
  3003. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  3004. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  3005. // Check if we were draining the stream and signal if finished.
  3006. if ( handle->drainCounter > 3 ) {
  3007. stream_.state = STREAM_STOPPING;
  3008. if ( handle->internalDrain == false )
  3009. SetEvent( handle->condition );
  3010. else { // spawn a thread to stop the stream
  3011. unsigned threadId;
  3012. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  3013. &stream_.callbackInfo, 0, &threadId );
  3014. }
  3015. return SUCCESS;
  3016. }
  3017. // Invoke user callback to get fresh output data UNLESS we are
  3018. // draining stream.
  3019. if ( handle->drainCounter == 0 ) {
  3020. RtAudioCallback callback = (RtAudioCallback) info->callback;
  3021. double streamTime = getStreamTime();
  3022. RtAudioStreamStatus status = 0;
  3023. if ( stream_.mode != INPUT && asioXRun == true ) {
  3024. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  3025. asioXRun = false;
  3026. }
  3027. if ( stream_.mode != OUTPUT && asioXRun == true ) {
  3028. status |= RTAUDIO_INPUT_OVERFLOW;
  3029. asioXRun = false;
  3030. }
  3031. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  3032. stream_.bufferSize, streamTime, status, info->userData );
  3033. if ( cbReturnValue == 2 ) {
  3034. stream_.state = STREAM_STOPPING;
  3035. handle->drainCounter = 2;
  3036. unsigned threadId;
  3037. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  3038. &stream_.callbackInfo, 0, &threadId );
  3039. return SUCCESS;
  3040. }
  3041. else if ( cbReturnValue == 1 ) {
  3042. handle->drainCounter = 1;
  3043. handle->internalDrain = true;
  3044. }
  3045. }
  3046. unsigned int nChannels, bufferBytes, i, j;
  3047. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  3048. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  3049. bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
  3050. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  3051. for ( i=0, j=0; i<nChannels; i++ ) {
  3052. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3053. memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
  3054. }
  3055. }
  3056. else if ( stream_.doConvertBuffer[0] ) {
  3057. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  3058. if ( stream_.doByteSwap[0] )
  3059. byteSwapBuffer( stream_.deviceBuffer,
  3060. stream_.bufferSize * stream_.nDeviceChannels[0],
  3061. stream_.deviceFormat[0] );
  3062. for ( i=0, j=0; i<nChannels; i++ ) {
  3063. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3064. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  3065. &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
  3066. }
  3067. }
  3068. else {
  3069. if ( stream_.doByteSwap[0] )
  3070. byteSwapBuffer( stream_.userBuffer[0],
  3071. stream_.bufferSize * stream_.nUserChannels[0],
  3072. stream_.userFormat );
  3073. for ( i=0, j=0; i<nChannels; i++ ) {
  3074. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3075. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  3076. &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
  3077. }
  3078. }
  3079. }
  3080. // Don't bother draining input
  3081. if ( handle->drainCounter ) {
  3082. handle->drainCounter++;
  3083. goto unlock;
  3084. }
  3085. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  3086. bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
  3087. if (stream_.doConvertBuffer[1]) {
  3088. // Always interleave ASIO input data.
  3089. for ( i=0, j=0; i<nChannels; i++ ) {
  3090. if ( handle->bufferInfos[i].isInput == ASIOTrue )
  3091. memcpy( &stream_.deviceBuffer[j++*bufferBytes],
  3092. handle->bufferInfos[i].buffers[bufferIndex],
  3093. bufferBytes );
  3094. }
  3095. if ( stream_.doByteSwap[1] )
  3096. byteSwapBuffer( stream_.deviceBuffer,
  3097. stream_.bufferSize * stream_.nDeviceChannels[1],
  3098. stream_.deviceFormat[1] );
  3099. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  3100. }
  3101. else {
  3102. for ( i=0, j=0; i<nChannels; i++ ) {
  3103. if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
  3104. memcpy( &stream_.userBuffer[1][bufferBytes*j++],
  3105. handle->bufferInfos[i].buffers[bufferIndex],
  3106. bufferBytes );
  3107. }
  3108. }
  3109. if ( stream_.doByteSwap[1] )
  3110. byteSwapBuffer( stream_.userBuffer[1],
  3111. stream_.bufferSize * stream_.nUserChannels[1],
  3112. stream_.userFormat );
  3113. }
  3114. }
  3115. unlock:
  3116. // The following call was suggested by Malte Clasen. While the API
  3117. // documentation indicates it should not be required, some device
  3118. // drivers apparently do not function correctly without it.
  3119. ASIOOutputReady();
  3120. RtApi::tickStreamTime();
  3121. return SUCCESS;
  3122. }
  3123. static void sampleRateChanged( ASIOSampleRate sRate )
  3124. {
  3125. // The ASIO documentation says that this usually only happens during
  3126. // external sync. Audio processing is not stopped by the driver,
  3127. // actual sample rate might not have even changed, maybe only the
  3128. // sample rate status of an AES/EBU or S/PDIF digital input at the
  3129. // audio device.
  3130. RtApi *object = (RtApi *) asioCallbackInfo->object;
  3131. try {
  3132. object->stopStream();
  3133. }
  3134. catch ( RtAudioError &exception ) {
  3135. std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
  3136. return;
  3137. }
  3138. std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
  3139. }
  3140. static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )
  3141. {
  3142. long ret = 0;
  3143. switch( selector ) {
  3144. case kAsioSelectorSupported:
  3145. if ( value == kAsioResetRequest
  3146. || value == kAsioEngineVersion
  3147. || value == kAsioResyncRequest
  3148. || value == kAsioLatenciesChanged
  3149. // The following three were added for ASIO 2.0, you don't
  3150. // necessarily have to support them.
  3151. || value == kAsioSupportsTimeInfo
  3152. || value == kAsioSupportsTimeCode
  3153. || value == kAsioSupportsInputMonitor)
  3154. ret = 1L;
  3155. break;
  3156. case kAsioResetRequest:
  3157. // Defer the task and perform the reset of the driver during the
  3158. // next "safe" situation. You cannot reset the driver right now,
  3159. // as this code is called from the driver. Reset the driver is
  3160. // done by completely destruct is. I.e. ASIOStop(),
  3161. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  3162. // driver again.
  3163. std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
  3164. ret = 1L;
  3165. break;
  3166. case kAsioResyncRequest:
  3167. // This informs the application that the driver encountered some
  3168. // non-fatal data loss. It is used for synchronization purposes
  3169. // of different media. Added mainly to work around the Win16Mutex
  3170. // problems in Windows 95/98 with the Windows Multimedia system,
  3171. // which could lose data because the Mutex was held too long by
  3172. // another thread. However a driver can issue it in other
  3173. // situations, too.
  3174. // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
  3175. asioXRun = true;
  3176. ret = 1L;
  3177. break;
  3178. case kAsioLatenciesChanged:
  3179. // This will inform the host application that the drivers were
  3180. // latencies changed. Beware, it this does not mean that the
  3181. // buffer sizes have changed! You might need to update internal
  3182. // delay data.
  3183. std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
  3184. ret = 1L;
  3185. break;
  3186. case kAsioEngineVersion:
  3187. // Return the supported ASIO version of the host application. If
  3188. // a host application does not implement this selector, ASIO 1.0
  3189. // is assumed by the driver.
  3190. ret = 2L;
  3191. break;
  3192. case kAsioSupportsTimeInfo:
  3193. // Informs the driver whether the
  3194. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  3195. // For compatibility with ASIO 1.0 drivers the host application
  3196. // should always support the "old" bufferSwitch method, too.
  3197. ret = 0;
  3198. break;
  3199. case kAsioSupportsTimeCode:
  3200. // Informs the driver whether application is interested in time
  3201. // code info. If an application does not need to know about time
  3202. // code, the driver has less work to do.
  3203. ret = 0;
  3204. break;
  3205. }
  3206. return ret;
  3207. }
  3208. static const char* getAsioErrorString( ASIOError result )
  3209. {
  3210. struct Messages
  3211. {
  3212. ASIOError value;
  3213. const char*message;
  3214. };
  3215. static const Messages m[] =
  3216. {
  3217. { ASE_NotPresent, "Hardware input or output is not present or available." },
  3218. { ASE_HWMalfunction, "Hardware is malfunctioning." },
  3219. { ASE_InvalidParameter, "Invalid input parameter." },
  3220. { ASE_InvalidMode, "Invalid mode." },
  3221. { ASE_SPNotAdvancing, "Sample position not advancing." },
  3222. { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
  3223. { ASE_NoMemory, "Not enough memory to complete the request." }
  3224. };
  3225. for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
  3226. if ( m[i].value == result ) return m[i].message;
  3227. return "Unknown error.";
  3228. }
  3229. //******************** End of __WINDOWS_ASIO__ *********************//
  3230. #endif
  3231. #if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
  3232. // Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014
  3233. // - Introduces support for the Windows WASAPI API
  3234. // - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required
  3235. // - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface
  3236. // - Includes automatic internal conversion of sample rate and buffer size between hardware and the user
  3237. #ifndef INITGUID
  3238. #define INITGUID
  3239. #endif
  3240. #include <mfapi.h>
  3241. #include <mferror.h>
  3242. #include <mfplay.h>
  3243. #include <mftransform.h>
  3244. #include <wmcodecdsp.h>
  3245. #include <audioclient.h>
  3246. #include <avrt.h>
  3247. #include <mmdeviceapi.h>
  3248. #include <functiondiscoverykeys_devpkey.h>
  3249. #ifndef MF_E_TRANSFORM_NEED_MORE_INPUT
  3250. #define MF_E_TRANSFORM_NEED_MORE_INPUT _HRESULT_TYPEDEF_(0xc00d6d72)
  3251. #endif
  3252. #ifndef MFSTARTUP_NOSOCKET
  3253. #define MFSTARTUP_NOSOCKET 0x1
  3254. #endif
  3255. #ifdef _MSC_VER
  3256. #pragma comment( lib, "ksuser" )
  3257. #pragma comment( lib, "mfplat.lib" )
  3258. #pragma comment( lib, "mfuuid.lib" )
  3259. #pragma comment( lib, "wmcodecdspuuid" )
  3260. #endif
  3261. //=============================================================================
  3262. #define SAFE_RELEASE( objectPtr )\
  3263. if ( objectPtr )\
  3264. {\
  3265. objectPtr->Release();\
  3266. objectPtr = NULL;\
  3267. }
  3268. typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );
  3269. //-----------------------------------------------------------------------------
  3270. // WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
  3271. // Therefore we must perform all necessary conversions to user buffers in order to satisfy these
  3272. // requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
  3273. // provide intermediate storage for read / write synchronization.
  3274. class WasapiBuffer
  3275. {
  3276. public:
  3277. WasapiBuffer()
  3278. : buffer_( NULL ),
  3279. bufferSize_( 0 ),
  3280. inIndex_( 0 ),
  3281. outIndex_( 0 ) {}
  3282. ~WasapiBuffer() {
  3283. free( buffer_ );
  3284. }
  3285. // sets the length of the internal ring buffer
  3286. void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {
  3287. free( buffer_ );
  3288. buffer_ = ( char* ) calloc( bufferSize, formatBytes );
  3289. bufferSize_ = bufferSize;
  3290. inIndex_ = 0;
  3291. outIndex_ = 0;
  3292. }
  3293. // attempt to push a buffer into the ring buffer at the current "in" index
  3294. bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3295. {
  3296. if ( !buffer || // incoming buffer is NULL
  3297. bufferSize == 0 || // incoming buffer has no data
  3298. bufferSize > bufferSize_ ) // incoming buffer too large
  3299. {
  3300. return false;
  3301. }
  3302. unsigned int relOutIndex = outIndex_;
  3303. unsigned int inIndexEnd = inIndex_ + bufferSize;
  3304. if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {
  3305. relOutIndex += bufferSize_;
  3306. }
  3307. // the "IN" index CAN BEGIN at the "OUT" index
  3308. // the "IN" index CANNOT END at the "OUT" index
  3309. if ( inIndex_ < relOutIndex && inIndexEnd >= relOutIndex ) {
  3310. return false; // not enough space between "in" index and "out" index
  3311. }
  3312. // copy buffer from external to internal
  3313. int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
  3314. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3315. int fromInSize = bufferSize - fromZeroSize;
  3316. switch( format )
  3317. {
  3318. case RTAUDIO_SINT8:
  3319. memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );
  3320. memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );
  3321. break;
  3322. case RTAUDIO_SINT16:
  3323. memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );
  3324. memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );
  3325. break;
  3326. case RTAUDIO_SINT24:
  3327. memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );
  3328. memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );
  3329. break;
  3330. case RTAUDIO_SINT32:
  3331. memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );
  3332. memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );
  3333. break;
  3334. case RTAUDIO_FLOAT32:
  3335. memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );
  3336. memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );
  3337. break;
  3338. case RTAUDIO_FLOAT64:
  3339. memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );
  3340. memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );
  3341. break;
  3342. }
  3343. // update "in" index
  3344. inIndex_ += bufferSize;
  3345. inIndex_ %= bufferSize_;
  3346. return true;
  3347. }
  3348. // attempt to pull a buffer from the ring buffer from the current "out" index
  3349. bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3350. {
  3351. if ( !buffer || // incoming buffer is NULL
  3352. bufferSize == 0 || // incoming buffer has no data
  3353. bufferSize > bufferSize_ ) // incoming buffer too large
  3354. {
  3355. return false;
  3356. }
  3357. unsigned int relInIndex = inIndex_;
  3358. unsigned int outIndexEnd = outIndex_ + bufferSize;
  3359. if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {
  3360. relInIndex += bufferSize_;
  3361. }
  3362. // the "OUT" index CANNOT BEGIN at the "IN" index
  3363. // the "OUT" index CAN END at the "IN" index
  3364. if ( outIndex_ <= relInIndex && outIndexEnd > relInIndex ) {
  3365. return false; // not enough space between "out" index and "in" index
  3366. }
  3367. // copy buffer from internal to external
  3368. int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
  3369. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3370. int fromOutSize = bufferSize - fromZeroSize;
  3371. switch( format )
  3372. {
  3373. case RTAUDIO_SINT8:
  3374. memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );
  3375. memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );
  3376. break;
  3377. case RTAUDIO_SINT16:
  3378. memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );
  3379. memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );
  3380. break;
  3381. case RTAUDIO_SINT24:
  3382. memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );
  3383. memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );
  3384. break;
  3385. case RTAUDIO_SINT32:
  3386. memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );
  3387. memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );
  3388. break;
  3389. case RTAUDIO_FLOAT32:
  3390. memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );
  3391. memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );
  3392. break;
  3393. case RTAUDIO_FLOAT64:
  3394. memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );
  3395. memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );
  3396. break;
  3397. }
  3398. // update "out" index
  3399. outIndex_ += bufferSize;
  3400. outIndex_ %= bufferSize_;
  3401. return true;
  3402. }
  3403. private:
  3404. char* buffer_;
  3405. unsigned int bufferSize_;
  3406. unsigned int inIndex_;
  3407. unsigned int outIndex_;
  3408. };
  3409. //-----------------------------------------------------------------------------
  3410. // In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate
  3411. // between HW and the user. The WasapiResampler class is used to perform this conversion between
  3412. // HwIn->UserIn and UserOut->HwOut during the stream callback loop.
  3413. class WasapiResampler
  3414. {
  3415. public:
  3416. WasapiResampler( bool isFloat, unsigned int bitsPerSample, unsigned int channelCount,
  3417. unsigned int inSampleRate, unsigned int outSampleRate )
  3418. : _bytesPerSample( bitsPerSample / 8 )
  3419. , _channelCount( channelCount )
  3420. , _sampleRatio( ( float ) outSampleRate / inSampleRate )
  3421. , _transformUnk( NULL )
  3422. , _transform( NULL )
  3423. , _mediaType( NULL )
  3424. , _inputMediaType( NULL )
  3425. , _outputMediaType( NULL )
  3426. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3427. , _resamplerProps( NULL )
  3428. #endif
  3429. {
  3430. // 1. Initialization
  3431. MFStartup( MF_VERSION, MFSTARTUP_NOSOCKET );
  3432. // 2. Create Resampler Transform Object
  3433. CoCreateInstance( CLSID_CResamplerMediaObject, NULL, CLSCTX_INPROC_SERVER,
  3434. IID_IUnknown, ( void** ) &_transformUnk );
  3435. _transformUnk->QueryInterface( IID_PPV_ARGS( &_transform ) );
  3436. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3437. _transformUnk->QueryInterface( IID_PPV_ARGS( &_resamplerProps ) );
  3438. _resamplerProps->SetHalfFilterLength( 60 ); // best conversion quality
  3439. #endif
  3440. // 3. Specify input / output format
  3441. MFCreateMediaType( &_mediaType );
  3442. _mediaType->SetGUID( MF_MT_MAJOR_TYPE, MFMediaType_Audio );
  3443. _mediaType->SetGUID( MF_MT_SUBTYPE, isFloat ? MFAudioFormat_Float : MFAudioFormat_PCM );
  3444. _mediaType->SetUINT32( MF_MT_AUDIO_NUM_CHANNELS, channelCount );
  3445. _mediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, inSampleRate );
  3446. _mediaType->SetUINT32( MF_MT_AUDIO_BLOCK_ALIGNMENT, _bytesPerSample * channelCount );
  3447. _mediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * inSampleRate );
  3448. _mediaType->SetUINT32( MF_MT_AUDIO_BITS_PER_SAMPLE, bitsPerSample );
  3449. _mediaType->SetUINT32( MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE );
  3450. MFCreateMediaType( &_inputMediaType );
  3451. _mediaType->CopyAllItems( _inputMediaType );
  3452. _transform->SetInputType( 0, _inputMediaType, 0 );
  3453. MFCreateMediaType( &_outputMediaType );
  3454. _mediaType->CopyAllItems( _outputMediaType );
  3455. _outputMediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, outSampleRate );
  3456. _outputMediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * outSampleRate );
  3457. _transform->SetOutputType( 0, _outputMediaType, 0 );
  3458. // 4. Send stream start messages to Resampler
  3459. _transform->ProcessMessage( MFT_MESSAGE_COMMAND_FLUSH, 0 );
  3460. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0 );
  3461. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0 );
  3462. }
  3463. ~WasapiResampler()
  3464. {
  3465. // 8. Send stream stop messages to Resampler
  3466. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0 );
  3467. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_STREAMING, 0 );
  3468. // 9. Cleanup
  3469. MFShutdown();
  3470. SAFE_RELEASE( _transformUnk );
  3471. SAFE_RELEASE( _transform );
  3472. SAFE_RELEASE( _mediaType );
  3473. SAFE_RELEASE( _inputMediaType );
  3474. SAFE_RELEASE( _outputMediaType );
  3475. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3476. SAFE_RELEASE( _resamplerProps );
  3477. #endif
  3478. }
  3479. void Convert( char* outBuffer, const char* inBuffer, unsigned int inSampleCount, unsigned int& outSampleCount )
  3480. {
  3481. unsigned int inputBufferSize = _bytesPerSample * _channelCount * inSampleCount;
  3482. if ( _sampleRatio == 1 )
  3483. {
  3484. // no sample rate conversion required
  3485. memcpy( outBuffer, inBuffer, inputBufferSize );
  3486. outSampleCount = inSampleCount;
  3487. return;
  3488. }
  3489. unsigned int outputBufferSize = ( unsigned int ) ceilf( inputBufferSize * _sampleRatio ) + ( _bytesPerSample * _channelCount );
  3490. IMFMediaBuffer* rInBuffer;
  3491. IMFSample* rInSample;
  3492. BYTE* rInByteBuffer = NULL;
  3493. // 5. Create Sample object from input data
  3494. MFCreateMemoryBuffer( inputBufferSize, &rInBuffer );
  3495. rInBuffer->Lock( &rInByteBuffer, NULL, NULL );
  3496. memcpy( rInByteBuffer, inBuffer, inputBufferSize );
  3497. rInBuffer->Unlock();
  3498. rInByteBuffer = NULL;
  3499. rInBuffer->SetCurrentLength( inputBufferSize );
  3500. MFCreateSample( &rInSample );
  3501. rInSample->AddBuffer( rInBuffer );
  3502. // 6. Pass input data to Resampler
  3503. _transform->ProcessInput( 0, rInSample, 0 );
  3504. SAFE_RELEASE( rInBuffer );
  3505. SAFE_RELEASE( rInSample );
  3506. // 7. Perform sample rate conversion
  3507. IMFMediaBuffer* rOutBuffer = NULL;
  3508. BYTE* rOutByteBuffer = NULL;
  3509. MFT_OUTPUT_DATA_BUFFER rOutDataBuffer;
  3510. DWORD rStatus;
  3511. DWORD rBytes = outputBufferSize; // maximum bytes accepted per ProcessOutput
  3512. // 7.1 Create Sample object for output data
  3513. memset( &rOutDataBuffer, 0, sizeof rOutDataBuffer );
  3514. MFCreateSample( &( rOutDataBuffer.pSample ) );
  3515. MFCreateMemoryBuffer( rBytes, &rOutBuffer );
  3516. rOutDataBuffer.pSample->AddBuffer( rOutBuffer );
  3517. rOutDataBuffer.dwStreamID = 0;
  3518. rOutDataBuffer.dwStatus = 0;
  3519. rOutDataBuffer.pEvents = NULL;
  3520. // 7.2 Get output data from Resampler
  3521. if ( _transform->ProcessOutput( 0, 1, &rOutDataBuffer, &rStatus ) == MF_E_TRANSFORM_NEED_MORE_INPUT )
  3522. {
  3523. outSampleCount = 0;
  3524. SAFE_RELEASE( rOutBuffer );
  3525. SAFE_RELEASE( rOutDataBuffer.pSample );
  3526. return;
  3527. }
  3528. // 7.3 Write output data to outBuffer
  3529. SAFE_RELEASE( rOutBuffer );
  3530. rOutDataBuffer.pSample->ConvertToContiguousBuffer( &rOutBuffer );
  3531. rOutBuffer->GetCurrentLength( &rBytes );
  3532. rOutBuffer->Lock( &rOutByteBuffer, NULL, NULL );
  3533. memcpy( outBuffer, rOutByteBuffer, rBytes );
  3534. rOutBuffer->Unlock();
  3535. rOutByteBuffer = NULL;
  3536. outSampleCount = rBytes / _bytesPerSample / _channelCount;
  3537. SAFE_RELEASE( rOutBuffer );
  3538. SAFE_RELEASE( rOutDataBuffer.pSample );
  3539. }
  3540. private:
  3541. unsigned int _bytesPerSample;
  3542. unsigned int _channelCount;
  3543. float _sampleRatio;
  3544. IUnknown* _transformUnk;
  3545. IMFTransform* _transform;
  3546. IMFMediaType* _mediaType;
  3547. IMFMediaType* _inputMediaType;
  3548. IMFMediaType* _outputMediaType;
  3549. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3550. IWMResamplerProps* _resamplerProps;
  3551. #endif
  3552. };
  3553. //-----------------------------------------------------------------------------
  3554. // A structure to hold various information related to the WASAPI implementation.
  3555. struct WasapiHandle
  3556. {
  3557. IAudioClient* captureAudioClient;
  3558. IAudioClient* renderAudioClient;
  3559. IAudioCaptureClient* captureClient;
  3560. IAudioRenderClient* renderClient;
  3561. HANDLE captureEvent;
  3562. HANDLE renderEvent;
  3563. WasapiHandle()
  3564. : captureAudioClient( NULL ),
  3565. renderAudioClient( NULL ),
  3566. captureClient( NULL ),
  3567. renderClient( NULL ),
  3568. captureEvent( NULL ),
  3569. renderEvent( NULL ) {}
  3570. };
  3571. //=============================================================================
  3572. RtApiWasapi::RtApiWasapi()
  3573. : coInitialized_( false ), deviceEnumerator_( NULL )
  3574. {
  3575. // WASAPI can run either apartment or multi-threaded
  3576. HRESULT hr = CoInitialize( NULL );
  3577. if ( !FAILED( hr ) )
  3578. coInitialized_ = true;
  3579. // Instantiate device enumerator
  3580. hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
  3581. CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
  3582. ( void** ) &deviceEnumerator_ );
  3583. // If this runs on an old Windows, it will fail. Ignore and proceed.
  3584. if ( FAILED( hr ) )
  3585. deviceEnumerator_ = NULL;
  3586. }
  3587. //-----------------------------------------------------------------------------
  3588. RtApiWasapi::~RtApiWasapi()
  3589. {
  3590. if ( stream_.state != STREAM_CLOSED )
  3591. closeStream();
  3592. SAFE_RELEASE( deviceEnumerator_ );
  3593. // If this object previously called CoInitialize()
  3594. if ( coInitialized_ )
  3595. CoUninitialize();
  3596. }
  3597. //=============================================================================
  3598. unsigned int RtApiWasapi::getDeviceCount( void )
  3599. {
  3600. unsigned int captureDeviceCount = 0;
  3601. unsigned int renderDeviceCount = 0;
  3602. IMMDeviceCollection* captureDevices = NULL;
  3603. IMMDeviceCollection* renderDevices = NULL;
  3604. if ( !deviceEnumerator_ )
  3605. return 0;
  3606. // Count capture devices
  3607. errorText_.clear();
  3608. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3609. if ( FAILED( hr ) ) {
  3610. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
  3611. goto Exit;
  3612. }
  3613. hr = captureDevices->GetCount( &captureDeviceCount );
  3614. if ( FAILED( hr ) ) {
  3615. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
  3616. goto Exit;
  3617. }
  3618. // Count render devices
  3619. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3620. if ( FAILED( hr ) ) {
  3621. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
  3622. goto Exit;
  3623. }
  3624. hr = renderDevices->GetCount( &renderDeviceCount );
  3625. if ( FAILED( hr ) ) {
  3626. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
  3627. goto Exit;
  3628. }
  3629. Exit:
  3630. // release all references
  3631. SAFE_RELEASE( captureDevices );
  3632. SAFE_RELEASE( renderDevices );
  3633. if ( errorText_.empty() )
  3634. return captureDeviceCount + renderDeviceCount;
  3635. error( RtAudioError::DRIVER_ERROR );
  3636. return 0;
  3637. }
  3638. //-----------------------------------------------------------------------------
  3639. RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
  3640. {
  3641. RtAudio::DeviceInfo info;
  3642. unsigned int captureDeviceCount = 0;
  3643. unsigned int renderDeviceCount = 0;
  3644. std::string defaultDeviceName;
  3645. bool isCaptureDevice = false;
  3646. PROPVARIANT deviceNameProp;
  3647. PROPVARIANT defaultDeviceNameProp;
  3648. IMMDeviceCollection* captureDevices = NULL;
  3649. IMMDeviceCollection* renderDevices = NULL;
  3650. IMMDevice* devicePtr = NULL;
  3651. IMMDevice* defaultDevicePtr = NULL;
  3652. IAudioClient* audioClient = NULL;
  3653. IPropertyStore* devicePropStore = NULL;
  3654. IPropertyStore* defaultDevicePropStore = NULL;
  3655. WAVEFORMATEX* deviceFormat = NULL;
  3656. WAVEFORMATEX* closestMatchFormat = NULL;
  3657. // probed
  3658. info.probed = false;
  3659. // Count capture devices
  3660. errorText_.clear();
  3661. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3662. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3663. if ( FAILED( hr ) ) {
  3664. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
  3665. goto Exit;
  3666. }
  3667. hr = captureDevices->GetCount( &captureDeviceCount );
  3668. if ( FAILED( hr ) ) {
  3669. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
  3670. goto Exit;
  3671. }
  3672. // Count render devices
  3673. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3674. if ( FAILED( hr ) ) {
  3675. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
  3676. goto Exit;
  3677. }
  3678. hr = renderDevices->GetCount( &renderDeviceCount );
  3679. if ( FAILED( hr ) ) {
  3680. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
  3681. goto Exit;
  3682. }
  3683. // validate device index
  3684. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3685. errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
  3686. errorType = RtAudioError::INVALID_USE;
  3687. goto Exit;
  3688. }
  3689. // determine whether index falls within capture or render devices
  3690. if ( device >= renderDeviceCount ) {
  3691. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3692. if ( FAILED( hr ) ) {
  3693. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
  3694. goto Exit;
  3695. }
  3696. isCaptureDevice = true;
  3697. }
  3698. else {
  3699. hr = renderDevices->Item( device, &devicePtr );
  3700. if ( FAILED( hr ) ) {
  3701. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
  3702. goto Exit;
  3703. }
  3704. isCaptureDevice = false;
  3705. }
  3706. // get default device name
  3707. if ( isCaptureDevice ) {
  3708. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );
  3709. if ( FAILED( hr ) ) {
  3710. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
  3711. goto Exit;
  3712. }
  3713. }
  3714. else {
  3715. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );
  3716. if ( FAILED( hr ) ) {
  3717. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
  3718. goto Exit;
  3719. }
  3720. }
  3721. hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );
  3722. if ( FAILED( hr ) ) {
  3723. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
  3724. goto Exit;
  3725. }
  3726. PropVariantInit( &defaultDeviceNameProp );
  3727. hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );
  3728. if ( FAILED( hr ) ) {
  3729. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
  3730. goto Exit;
  3731. }
  3732. defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);
  3733. // name
  3734. hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
  3735. if ( FAILED( hr ) ) {
  3736. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
  3737. goto Exit;
  3738. }
  3739. PropVariantInit( &deviceNameProp );
  3740. hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
  3741. if ( FAILED( hr ) ) {
  3742. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
  3743. goto Exit;
  3744. }
  3745. info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);
  3746. // is default
  3747. if ( isCaptureDevice ) {
  3748. info.isDefaultInput = info.name == defaultDeviceName;
  3749. info.isDefaultOutput = false;
  3750. }
  3751. else {
  3752. info.isDefaultInput = false;
  3753. info.isDefaultOutput = info.name == defaultDeviceName;
  3754. }
  3755. // channel count
  3756. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
  3757. if ( FAILED( hr ) ) {
  3758. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
  3759. goto Exit;
  3760. }
  3761. hr = audioClient->GetMixFormat( &deviceFormat );
  3762. if ( FAILED( hr ) ) {
  3763. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
  3764. goto Exit;
  3765. }
  3766. if ( isCaptureDevice ) {
  3767. info.inputChannels = deviceFormat->nChannels;
  3768. info.outputChannels = 0;
  3769. info.duplexChannels = 0;
  3770. }
  3771. else {
  3772. info.inputChannels = 0;
  3773. info.outputChannels = deviceFormat->nChannels;
  3774. info.duplexChannels = 0;
  3775. }
  3776. // sample rates
  3777. info.sampleRates.clear();
  3778. // allow support for all sample rates as we have a built-in sample rate converter
  3779. for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {
  3780. info.sampleRates.push_back( SAMPLE_RATES[i] );
  3781. }
  3782. info.preferredSampleRate = deviceFormat->nSamplesPerSec;
  3783. // native format
  3784. info.nativeFormats = 0;
  3785. if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
  3786. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3787. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
  3788. {
  3789. if ( deviceFormat->wBitsPerSample == 32 ) {
  3790. info.nativeFormats |= RTAUDIO_FLOAT32;
  3791. }
  3792. else if ( deviceFormat->wBitsPerSample == 64 ) {
  3793. info.nativeFormats |= RTAUDIO_FLOAT64;
  3794. }
  3795. }
  3796. else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
  3797. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3798. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
  3799. {
  3800. if ( deviceFormat->wBitsPerSample == 8 ) {
  3801. info.nativeFormats |= RTAUDIO_SINT8;
  3802. }
  3803. else if ( deviceFormat->wBitsPerSample == 16 ) {
  3804. info.nativeFormats |= RTAUDIO_SINT16;
  3805. }
  3806. else if ( deviceFormat->wBitsPerSample == 24 ) {
  3807. info.nativeFormats |= RTAUDIO_SINT24;
  3808. }
  3809. else if ( deviceFormat->wBitsPerSample == 32 ) {
  3810. info.nativeFormats |= RTAUDIO_SINT32;
  3811. }
  3812. }
  3813. // probed
  3814. info.probed = true;
  3815. Exit:
  3816. // release all references
  3817. PropVariantClear( &deviceNameProp );
  3818. PropVariantClear( &defaultDeviceNameProp );
  3819. SAFE_RELEASE( captureDevices );
  3820. SAFE_RELEASE( renderDevices );
  3821. SAFE_RELEASE( devicePtr );
  3822. SAFE_RELEASE( defaultDevicePtr );
  3823. SAFE_RELEASE( audioClient );
  3824. SAFE_RELEASE( devicePropStore );
  3825. SAFE_RELEASE( defaultDevicePropStore );
  3826. CoTaskMemFree( deviceFormat );
  3827. CoTaskMemFree( closestMatchFormat );
  3828. if ( !errorText_.empty() )
  3829. error( errorType );
  3830. return info;
  3831. }
  3832. //-----------------------------------------------------------------------------
  3833. unsigned int RtApiWasapi::getDefaultOutputDevice( void )
  3834. {
  3835. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3836. if ( getDeviceInfo( i ).isDefaultOutput ) {
  3837. return i;
  3838. }
  3839. }
  3840. return 0;
  3841. }
  3842. //-----------------------------------------------------------------------------
  3843. unsigned int RtApiWasapi::getDefaultInputDevice( void )
  3844. {
  3845. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3846. if ( getDeviceInfo( i ).isDefaultInput ) {
  3847. return i;
  3848. }
  3849. }
  3850. return 0;
  3851. }
  3852. //-----------------------------------------------------------------------------
  3853. void RtApiWasapi::closeStream( void )
  3854. {
  3855. if ( stream_.state == STREAM_CLOSED ) {
  3856. errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
  3857. error( RtAudioError::WARNING );
  3858. return;
  3859. }
  3860. if ( stream_.state != STREAM_STOPPED )
  3861. stopStream();
  3862. // clean up stream memory
  3863. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
  3864. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
  3865. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )
  3866. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )
  3867. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
  3868. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
  3869. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
  3870. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
  3871. delete ( WasapiHandle* ) stream_.apiHandle;
  3872. stream_.apiHandle = NULL;
  3873. for ( int i = 0; i < 2; i++ ) {
  3874. if ( stream_.userBuffer[i] ) {
  3875. free( stream_.userBuffer[i] );
  3876. stream_.userBuffer[i] = 0;
  3877. }
  3878. }
  3879. if ( stream_.deviceBuffer ) {
  3880. free( stream_.deviceBuffer );
  3881. stream_.deviceBuffer = 0;
  3882. }
  3883. // update stream state
  3884. stream_.state = STREAM_CLOSED;
  3885. }
  3886. //-----------------------------------------------------------------------------
  3887. void RtApiWasapi::startStream( void )
  3888. {
  3889. verifyStream();
  3890. if ( stream_.state == STREAM_RUNNING ) {
  3891. errorText_ = "RtApiWasapi::startStream: The stream is already running.";
  3892. error( RtAudioError::WARNING );
  3893. return;
  3894. }
  3895. #if defined( HAVE_GETTIMEOFDAY )
  3896. gettimeofday( &stream_.lastTickTimestamp, NULL );
  3897. #endif
  3898. // update stream state
  3899. stream_.state = STREAM_RUNNING;
  3900. // create WASAPI stream thread
  3901. stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
  3902. if ( !stream_.callbackInfo.thread ) {
  3903. errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
  3904. error( RtAudioError::THREAD_ERROR );
  3905. }
  3906. else {
  3907. SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
  3908. ResumeThread( ( void* ) stream_.callbackInfo.thread );
  3909. }
  3910. }
  3911. //-----------------------------------------------------------------------------
  3912. void RtApiWasapi::stopStream( void )
  3913. {
  3914. verifyStream();
  3915. if ( stream_.state == STREAM_STOPPED ) {
  3916. errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
  3917. error( RtAudioError::WARNING );
  3918. return;
  3919. }
  3920. // inform stream thread by setting stream state to STREAM_STOPPING
  3921. stream_.state = STREAM_STOPPING;
  3922. // wait until stream thread is stopped
  3923. while( stream_.state != STREAM_STOPPED ) {
  3924. Sleep( 1 );
  3925. }
  3926. // Wait for the last buffer to play before stopping.
  3927. Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );
  3928. // close thread handle
  3929. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3930. errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
  3931. error( RtAudioError::THREAD_ERROR );
  3932. return;
  3933. }
  3934. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3935. }
  3936. //-----------------------------------------------------------------------------
  3937. void RtApiWasapi::abortStream( void )
  3938. {
  3939. verifyStream();
  3940. if ( stream_.state == STREAM_STOPPED ) {
  3941. errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
  3942. error( RtAudioError::WARNING );
  3943. return;
  3944. }
  3945. // inform stream thread by setting stream state to STREAM_STOPPING
  3946. stream_.state = STREAM_STOPPING;
  3947. // wait until stream thread is stopped
  3948. while ( stream_.state != STREAM_STOPPED ) {
  3949. Sleep( 1 );
  3950. }
  3951. // close thread handle
  3952. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3953. errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
  3954. error( RtAudioError::THREAD_ERROR );
  3955. return;
  3956. }
  3957. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3958. }
  3959. //-----------------------------------------------------------------------------
  3960. bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3961. unsigned int firstChannel, unsigned int sampleRate,
  3962. RtAudioFormat format, unsigned int* bufferSize,
  3963. RtAudio::StreamOptions* options )
  3964. {
  3965. bool methodResult = FAILURE;
  3966. unsigned int captureDeviceCount = 0;
  3967. unsigned int renderDeviceCount = 0;
  3968. IMMDeviceCollection* captureDevices = NULL;
  3969. IMMDeviceCollection* renderDevices = NULL;
  3970. IMMDevice* devicePtr = NULL;
  3971. WAVEFORMATEX* deviceFormat = NULL;
  3972. unsigned int bufferBytes;
  3973. stream_.state = STREAM_STOPPED;
  3974. // create API Handle if not already created
  3975. if ( !stream_.apiHandle )
  3976. stream_.apiHandle = ( void* ) new WasapiHandle();
  3977. // Count capture devices
  3978. errorText_.clear();
  3979. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3980. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3981. if ( FAILED( hr ) ) {
  3982. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
  3983. goto Exit;
  3984. }
  3985. hr = captureDevices->GetCount( &captureDeviceCount );
  3986. if ( FAILED( hr ) ) {
  3987. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
  3988. goto Exit;
  3989. }
  3990. // Count render devices
  3991. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3992. if ( FAILED( hr ) ) {
  3993. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
  3994. goto Exit;
  3995. }
  3996. hr = renderDevices->GetCount( &renderDeviceCount );
  3997. if ( FAILED( hr ) ) {
  3998. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
  3999. goto Exit;
  4000. }
  4001. // validate device index
  4002. if ( device >= captureDeviceCount + renderDeviceCount ) {
  4003. errorType = RtAudioError::INVALID_USE;
  4004. errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
  4005. goto Exit;
  4006. }
  4007. // if device index falls within capture devices
  4008. if ( device >= renderDeviceCount ) {
  4009. if ( mode != INPUT ) {
  4010. errorType = RtAudioError::INVALID_USE;
  4011. errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
  4012. goto Exit;
  4013. }
  4014. // retrieve captureAudioClient from devicePtr
  4015. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4016. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  4017. if ( FAILED( hr ) ) {
  4018. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
  4019. goto Exit;
  4020. }
  4021. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4022. NULL, ( void** ) &captureAudioClient );
  4023. if ( FAILED( hr ) ) {
  4024. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device audio client.";
  4025. goto Exit;
  4026. }
  4027. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  4028. if ( FAILED( hr ) ) {
  4029. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device mix format.";
  4030. goto Exit;
  4031. }
  4032. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4033. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4034. }
  4035. // if device index falls within render devices and is configured for loopback
  4036. if ( device < renderDeviceCount && mode == INPUT )
  4037. {
  4038. // if renderAudioClient is not initialised, initialise it now
  4039. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4040. if ( !renderAudioClient )
  4041. {
  4042. probeDeviceOpen( device, OUTPUT, channels, firstChannel, sampleRate, format, bufferSize, options );
  4043. }
  4044. // retrieve captureAudioClient from devicePtr
  4045. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4046. hr = renderDevices->Item( device, &devicePtr );
  4047. if ( FAILED( hr ) ) {
  4048. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  4049. goto Exit;
  4050. }
  4051. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4052. NULL, ( void** ) &captureAudioClient );
  4053. if ( FAILED( hr ) ) {
  4054. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
  4055. goto Exit;
  4056. }
  4057. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  4058. if ( FAILED( hr ) ) {
  4059. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
  4060. goto Exit;
  4061. }
  4062. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4063. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4064. }
  4065. // if device index falls within render devices and is configured for output
  4066. if ( device < renderDeviceCount && mode == OUTPUT )
  4067. {
  4068. // if renderAudioClient is already initialised, don't initialise it again
  4069. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4070. if ( renderAudioClient )
  4071. {
  4072. methodResult = SUCCESS;
  4073. goto Exit;
  4074. }
  4075. hr = renderDevices->Item( device, &devicePtr );
  4076. if ( FAILED( hr ) ) {
  4077. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  4078. goto Exit;
  4079. }
  4080. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4081. NULL, ( void** ) &renderAudioClient );
  4082. if ( FAILED( hr ) ) {
  4083. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
  4084. goto Exit;
  4085. }
  4086. hr = renderAudioClient->GetMixFormat( &deviceFormat );
  4087. if ( FAILED( hr ) ) {
  4088. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
  4089. goto Exit;
  4090. }
  4091. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4092. renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4093. }
  4094. // fill stream data
  4095. if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
  4096. ( stream_.mode == INPUT && mode == OUTPUT ) ) {
  4097. stream_.mode = DUPLEX;
  4098. }
  4099. else {
  4100. stream_.mode = mode;
  4101. }
  4102. stream_.device[mode] = device;
  4103. stream_.doByteSwap[mode] = false;
  4104. stream_.sampleRate = sampleRate;
  4105. stream_.bufferSize = *bufferSize;
  4106. stream_.nBuffers = 1;
  4107. stream_.nUserChannels[mode] = channels;
  4108. stream_.channelOffset[mode] = firstChannel;
  4109. stream_.userFormat = format;
  4110. stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats;
  4111. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  4112. stream_.userInterleaved = false;
  4113. else
  4114. stream_.userInterleaved = true;
  4115. stream_.deviceInterleaved[mode] = true;
  4116. // Set flags for buffer conversion.
  4117. stream_.doConvertBuffer[mode] = false;
  4118. if ( stream_.userFormat != stream_.deviceFormat[mode] ||
  4119. stream_.nUserChannels[0] != stream_.nDeviceChannels[0] ||
  4120. stream_.nUserChannels[1] != stream_.nDeviceChannels[1] )
  4121. stream_.doConvertBuffer[mode] = true;
  4122. else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4123. stream_.nUserChannels[mode] > 1 )
  4124. stream_.doConvertBuffer[mode] = true;
  4125. if ( stream_.doConvertBuffer[mode] )
  4126. setConvertInfo( mode, 0 );
  4127. // Allocate necessary internal buffers
  4128. bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
  4129. stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
  4130. if ( !stream_.userBuffer[mode] ) {
  4131. errorType = RtAudioError::MEMORY_ERROR;
  4132. errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
  4133. goto Exit;
  4134. }
  4135. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
  4136. stream_.callbackInfo.priority = 15;
  4137. else
  4138. stream_.callbackInfo.priority = 0;
  4139. ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
  4140. ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
  4141. methodResult = SUCCESS;
  4142. Exit:
  4143. //clean up
  4144. SAFE_RELEASE( captureDevices );
  4145. SAFE_RELEASE( renderDevices );
  4146. SAFE_RELEASE( devicePtr );
  4147. CoTaskMemFree( deviceFormat );
  4148. // if method failed, close the stream
  4149. if ( methodResult == FAILURE )
  4150. closeStream();
  4151. if ( !errorText_.empty() )
  4152. error( errorType );
  4153. return methodResult;
  4154. }
  4155. //=============================================================================
  4156. DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
  4157. {
  4158. if ( wasapiPtr )
  4159. ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
  4160. return 0;
  4161. }
  4162. DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
  4163. {
  4164. if ( wasapiPtr )
  4165. ( ( RtApiWasapi* ) wasapiPtr )->stopStream();
  4166. return 0;
  4167. }
  4168. DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
  4169. {
  4170. if ( wasapiPtr )
  4171. ( ( RtApiWasapi* ) wasapiPtr )->abortStream();
  4172. return 0;
  4173. }
  4174. //-----------------------------------------------------------------------------
  4175. void RtApiWasapi::wasapiThread()
  4176. {
  4177. // as this is a new thread, we must CoInitialize it
  4178. CoInitialize( NULL );
  4179. HRESULT hr;
  4180. IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4181. IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4182. IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
  4183. IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
  4184. HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
  4185. HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
  4186. WAVEFORMATEX* captureFormat = NULL;
  4187. WAVEFORMATEX* renderFormat = NULL;
  4188. float captureSrRatio = 0.0f;
  4189. float renderSrRatio = 0.0f;
  4190. WasapiBuffer captureBuffer;
  4191. WasapiBuffer renderBuffer;
  4192. WasapiResampler* captureResampler = NULL;
  4193. WasapiResampler* renderResampler = NULL;
  4194. // declare local stream variables
  4195. RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
  4196. BYTE* streamBuffer = NULL;
  4197. unsigned long captureFlags = 0;
  4198. unsigned int bufferFrameCount = 0;
  4199. unsigned int numFramesPadding = 0;
  4200. unsigned int convBufferSize = 0;
  4201. bool loopbackEnabled = stream_.device[INPUT] == stream_.device[OUTPUT];
  4202. bool callbackPushed = true;
  4203. bool callbackPulled = false;
  4204. bool callbackStopped = false;
  4205. int callbackResult = 0;
  4206. // convBuffer is used to store converted buffers between WASAPI and the user
  4207. char* convBuffer = NULL;
  4208. unsigned int convBuffSize = 0;
  4209. unsigned int deviceBuffSize = 0;
  4210. std::string errorText;
  4211. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  4212. // Attempt to assign "Pro Audio" characteristic to thread
  4213. HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );
  4214. if ( AvrtDll ) {
  4215. DWORD taskIndex = 0;
  4216. TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr =
  4217. ( TAvSetMmThreadCharacteristicsPtr ) (void(*)()) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
  4218. AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
  4219. FreeLibrary( AvrtDll );
  4220. }
  4221. // start capture stream if applicable
  4222. if ( captureAudioClient ) {
  4223. hr = captureAudioClient->GetMixFormat( &captureFormat );
  4224. if ( FAILED( hr ) ) {
  4225. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4226. goto Exit;
  4227. }
  4228. // init captureResampler
  4229. captureResampler = new WasapiResampler( stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT64,
  4230. formatBytes( stream_.deviceFormat[INPUT] ) * 8, stream_.nDeviceChannels[INPUT],
  4231. captureFormat->nSamplesPerSec, stream_.sampleRate );
  4232. captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );
  4233. if ( !captureClient ) {
  4234. hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4235. loopbackEnabled ? AUDCLNT_STREAMFLAGS_LOOPBACK : AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4236. 0,
  4237. 0,
  4238. captureFormat,
  4239. NULL );
  4240. if ( FAILED( hr ) ) {
  4241. errorText = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
  4242. goto Exit;
  4243. }
  4244. hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
  4245. ( void** ) &captureClient );
  4246. if ( FAILED( hr ) ) {
  4247. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
  4248. goto Exit;
  4249. }
  4250. // don't configure captureEvent if in loopback mode
  4251. if ( !loopbackEnabled )
  4252. {
  4253. // configure captureEvent to trigger on every available capture buffer
  4254. captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4255. if ( !captureEvent ) {
  4256. errorType = RtAudioError::SYSTEM_ERROR;
  4257. errorText = "RtApiWasapi::wasapiThread: Unable to create capture event.";
  4258. goto Exit;
  4259. }
  4260. hr = captureAudioClient->SetEventHandle( captureEvent );
  4261. if ( FAILED( hr ) ) {
  4262. errorText = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
  4263. goto Exit;
  4264. }
  4265. ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
  4266. }
  4267. ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
  4268. // reset the capture stream
  4269. hr = captureAudioClient->Reset();
  4270. if ( FAILED( hr ) ) {
  4271. errorText = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
  4272. goto Exit;
  4273. }
  4274. // start the capture stream
  4275. hr = captureAudioClient->Start();
  4276. if ( FAILED( hr ) ) {
  4277. errorText = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
  4278. goto Exit;
  4279. }
  4280. }
  4281. unsigned int inBufferSize = 0;
  4282. hr = captureAudioClient->GetBufferSize( &inBufferSize );
  4283. if ( FAILED( hr ) ) {
  4284. errorText = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
  4285. goto Exit;
  4286. }
  4287. // scale outBufferSize according to stream->user sample rate ratio
  4288. unsigned int outBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];
  4289. inBufferSize *= stream_.nDeviceChannels[INPUT];
  4290. // set captureBuffer size
  4291. captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
  4292. }
  4293. // start render stream if applicable
  4294. if ( renderAudioClient ) {
  4295. hr = renderAudioClient->GetMixFormat( &renderFormat );
  4296. if ( FAILED( hr ) ) {
  4297. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4298. goto Exit;
  4299. }
  4300. // init renderResampler
  4301. renderResampler = new WasapiResampler( stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT64,
  4302. formatBytes( stream_.deviceFormat[OUTPUT] ) * 8, stream_.nDeviceChannels[OUTPUT],
  4303. stream_.sampleRate, renderFormat->nSamplesPerSec );
  4304. renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );
  4305. if ( !renderClient ) {
  4306. hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4307. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4308. 0,
  4309. 0,
  4310. renderFormat,
  4311. NULL );
  4312. if ( FAILED( hr ) ) {
  4313. errorText = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
  4314. goto Exit;
  4315. }
  4316. hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
  4317. ( void** ) &renderClient );
  4318. if ( FAILED( hr ) ) {
  4319. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
  4320. goto Exit;
  4321. }
  4322. // configure renderEvent to trigger on every available render buffer
  4323. renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4324. if ( !renderEvent ) {
  4325. errorType = RtAudioError::SYSTEM_ERROR;
  4326. errorText = "RtApiWasapi::wasapiThread: Unable to create render event.";
  4327. goto Exit;
  4328. }
  4329. hr = renderAudioClient->SetEventHandle( renderEvent );
  4330. if ( FAILED( hr ) ) {
  4331. errorText = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
  4332. goto Exit;
  4333. }
  4334. ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
  4335. ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
  4336. // reset the render stream
  4337. hr = renderAudioClient->Reset();
  4338. if ( FAILED( hr ) ) {
  4339. errorText = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
  4340. goto Exit;
  4341. }
  4342. // start the render stream
  4343. hr = renderAudioClient->Start();
  4344. if ( FAILED( hr ) ) {
  4345. errorText = "RtApiWasapi::wasapiThread: Unable to start render stream.";
  4346. goto Exit;
  4347. }
  4348. }
  4349. unsigned int outBufferSize = 0;
  4350. hr = renderAudioClient->GetBufferSize( &outBufferSize );
  4351. if ( FAILED( hr ) ) {
  4352. errorText = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
  4353. goto Exit;
  4354. }
  4355. // scale inBufferSize according to user->stream sample rate ratio
  4356. unsigned int inBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];
  4357. outBufferSize *= stream_.nDeviceChannels[OUTPUT];
  4358. // set renderBuffer size
  4359. renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4360. }
  4361. // malloc buffer memory
  4362. if ( stream_.mode == INPUT )
  4363. {
  4364. using namespace std; // for ceilf
  4365. convBuffSize = ( size_t ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4366. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4367. }
  4368. else if ( stream_.mode == OUTPUT )
  4369. {
  4370. convBuffSize = ( size_t ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4371. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4372. }
  4373. else if ( stream_.mode == DUPLEX )
  4374. {
  4375. convBuffSize = std::max( ( size_t ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4376. ( size_t ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4377. deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4378. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4379. }
  4380. convBuffSize *= 2; // allow overflow for *SrRatio remainders
  4381. convBuffer = ( char* ) calloc( convBuffSize, 1 );
  4382. stream_.deviceBuffer = ( char* ) calloc( deviceBuffSize, 1 );
  4383. if ( !convBuffer || !stream_.deviceBuffer ) {
  4384. errorType = RtAudioError::MEMORY_ERROR;
  4385. errorText = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
  4386. goto Exit;
  4387. }
  4388. // stream process loop
  4389. while ( stream_.state != STREAM_STOPPING ) {
  4390. if ( !callbackPulled ) {
  4391. // Callback Input
  4392. // ==============
  4393. // 1. Pull callback buffer from inputBuffer
  4394. // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count
  4395. // Convert callback buffer to user format
  4396. if ( captureAudioClient )
  4397. {
  4398. int samplesToPull = ( unsigned int ) floorf( stream_.bufferSize * captureSrRatio );
  4399. if ( captureSrRatio != 1 )
  4400. {
  4401. // account for remainders
  4402. samplesToPull--;
  4403. }
  4404. convBufferSize = 0;
  4405. while ( convBufferSize < stream_.bufferSize )
  4406. {
  4407. // Pull callback buffer from inputBuffer
  4408. callbackPulled = captureBuffer.pullBuffer( convBuffer,
  4409. samplesToPull * stream_.nDeviceChannels[INPUT],
  4410. stream_.deviceFormat[INPUT] );
  4411. if ( !callbackPulled )
  4412. {
  4413. break;
  4414. }
  4415. // Convert callback buffer to user sample rate
  4416. unsigned int deviceBufferOffset = convBufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4417. unsigned int convSamples = 0;
  4418. captureResampler->Convert( stream_.deviceBuffer + deviceBufferOffset,
  4419. convBuffer,
  4420. samplesToPull,
  4421. convSamples );
  4422. convBufferSize += convSamples;
  4423. samplesToPull = 1; // now pull one sample at a time until we have stream_.bufferSize samples
  4424. }
  4425. if ( callbackPulled )
  4426. {
  4427. if ( stream_.doConvertBuffer[INPUT] ) {
  4428. // Convert callback buffer to user format
  4429. convertBuffer( stream_.userBuffer[INPUT],
  4430. stream_.deviceBuffer,
  4431. stream_.convertInfo[INPUT] );
  4432. }
  4433. else {
  4434. // no further conversion, simple copy deviceBuffer to userBuffer
  4435. memcpy( stream_.userBuffer[INPUT],
  4436. stream_.deviceBuffer,
  4437. stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
  4438. }
  4439. }
  4440. }
  4441. else {
  4442. // if there is no capture stream, set callbackPulled flag
  4443. callbackPulled = true;
  4444. }
  4445. // Execute Callback
  4446. // ================
  4447. // 1. Execute user callback method
  4448. // 2. Handle return value from callback
  4449. // if callback has not requested the stream to stop
  4450. if ( callbackPulled && !callbackStopped ) {
  4451. // Execute user callback method
  4452. callbackResult = callback( stream_.userBuffer[OUTPUT],
  4453. stream_.userBuffer[INPUT],
  4454. stream_.bufferSize,
  4455. getStreamTime(),
  4456. captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
  4457. stream_.callbackInfo.userData );
  4458. // tick stream time
  4459. RtApi::tickStreamTime();
  4460. // Handle return value from callback
  4461. if ( callbackResult == 1 ) {
  4462. // instantiate a thread to stop this thread
  4463. HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
  4464. if ( !threadHandle ) {
  4465. errorType = RtAudioError::THREAD_ERROR;
  4466. errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
  4467. goto Exit;
  4468. }
  4469. else if ( !CloseHandle( threadHandle ) ) {
  4470. errorType = RtAudioError::THREAD_ERROR;
  4471. errorText = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
  4472. goto Exit;
  4473. }
  4474. callbackStopped = true;
  4475. }
  4476. else if ( callbackResult == 2 ) {
  4477. // instantiate a thread to stop this thread
  4478. HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
  4479. if ( !threadHandle ) {
  4480. errorType = RtAudioError::THREAD_ERROR;
  4481. errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
  4482. goto Exit;
  4483. }
  4484. else if ( !CloseHandle( threadHandle ) ) {
  4485. errorType = RtAudioError::THREAD_ERROR;
  4486. errorText = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
  4487. goto Exit;
  4488. }
  4489. callbackStopped = true;
  4490. }
  4491. }
  4492. }
  4493. // Callback Output
  4494. // ===============
  4495. // 1. Convert callback buffer to stream format
  4496. // 2. Convert callback buffer to stream sample rate and channel count
  4497. // 3. Push callback buffer into outputBuffer
  4498. if ( renderAudioClient && callbackPulled )
  4499. {
  4500. // if the last call to renderBuffer.PushBuffer() was successful
  4501. if ( callbackPushed || convBufferSize == 0 )
  4502. {
  4503. if ( stream_.doConvertBuffer[OUTPUT] )
  4504. {
  4505. // Convert callback buffer to stream format
  4506. convertBuffer( stream_.deviceBuffer,
  4507. stream_.userBuffer[OUTPUT],
  4508. stream_.convertInfo[OUTPUT] );
  4509. }
  4510. else {
  4511. // no further conversion, simple copy userBuffer to deviceBuffer
  4512. memcpy( stream_.deviceBuffer,
  4513. stream_.userBuffer[OUTPUT],
  4514. stream_.bufferSize * stream_.nUserChannels[OUTPUT] * formatBytes( stream_.userFormat ) );
  4515. }
  4516. // Convert callback buffer to stream sample rate
  4517. renderResampler->Convert( convBuffer,
  4518. stream_.deviceBuffer,
  4519. stream_.bufferSize,
  4520. convBufferSize );
  4521. }
  4522. // Push callback buffer into outputBuffer
  4523. callbackPushed = renderBuffer.pushBuffer( convBuffer,
  4524. convBufferSize * stream_.nDeviceChannels[OUTPUT],
  4525. stream_.deviceFormat[OUTPUT] );
  4526. }
  4527. else {
  4528. // if there is no render stream, set callbackPushed flag
  4529. callbackPushed = true;
  4530. }
  4531. // Stream Capture
  4532. // ==============
  4533. // 1. Get capture buffer from stream
  4534. // 2. Push capture buffer into inputBuffer
  4535. // 3. If 2. was successful: Release capture buffer
  4536. if ( captureAudioClient ) {
  4537. // if the callback input buffer was not pulled from captureBuffer, wait for next capture event
  4538. if ( !callbackPulled ) {
  4539. WaitForSingleObject( loopbackEnabled ? renderEvent : captureEvent, INFINITE );
  4540. }
  4541. // Get capture buffer from stream
  4542. hr = captureClient->GetBuffer( &streamBuffer,
  4543. &bufferFrameCount,
  4544. &captureFlags, NULL, NULL );
  4545. if ( FAILED( hr ) ) {
  4546. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
  4547. goto Exit;
  4548. }
  4549. if ( bufferFrameCount != 0 ) {
  4550. // Push capture buffer into inputBuffer
  4551. if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
  4552. bufferFrameCount * stream_.nDeviceChannels[INPUT],
  4553. stream_.deviceFormat[INPUT] ) )
  4554. {
  4555. // Release capture buffer
  4556. hr = captureClient->ReleaseBuffer( bufferFrameCount );
  4557. if ( FAILED( hr ) ) {
  4558. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4559. goto Exit;
  4560. }
  4561. }
  4562. else
  4563. {
  4564. // Inform WASAPI that capture was unsuccessful
  4565. hr = captureClient->ReleaseBuffer( 0 );
  4566. if ( FAILED( hr ) ) {
  4567. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4568. goto Exit;
  4569. }
  4570. }
  4571. }
  4572. else
  4573. {
  4574. // Inform WASAPI that capture was unsuccessful
  4575. hr = captureClient->ReleaseBuffer( 0 );
  4576. if ( FAILED( hr ) ) {
  4577. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4578. goto Exit;
  4579. }
  4580. }
  4581. }
  4582. // Stream Render
  4583. // =============
  4584. // 1. Get render buffer from stream
  4585. // 2. Pull next buffer from outputBuffer
  4586. // 3. If 2. was successful: Fill render buffer with next buffer
  4587. // Release render buffer
  4588. if ( renderAudioClient ) {
  4589. // if the callback output buffer was not pushed to renderBuffer, wait for next render event
  4590. if ( callbackPulled && !callbackPushed ) {
  4591. WaitForSingleObject( renderEvent, INFINITE );
  4592. }
  4593. // Get render buffer from stream
  4594. hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
  4595. if ( FAILED( hr ) ) {
  4596. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
  4597. goto Exit;
  4598. }
  4599. hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
  4600. if ( FAILED( hr ) ) {
  4601. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
  4602. goto Exit;
  4603. }
  4604. bufferFrameCount -= numFramesPadding;
  4605. if ( bufferFrameCount != 0 ) {
  4606. hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
  4607. if ( FAILED( hr ) ) {
  4608. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
  4609. goto Exit;
  4610. }
  4611. // Pull next buffer from outputBuffer
  4612. // Fill render buffer with next buffer
  4613. if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
  4614. bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
  4615. stream_.deviceFormat[OUTPUT] ) )
  4616. {
  4617. // Release render buffer
  4618. hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
  4619. if ( FAILED( hr ) ) {
  4620. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4621. goto Exit;
  4622. }
  4623. }
  4624. else
  4625. {
  4626. // Inform WASAPI that render was unsuccessful
  4627. hr = renderClient->ReleaseBuffer( 0, 0 );
  4628. if ( FAILED( hr ) ) {
  4629. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4630. goto Exit;
  4631. }
  4632. }
  4633. }
  4634. else
  4635. {
  4636. // Inform WASAPI that render was unsuccessful
  4637. hr = renderClient->ReleaseBuffer( 0, 0 );
  4638. if ( FAILED( hr ) ) {
  4639. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4640. goto Exit;
  4641. }
  4642. }
  4643. }
  4644. // if the callback buffer was pushed renderBuffer reset callbackPulled flag
  4645. if ( callbackPushed ) {
  4646. // unsetting the callbackPulled flag lets the stream know that
  4647. // the audio device is ready for another callback output buffer.
  4648. callbackPulled = false;
  4649. }
  4650. }
  4651. Exit:
  4652. // clean up
  4653. CoTaskMemFree( captureFormat );
  4654. CoTaskMemFree( renderFormat );
  4655. free ( convBuffer );
  4656. delete renderResampler;
  4657. delete captureResampler;
  4658. CoUninitialize();
  4659. // update stream state
  4660. stream_.state = STREAM_STOPPED;
  4661. if ( !errorText.empty() )
  4662. {
  4663. errorText_ = errorText;
  4664. error( errorType );
  4665. }
  4666. }
  4667. //******************** End of __WINDOWS_WASAPI__ *********************//
  4668. #endif
  4669. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  4670. // Modified by Robin Davies, October 2005
  4671. // - Improvements to DirectX pointer chasing.
  4672. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  4673. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  4674. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  4675. // Changed device query structure for RtAudio 4.0.7, January 2010
  4676. #include <windows.h>
  4677. #include <process.h>
  4678. #include <mmsystem.h>
  4679. #include <mmreg.h>
  4680. #include <dsound.h>
  4681. #include <assert.h>
  4682. #include <algorithm>
  4683. #if defined(__MINGW32__)
  4684. // missing from latest mingw winapi
  4685. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  4686. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  4687. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  4688. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  4689. #endif
  4690. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  4691. #ifdef _MSC_VER // if Microsoft Visual C++
  4692. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  4693. #endif
  4694. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  4695. {
  4696. if ( pointer > bufferSize ) pointer -= bufferSize;
  4697. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  4698. if ( pointer < earlierPointer ) pointer += bufferSize;
  4699. return pointer >= earlierPointer && pointer < laterPointer;
  4700. }
  4701. // A structure to hold various information related to the DirectSound
  4702. // API implementation.
  4703. struct DsHandle {
  4704. unsigned int drainCounter; // Tracks callback counts when draining
  4705. bool internalDrain; // Indicates if stop is initiated from callback or not.
  4706. void *id[2];
  4707. void *buffer[2];
  4708. bool xrun[2];
  4709. UINT bufferPointer[2];
  4710. DWORD dsBufferSize[2];
  4711. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  4712. HANDLE condition;
  4713. DsHandle()
  4714. :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; }
  4715. };
  4716. // Declarations for utility functions, callbacks, and structures
  4717. // specific to the DirectSound implementation.
  4718. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4719. LPCTSTR description,
  4720. LPCTSTR module,
  4721. LPVOID lpContext );
  4722. static const char* getErrorString( int code );
  4723. static unsigned __stdcall callbackHandler( void *ptr );
  4724. struct DsDevice {
  4725. LPGUID id[2];
  4726. bool validId[2];
  4727. bool found;
  4728. std::string name;
  4729. DsDevice()
  4730. : found(false) { validId[0] = false; validId[1] = false; }
  4731. };
  4732. struct DsProbeData {
  4733. bool isInput;
  4734. std::vector<struct DsDevice>* dsDevices;
  4735. };
  4736. RtApiDs :: RtApiDs()
  4737. {
  4738. // Dsound will run both-threaded. If CoInitialize fails, then just
  4739. // accept whatever the mainline chose for a threading model.
  4740. coInitialized_ = false;
  4741. HRESULT hr = CoInitialize( NULL );
  4742. if ( !FAILED( hr ) ) coInitialized_ = true;
  4743. }
  4744. RtApiDs :: ~RtApiDs()
  4745. {
  4746. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4747. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  4748. }
  4749. // The DirectSound default output is always the first device.
  4750. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  4751. {
  4752. return 0;
  4753. }
  4754. // The DirectSound default input is always the first input device,
  4755. // which is the first capture device enumerated.
  4756. unsigned int RtApiDs :: getDefaultInputDevice( void )
  4757. {
  4758. return 0;
  4759. }
  4760. unsigned int RtApiDs :: getDeviceCount( void )
  4761. {
  4762. // Set query flag for previously found devices to false, so that we
  4763. // can check for any devices that have disappeared.
  4764. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4765. dsDevices[i].found = false;
  4766. // Query DirectSound devices.
  4767. struct DsProbeData probeInfo;
  4768. probeInfo.isInput = false;
  4769. probeInfo.dsDevices = &dsDevices;
  4770. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4771. if ( FAILED( result ) ) {
  4772. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  4773. errorText_ = errorStream_.str();
  4774. error( RtAudioError::WARNING );
  4775. }
  4776. // Query DirectSoundCapture devices.
  4777. probeInfo.isInput = true;
  4778. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4779. if ( FAILED( result ) ) {
  4780. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  4781. errorText_ = errorStream_.str();
  4782. error( RtAudioError::WARNING );
  4783. }
  4784. // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).
  4785. for ( unsigned int i=0; i<dsDevices.size(); ) {
  4786. if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );
  4787. else i++;
  4788. }
  4789. return static_cast<unsigned int>(dsDevices.size());
  4790. }
  4791. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  4792. {
  4793. RtAudio::DeviceInfo info;
  4794. info.probed = false;
  4795. if ( dsDevices.size() == 0 ) {
  4796. // Force a query of all devices
  4797. getDeviceCount();
  4798. if ( dsDevices.size() == 0 ) {
  4799. errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
  4800. error( RtAudioError::INVALID_USE );
  4801. return info;
  4802. }
  4803. }
  4804. if ( device >= dsDevices.size() ) {
  4805. errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
  4806. error( RtAudioError::INVALID_USE );
  4807. return info;
  4808. }
  4809. HRESULT result;
  4810. if ( dsDevices[ device ].validId[0] == false ) goto probeInput;
  4811. LPDIRECTSOUND output;
  4812. DSCAPS outCaps;
  4813. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4814. if ( FAILED( result ) ) {
  4815. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4816. errorText_ = errorStream_.str();
  4817. error( RtAudioError::WARNING );
  4818. goto probeInput;
  4819. }
  4820. outCaps.dwSize = sizeof( outCaps );
  4821. result = output->GetCaps( &outCaps );
  4822. if ( FAILED( result ) ) {
  4823. output->Release();
  4824. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  4825. errorText_ = errorStream_.str();
  4826. error( RtAudioError::WARNING );
  4827. goto probeInput;
  4828. }
  4829. // Get output channel information.
  4830. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  4831. // Get sample rate information.
  4832. info.sampleRates.clear();
  4833. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  4834. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  4835. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {
  4836. info.sampleRates.push_back( SAMPLE_RATES[k] );
  4837. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  4838. info.preferredSampleRate = SAMPLE_RATES[k];
  4839. }
  4840. }
  4841. // Get format information.
  4842. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  4843. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  4844. output->Release();
  4845. if ( getDefaultOutputDevice() == device )
  4846. info.isDefaultOutput = true;
  4847. if ( dsDevices[ device ].validId[1] == false ) {
  4848. info.name = dsDevices[ device ].name;
  4849. info.probed = true;
  4850. return info;
  4851. }
  4852. probeInput:
  4853. LPDIRECTSOUNDCAPTURE input;
  4854. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4855. if ( FAILED( result ) ) {
  4856. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4857. errorText_ = errorStream_.str();
  4858. error( RtAudioError::WARNING );
  4859. return info;
  4860. }
  4861. DSCCAPS inCaps;
  4862. inCaps.dwSize = sizeof( inCaps );
  4863. result = input->GetCaps( &inCaps );
  4864. if ( FAILED( result ) ) {
  4865. input->Release();
  4866. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";
  4867. errorText_ = errorStream_.str();
  4868. error( RtAudioError::WARNING );
  4869. return info;
  4870. }
  4871. // Get input channel information.
  4872. info.inputChannels = inCaps.dwChannels;
  4873. // Get sample rate and format information.
  4874. std::vector<unsigned int> rates;
  4875. if ( inCaps.dwChannels >= 2 ) {
  4876. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4877. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4878. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4879. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4880. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4881. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4882. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4883. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4884. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4885. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
  4886. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
  4887. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
  4888. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
  4889. }
  4890. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4891. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
  4892. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
  4893. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
  4894. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
  4895. }
  4896. }
  4897. else if ( inCaps.dwChannels == 1 ) {
  4898. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4899. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4900. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4901. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4902. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4903. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4904. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4905. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4906. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4907. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
  4908. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
  4909. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
  4910. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
  4911. }
  4912. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4913. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
  4914. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
  4915. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
  4916. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
  4917. }
  4918. }
  4919. else info.inputChannels = 0; // technically, this would be an error
  4920. input->Release();
  4921. if ( info.inputChannels == 0 ) return info;
  4922. // Copy the supported rates to the info structure but avoid duplication.
  4923. bool found;
  4924. for ( unsigned int i=0; i<rates.size(); i++ ) {
  4925. found = false;
  4926. for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
  4927. if ( rates[i] == info.sampleRates[j] ) {
  4928. found = true;
  4929. break;
  4930. }
  4931. }
  4932. if ( found == false ) info.sampleRates.push_back( rates[i] );
  4933. }
  4934. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  4935. // If device opens for both playback and capture, we determine the channels.
  4936. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4937. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4938. if ( device == 0 ) info.isDefaultInput = true;
  4939. // Copy name and return.
  4940. info.name = dsDevices[ device ].name;
  4941. info.probed = true;
  4942. return info;
  4943. }
  4944. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4945. unsigned int firstChannel, unsigned int sampleRate,
  4946. RtAudioFormat format, unsigned int *bufferSize,
  4947. RtAudio::StreamOptions *options )
  4948. {
  4949. if ( channels + firstChannel > 2 ) {
  4950. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  4951. return FAILURE;
  4952. }
  4953. size_t nDevices = dsDevices.size();
  4954. if ( nDevices == 0 ) {
  4955. // This should not happen because a check is made before this function is called.
  4956. errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
  4957. return FAILURE;
  4958. }
  4959. if ( device >= nDevices ) {
  4960. // This should not happen because a check is made before this function is called.
  4961. errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
  4962. return FAILURE;
  4963. }
  4964. if ( mode == OUTPUT ) {
  4965. if ( dsDevices[ device ].validId[0] == false ) {
  4966. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  4967. errorText_ = errorStream_.str();
  4968. return FAILURE;
  4969. }
  4970. }
  4971. else { // mode == INPUT
  4972. if ( dsDevices[ device ].validId[1] == false ) {
  4973. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  4974. errorText_ = errorStream_.str();
  4975. return FAILURE;
  4976. }
  4977. }
  4978. // According to a note in PortAudio, using GetDesktopWindow()
  4979. // instead of GetForegroundWindow() is supposed to avoid problems
  4980. // that occur when the application's window is not the foreground
  4981. // window. Also, if the application window closes before the
  4982. // DirectSound buffer, DirectSound can crash. In the past, I had
  4983. // problems when using GetDesktopWindow() but it seems fine now
  4984. // (January 2010). I'll leave it commented here.
  4985. // HWND hWnd = GetForegroundWindow();
  4986. HWND hWnd = GetDesktopWindow();
  4987. // Check the numberOfBuffers parameter and limit the lowest value to
  4988. // two. This is a judgement call and a value of two is probably too
  4989. // low for capture, but it should work for playback.
  4990. int nBuffers = 0;
  4991. if ( options ) nBuffers = options->numberOfBuffers;
  4992. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  4993. if ( nBuffers < 2 ) nBuffers = 3;
  4994. // Check the lower range of the user-specified buffer size and set
  4995. // (arbitrarily) to a lower bound of 32.
  4996. if ( *bufferSize < 32 ) *bufferSize = 32;
  4997. // Create the wave format structure. The data format setting will
  4998. // be determined later.
  4999. WAVEFORMATEX waveFormat;
  5000. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  5001. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  5002. waveFormat.nChannels = channels + firstChannel;
  5003. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  5004. // Determine the device buffer size. By default, we'll use the value
  5005. // defined above (32K), but we will grow it to make allowances for
  5006. // very large software buffer sizes.
  5007. DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
  5008. DWORD dsPointerLeadTime = 0;
  5009. void *ohandle = 0, *bhandle = 0;
  5010. HRESULT result;
  5011. if ( mode == OUTPUT ) {
  5012. LPDIRECTSOUND output;
  5013. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  5014. if ( FAILED( result ) ) {
  5015. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  5016. errorText_ = errorStream_.str();
  5017. return FAILURE;
  5018. }
  5019. DSCAPS outCaps;
  5020. outCaps.dwSize = sizeof( outCaps );
  5021. result = output->GetCaps( &outCaps );
  5022. if ( FAILED( result ) ) {
  5023. output->Release();
  5024. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";
  5025. errorText_ = errorStream_.str();
  5026. return FAILURE;
  5027. }
  5028. // Check channel information.
  5029. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  5030. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";
  5031. errorText_ = errorStream_.str();
  5032. return FAILURE;
  5033. }
  5034. // Check format information. Use 16-bit format unless not
  5035. // supported or user requests 8-bit.
  5036. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  5037. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  5038. waveFormat.wBitsPerSample = 16;
  5039. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5040. }
  5041. else {
  5042. waveFormat.wBitsPerSample = 8;
  5043. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5044. }
  5045. stream_.userFormat = format;
  5046. // Update wave format structure and buffer information.
  5047. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  5048. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  5049. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  5050. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  5051. while ( dsPointerLeadTime * 2U > dsBufferSize )
  5052. dsBufferSize *= 2;
  5053. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  5054. // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  5055. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  5056. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  5057. if ( FAILED( result ) ) {
  5058. output->Release();
  5059. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";
  5060. errorText_ = errorStream_.str();
  5061. return FAILURE;
  5062. }
  5063. // Even though we will write to the secondary buffer, we need to
  5064. // access the primary buffer to set the correct output format
  5065. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  5066. // buffer description.
  5067. DSBUFFERDESC bufferDescription;
  5068. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  5069. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  5070. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  5071. // Obtain the primary buffer
  5072. LPDIRECTSOUNDBUFFER buffer;
  5073. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5074. if ( FAILED( result ) ) {
  5075. output->Release();
  5076. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";
  5077. errorText_ = errorStream_.str();
  5078. return FAILURE;
  5079. }
  5080. // Set the primary DS buffer sound format.
  5081. result = buffer->SetFormat( &waveFormat );
  5082. if ( FAILED( result ) ) {
  5083. output->Release();
  5084. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";
  5085. errorText_ = errorStream_.str();
  5086. return FAILURE;
  5087. }
  5088. // Setup the secondary DS buffer description.
  5089. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  5090. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  5091. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  5092. DSBCAPS_GLOBALFOCUS |
  5093. DSBCAPS_GETCURRENTPOSITION2 |
  5094. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  5095. bufferDescription.dwBufferBytes = dsBufferSize;
  5096. bufferDescription.lpwfxFormat = &waveFormat;
  5097. // Try to create the secondary DS buffer. If that doesn't work,
  5098. // try to use software mixing. Otherwise, there's a problem.
  5099. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5100. if ( FAILED( result ) ) {
  5101. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  5102. DSBCAPS_GLOBALFOCUS |
  5103. DSBCAPS_GETCURRENTPOSITION2 |
  5104. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  5105. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5106. if ( FAILED( result ) ) {
  5107. output->Release();
  5108. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";
  5109. errorText_ = errorStream_.str();
  5110. return FAILURE;
  5111. }
  5112. }
  5113. // Get the buffer size ... might be different from what we specified.
  5114. DSBCAPS dsbcaps;
  5115. dsbcaps.dwSize = sizeof( DSBCAPS );
  5116. result = buffer->GetCaps( &dsbcaps );
  5117. if ( FAILED( result ) ) {
  5118. output->Release();
  5119. buffer->Release();
  5120. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  5121. errorText_ = errorStream_.str();
  5122. return FAILURE;
  5123. }
  5124. dsBufferSize = dsbcaps.dwBufferBytes;
  5125. // Lock the DS buffer
  5126. LPVOID audioPtr;
  5127. DWORD dataLen;
  5128. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  5129. if ( FAILED( result ) ) {
  5130. output->Release();
  5131. buffer->Release();
  5132. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";
  5133. errorText_ = errorStream_.str();
  5134. return FAILURE;
  5135. }
  5136. // Zero the DS buffer
  5137. ZeroMemory( audioPtr, dataLen );
  5138. // Unlock the DS buffer
  5139. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5140. if ( FAILED( result ) ) {
  5141. output->Release();
  5142. buffer->Release();
  5143. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";
  5144. errorText_ = errorStream_.str();
  5145. return FAILURE;
  5146. }
  5147. ohandle = (void *) output;
  5148. bhandle = (void *) buffer;
  5149. }
  5150. if ( mode == INPUT ) {
  5151. LPDIRECTSOUNDCAPTURE input;
  5152. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  5153. if ( FAILED( result ) ) {
  5154. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  5155. errorText_ = errorStream_.str();
  5156. return FAILURE;
  5157. }
  5158. DSCCAPS inCaps;
  5159. inCaps.dwSize = sizeof( inCaps );
  5160. result = input->GetCaps( &inCaps );
  5161. if ( FAILED( result ) ) {
  5162. input->Release();
  5163. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";
  5164. errorText_ = errorStream_.str();
  5165. return FAILURE;
  5166. }
  5167. // Check channel information.
  5168. if ( inCaps.dwChannels < channels + firstChannel ) {
  5169. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  5170. return FAILURE;
  5171. }
  5172. // Check format information. Use 16-bit format unless user
  5173. // requests 8-bit.
  5174. DWORD deviceFormats;
  5175. if ( channels + firstChannel == 2 ) {
  5176. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  5177. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5178. waveFormat.wBitsPerSample = 8;
  5179. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5180. }
  5181. else { // assume 16-bit is supported
  5182. waveFormat.wBitsPerSample = 16;
  5183. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5184. }
  5185. }
  5186. else { // channel == 1
  5187. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  5188. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5189. waveFormat.wBitsPerSample = 8;
  5190. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5191. }
  5192. else { // assume 16-bit is supported
  5193. waveFormat.wBitsPerSample = 16;
  5194. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5195. }
  5196. }
  5197. stream_.userFormat = format;
  5198. // Update wave format structure and buffer information.
  5199. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  5200. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  5201. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  5202. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  5203. while ( dsPointerLeadTime * 2U > dsBufferSize )
  5204. dsBufferSize *= 2;
  5205. // Setup the secondary DS buffer description.
  5206. DSCBUFFERDESC bufferDescription;
  5207. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  5208. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  5209. bufferDescription.dwFlags = 0;
  5210. bufferDescription.dwReserved = 0;
  5211. bufferDescription.dwBufferBytes = dsBufferSize;
  5212. bufferDescription.lpwfxFormat = &waveFormat;
  5213. // Create the capture buffer.
  5214. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  5215. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  5216. if ( FAILED( result ) ) {
  5217. input->Release();
  5218. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";
  5219. errorText_ = errorStream_.str();
  5220. return FAILURE;
  5221. }
  5222. // Get the buffer size ... might be different from what we specified.
  5223. DSCBCAPS dscbcaps;
  5224. dscbcaps.dwSize = sizeof( DSCBCAPS );
  5225. result = buffer->GetCaps( &dscbcaps );
  5226. if ( FAILED( result ) ) {
  5227. input->Release();
  5228. buffer->Release();
  5229. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  5230. errorText_ = errorStream_.str();
  5231. return FAILURE;
  5232. }
  5233. dsBufferSize = dscbcaps.dwBufferBytes;
  5234. // NOTE: We could have a problem here if this is a duplex stream
  5235. // and the play and capture hardware buffer sizes are different
  5236. // (I'm actually not sure if that is a problem or not).
  5237. // Currently, we are not verifying that.
  5238. // Lock the capture buffer
  5239. LPVOID audioPtr;
  5240. DWORD dataLen;
  5241. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  5242. if ( FAILED( result ) ) {
  5243. input->Release();
  5244. buffer->Release();
  5245. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";
  5246. errorText_ = errorStream_.str();
  5247. return FAILURE;
  5248. }
  5249. // Zero the buffer
  5250. ZeroMemory( audioPtr, dataLen );
  5251. // Unlock the buffer
  5252. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5253. if ( FAILED( result ) ) {
  5254. input->Release();
  5255. buffer->Release();
  5256. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";
  5257. errorText_ = errorStream_.str();
  5258. return FAILURE;
  5259. }
  5260. ohandle = (void *) input;
  5261. bhandle = (void *) buffer;
  5262. }
  5263. // Set various stream parameters
  5264. DsHandle *handle = 0;
  5265. stream_.nDeviceChannels[mode] = channels + firstChannel;
  5266. stream_.nUserChannels[mode] = channels;
  5267. stream_.bufferSize = *bufferSize;
  5268. stream_.channelOffset[mode] = firstChannel;
  5269. stream_.deviceInterleaved[mode] = true;
  5270. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  5271. else stream_.userInterleaved = true;
  5272. // Set flag for buffer conversion
  5273. stream_.doConvertBuffer[mode] = false;
  5274. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  5275. stream_.doConvertBuffer[mode] = true;
  5276. if (stream_.userFormat != stream_.deviceFormat[mode])
  5277. stream_.doConvertBuffer[mode] = true;
  5278. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  5279. stream_.nUserChannels[mode] > 1 )
  5280. stream_.doConvertBuffer[mode] = true;
  5281. // Allocate necessary internal buffers
  5282. long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  5283. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  5284. if ( stream_.userBuffer[mode] == NULL ) {
  5285. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  5286. goto error;
  5287. }
  5288. if ( stream_.doConvertBuffer[mode] ) {
  5289. bool makeBuffer = true;
  5290. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  5291. if ( mode == INPUT ) {
  5292. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  5293. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  5294. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  5295. }
  5296. }
  5297. if ( makeBuffer ) {
  5298. bufferBytes *= *bufferSize;
  5299. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  5300. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  5301. if ( stream_.deviceBuffer == NULL ) {
  5302. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  5303. goto error;
  5304. }
  5305. }
  5306. }
  5307. // Allocate our DsHandle structures for the stream.
  5308. if ( stream_.apiHandle == 0 ) {
  5309. try {
  5310. handle = new DsHandle;
  5311. }
  5312. catch ( std::bad_alloc& ) {
  5313. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  5314. goto error;
  5315. }
  5316. // Create a manual-reset event.
  5317. handle->condition = CreateEvent( NULL, // no security
  5318. TRUE, // manual-reset
  5319. FALSE, // non-signaled initially
  5320. NULL ); // unnamed
  5321. stream_.apiHandle = (void *) handle;
  5322. }
  5323. else
  5324. handle = (DsHandle *) stream_.apiHandle;
  5325. handle->id[mode] = ohandle;
  5326. handle->buffer[mode] = bhandle;
  5327. handle->dsBufferSize[mode] = dsBufferSize;
  5328. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  5329. stream_.device[mode] = device;
  5330. stream_.state = STREAM_STOPPED;
  5331. if ( stream_.mode == OUTPUT && mode == INPUT )
  5332. // We had already set up an output stream.
  5333. stream_.mode = DUPLEX;
  5334. else
  5335. stream_.mode = mode;
  5336. stream_.nBuffers = nBuffers;
  5337. stream_.sampleRate = sampleRate;
  5338. // Setup the buffer conversion information structure.
  5339. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  5340. // Setup the callback thread.
  5341. if ( stream_.callbackInfo.isRunning == false ) {
  5342. unsigned threadId;
  5343. stream_.callbackInfo.isRunning = true;
  5344. stream_.callbackInfo.object = (void *) this;
  5345. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  5346. &stream_.callbackInfo, 0, &threadId );
  5347. if ( stream_.callbackInfo.thread == 0 ) {
  5348. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  5349. goto error;
  5350. }
  5351. // Boost DS thread priority
  5352. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  5353. }
  5354. return SUCCESS;
  5355. error:
  5356. if ( handle ) {
  5357. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5358. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5359. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5360. if ( buffer ) buffer->Release();
  5361. object->Release();
  5362. }
  5363. if ( handle->buffer[1] ) {
  5364. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5365. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5366. if ( buffer ) buffer->Release();
  5367. object->Release();
  5368. }
  5369. CloseHandle( handle->condition );
  5370. delete handle;
  5371. stream_.apiHandle = 0;
  5372. }
  5373. for ( int i=0; i<2; i++ ) {
  5374. if ( stream_.userBuffer[i] ) {
  5375. free( stream_.userBuffer[i] );
  5376. stream_.userBuffer[i] = 0;
  5377. }
  5378. }
  5379. if ( stream_.deviceBuffer ) {
  5380. free( stream_.deviceBuffer );
  5381. stream_.deviceBuffer = 0;
  5382. }
  5383. stream_.state = STREAM_CLOSED;
  5384. return FAILURE;
  5385. }
  5386. void RtApiDs :: closeStream()
  5387. {
  5388. if ( stream_.state == STREAM_CLOSED ) {
  5389. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  5390. error( RtAudioError::WARNING );
  5391. return;
  5392. }
  5393. // Stop the callback thread.
  5394. stream_.callbackInfo.isRunning = false;
  5395. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  5396. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  5397. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5398. if ( handle ) {
  5399. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5400. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5401. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5402. if ( buffer ) {
  5403. buffer->Stop();
  5404. buffer->Release();
  5405. }
  5406. object->Release();
  5407. }
  5408. if ( handle->buffer[1] ) {
  5409. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5410. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5411. if ( buffer ) {
  5412. buffer->Stop();
  5413. buffer->Release();
  5414. }
  5415. object->Release();
  5416. }
  5417. CloseHandle( handle->condition );
  5418. delete handle;
  5419. stream_.apiHandle = 0;
  5420. }
  5421. for ( int i=0; i<2; i++ ) {
  5422. if ( stream_.userBuffer[i] ) {
  5423. free( stream_.userBuffer[i] );
  5424. stream_.userBuffer[i] = 0;
  5425. }
  5426. }
  5427. if ( stream_.deviceBuffer ) {
  5428. free( stream_.deviceBuffer );
  5429. stream_.deviceBuffer = 0;
  5430. }
  5431. stream_.mode = UNINITIALIZED;
  5432. stream_.state = STREAM_CLOSED;
  5433. }
  5434. void RtApiDs :: startStream()
  5435. {
  5436. verifyStream();
  5437. if ( stream_.state == STREAM_RUNNING ) {
  5438. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  5439. error( RtAudioError::WARNING );
  5440. return;
  5441. }
  5442. #if defined( HAVE_GETTIMEOFDAY )
  5443. gettimeofday( &stream_.lastTickTimestamp, NULL );
  5444. #endif
  5445. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5446. // Increase scheduler frequency on lesser windows (a side-effect of
  5447. // increasing timer accuracy). On greater windows (Win2K or later),
  5448. // this is already in effect.
  5449. timeBeginPeriod( 1 );
  5450. buffersRolling = false;
  5451. duplexPrerollBytes = 0;
  5452. if ( stream_.mode == DUPLEX ) {
  5453. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  5454. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  5455. }
  5456. HRESULT result = 0;
  5457. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5458. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5459. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  5460. if ( FAILED( result ) ) {
  5461. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  5462. errorText_ = errorStream_.str();
  5463. goto unlock;
  5464. }
  5465. }
  5466. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5467. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5468. result = buffer->Start( DSCBSTART_LOOPING );
  5469. if ( FAILED( result ) ) {
  5470. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  5471. errorText_ = errorStream_.str();
  5472. goto unlock;
  5473. }
  5474. }
  5475. handle->drainCounter = 0;
  5476. handle->internalDrain = false;
  5477. ResetEvent( handle->condition );
  5478. stream_.state = STREAM_RUNNING;
  5479. unlock:
  5480. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5481. }
  5482. void RtApiDs :: stopStream()
  5483. {
  5484. verifyStream();
  5485. if ( stream_.state == STREAM_STOPPED ) {
  5486. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  5487. error( RtAudioError::WARNING );
  5488. return;
  5489. }
  5490. HRESULT result = 0;
  5491. LPVOID audioPtr;
  5492. DWORD dataLen;
  5493. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5494. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5495. if ( handle->drainCounter == 0 ) {
  5496. handle->drainCounter = 2;
  5497. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  5498. }
  5499. stream_.state = STREAM_STOPPED;
  5500. MUTEX_LOCK( &stream_.mutex );
  5501. // Stop the buffer and clear memory
  5502. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5503. result = buffer->Stop();
  5504. if ( FAILED( result ) ) {
  5505. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  5506. errorText_ = errorStream_.str();
  5507. goto unlock;
  5508. }
  5509. // Lock the buffer and clear it so that if we start to play again,
  5510. // we won't have old data playing.
  5511. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  5512. if ( FAILED( result ) ) {
  5513. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
  5514. errorText_ = errorStream_.str();
  5515. goto unlock;
  5516. }
  5517. // Zero the DS buffer
  5518. ZeroMemory( audioPtr, dataLen );
  5519. // Unlock the DS buffer
  5520. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5521. if ( FAILED( result ) ) {
  5522. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  5523. errorText_ = errorStream_.str();
  5524. goto unlock;
  5525. }
  5526. // If we start playing again, we must begin at beginning of buffer.
  5527. handle->bufferPointer[0] = 0;
  5528. }
  5529. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5530. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5531. audioPtr = NULL;
  5532. dataLen = 0;
  5533. stream_.state = STREAM_STOPPED;
  5534. if ( stream_.mode != DUPLEX )
  5535. MUTEX_LOCK( &stream_.mutex );
  5536. result = buffer->Stop();
  5537. if ( FAILED( result ) ) {
  5538. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  5539. errorText_ = errorStream_.str();
  5540. goto unlock;
  5541. }
  5542. // Lock the buffer and clear it so that if we start to play again,
  5543. // we won't have old data playing.
  5544. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  5545. if ( FAILED( result ) ) {
  5546. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
  5547. errorText_ = errorStream_.str();
  5548. goto unlock;
  5549. }
  5550. // Zero the DS buffer
  5551. ZeroMemory( audioPtr, dataLen );
  5552. // Unlock the DS buffer
  5553. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5554. if ( FAILED( result ) ) {
  5555. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  5556. errorText_ = errorStream_.str();
  5557. goto unlock;
  5558. }
  5559. // If we start recording again, we must begin at beginning of buffer.
  5560. handle->bufferPointer[1] = 0;
  5561. }
  5562. unlock:
  5563. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  5564. MUTEX_UNLOCK( &stream_.mutex );
  5565. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5566. }
  5567. void RtApiDs :: abortStream()
  5568. {
  5569. verifyStream();
  5570. if ( stream_.state == STREAM_STOPPED ) {
  5571. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  5572. error( RtAudioError::WARNING );
  5573. return;
  5574. }
  5575. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5576. handle->drainCounter = 2;
  5577. stopStream();
  5578. }
  5579. void RtApiDs :: callbackEvent()
  5580. {
  5581. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
  5582. Sleep( 50 ); // sleep 50 milliseconds
  5583. return;
  5584. }
  5585. if ( stream_.state == STREAM_CLOSED ) {
  5586. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5587. error( RtAudioError::WARNING );
  5588. return;
  5589. }
  5590. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  5591. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5592. // Check if we were draining the stream and signal is finished.
  5593. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  5594. stream_.state = STREAM_STOPPING;
  5595. if ( handle->internalDrain == false )
  5596. SetEvent( handle->condition );
  5597. else
  5598. stopStream();
  5599. return;
  5600. }
  5601. // Invoke user callback to get fresh output data UNLESS we are
  5602. // draining stream.
  5603. if ( handle->drainCounter == 0 ) {
  5604. RtAudioCallback callback = (RtAudioCallback) info->callback;
  5605. double streamTime = getStreamTime();
  5606. RtAudioStreamStatus status = 0;
  5607. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  5608. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5609. handle->xrun[0] = false;
  5610. }
  5611. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  5612. status |= RTAUDIO_INPUT_OVERFLOW;
  5613. handle->xrun[1] = false;
  5614. }
  5615. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5616. stream_.bufferSize, streamTime, status, info->userData );
  5617. if ( cbReturnValue == 2 ) {
  5618. stream_.state = STREAM_STOPPING;
  5619. handle->drainCounter = 2;
  5620. abortStream();
  5621. return;
  5622. }
  5623. else if ( cbReturnValue == 1 ) {
  5624. handle->drainCounter = 1;
  5625. handle->internalDrain = true;
  5626. }
  5627. }
  5628. HRESULT result;
  5629. DWORD currentWritePointer, safeWritePointer;
  5630. DWORD currentReadPointer, safeReadPointer;
  5631. UINT nextWritePointer;
  5632. LPVOID buffer1 = NULL;
  5633. LPVOID buffer2 = NULL;
  5634. DWORD bufferSize1 = 0;
  5635. DWORD bufferSize2 = 0;
  5636. char *buffer;
  5637. long bufferBytes;
  5638. MUTEX_LOCK( &stream_.mutex );
  5639. if ( stream_.state == STREAM_STOPPED ) {
  5640. MUTEX_UNLOCK( &stream_.mutex );
  5641. return;
  5642. }
  5643. if ( buffersRolling == false ) {
  5644. if ( stream_.mode == DUPLEX ) {
  5645. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5646. // It takes a while for the devices to get rolling. As a result,
  5647. // there's no guarantee that the capture and write device pointers
  5648. // will move in lockstep. Wait here for both devices to start
  5649. // rolling, and then set our buffer pointers accordingly.
  5650. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  5651. // bytes later than the write buffer.
  5652. // Stub: a serious risk of having a pre-emptive scheduling round
  5653. // take place between the two GetCurrentPosition calls... but I'm
  5654. // really not sure how to solve the problem. Temporarily boost to
  5655. // Realtime priority, maybe; but I'm not sure what priority the
  5656. // DirectSound service threads run at. We *should* be roughly
  5657. // within a ms or so of correct.
  5658. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5659. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5660. DWORD startSafeWritePointer, startSafeReadPointer;
  5661. result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
  5662. if ( FAILED( result ) ) {
  5663. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5664. errorText_ = errorStream_.str();
  5665. MUTEX_UNLOCK( &stream_.mutex );
  5666. error( RtAudioError::SYSTEM_ERROR );
  5667. return;
  5668. }
  5669. result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
  5670. if ( FAILED( result ) ) {
  5671. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5672. errorText_ = errorStream_.str();
  5673. MUTEX_UNLOCK( &stream_.mutex );
  5674. error( RtAudioError::SYSTEM_ERROR );
  5675. return;
  5676. }
  5677. while ( true ) {
  5678. result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
  5679. if ( FAILED( result ) ) {
  5680. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5681. errorText_ = errorStream_.str();
  5682. MUTEX_UNLOCK( &stream_.mutex );
  5683. error( RtAudioError::SYSTEM_ERROR );
  5684. return;
  5685. }
  5686. result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
  5687. if ( FAILED( result ) ) {
  5688. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5689. errorText_ = errorStream_.str();
  5690. MUTEX_UNLOCK( &stream_.mutex );
  5691. error( RtAudioError::SYSTEM_ERROR );
  5692. return;
  5693. }
  5694. if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
  5695. Sleep( 1 );
  5696. }
  5697. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5698. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5699. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5700. handle->bufferPointer[1] = safeReadPointer;
  5701. }
  5702. else if ( stream_.mode == OUTPUT ) {
  5703. // Set the proper nextWritePosition after initial startup.
  5704. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5705. result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5706. if ( FAILED( result ) ) {
  5707. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5708. errorText_ = errorStream_.str();
  5709. MUTEX_UNLOCK( &stream_.mutex );
  5710. error( RtAudioError::SYSTEM_ERROR );
  5711. return;
  5712. }
  5713. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5714. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5715. }
  5716. buffersRolling = true;
  5717. }
  5718. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5719. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5720. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  5721. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5722. bufferBytes *= formatBytes( stream_.userFormat );
  5723. memset( stream_.userBuffer[0], 0, bufferBytes );
  5724. }
  5725. // Setup parameters and do buffer conversion if necessary.
  5726. if ( stream_.doConvertBuffer[0] ) {
  5727. buffer = stream_.deviceBuffer;
  5728. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5729. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  5730. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  5731. }
  5732. else {
  5733. buffer = stream_.userBuffer[0];
  5734. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5735. bufferBytes *= formatBytes( stream_.userFormat );
  5736. }
  5737. // No byte swapping necessary in DirectSound implementation.
  5738. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  5739. // unsigned. So, we need to convert our signed 8-bit data here to
  5740. // unsigned.
  5741. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  5742. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  5743. DWORD dsBufferSize = handle->dsBufferSize[0];
  5744. nextWritePointer = handle->bufferPointer[0];
  5745. DWORD endWrite, leadPointer;
  5746. while ( true ) {
  5747. // Find out where the read and "safe write" pointers are.
  5748. result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5749. if ( FAILED( result ) ) {
  5750. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5751. errorText_ = errorStream_.str();
  5752. MUTEX_UNLOCK( &stream_.mutex );
  5753. error( RtAudioError::SYSTEM_ERROR );
  5754. return;
  5755. }
  5756. // We will copy our output buffer into the region between
  5757. // safeWritePointer and leadPointer. If leadPointer is not
  5758. // beyond the next endWrite position, wait until it is.
  5759. leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
  5760. //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
  5761. if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
  5762. if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
  5763. endWrite = nextWritePointer + bufferBytes;
  5764. // Check whether the entire write region is behind the play pointer.
  5765. if ( leadPointer >= endWrite ) break;
  5766. // If we are here, then we must wait until the leadPointer advances
  5767. // beyond the end of our next write region. We use the
  5768. // Sleep() function to suspend operation until that happens.
  5769. double millis = ( endWrite - leadPointer ) * 1000.0;
  5770. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  5771. if ( millis < 1.0 ) millis = 1.0;
  5772. Sleep( (DWORD) millis );
  5773. }
  5774. if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
  5775. || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
  5776. // We've strayed into the forbidden zone ... resync the read pointer.
  5777. handle->xrun[0] = true;
  5778. nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
  5779. if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
  5780. handle->bufferPointer[0] = nextWritePointer;
  5781. endWrite = nextWritePointer + bufferBytes;
  5782. }
  5783. // Lock free space in the buffer
  5784. result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
  5785. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5786. if ( FAILED( result ) ) {
  5787. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  5788. errorText_ = errorStream_.str();
  5789. MUTEX_UNLOCK( &stream_.mutex );
  5790. error( RtAudioError::SYSTEM_ERROR );
  5791. return;
  5792. }
  5793. // Copy our buffer into the DS buffer
  5794. CopyMemory( buffer1, buffer, bufferSize1 );
  5795. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  5796. // Update our buffer offset and unlock sound buffer
  5797. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5798. if ( FAILED( result ) ) {
  5799. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  5800. errorText_ = errorStream_.str();
  5801. MUTEX_UNLOCK( &stream_.mutex );
  5802. error( RtAudioError::SYSTEM_ERROR );
  5803. return;
  5804. }
  5805. nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5806. handle->bufferPointer[0] = nextWritePointer;
  5807. }
  5808. // Don't bother draining input
  5809. if ( handle->drainCounter ) {
  5810. handle->drainCounter++;
  5811. goto unlock;
  5812. }
  5813. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5814. // Setup parameters.
  5815. if ( stream_.doConvertBuffer[1] ) {
  5816. buffer = stream_.deviceBuffer;
  5817. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  5818. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  5819. }
  5820. else {
  5821. buffer = stream_.userBuffer[1];
  5822. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  5823. bufferBytes *= formatBytes( stream_.userFormat );
  5824. }
  5825. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5826. long nextReadPointer = handle->bufferPointer[1];
  5827. DWORD dsBufferSize = handle->dsBufferSize[1];
  5828. // Find out where the write and "safe read" pointers are.
  5829. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5830. if ( FAILED( result ) ) {
  5831. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5832. errorText_ = errorStream_.str();
  5833. MUTEX_UNLOCK( &stream_.mutex );
  5834. error( RtAudioError::SYSTEM_ERROR );
  5835. return;
  5836. }
  5837. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5838. DWORD endRead = nextReadPointer + bufferBytes;
  5839. // Handling depends on whether we are INPUT or DUPLEX.
  5840. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  5841. // then a wait here will drag the write pointers into the forbidden zone.
  5842. //
  5843. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  5844. // it's in a safe position. This causes dropouts, but it seems to be the only
  5845. // practical way to sync up the read and write pointers reliably, given the
  5846. // the very complex relationship between phase and increment of the read and write
  5847. // pointers.
  5848. //
  5849. // In order to minimize audible dropouts in DUPLEX mode, we will
  5850. // provide a pre-roll period of 0.5 seconds in which we return
  5851. // zeros from the read buffer while the pointers sync up.
  5852. if ( stream_.mode == DUPLEX ) {
  5853. if ( safeReadPointer < endRead ) {
  5854. if ( duplexPrerollBytes <= 0 ) {
  5855. // Pre-roll time over. Be more agressive.
  5856. int adjustment = endRead-safeReadPointer;
  5857. handle->xrun[1] = true;
  5858. // Two cases:
  5859. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  5860. // and perform fine adjustments later.
  5861. // - small adjustments: back off by twice as much.
  5862. if ( adjustment >= 2*bufferBytes )
  5863. nextReadPointer = safeReadPointer-2*bufferBytes;
  5864. else
  5865. nextReadPointer = safeReadPointer-bufferBytes-adjustment;
  5866. if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5867. }
  5868. else {
  5869. // In pre=roll time. Just do it.
  5870. nextReadPointer = safeReadPointer - bufferBytes;
  5871. while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5872. }
  5873. endRead = nextReadPointer + bufferBytes;
  5874. }
  5875. }
  5876. else { // mode == INPUT
  5877. while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
  5878. // See comments for playback.
  5879. double millis = (endRead - safeReadPointer) * 1000.0;
  5880. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  5881. if ( millis < 1.0 ) millis = 1.0;
  5882. Sleep( (DWORD) millis );
  5883. // Wake up and find out where we are now.
  5884. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5885. if ( FAILED( result ) ) {
  5886. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5887. errorText_ = errorStream_.str();
  5888. MUTEX_UNLOCK( &stream_.mutex );
  5889. error( RtAudioError::SYSTEM_ERROR );
  5890. return;
  5891. }
  5892. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5893. }
  5894. }
  5895. // Lock free space in the buffer
  5896. result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
  5897. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5898. if ( FAILED( result ) ) {
  5899. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  5900. errorText_ = errorStream_.str();
  5901. MUTEX_UNLOCK( &stream_.mutex );
  5902. error( RtAudioError::SYSTEM_ERROR );
  5903. return;
  5904. }
  5905. if ( duplexPrerollBytes <= 0 ) {
  5906. // Copy our buffer into the DS buffer
  5907. CopyMemory( buffer, buffer1, bufferSize1 );
  5908. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  5909. }
  5910. else {
  5911. memset( buffer, 0, bufferSize1 );
  5912. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  5913. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  5914. }
  5915. // Update our buffer offset and unlock sound buffer
  5916. nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5917. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5918. if ( FAILED( result ) ) {
  5919. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  5920. errorText_ = errorStream_.str();
  5921. MUTEX_UNLOCK( &stream_.mutex );
  5922. error( RtAudioError::SYSTEM_ERROR );
  5923. return;
  5924. }
  5925. handle->bufferPointer[1] = nextReadPointer;
  5926. // No byte swapping necessary in DirectSound implementation.
  5927. // If necessary, convert 8-bit data from unsigned to signed.
  5928. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  5929. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  5930. // Do buffer conversion if necessary.
  5931. if ( stream_.doConvertBuffer[1] )
  5932. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5933. }
  5934. unlock:
  5935. MUTEX_UNLOCK( &stream_.mutex );
  5936. RtApi::tickStreamTime();
  5937. }
  5938. // Definitions for utility functions and callbacks
  5939. // specific to the DirectSound implementation.
  5940. static unsigned __stdcall callbackHandler( void *ptr )
  5941. {
  5942. CallbackInfo *info = (CallbackInfo *) ptr;
  5943. RtApiDs *object = (RtApiDs *) info->object;
  5944. bool* isRunning = &info->isRunning;
  5945. while ( *isRunning == true ) {
  5946. object->callbackEvent();
  5947. }
  5948. _endthreadex( 0 );
  5949. return 0;
  5950. }
  5951. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  5952. LPCTSTR description,
  5953. LPCTSTR /*module*/,
  5954. LPVOID lpContext )
  5955. {
  5956. struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
  5957. std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
  5958. HRESULT hr;
  5959. bool validDevice = false;
  5960. if ( probeInfo.isInput == true ) {
  5961. DSCCAPS caps;
  5962. LPDIRECTSOUNDCAPTURE object;
  5963. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  5964. if ( hr != DS_OK ) return TRUE;
  5965. caps.dwSize = sizeof(caps);
  5966. hr = object->GetCaps( &caps );
  5967. if ( hr == DS_OK ) {
  5968. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  5969. validDevice = true;
  5970. }
  5971. object->Release();
  5972. }
  5973. else {
  5974. DSCAPS caps;
  5975. LPDIRECTSOUND object;
  5976. hr = DirectSoundCreate( lpguid, &object, NULL );
  5977. if ( hr != DS_OK ) return TRUE;
  5978. caps.dwSize = sizeof(caps);
  5979. hr = object->GetCaps( &caps );
  5980. if ( hr == DS_OK ) {
  5981. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  5982. validDevice = true;
  5983. }
  5984. object->Release();
  5985. }
  5986. // If good device, then save its name and guid.
  5987. std::string name = convertCharPointerToStdString( description );
  5988. //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
  5989. if ( lpguid == NULL )
  5990. name = "Default Device";
  5991. if ( validDevice ) {
  5992. for ( unsigned int i=0; i<dsDevices.size(); i++ ) {
  5993. if ( dsDevices[i].name == name ) {
  5994. dsDevices[i].found = true;
  5995. if ( probeInfo.isInput ) {
  5996. dsDevices[i].id[1] = lpguid;
  5997. dsDevices[i].validId[1] = true;
  5998. }
  5999. else {
  6000. dsDevices[i].id[0] = lpguid;
  6001. dsDevices[i].validId[0] = true;
  6002. }
  6003. return TRUE;
  6004. }
  6005. }
  6006. DsDevice device;
  6007. device.name = name;
  6008. device.found = true;
  6009. if ( probeInfo.isInput ) {
  6010. device.id[1] = lpguid;
  6011. device.validId[1] = true;
  6012. }
  6013. else {
  6014. device.id[0] = lpguid;
  6015. device.validId[0] = true;
  6016. }
  6017. dsDevices.push_back( device );
  6018. }
  6019. return TRUE;
  6020. }
  6021. static const char* getErrorString( int code )
  6022. {
  6023. switch ( code ) {
  6024. case DSERR_ALLOCATED:
  6025. return "Already allocated";
  6026. case DSERR_CONTROLUNAVAIL:
  6027. return "Control unavailable";
  6028. case DSERR_INVALIDPARAM:
  6029. return "Invalid parameter";
  6030. case DSERR_INVALIDCALL:
  6031. return "Invalid call";
  6032. case DSERR_GENERIC:
  6033. return "Generic error";
  6034. case DSERR_PRIOLEVELNEEDED:
  6035. return "Priority level needed";
  6036. case DSERR_OUTOFMEMORY:
  6037. return "Out of memory";
  6038. case DSERR_BADFORMAT:
  6039. return "The sample rate or the channel format is not supported";
  6040. case DSERR_UNSUPPORTED:
  6041. return "Not supported";
  6042. case DSERR_NODRIVER:
  6043. return "No driver";
  6044. case DSERR_ALREADYINITIALIZED:
  6045. return "Already initialized";
  6046. case DSERR_NOAGGREGATION:
  6047. return "No aggregation";
  6048. case DSERR_BUFFERLOST:
  6049. return "Buffer lost";
  6050. case DSERR_OTHERAPPHASPRIO:
  6051. return "Another application already has priority";
  6052. case DSERR_UNINITIALIZED:
  6053. return "Uninitialized";
  6054. default:
  6055. return "DirectSound unknown error";
  6056. }
  6057. }
  6058. //******************** End of __WINDOWS_DS__ *********************//
  6059. #endif
  6060. #if defined(__LINUX_ALSA__)
  6061. #include <alsa/asoundlib.h>
  6062. #include <unistd.h>
  6063. // A structure to hold various information related to the ALSA API
  6064. // implementation.
  6065. struct AlsaHandle {
  6066. snd_pcm_t *handles[2];
  6067. bool synchronized;
  6068. bool xrun[2];
  6069. pthread_cond_t runnable_cv;
  6070. bool runnable;
  6071. AlsaHandle()
  6072. :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
  6073. };
  6074. static void *alsaCallbackHandler( void * ptr );
  6075. RtApiAlsa :: RtApiAlsa()
  6076. {
  6077. // Nothing to do here.
  6078. }
  6079. RtApiAlsa :: ~RtApiAlsa()
  6080. {
  6081. if ( stream_.state != STREAM_CLOSED ) closeStream();
  6082. }
  6083. unsigned int RtApiAlsa :: getDeviceCount( void )
  6084. {
  6085. unsigned nDevices = 0;
  6086. int result, subdevice, card;
  6087. char name[64];
  6088. snd_ctl_t *handle = 0;
  6089. // Count cards and devices
  6090. card = -1;
  6091. snd_card_next( &card );
  6092. while ( card >= 0 ) {
  6093. sprintf( name, "hw:%d", card );
  6094. result = snd_ctl_open( &handle, name, 0 );
  6095. if ( result < 0 ) {
  6096. handle = 0;
  6097. errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6098. errorText_ = errorStream_.str();
  6099. error( RtAudioError::WARNING );
  6100. goto nextcard;
  6101. }
  6102. subdevice = -1;
  6103. while( 1 ) {
  6104. result = snd_ctl_pcm_next_device( handle, &subdevice );
  6105. if ( result < 0 ) {
  6106. errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  6107. errorText_ = errorStream_.str();
  6108. error( RtAudioError::WARNING );
  6109. break;
  6110. }
  6111. if ( subdevice < 0 )
  6112. break;
  6113. nDevices++;
  6114. }
  6115. nextcard:
  6116. if ( handle )
  6117. snd_ctl_close( handle );
  6118. snd_card_next( &card );
  6119. }
  6120. result = snd_ctl_open( &handle, "default", 0 );
  6121. if (result == 0) {
  6122. nDevices++;
  6123. snd_ctl_close( handle );
  6124. }
  6125. return nDevices;
  6126. }
  6127. RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
  6128. {
  6129. RtAudio::DeviceInfo info;
  6130. info.probed = false;
  6131. unsigned nDevices = 0;
  6132. int result, subdevice, card;
  6133. char name[64];
  6134. snd_ctl_t *chandle = 0;
  6135. // Count cards and devices
  6136. card = -1;
  6137. subdevice = -1;
  6138. snd_card_next( &card );
  6139. while ( card >= 0 ) {
  6140. sprintf( name, "hw:%d", card );
  6141. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  6142. if ( result < 0 ) {
  6143. chandle = 0;
  6144. errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6145. errorText_ = errorStream_.str();
  6146. error( RtAudioError::WARNING );
  6147. goto nextcard;
  6148. }
  6149. subdevice = -1;
  6150. while( 1 ) {
  6151. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  6152. if ( result < 0 ) {
  6153. errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  6154. errorText_ = errorStream_.str();
  6155. error( RtAudioError::WARNING );
  6156. break;
  6157. }
  6158. if ( subdevice < 0 ) break;
  6159. if ( nDevices == device ) {
  6160. sprintf( name, "hw:%d,%d", card, subdevice );
  6161. goto foundDevice;
  6162. }
  6163. nDevices++;
  6164. }
  6165. nextcard:
  6166. if ( chandle )
  6167. snd_ctl_close( chandle );
  6168. snd_card_next( &card );
  6169. }
  6170. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6171. if ( result == 0 ) {
  6172. if ( nDevices == device ) {
  6173. strcpy( name, "default" );
  6174. goto foundDevice;
  6175. }
  6176. nDevices++;
  6177. }
  6178. if ( nDevices == 0 ) {
  6179. errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
  6180. error( RtAudioError::INVALID_USE );
  6181. return info;
  6182. }
  6183. if ( device >= nDevices ) {
  6184. errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
  6185. error( RtAudioError::INVALID_USE );
  6186. return info;
  6187. }
  6188. foundDevice:
  6189. // If a stream is already open, we cannot probe the stream devices.
  6190. // Thus, use the saved results.
  6191. if ( stream_.state != STREAM_CLOSED &&
  6192. ( stream_.device[0] == device || stream_.device[1] == device ) ) {
  6193. snd_ctl_close( chandle );
  6194. if ( device >= devices_.size() ) {
  6195. errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
  6196. error( RtAudioError::WARNING );
  6197. return info;
  6198. }
  6199. return devices_[ device ];
  6200. }
  6201. int openMode = SND_PCM_ASYNC;
  6202. snd_pcm_stream_t stream;
  6203. snd_pcm_info_t *pcminfo;
  6204. snd_pcm_info_alloca( &pcminfo );
  6205. snd_pcm_t *phandle;
  6206. snd_pcm_hw_params_t *params;
  6207. snd_pcm_hw_params_alloca( &params );
  6208. // First try for playback unless default device (which has subdev -1)
  6209. stream = SND_PCM_STREAM_PLAYBACK;
  6210. snd_pcm_info_set_stream( pcminfo, stream );
  6211. if ( subdevice != -1 ) {
  6212. snd_pcm_info_set_device( pcminfo, subdevice );
  6213. snd_pcm_info_set_subdevice( pcminfo, 0 );
  6214. result = snd_ctl_pcm_info( chandle, pcminfo );
  6215. if ( result < 0 ) {
  6216. // Device probably doesn't support playback.
  6217. goto captureProbe;
  6218. }
  6219. }
  6220. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
  6221. if ( result < 0 ) {
  6222. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6223. errorText_ = errorStream_.str();
  6224. error( RtAudioError::WARNING );
  6225. goto captureProbe;
  6226. }
  6227. // The device is open ... fill the parameter structure.
  6228. result = snd_pcm_hw_params_any( phandle, params );
  6229. if ( result < 0 ) {
  6230. snd_pcm_close( phandle );
  6231. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6232. errorText_ = errorStream_.str();
  6233. error( RtAudioError::WARNING );
  6234. goto captureProbe;
  6235. }
  6236. // Get output channel information.
  6237. unsigned int value;
  6238. result = snd_pcm_hw_params_get_channels_max( params, &value );
  6239. if ( result < 0 ) {
  6240. snd_pcm_close( phandle );
  6241. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
  6242. errorText_ = errorStream_.str();
  6243. error( RtAudioError::WARNING );
  6244. goto captureProbe;
  6245. }
  6246. info.outputChannels = value;
  6247. snd_pcm_close( phandle );
  6248. captureProbe:
  6249. stream = SND_PCM_STREAM_CAPTURE;
  6250. snd_pcm_info_set_stream( pcminfo, stream );
  6251. // Now try for capture unless default device (with subdev = -1)
  6252. if ( subdevice != -1 ) {
  6253. result = snd_ctl_pcm_info( chandle, pcminfo );
  6254. snd_ctl_close( chandle );
  6255. if ( result < 0 ) {
  6256. // Device probably doesn't support capture.
  6257. if ( info.outputChannels == 0 ) return info;
  6258. goto probeParameters;
  6259. }
  6260. }
  6261. else
  6262. snd_ctl_close( chandle );
  6263. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  6264. if ( result < 0 ) {
  6265. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6266. errorText_ = errorStream_.str();
  6267. error( RtAudioError::WARNING );
  6268. if ( info.outputChannels == 0 ) return info;
  6269. goto probeParameters;
  6270. }
  6271. // The device is open ... fill the parameter structure.
  6272. result = snd_pcm_hw_params_any( phandle, params );
  6273. if ( result < 0 ) {
  6274. snd_pcm_close( phandle );
  6275. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6276. errorText_ = errorStream_.str();
  6277. error( RtAudioError::WARNING );
  6278. if ( info.outputChannels == 0 ) return info;
  6279. goto probeParameters;
  6280. }
  6281. result = snd_pcm_hw_params_get_channels_max( params, &value );
  6282. if ( result < 0 ) {
  6283. snd_pcm_close( phandle );
  6284. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
  6285. errorText_ = errorStream_.str();
  6286. error( RtAudioError::WARNING );
  6287. if ( info.outputChannels == 0 ) return info;
  6288. goto probeParameters;
  6289. }
  6290. info.inputChannels = value;
  6291. snd_pcm_close( phandle );
  6292. // If device opens for both playback and capture, we determine the channels.
  6293. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  6294. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  6295. // ALSA doesn't provide default devices so we'll use the first available one.
  6296. if ( device == 0 && info.outputChannels > 0 )
  6297. info.isDefaultOutput = true;
  6298. if ( device == 0 && info.inputChannels > 0 )
  6299. info.isDefaultInput = true;
  6300. probeParameters:
  6301. // At this point, we just need to figure out the supported data
  6302. // formats and sample rates. We'll proceed by opening the device in
  6303. // the direction with the maximum number of channels, or playback if
  6304. // they are equal. This might limit our sample rate options, but so
  6305. // be it.
  6306. if ( info.outputChannels >= info.inputChannels )
  6307. stream = SND_PCM_STREAM_PLAYBACK;
  6308. else
  6309. stream = SND_PCM_STREAM_CAPTURE;
  6310. snd_pcm_info_set_stream( pcminfo, stream );
  6311. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  6312. if ( result < 0 ) {
  6313. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6314. errorText_ = errorStream_.str();
  6315. error( RtAudioError::WARNING );
  6316. return info;
  6317. }
  6318. // The device is open ... fill the parameter structure.
  6319. result = snd_pcm_hw_params_any( phandle, params );
  6320. if ( result < 0 ) {
  6321. snd_pcm_close( phandle );
  6322. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6323. errorText_ = errorStream_.str();
  6324. error( RtAudioError::WARNING );
  6325. return info;
  6326. }
  6327. // Test our discrete set of sample rate values.
  6328. info.sampleRates.clear();
  6329. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  6330. if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {
  6331. info.sampleRates.push_back( SAMPLE_RATES[i] );
  6332. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  6333. info.preferredSampleRate = SAMPLE_RATES[i];
  6334. }
  6335. }
  6336. if ( info.sampleRates.size() == 0 ) {
  6337. snd_pcm_close( phandle );
  6338. errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
  6339. errorText_ = errorStream_.str();
  6340. error( RtAudioError::WARNING );
  6341. return info;
  6342. }
  6343. // Probe the supported data formats ... we don't care about endian-ness just yet
  6344. snd_pcm_format_t format;
  6345. info.nativeFormats = 0;
  6346. format = SND_PCM_FORMAT_S8;
  6347. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6348. info.nativeFormats |= RTAUDIO_SINT8;
  6349. format = SND_PCM_FORMAT_S16;
  6350. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6351. info.nativeFormats |= RTAUDIO_SINT16;
  6352. format = SND_PCM_FORMAT_S24;
  6353. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6354. info.nativeFormats |= RTAUDIO_SINT24;
  6355. format = SND_PCM_FORMAT_S32;
  6356. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6357. info.nativeFormats |= RTAUDIO_SINT32;
  6358. format = SND_PCM_FORMAT_FLOAT;
  6359. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6360. info.nativeFormats |= RTAUDIO_FLOAT32;
  6361. format = SND_PCM_FORMAT_FLOAT64;
  6362. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6363. info.nativeFormats |= RTAUDIO_FLOAT64;
  6364. // Check that we have at least one supported format
  6365. if ( info.nativeFormats == 0 ) {
  6366. snd_pcm_close( phandle );
  6367. errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
  6368. errorText_ = errorStream_.str();
  6369. error( RtAudioError::WARNING );
  6370. return info;
  6371. }
  6372. // Get the device name
  6373. char *cardname;
  6374. result = snd_card_get_name( card, &cardname );
  6375. if ( result >= 0 ) {
  6376. sprintf( name, "hw:%s,%d", cardname, subdevice );
  6377. free( cardname );
  6378. }
  6379. info.name = name;
  6380. // That's all ... close the device and return
  6381. snd_pcm_close( phandle );
  6382. info.probed = true;
  6383. return info;
  6384. }
  6385. void RtApiAlsa :: saveDeviceInfo( void )
  6386. {
  6387. devices_.clear();
  6388. unsigned int nDevices = getDeviceCount();
  6389. devices_.resize( nDevices );
  6390. for ( unsigned int i=0; i<nDevices; i++ )
  6391. devices_[i] = getDeviceInfo( i );
  6392. }
  6393. bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  6394. unsigned int firstChannel, unsigned int sampleRate,
  6395. RtAudioFormat format, unsigned int *bufferSize,
  6396. RtAudio::StreamOptions *options )
  6397. {
  6398. #if defined(__RTAUDIO_DEBUG__)
  6399. snd_output_t *out;
  6400. snd_output_stdio_attach(&out, stderr, 0);
  6401. #endif
  6402. // I'm not using the "plug" interface ... too much inconsistent behavior.
  6403. unsigned nDevices = 0;
  6404. int result, subdevice, card;
  6405. char name[64];
  6406. snd_ctl_t *chandle;
  6407. if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )
  6408. snprintf(name, sizeof(name), "%s", "default");
  6409. else {
  6410. // Count cards and devices
  6411. card = -1;
  6412. snd_card_next( &card );
  6413. while ( card >= 0 ) {
  6414. sprintf( name, "hw:%d", card );
  6415. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  6416. if ( result < 0 ) {
  6417. errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6418. errorText_ = errorStream_.str();
  6419. return FAILURE;
  6420. }
  6421. subdevice = -1;
  6422. while( 1 ) {
  6423. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  6424. if ( result < 0 ) break;
  6425. if ( subdevice < 0 ) break;
  6426. if ( nDevices == device ) {
  6427. sprintf( name, "hw:%d,%d", card, subdevice );
  6428. snd_ctl_close( chandle );
  6429. goto foundDevice;
  6430. }
  6431. nDevices++;
  6432. }
  6433. snd_ctl_close( chandle );
  6434. snd_card_next( &card );
  6435. }
  6436. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6437. if ( result == 0 ) {
  6438. if ( nDevices == device ) {
  6439. strcpy( name, "default" );
  6440. snd_ctl_close( chandle );
  6441. goto foundDevice;
  6442. }
  6443. nDevices++;
  6444. }
  6445. snd_ctl_close( chandle );
  6446. if ( nDevices == 0 ) {
  6447. // This should not happen because a check is made before this function is called.
  6448. errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
  6449. return FAILURE;
  6450. }
  6451. if ( device >= nDevices ) {
  6452. // This should not happen because a check is made before this function is called.
  6453. errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
  6454. return FAILURE;
  6455. }
  6456. }
  6457. foundDevice:
  6458. // The getDeviceInfo() function will not work for a device that is
  6459. // already open. Thus, we'll probe the system before opening a
  6460. // stream and save the results for use by getDeviceInfo().
  6461. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
  6462. this->saveDeviceInfo();
  6463. snd_pcm_stream_t stream;
  6464. if ( mode == OUTPUT )
  6465. stream = SND_PCM_STREAM_PLAYBACK;
  6466. else
  6467. stream = SND_PCM_STREAM_CAPTURE;
  6468. snd_pcm_t *phandle;
  6469. int openMode = SND_PCM_ASYNC;
  6470. result = snd_pcm_open( &phandle, name, stream, openMode );
  6471. if ( result < 0 ) {
  6472. if ( mode == OUTPUT )
  6473. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
  6474. else
  6475. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
  6476. errorText_ = errorStream_.str();
  6477. return FAILURE;
  6478. }
  6479. // Fill the parameter structure.
  6480. snd_pcm_hw_params_t *hw_params;
  6481. snd_pcm_hw_params_alloca( &hw_params );
  6482. result = snd_pcm_hw_params_any( phandle, hw_params );
  6483. if ( result < 0 ) {
  6484. snd_pcm_close( phandle );
  6485. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
  6486. errorText_ = errorStream_.str();
  6487. return FAILURE;
  6488. }
  6489. #if defined(__RTAUDIO_DEBUG__)
  6490. fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
  6491. snd_pcm_hw_params_dump( hw_params, out );
  6492. #endif
  6493. // Set access ... check user preference.
  6494. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
  6495. stream_.userInterleaved = false;
  6496. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6497. if ( result < 0 ) {
  6498. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6499. stream_.deviceInterleaved[mode] = true;
  6500. }
  6501. else
  6502. stream_.deviceInterleaved[mode] = false;
  6503. }
  6504. else {
  6505. stream_.userInterleaved = true;
  6506. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6507. if ( result < 0 ) {
  6508. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6509. stream_.deviceInterleaved[mode] = false;
  6510. }
  6511. else
  6512. stream_.deviceInterleaved[mode] = true;
  6513. }
  6514. if ( result < 0 ) {
  6515. snd_pcm_close( phandle );
  6516. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
  6517. errorText_ = errorStream_.str();
  6518. return FAILURE;
  6519. }
  6520. // Determine how to set the device format.
  6521. stream_.userFormat = format;
  6522. snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
  6523. if ( format == RTAUDIO_SINT8 )
  6524. deviceFormat = SND_PCM_FORMAT_S8;
  6525. else if ( format == RTAUDIO_SINT16 )
  6526. deviceFormat = SND_PCM_FORMAT_S16;
  6527. else if ( format == RTAUDIO_SINT24 )
  6528. deviceFormat = SND_PCM_FORMAT_S24;
  6529. else if ( format == RTAUDIO_SINT32 )
  6530. deviceFormat = SND_PCM_FORMAT_S32;
  6531. else if ( format == RTAUDIO_FLOAT32 )
  6532. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6533. else if ( format == RTAUDIO_FLOAT64 )
  6534. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6535. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
  6536. stream_.deviceFormat[mode] = format;
  6537. goto setFormat;
  6538. }
  6539. // The user requested format is not natively supported by the device.
  6540. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6541. if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
  6542. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  6543. goto setFormat;
  6544. }
  6545. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6546. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6547. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  6548. goto setFormat;
  6549. }
  6550. deviceFormat = SND_PCM_FORMAT_S32;
  6551. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6552. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  6553. goto setFormat;
  6554. }
  6555. deviceFormat = SND_PCM_FORMAT_S24;
  6556. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6557. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  6558. goto setFormat;
  6559. }
  6560. deviceFormat = SND_PCM_FORMAT_S16;
  6561. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6562. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  6563. goto setFormat;
  6564. }
  6565. deviceFormat = SND_PCM_FORMAT_S8;
  6566. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6567. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  6568. goto setFormat;
  6569. }
  6570. // If we get here, no supported format was found.
  6571. snd_pcm_close( phandle );
  6572. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
  6573. errorText_ = errorStream_.str();
  6574. return FAILURE;
  6575. setFormat:
  6576. result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
  6577. if ( result < 0 ) {
  6578. snd_pcm_close( phandle );
  6579. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
  6580. errorText_ = errorStream_.str();
  6581. return FAILURE;
  6582. }
  6583. // Determine whether byte-swaping is necessary.
  6584. stream_.doByteSwap[mode] = false;
  6585. if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
  6586. result = snd_pcm_format_cpu_endian( deviceFormat );
  6587. if ( result == 0 )
  6588. stream_.doByteSwap[mode] = true;
  6589. else if (result < 0) {
  6590. snd_pcm_close( phandle );
  6591. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
  6592. errorText_ = errorStream_.str();
  6593. return FAILURE;
  6594. }
  6595. }
  6596. // Set the sample rate.
  6597. result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
  6598. if ( result < 0 ) {
  6599. snd_pcm_close( phandle );
  6600. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
  6601. errorText_ = errorStream_.str();
  6602. return FAILURE;
  6603. }
  6604. // Determine the number of channels for this device. We support a possible
  6605. // minimum device channel number > than the value requested by the user.
  6606. stream_.nUserChannels[mode] = channels;
  6607. unsigned int value;
  6608. result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
  6609. unsigned int deviceChannels = value;
  6610. if ( result < 0 || deviceChannels < channels + firstChannel ) {
  6611. snd_pcm_close( phandle );
  6612. errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
  6613. errorText_ = errorStream_.str();
  6614. return FAILURE;
  6615. }
  6616. result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
  6617. if ( result < 0 ) {
  6618. snd_pcm_close( phandle );
  6619. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6620. errorText_ = errorStream_.str();
  6621. return FAILURE;
  6622. }
  6623. deviceChannels = value;
  6624. if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
  6625. stream_.nDeviceChannels[mode] = deviceChannels;
  6626. // Set the device channels.
  6627. result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
  6628. if ( result < 0 ) {
  6629. snd_pcm_close( phandle );
  6630. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6631. errorText_ = errorStream_.str();
  6632. return FAILURE;
  6633. }
  6634. // Set the buffer (or period) size.
  6635. int dir = 0;
  6636. snd_pcm_uframes_t periodSize = *bufferSize;
  6637. result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
  6638. if ( result < 0 ) {
  6639. snd_pcm_close( phandle );
  6640. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
  6641. errorText_ = errorStream_.str();
  6642. return FAILURE;
  6643. }
  6644. *bufferSize = periodSize;
  6645. // Set the buffer number, which in ALSA is referred to as the "period".
  6646. unsigned int periods = 0;
  6647. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
  6648. if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;
  6649. if ( periods < 2 ) periods = 4; // a fairly safe default value
  6650. result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
  6651. if ( result < 0 ) {
  6652. snd_pcm_close( phandle );
  6653. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
  6654. errorText_ = errorStream_.str();
  6655. return FAILURE;
  6656. }
  6657. // If attempting to setup a duplex stream, the bufferSize parameter
  6658. // MUST be the same in both directions!
  6659. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  6660. snd_pcm_close( phandle );
  6661. errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
  6662. errorText_ = errorStream_.str();
  6663. return FAILURE;
  6664. }
  6665. stream_.bufferSize = *bufferSize;
  6666. // Install the hardware configuration
  6667. result = snd_pcm_hw_params( phandle, hw_params );
  6668. if ( result < 0 ) {
  6669. snd_pcm_close( phandle );
  6670. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6671. errorText_ = errorStream_.str();
  6672. return FAILURE;
  6673. }
  6674. #if defined(__RTAUDIO_DEBUG__)
  6675. fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
  6676. snd_pcm_hw_params_dump( hw_params, out );
  6677. #endif
  6678. // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
  6679. snd_pcm_sw_params_t *sw_params = NULL;
  6680. snd_pcm_sw_params_alloca( &sw_params );
  6681. snd_pcm_sw_params_current( phandle, sw_params );
  6682. snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
  6683. snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
  6684. snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
  6685. // The following two settings were suggested by Theo Veenker
  6686. //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
  6687. //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
  6688. // here are two options for a fix
  6689. //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
  6690. snd_pcm_uframes_t val;
  6691. snd_pcm_sw_params_get_boundary( sw_params, &val );
  6692. snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
  6693. result = snd_pcm_sw_params( phandle, sw_params );
  6694. if ( result < 0 ) {
  6695. snd_pcm_close( phandle );
  6696. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6697. errorText_ = errorStream_.str();
  6698. return FAILURE;
  6699. }
  6700. #if defined(__RTAUDIO_DEBUG__)
  6701. fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
  6702. snd_pcm_sw_params_dump( sw_params, out );
  6703. #endif
  6704. // Set flags for buffer conversion
  6705. stream_.doConvertBuffer[mode] = false;
  6706. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  6707. stream_.doConvertBuffer[mode] = true;
  6708. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  6709. stream_.doConvertBuffer[mode] = true;
  6710. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  6711. stream_.nUserChannels[mode] > 1 )
  6712. stream_.doConvertBuffer[mode] = true;
  6713. // Allocate the ApiHandle if necessary and then save.
  6714. AlsaHandle *apiInfo = 0;
  6715. if ( stream_.apiHandle == 0 ) {
  6716. try {
  6717. apiInfo = (AlsaHandle *) new AlsaHandle;
  6718. }
  6719. catch ( std::bad_alloc& ) {
  6720. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
  6721. goto error;
  6722. }
  6723. if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {
  6724. errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
  6725. goto error;
  6726. }
  6727. stream_.apiHandle = (void *) apiInfo;
  6728. apiInfo->handles[0] = 0;
  6729. apiInfo->handles[1] = 0;
  6730. }
  6731. else {
  6732. apiInfo = (AlsaHandle *) stream_.apiHandle;
  6733. }
  6734. apiInfo->handles[mode] = phandle;
  6735. phandle = 0;
  6736. // Allocate necessary internal buffers.
  6737. unsigned long bufferBytes;
  6738. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  6739. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  6740. if ( stream_.userBuffer[mode] == NULL ) {
  6741. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
  6742. goto error;
  6743. }
  6744. if ( stream_.doConvertBuffer[mode] ) {
  6745. bool makeBuffer = true;
  6746. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  6747. if ( mode == INPUT ) {
  6748. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  6749. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  6750. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  6751. }
  6752. }
  6753. if ( makeBuffer ) {
  6754. bufferBytes *= *bufferSize;
  6755. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  6756. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  6757. if ( stream_.deviceBuffer == NULL ) {
  6758. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
  6759. goto error;
  6760. }
  6761. }
  6762. }
  6763. stream_.sampleRate = sampleRate;
  6764. stream_.nBuffers = periods;
  6765. stream_.device[mode] = device;
  6766. stream_.state = STREAM_STOPPED;
  6767. // Setup the buffer conversion information structure.
  6768. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  6769. // Setup thread if necessary.
  6770. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  6771. // We had already set up an output stream.
  6772. stream_.mode = DUPLEX;
  6773. // Link the streams if possible.
  6774. apiInfo->synchronized = false;
  6775. if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
  6776. apiInfo->synchronized = true;
  6777. else {
  6778. errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
  6779. error( RtAudioError::WARNING );
  6780. }
  6781. }
  6782. else {
  6783. stream_.mode = mode;
  6784. // Setup callback thread.
  6785. stream_.callbackInfo.object = (void *) this;
  6786. // Set the thread attributes for joinable and realtime scheduling
  6787. // priority (optional). The higher priority will only take affect
  6788. // if the program is run as root or suid. Note, under Linux
  6789. // processes with CAP_SYS_NICE privilege, a user can change
  6790. // scheduling policy and priority (thus need not be root). See
  6791. // POSIX "capabilities".
  6792. pthread_attr_t attr;
  6793. pthread_attr_init( &attr );
  6794. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  6795. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  6796. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  6797. stream_.callbackInfo.doRealtime = true;
  6798. struct sched_param param;
  6799. int priority = options->priority;
  6800. int min = sched_get_priority_min( SCHED_RR );
  6801. int max = sched_get_priority_max( SCHED_RR );
  6802. if ( priority < min ) priority = min;
  6803. else if ( priority > max ) priority = max;
  6804. param.sched_priority = priority;
  6805. // Set the policy BEFORE the priority. Otherwise it fails.
  6806. pthread_attr_setschedpolicy(&attr, SCHED_RR);
  6807. pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
  6808. // This is definitely required. Otherwise it fails.
  6809. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
  6810. pthread_attr_setschedparam(&attr, &param);
  6811. }
  6812. else
  6813. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  6814. #else
  6815. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  6816. #endif
  6817. stream_.callbackInfo.isRunning = true;
  6818. result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
  6819. pthread_attr_destroy( &attr );
  6820. if ( result ) {
  6821. // Failed. Try instead with default attributes.
  6822. result = pthread_create( &stream_.callbackInfo.thread, NULL, alsaCallbackHandler, &stream_.callbackInfo );
  6823. if ( result ) {
  6824. stream_.callbackInfo.isRunning = false;
  6825. errorText_ = "RtApiAlsa::error creating callback thread!";
  6826. goto error;
  6827. }
  6828. }
  6829. }
  6830. return SUCCESS;
  6831. error:
  6832. if ( apiInfo ) {
  6833. pthread_cond_destroy( &apiInfo->runnable_cv );
  6834. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6835. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6836. delete apiInfo;
  6837. stream_.apiHandle = 0;
  6838. }
  6839. if ( phandle) snd_pcm_close( phandle );
  6840. for ( int i=0; i<2; i++ ) {
  6841. if ( stream_.userBuffer[i] ) {
  6842. free( stream_.userBuffer[i] );
  6843. stream_.userBuffer[i] = 0;
  6844. }
  6845. }
  6846. if ( stream_.deviceBuffer ) {
  6847. free( stream_.deviceBuffer );
  6848. stream_.deviceBuffer = 0;
  6849. }
  6850. stream_.state = STREAM_CLOSED;
  6851. return FAILURE;
  6852. }
  6853. void RtApiAlsa :: closeStream()
  6854. {
  6855. if ( stream_.state == STREAM_CLOSED ) {
  6856. errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
  6857. error( RtAudioError::WARNING );
  6858. return;
  6859. }
  6860. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6861. stream_.callbackInfo.isRunning = false;
  6862. MUTEX_LOCK( &stream_.mutex );
  6863. if ( stream_.state == STREAM_STOPPED ) {
  6864. apiInfo->runnable = true;
  6865. pthread_cond_signal( &apiInfo->runnable_cv );
  6866. }
  6867. MUTEX_UNLOCK( &stream_.mutex );
  6868. pthread_join( stream_.callbackInfo.thread, NULL );
  6869. if ( stream_.state == STREAM_RUNNING ) {
  6870. stream_.state = STREAM_STOPPED;
  6871. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  6872. snd_pcm_drop( apiInfo->handles[0] );
  6873. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  6874. snd_pcm_drop( apiInfo->handles[1] );
  6875. }
  6876. if ( apiInfo ) {
  6877. pthread_cond_destroy( &apiInfo->runnable_cv );
  6878. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6879. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6880. delete apiInfo;
  6881. stream_.apiHandle = 0;
  6882. }
  6883. for ( int i=0; i<2; i++ ) {
  6884. if ( stream_.userBuffer[i] ) {
  6885. free( stream_.userBuffer[i] );
  6886. stream_.userBuffer[i] = 0;
  6887. }
  6888. }
  6889. if ( stream_.deviceBuffer ) {
  6890. free( stream_.deviceBuffer );
  6891. stream_.deviceBuffer = 0;
  6892. }
  6893. stream_.mode = UNINITIALIZED;
  6894. stream_.state = STREAM_CLOSED;
  6895. }
  6896. void RtApiAlsa :: startStream()
  6897. {
  6898. // This method calls snd_pcm_prepare if the device isn't already in that state.
  6899. verifyStream();
  6900. if ( stream_.state == STREAM_RUNNING ) {
  6901. errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
  6902. error( RtAudioError::WARNING );
  6903. return;
  6904. }
  6905. MUTEX_LOCK( &stream_.mutex );
  6906. #if defined( HAVE_GETTIMEOFDAY )
  6907. gettimeofday( &stream_.lastTickTimestamp, NULL );
  6908. #endif
  6909. int result = 0;
  6910. snd_pcm_state_t state;
  6911. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6912. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6913. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6914. state = snd_pcm_state( handle[0] );
  6915. if ( state != SND_PCM_STATE_PREPARED ) {
  6916. result = snd_pcm_prepare( handle[0] );
  6917. if ( result < 0 ) {
  6918. errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
  6919. errorText_ = errorStream_.str();
  6920. goto unlock;
  6921. }
  6922. }
  6923. }
  6924. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6925. result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open
  6926. state = snd_pcm_state( handle[1] );
  6927. if ( state != SND_PCM_STATE_PREPARED ) {
  6928. result = snd_pcm_prepare( handle[1] );
  6929. if ( result < 0 ) {
  6930. errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
  6931. errorText_ = errorStream_.str();
  6932. goto unlock;
  6933. }
  6934. }
  6935. }
  6936. stream_.state = STREAM_RUNNING;
  6937. unlock:
  6938. apiInfo->runnable = true;
  6939. pthread_cond_signal( &apiInfo->runnable_cv );
  6940. MUTEX_UNLOCK( &stream_.mutex );
  6941. if ( result >= 0 ) return;
  6942. error( RtAudioError::SYSTEM_ERROR );
  6943. }
  6944. void RtApiAlsa :: stopStream()
  6945. {
  6946. verifyStream();
  6947. if ( stream_.state == STREAM_STOPPED ) {
  6948. errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
  6949. error( RtAudioError::WARNING );
  6950. return;
  6951. }
  6952. stream_.state = STREAM_STOPPED;
  6953. MUTEX_LOCK( &stream_.mutex );
  6954. int result = 0;
  6955. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6956. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6957. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6958. if ( apiInfo->synchronized )
  6959. result = snd_pcm_drop( handle[0] );
  6960. else
  6961. result = snd_pcm_drain( handle[0] );
  6962. if ( result < 0 ) {
  6963. errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
  6964. errorText_ = errorStream_.str();
  6965. goto unlock;
  6966. }
  6967. }
  6968. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6969. result = snd_pcm_drop( handle[1] );
  6970. if ( result < 0 ) {
  6971. errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
  6972. errorText_ = errorStream_.str();
  6973. goto unlock;
  6974. }
  6975. }
  6976. unlock:
  6977. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6978. MUTEX_UNLOCK( &stream_.mutex );
  6979. if ( result >= 0 ) return;
  6980. error( RtAudioError::SYSTEM_ERROR );
  6981. }
  6982. void RtApiAlsa :: abortStream()
  6983. {
  6984. verifyStream();
  6985. if ( stream_.state == STREAM_STOPPED ) {
  6986. errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
  6987. error( RtAudioError::WARNING );
  6988. return;
  6989. }
  6990. stream_.state = STREAM_STOPPED;
  6991. MUTEX_LOCK( &stream_.mutex );
  6992. int result = 0;
  6993. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6994. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6995. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6996. result = snd_pcm_drop( handle[0] );
  6997. if ( result < 0 ) {
  6998. errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
  6999. errorText_ = errorStream_.str();
  7000. goto unlock;
  7001. }
  7002. }
  7003. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  7004. result = snd_pcm_drop( handle[1] );
  7005. if ( result < 0 ) {
  7006. errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
  7007. errorText_ = errorStream_.str();
  7008. goto unlock;
  7009. }
  7010. }
  7011. unlock:
  7012. apiInfo->runnable = false; // fixes high CPU usage when stopped
  7013. MUTEX_UNLOCK( &stream_.mutex );
  7014. if ( result >= 0 ) return;
  7015. error( RtAudioError::SYSTEM_ERROR );
  7016. }
  7017. void RtApiAlsa :: callbackEvent()
  7018. {
  7019. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  7020. if ( stream_.state == STREAM_STOPPED ) {
  7021. MUTEX_LOCK( &stream_.mutex );
  7022. while ( !apiInfo->runnable )
  7023. pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );
  7024. if ( stream_.state != STREAM_RUNNING ) {
  7025. MUTEX_UNLOCK( &stream_.mutex );
  7026. return;
  7027. }
  7028. MUTEX_UNLOCK( &stream_.mutex );
  7029. }
  7030. if ( stream_.state == STREAM_CLOSED ) {
  7031. errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
  7032. error( RtAudioError::WARNING );
  7033. return;
  7034. }
  7035. int doStopStream = 0;
  7036. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  7037. double streamTime = getStreamTime();
  7038. RtAudioStreamStatus status = 0;
  7039. if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
  7040. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  7041. apiInfo->xrun[0] = false;
  7042. }
  7043. if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
  7044. status |= RTAUDIO_INPUT_OVERFLOW;
  7045. apiInfo->xrun[1] = false;
  7046. }
  7047. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  7048. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  7049. if ( doStopStream == 2 ) {
  7050. abortStream();
  7051. return;
  7052. }
  7053. MUTEX_LOCK( &stream_.mutex );
  7054. // The state might change while waiting on a mutex.
  7055. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  7056. int result;
  7057. char *buffer;
  7058. int channels;
  7059. snd_pcm_t **handle;
  7060. snd_pcm_sframes_t frames;
  7061. RtAudioFormat format;
  7062. handle = (snd_pcm_t **) apiInfo->handles;
  7063. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  7064. // Setup parameters.
  7065. if ( stream_.doConvertBuffer[1] ) {
  7066. buffer = stream_.deviceBuffer;
  7067. channels = stream_.nDeviceChannels[1];
  7068. format = stream_.deviceFormat[1];
  7069. }
  7070. else {
  7071. buffer = stream_.userBuffer[1];
  7072. channels = stream_.nUserChannels[1];
  7073. format = stream_.userFormat;
  7074. }
  7075. // Read samples from device in interleaved/non-interleaved format.
  7076. if ( stream_.deviceInterleaved[1] )
  7077. result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
  7078. else {
  7079. void *bufs[channels];
  7080. size_t offset = stream_.bufferSize * formatBytes( format );
  7081. for ( int i=0; i<channels; i++ )
  7082. bufs[i] = (void *) (buffer + (i * offset));
  7083. result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
  7084. }
  7085. if ( result < (int) stream_.bufferSize ) {
  7086. // Either an error or overrun occured.
  7087. if ( result == -EPIPE ) {
  7088. snd_pcm_state_t state = snd_pcm_state( handle[1] );
  7089. if ( state == SND_PCM_STATE_XRUN ) {
  7090. apiInfo->xrun[1] = true;
  7091. result = snd_pcm_prepare( handle[1] );
  7092. if ( result < 0 ) {
  7093. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
  7094. errorText_ = errorStream_.str();
  7095. }
  7096. }
  7097. else {
  7098. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  7099. errorText_ = errorStream_.str();
  7100. }
  7101. }
  7102. else {
  7103. errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
  7104. errorText_ = errorStream_.str();
  7105. }
  7106. error( RtAudioError::WARNING );
  7107. goto tryOutput;
  7108. }
  7109. // Do byte swapping if necessary.
  7110. if ( stream_.doByteSwap[1] )
  7111. byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
  7112. // Do buffer conversion if necessary.
  7113. if ( stream_.doConvertBuffer[1] )
  7114. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  7115. // Check stream latency
  7116. result = snd_pcm_delay( handle[1], &frames );
  7117. if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
  7118. }
  7119. tryOutput:
  7120. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7121. // Setup parameters and do buffer conversion if necessary.
  7122. if ( stream_.doConvertBuffer[0] ) {
  7123. buffer = stream_.deviceBuffer;
  7124. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  7125. channels = stream_.nDeviceChannels[0];
  7126. format = stream_.deviceFormat[0];
  7127. }
  7128. else {
  7129. buffer = stream_.userBuffer[0];
  7130. channels = stream_.nUserChannels[0];
  7131. format = stream_.userFormat;
  7132. }
  7133. // Do byte swapping if necessary.
  7134. if ( stream_.doByteSwap[0] )
  7135. byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
  7136. // Write samples to device in interleaved/non-interleaved format.
  7137. if ( stream_.deviceInterleaved[0] )
  7138. result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
  7139. else {
  7140. void *bufs[channels];
  7141. size_t offset = stream_.bufferSize * formatBytes( format );
  7142. for ( int i=0; i<channels; i++ )
  7143. bufs[i] = (void *) (buffer + (i * offset));
  7144. result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
  7145. }
  7146. if ( result < (int) stream_.bufferSize ) {
  7147. // Either an error or underrun occured.
  7148. if ( result == -EPIPE ) {
  7149. snd_pcm_state_t state = snd_pcm_state( handle[0] );
  7150. if ( state == SND_PCM_STATE_XRUN ) {
  7151. apiInfo->xrun[0] = true;
  7152. result = snd_pcm_prepare( handle[0] );
  7153. if ( result < 0 ) {
  7154. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
  7155. errorText_ = errorStream_.str();
  7156. }
  7157. else
  7158. errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun.";
  7159. }
  7160. else {
  7161. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  7162. errorText_ = errorStream_.str();
  7163. }
  7164. }
  7165. else {
  7166. errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
  7167. errorText_ = errorStream_.str();
  7168. }
  7169. error( RtAudioError::WARNING );
  7170. goto unlock;
  7171. }
  7172. // Check stream latency
  7173. result = snd_pcm_delay( handle[0], &frames );
  7174. if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
  7175. }
  7176. unlock:
  7177. MUTEX_UNLOCK( &stream_.mutex );
  7178. RtApi::tickStreamTime();
  7179. if ( doStopStream == 1 ) this->stopStream();
  7180. }
  7181. static void *alsaCallbackHandler( void *ptr )
  7182. {
  7183. CallbackInfo *info = (CallbackInfo *) ptr;
  7184. RtApiAlsa *object = (RtApiAlsa *) info->object;
  7185. bool *isRunning = &info->isRunning;
  7186. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  7187. if ( info->doRealtime ) {
  7188. std::cerr << "RtAudio alsa: " <<
  7189. (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
  7190. "running realtime scheduling" << std::endl;
  7191. }
  7192. #endif
  7193. while ( *isRunning == true ) {
  7194. pthread_testcancel();
  7195. object->callbackEvent();
  7196. }
  7197. pthread_exit( NULL );
  7198. }
  7199. //******************** End of __LINUX_ALSA__ *********************//
  7200. #endif
  7201. #if defined(__LINUX_PULSE__)
  7202. // Code written by Peter Meerwald, pmeerw@pmeerw.net
  7203. // and Tristan Matthews.
  7204. #include <pulse/error.h>
  7205. #include <pulse/simple.h>
  7206. #include <cstdio>
  7207. static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,
  7208. 44100, 48000, 96000, 0};
  7209. struct rtaudio_pa_format_mapping_t {
  7210. RtAudioFormat rtaudio_format;
  7211. pa_sample_format_t pa_format;
  7212. };
  7213. static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {
  7214. {RTAUDIO_SINT16, PA_SAMPLE_S16LE},
  7215. {RTAUDIO_SINT32, PA_SAMPLE_S32LE},
  7216. {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},
  7217. {0, PA_SAMPLE_INVALID}};
  7218. struct PulseAudioHandle {
  7219. pa_simple *s_play;
  7220. pa_simple *s_rec;
  7221. pthread_t thread;
  7222. pthread_cond_t runnable_cv;
  7223. bool runnable;
  7224. PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }
  7225. };
  7226. RtApiPulse::~RtApiPulse()
  7227. {
  7228. if ( stream_.state != STREAM_CLOSED )
  7229. closeStream();
  7230. }
  7231. unsigned int RtApiPulse::getDeviceCount( void )
  7232. {
  7233. return 1;
  7234. }
  7235. RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )
  7236. {
  7237. RtAudio::DeviceInfo info;
  7238. info.probed = true;
  7239. info.name = "PulseAudio";
  7240. info.outputChannels = 2;
  7241. info.inputChannels = 2;
  7242. info.duplexChannels = 2;
  7243. info.isDefaultOutput = true;
  7244. info.isDefaultInput = true;
  7245. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )
  7246. info.sampleRates.push_back( *sr );
  7247. info.preferredSampleRate = 48000;
  7248. info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;
  7249. return info;
  7250. }
  7251. static void *pulseaudio_callback( void * user )
  7252. {
  7253. CallbackInfo *cbi = static_cast<CallbackInfo *>( user );
  7254. RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );
  7255. volatile bool *isRunning = &cbi->isRunning;
  7256. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  7257. if (cbi->doRealtime) {
  7258. std::cerr << "RtAudio pulse: " <<
  7259. (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
  7260. "running realtime scheduling" << std::endl;
  7261. }
  7262. #endif
  7263. while ( *isRunning ) {
  7264. pthread_testcancel();
  7265. context->callbackEvent();
  7266. }
  7267. pthread_exit( NULL );
  7268. }
  7269. void RtApiPulse::closeStream( void )
  7270. {
  7271. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7272. stream_.callbackInfo.isRunning = false;
  7273. if ( pah ) {
  7274. MUTEX_LOCK( &stream_.mutex );
  7275. if ( stream_.state == STREAM_STOPPED ) {
  7276. pah->runnable = true;
  7277. pthread_cond_signal( &pah->runnable_cv );
  7278. }
  7279. MUTEX_UNLOCK( &stream_.mutex );
  7280. pthread_join( pah->thread, 0 );
  7281. if ( pah->s_play ) {
  7282. pa_simple_flush( pah->s_play, NULL );
  7283. pa_simple_free( pah->s_play );
  7284. }
  7285. if ( pah->s_rec )
  7286. pa_simple_free( pah->s_rec );
  7287. pthread_cond_destroy( &pah->runnable_cv );
  7288. delete pah;
  7289. stream_.apiHandle = 0;
  7290. }
  7291. if ( stream_.userBuffer[0] ) {
  7292. free( stream_.userBuffer[0] );
  7293. stream_.userBuffer[0] = 0;
  7294. }
  7295. if ( stream_.userBuffer[1] ) {
  7296. free( stream_.userBuffer[1] );
  7297. stream_.userBuffer[1] = 0;
  7298. }
  7299. stream_.state = STREAM_CLOSED;
  7300. stream_.mode = UNINITIALIZED;
  7301. }
  7302. void RtApiPulse::callbackEvent( void )
  7303. {
  7304. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7305. if ( stream_.state == STREAM_STOPPED ) {
  7306. MUTEX_LOCK( &stream_.mutex );
  7307. while ( !pah->runnable )
  7308. pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );
  7309. if ( stream_.state != STREAM_RUNNING ) {
  7310. MUTEX_UNLOCK( &stream_.mutex );
  7311. return;
  7312. }
  7313. MUTEX_UNLOCK( &stream_.mutex );
  7314. }
  7315. if ( stream_.state == STREAM_CLOSED ) {
  7316. errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "
  7317. "this shouldn't happen!";
  7318. error( RtAudioError::WARNING );
  7319. return;
  7320. }
  7321. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  7322. double streamTime = getStreamTime();
  7323. RtAudioStreamStatus status = 0;
  7324. int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],
  7325. stream_.bufferSize, streamTime, status,
  7326. stream_.callbackInfo.userData );
  7327. if ( doStopStream == 2 ) {
  7328. abortStream();
  7329. return;
  7330. }
  7331. MUTEX_LOCK( &stream_.mutex );
  7332. void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];
  7333. void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];
  7334. if ( stream_.state != STREAM_RUNNING )
  7335. goto unlock;
  7336. int pa_error;
  7337. size_t bytes;
  7338. if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7339. if ( stream_.doConvertBuffer[OUTPUT] ) {
  7340. convertBuffer( stream_.deviceBuffer,
  7341. stream_.userBuffer[OUTPUT],
  7342. stream_.convertInfo[OUTPUT] );
  7343. bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *
  7344. formatBytes( stream_.deviceFormat[OUTPUT] );
  7345. } else
  7346. bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *
  7347. formatBytes( stream_.userFormat );
  7348. if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {
  7349. errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<
  7350. pa_strerror( pa_error ) << ".";
  7351. errorText_ = errorStream_.str();
  7352. error( RtAudioError::WARNING );
  7353. }
  7354. }
  7355. if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {
  7356. if ( stream_.doConvertBuffer[INPUT] )
  7357. bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *
  7358. formatBytes( stream_.deviceFormat[INPUT] );
  7359. else
  7360. bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *
  7361. formatBytes( stream_.userFormat );
  7362. if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {
  7363. errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<
  7364. pa_strerror( pa_error ) << ".";
  7365. errorText_ = errorStream_.str();
  7366. error( RtAudioError::WARNING );
  7367. }
  7368. if ( stream_.doConvertBuffer[INPUT] ) {
  7369. convertBuffer( stream_.userBuffer[INPUT],
  7370. stream_.deviceBuffer,
  7371. stream_.convertInfo[INPUT] );
  7372. }
  7373. }
  7374. unlock:
  7375. MUTEX_UNLOCK( &stream_.mutex );
  7376. RtApi::tickStreamTime();
  7377. if ( doStopStream == 1 )
  7378. stopStream();
  7379. }
  7380. void RtApiPulse::startStream( void )
  7381. {
  7382. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7383. if ( stream_.state == STREAM_CLOSED ) {
  7384. errorText_ = "RtApiPulse::startStream(): the stream is not open!";
  7385. error( RtAudioError::INVALID_USE );
  7386. return;
  7387. }
  7388. if ( stream_.state == STREAM_RUNNING ) {
  7389. errorText_ = "RtApiPulse::startStream(): the stream is already running!";
  7390. error( RtAudioError::WARNING );
  7391. return;
  7392. }
  7393. MUTEX_LOCK( &stream_.mutex );
  7394. #if defined( HAVE_GETTIMEOFDAY )
  7395. gettimeofday( &stream_.lastTickTimestamp, NULL );
  7396. #endif
  7397. stream_.state = STREAM_RUNNING;
  7398. pah->runnable = true;
  7399. pthread_cond_signal( &pah->runnable_cv );
  7400. MUTEX_UNLOCK( &stream_.mutex );
  7401. }
  7402. void RtApiPulse::stopStream( void )
  7403. {
  7404. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7405. if ( stream_.state == STREAM_CLOSED ) {
  7406. errorText_ = "RtApiPulse::stopStream(): the stream is not open!";
  7407. error( RtAudioError::INVALID_USE );
  7408. return;
  7409. }
  7410. if ( stream_.state == STREAM_STOPPED ) {
  7411. errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";
  7412. error( RtAudioError::WARNING );
  7413. return;
  7414. }
  7415. stream_.state = STREAM_STOPPED;
  7416. MUTEX_LOCK( &stream_.mutex );
  7417. if ( pah && pah->s_play ) {
  7418. int pa_error;
  7419. if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {
  7420. errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<
  7421. pa_strerror( pa_error ) << ".";
  7422. errorText_ = errorStream_.str();
  7423. MUTEX_UNLOCK( &stream_.mutex );
  7424. error( RtAudioError::SYSTEM_ERROR );
  7425. return;
  7426. }
  7427. }
  7428. stream_.state = STREAM_STOPPED;
  7429. MUTEX_UNLOCK( &stream_.mutex );
  7430. }
  7431. void RtApiPulse::abortStream( void )
  7432. {
  7433. PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );
  7434. if ( stream_.state == STREAM_CLOSED ) {
  7435. errorText_ = "RtApiPulse::abortStream(): the stream is not open!";
  7436. error( RtAudioError::INVALID_USE );
  7437. return;
  7438. }
  7439. if ( stream_.state == STREAM_STOPPED ) {
  7440. errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";
  7441. error( RtAudioError::WARNING );
  7442. return;
  7443. }
  7444. stream_.state = STREAM_STOPPED;
  7445. MUTEX_LOCK( &stream_.mutex );
  7446. if ( pah && pah->s_play ) {
  7447. int pa_error;
  7448. if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {
  7449. errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<
  7450. pa_strerror( pa_error ) << ".";
  7451. errorText_ = errorStream_.str();
  7452. MUTEX_UNLOCK( &stream_.mutex );
  7453. error( RtAudioError::SYSTEM_ERROR );
  7454. return;
  7455. }
  7456. }
  7457. stream_.state = STREAM_STOPPED;
  7458. MUTEX_UNLOCK( &stream_.mutex );
  7459. }
  7460. bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
  7461. unsigned int channels, unsigned int firstChannel,
  7462. unsigned int sampleRate, RtAudioFormat format,
  7463. unsigned int *bufferSize, RtAudio::StreamOptions *options )
  7464. {
  7465. PulseAudioHandle *pah = 0;
  7466. unsigned long bufferBytes = 0;
  7467. pa_sample_spec ss;
  7468. if ( device != 0 ) return false;
  7469. if ( mode != INPUT && mode != OUTPUT ) return false;
  7470. if ( channels != 1 && channels != 2 ) {
  7471. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";
  7472. return false;
  7473. }
  7474. ss.channels = channels;
  7475. if ( firstChannel != 0 ) return false;
  7476. bool sr_found = false;
  7477. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {
  7478. if ( sampleRate == *sr ) {
  7479. sr_found = true;
  7480. stream_.sampleRate = sampleRate;
  7481. ss.rate = sampleRate;
  7482. break;
  7483. }
  7484. }
  7485. if ( !sr_found ) {
  7486. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";
  7487. return false;
  7488. }
  7489. bool sf_found = 0;
  7490. for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;
  7491. sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {
  7492. if ( format == sf->rtaudio_format ) {
  7493. sf_found = true;
  7494. stream_.userFormat = sf->rtaudio_format;
  7495. stream_.deviceFormat[mode] = stream_.userFormat;
  7496. ss.format = sf->pa_format;
  7497. break;
  7498. }
  7499. }
  7500. if ( !sf_found ) { // Use internal data format conversion.
  7501. stream_.userFormat = format;
  7502. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  7503. ss.format = PA_SAMPLE_FLOAT32LE;
  7504. }
  7505. // Set other stream parameters.
  7506. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  7507. else stream_.userInterleaved = true;
  7508. stream_.deviceInterleaved[mode] = true;
  7509. stream_.nBuffers = 1;
  7510. stream_.doByteSwap[mode] = false;
  7511. stream_.nUserChannels[mode] = channels;
  7512. stream_.nDeviceChannels[mode] = channels + firstChannel;
  7513. stream_.channelOffset[mode] = 0;
  7514. std::string streamName = "RtAudio";
  7515. // Set flags for buffer conversion.
  7516. stream_.doConvertBuffer[mode] = false;
  7517. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7518. stream_.doConvertBuffer[mode] = true;
  7519. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7520. stream_.doConvertBuffer[mode] = true;
  7521. // Allocate necessary internal buffers.
  7522. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7523. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7524. if ( stream_.userBuffer[mode] == NULL ) {
  7525. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";
  7526. goto error;
  7527. }
  7528. stream_.bufferSize = *bufferSize;
  7529. if ( stream_.doConvertBuffer[mode] ) {
  7530. bool makeBuffer = true;
  7531. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7532. if ( mode == INPUT ) {
  7533. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7534. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7535. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7536. }
  7537. }
  7538. if ( makeBuffer ) {
  7539. bufferBytes *= *bufferSize;
  7540. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7541. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7542. if ( stream_.deviceBuffer == NULL ) {
  7543. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";
  7544. goto error;
  7545. }
  7546. }
  7547. }
  7548. stream_.device[mode] = device;
  7549. // Setup the buffer conversion information structure.
  7550. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7551. if ( !stream_.apiHandle ) {
  7552. PulseAudioHandle *pah = new PulseAudioHandle;
  7553. if ( !pah ) {
  7554. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";
  7555. goto error;
  7556. }
  7557. stream_.apiHandle = pah;
  7558. if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {
  7559. errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";
  7560. goto error;
  7561. }
  7562. }
  7563. pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7564. int error;
  7565. if ( options && !options->streamName.empty() ) streamName = options->streamName;
  7566. switch ( mode ) {
  7567. case INPUT:
  7568. pa_buffer_attr buffer_attr;
  7569. buffer_attr.fragsize = bufferBytes;
  7570. buffer_attr.maxlength = -1;
  7571. pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );
  7572. if ( !pah->s_rec ) {
  7573. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";
  7574. goto error;
  7575. }
  7576. break;
  7577. case OUTPUT:
  7578. pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );
  7579. if ( !pah->s_play ) {
  7580. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";
  7581. goto error;
  7582. }
  7583. break;
  7584. default:
  7585. goto error;
  7586. }
  7587. if ( stream_.mode == UNINITIALIZED )
  7588. stream_.mode = mode;
  7589. else if ( stream_.mode == mode )
  7590. goto error;
  7591. else
  7592. stream_.mode = DUPLEX;
  7593. if ( !stream_.callbackInfo.isRunning ) {
  7594. stream_.callbackInfo.object = this;
  7595. stream_.state = STREAM_STOPPED;
  7596. // Set the thread attributes for joinable and realtime scheduling
  7597. // priority (optional). The higher priority will only take affect
  7598. // if the program is run as root or suid. Note, under Linux
  7599. // processes with CAP_SYS_NICE privilege, a user can change
  7600. // scheduling policy and priority (thus need not be root). See
  7601. // POSIX "capabilities".
  7602. pthread_attr_t attr;
  7603. pthread_attr_init( &attr );
  7604. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  7605. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  7606. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  7607. stream_.callbackInfo.doRealtime = true;
  7608. struct sched_param param;
  7609. int priority = options->priority;
  7610. int min = sched_get_priority_min( SCHED_RR );
  7611. int max = sched_get_priority_max( SCHED_RR );
  7612. if ( priority < min ) priority = min;
  7613. else if ( priority > max ) priority = max;
  7614. param.sched_priority = priority;
  7615. // Set the policy BEFORE the priority. Otherwise it fails.
  7616. pthread_attr_setschedpolicy(&attr, SCHED_RR);
  7617. pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
  7618. // This is definitely required. Otherwise it fails.
  7619. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
  7620. pthread_attr_setschedparam(&attr, &param);
  7621. }
  7622. else
  7623. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7624. #else
  7625. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7626. #endif
  7627. stream_.callbackInfo.isRunning = true;
  7628. int result = pthread_create( &pah->thread, &attr, pulseaudio_callback, (void *)&stream_.callbackInfo);
  7629. pthread_attr_destroy(&attr);
  7630. if(result != 0) {
  7631. // Failed. Try instead with default attributes.
  7632. result = pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo);
  7633. if(result != 0) {
  7634. stream_.callbackInfo.isRunning = false;
  7635. errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";
  7636. goto error;
  7637. }
  7638. }
  7639. }
  7640. return SUCCESS;
  7641. error:
  7642. if ( pah && stream_.callbackInfo.isRunning ) {
  7643. pthread_cond_destroy( &pah->runnable_cv );
  7644. delete pah;
  7645. stream_.apiHandle = 0;
  7646. }
  7647. for ( int i=0; i<2; i++ ) {
  7648. if ( stream_.userBuffer[i] ) {
  7649. free( stream_.userBuffer[i] );
  7650. stream_.userBuffer[i] = 0;
  7651. }
  7652. }
  7653. if ( stream_.deviceBuffer ) {
  7654. free( stream_.deviceBuffer );
  7655. stream_.deviceBuffer = 0;
  7656. }
  7657. stream_.state = STREAM_CLOSED;
  7658. return FAILURE;
  7659. }
  7660. //******************** End of __LINUX_PULSE__ *********************//
  7661. #endif
  7662. #if defined(__LINUX_OSS__)
  7663. #include <unistd.h>
  7664. #include <sys/ioctl.h>
  7665. #include <unistd.h>
  7666. #include <fcntl.h>
  7667. #include <sys/soundcard.h>
  7668. #include <errno.h>
  7669. #include <math.h>
  7670. static void *ossCallbackHandler(void * ptr);
  7671. // A structure to hold various information related to the OSS API
  7672. // implementation.
  7673. struct OssHandle {
  7674. int id[2]; // device ids
  7675. bool xrun[2];
  7676. bool triggered;
  7677. pthread_cond_t runnable;
  7678. OssHandle()
  7679. :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  7680. };
  7681. RtApiOss :: RtApiOss()
  7682. {
  7683. // Nothing to do here.
  7684. }
  7685. RtApiOss :: ~RtApiOss()
  7686. {
  7687. if ( stream_.state != STREAM_CLOSED ) closeStream();
  7688. }
  7689. unsigned int RtApiOss :: getDeviceCount( void )
  7690. {
  7691. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7692. if ( mixerfd == -1 ) {
  7693. errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
  7694. error( RtAudioError::WARNING );
  7695. return 0;
  7696. }
  7697. oss_sysinfo sysinfo;
  7698. if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
  7699. close( mixerfd );
  7700. errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
  7701. error( RtAudioError::WARNING );
  7702. return 0;
  7703. }
  7704. close( mixerfd );
  7705. return sysinfo.numaudios;
  7706. }
  7707. RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
  7708. {
  7709. RtAudio::DeviceInfo info;
  7710. info.probed = false;
  7711. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7712. if ( mixerfd == -1 ) {
  7713. errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
  7714. error( RtAudioError::WARNING );
  7715. return info;
  7716. }
  7717. oss_sysinfo sysinfo;
  7718. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7719. if ( result == -1 ) {
  7720. close( mixerfd );
  7721. errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
  7722. error( RtAudioError::WARNING );
  7723. return info;
  7724. }
  7725. unsigned nDevices = sysinfo.numaudios;
  7726. if ( nDevices == 0 ) {
  7727. close( mixerfd );
  7728. errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
  7729. error( RtAudioError::INVALID_USE );
  7730. return info;
  7731. }
  7732. if ( device >= nDevices ) {
  7733. close( mixerfd );
  7734. errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
  7735. error( RtAudioError::INVALID_USE );
  7736. return info;
  7737. }
  7738. oss_audioinfo ainfo;
  7739. ainfo.dev = device;
  7740. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7741. close( mixerfd );
  7742. if ( result == -1 ) {
  7743. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7744. errorText_ = errorStream_.str();
  7745. error( RtAudioError::WARNING );
  7746. return info;
  7747. }
  7748. // Probe channels
  7749. if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
  7750. if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
  7751. if ( ainfo.caps & PCM_CAP_DUPLEX ) {
  7752. if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
  7753. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  7754. }
  7755. // Probe data formats ... do for input
  7756. unsigned long mask = ainfo.iformats;
  7757. if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
  7758. info.nativeFormats |= RTAUDIO_SINT16;
  7759. if ( mask & AFMT_S8 )
  7760. info.nativeFormats |= RTAUDIO_SINT8;
  7761. if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
  7762. info.nativeFormats |= RTAUDIO_SINT32;
  7763. #ifdef AFMT_FLOAT
  7764. if ( mask & AFMT_FLOAT )
  7765. info.nativeFormats |= RTAUDIO_FLOAT32;
  7766. #endif
  7767. if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
  7768. info.nativeFormats |= RTAUDIO_SINT24;
  7769. // Check that we have at least one supported format
  7770. if ( info.nativeFormats == 0 ) {
  7771. errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7772. errorText_ = errorStream_.str();
  7773. error( RtAudioError::WARNING );
  7774. return info;
  7775. }
  7776. // Probe the supported sample rates.
  7777. info.sampleRates.clear();
  7778. if ( ainfo.nrates ) {
  7779. for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
  7780. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7781. if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
  7782. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7783. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7784. info.preferredSampleRate = SAMPLE_RATES[k];
  7785. break;
  7786. }
  7787. }
  7788. }
  7789. }
  7790. else {
  7791. // Check min and max rate values;
  7792. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7793. if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {
  7794. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7795. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7796. info.preferredSampleRate = SAMPLE_RATES[k];
  7797. }
  7798. }
  7799. }
  7800. if ( info.sampleRates.size() == 0 ) {
  7801. errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
  7802. errorText_ = errorStream_.str();
  7803. error( RtAudioError::WARNING );
  7804. }
  7805. else {
  7806. info.probed = true;
  7807. info.name = ainfo.name;
  7808. }
  7809. return info;
  7810. }
  7811. bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  7812. unsigned int firstChannel, unsigned int sampleRate,
  7813. RtAudioFormat format, unsigned int *bufferSize,
  7814. RtAudio::StreamOptions *options )
  7815. {
  7816. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7817. if ( mixerfd == -1 ) {
  7818. errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
  7819. return FAILURE;
  7820. }
  7821. oss_sysinfo sysinfo;
  7822. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7823. if ( result == -1 ) {
  7824. close( mixerfd );
  7825. errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
  7826. return FAILURE;
  7827. }
  7828. unsigned nDevices = sysinfo.numaudios;
  7829. if ( nDevices == 0 ) {
  7830. // This should not happen because a check is made before this function is called.
  7831. close( mixerfd );
  7832. errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
  7833. return FAILURE;
  7834. }
  7835. if ( device >= nDevices ) {
  7836. // This should not happen because a check is made before this function is called.
  7837. close( mixerfd );
  7838. errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
  7839. return FAILURE;
  7840. }
  7841. oss_audioinfo ainfo;
  7842. ainfo.dev = device;
  7843. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7844. close( mixerfd );
  7845. if ( result == -1 ) {
  7846. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7847. errorText_ = errorStream_.str();
  7848. return FAILURE;
  7849. }
  7850. // Check if device supports input or output
  7851. if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
  7852. ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
  7853. if ( mode == OUTPUT )
  7854. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
  7855. else
  7856. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
  7857. errorText_ = errorStream_.str();
  7858. return FAILURE;
  7859. }
  7860. int flags = 0;
  7861. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7862. if ( mode == OUTPUT )
  7863. flags |= O_WRONLY;
  7864. else { // mode == INPUT
  7865. if (stream_.mode == OUTPUT && stream_.device[0] == device) {
  7866. // We just set the same device for playback ... close and reopen for duplex (OSS only).
  7867. close( handle->id[0] );
  7868. handle->id[0] = 0;
  7869. if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
  7870. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
  7871. errorText_ = errorStream_.str();
  7872. return FAILURE;
  7873. }
  7874. // Check that the number previously set channels is the same.
  7875. if ( stream_.nUserChannels[0] != channels ) {
  7876. errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
  7877. errorText_ = errorStream_.str();
  7878. return FAILURE;
  7879. }
  7880. flags |= O_RDWR;
  7881. }
  7882. else
  7883. flags |= O_RDONLY;
  7884. }
  7885. // Set exclusive access if specified.
  7886. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
  7887. // Try to open the device.
  7888. int fd;
  7889. fd = open( ainfo.devnode, flags, 0 );
  7890. if ( fd == -1 ) {
  7891. if ( errno == EBUSY )
  7892. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
  7893. else
  7894. errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
  7895. errorText_ = errorStream_.str();
  7896. return FAILURE;
  7897. }
  7898. // For duplex operation, specifically set this mode (this doesn't seem to work).
  7899. /*
  7900. if ( flags | O_RDWR ) {
  7901. result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
  7902. if ( result == -1) {
  7903. errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
  7904. errorText_ = errorStream_.str();
  7905. return FAILURE;
  7906. }
  7907. }
  7908. */
  7909. // Check the device channel support.
  7910. stream_.nUserChannels[mode] = channels;
  7911. if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
  7912. close( fd );
  7913. errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
  7914. errorText_ = errorStream_.str();
  7915. return FAILURE;
  7916. }
  7917. // Set the number of channels.
  7918. int deviceChannels = channels + firstChannel;
  7919. result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
  7920. if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
  7921. close( fd );
  7922. errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
  7923. errorText_ = errorStream_.str();
  7924. return FAILURE;
  7925. }
  7926. stream_.nDeviceChannels[mode] = deviceChannels;
  7927. // Get the data format mask
  7928. int mask;
  7929. result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
  7930. if ( result == -1 ) {
  7931. close( fd );
  7932. errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
  7933. errorText_ = errorStream_.str();
  7934. return FAILURE;
  7935. }
  7936. // Determine how to set the device format.
  7937. stream_.userFormat = format;
  7938. int deviceFormat = -1;
  7939. stream_.doByteSwap[mode] = false;
  7940. if ( format == RTAUDIO_SINT8 ) {
  7941. if ( mask & AFMT_S8 ) {
  7942. deviceFormat = AFMT_S8;
  7943. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7944. }
  7945. }
  7946. else if ( format == RTAUDIO_SINT16 ) {
  7947. if ( mask & AFMT_S16_NE ) {
  7948. deviceFormat = AFMT_S16_NE;
  7949. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7950. }
  7951. else if ( mask & AFMT_S16_OE ) {
  7952. deviceFormat = AFMT_S16_OE;
  7953. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7954. stream_.doByteSwap[mode] = true;
  7955. }
  7956. }
  7957. else if ( format == RTAUDIO_SINT24 ) {
  7958. if ( mask & AFMT_S24_NE ) {
  7959. deviceFormat = AFMT_S24_NE;
  7960. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7961. }
  7962. else if ( mask & AFMT_S24_OE ) {
  7963. deviceFormat = AFMT_S24_OE;
  7964. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7965. stream_.doByteSwap[mode] = true;
  7966. }
  7967. }
  7968. else if ( format == RTAUDIO_SINT32 ) {
  7969. if ( mask & AFMT_S32_NE ) {
  7970. deviceFormat = AFMT_S32_NE;
  7971. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7972. }
  7973. else if ( mask & AFMT_S32_OE ) {
  7974. deviceFormat = AFMT_S32_OE;
  7975. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7976. stream_.doByteSwap[mode] = true;
  7977. }
  7978. }
  7979. if ( deviceFormat == -1 ) {
  7980. // The user requested format is not natively supported by the device.
  7981. if ( mask & AFMT_S16_NE ) {
  7982. deviceFormat = AFMT_S16_NE;
  7983. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7984. }
  7985. else if ( mask & AFMT_S32_NE ) {
  7986. deviceFormat = AFMT_S32_NE;
  7987. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7988. }
  7989. else if ( mask & AFMT_S24_NE ) {
  7990. deviceFormat = AFMT_S24_NE;
  7991. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7992. }
  7993. else if ( mask & AFMT_S16_OE ) {
  7994. deviceFormat = AFMT_S16_OE;
  7995. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7996. stream_.doByteSwap[mode] = true;
  7997. }
  7998. else if ( mask & AFMT_S32_OE ) {
  7999. deviceFormat = AFMT_S32_OE;
  8000. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  8001. stream_.doByteSwap[mode] = true;
  8002. }
  8003. else if ( mask & AFMT_S24_OE ) {
  8004. deviceFormat = AFMT_S24_OE;
  8005. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  8006. stream_.doByteSwap[mode] = true;
  8007. }
  8008. else if ( mask & AFMT_S8) {
  8009. deviceFormat = AFMT_S8;
  8010. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  8011. }
  8012. }
  8013. if ( stream_.deviceFormat[mode] == 0 ) {
  8014. // This really shouldn't happen ...
  8015. close( fd );
  8016. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
  8017. errorText_ = errorStream_.str();
  8018. return FAILURE;
  8019. }
  8020. // Set the data format.
  8021. int temp = deviceFormat;
  8022. result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
  8023. if ( result == -1 || deviceFormat != temp ) {
  8024. close( fd );
  8025. errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
  8026. errorText_ = errorStream_.str();
  8027. return FAILURE;
  8028. }
  8029. // Attempt to set the buffer size. According to OSS, the minimum
  8030. // number of buffers is two. The supposed minimum buffer size is 16
  8031. // bytes, so that will be our lower bound. The argument to this
  8032. // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
  8033. // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
  8034. // We'll check the actual value used near the end of the setup
  8035. // procedure.
  8036. int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
  8037. if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
  8038. int buffers = 0;
  8039. if ( options ) buffers = options->numberOfBuffers;
  8040. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
  8041. if ( buffers < 2 ) buffers = 3;
  8042. temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
  8043. result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
  8044. if ( result == -1 ) {
  8045. close( fd );
  8046. errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
  8047. errorText_ = errorStream_.str();
  8048. return FAILURE;
  8049. }
  8050. stream_.nBuffers = buffers;
  8051. // Save buffer size (in sample frames).
  8052. *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
  8053. stream_.bufferSize = *bufferSize;
  8054. // Set the sample rate.
  8055. int srate = sampleRate;
  8056. result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
  8057. if ( result == -1 ) {
  8058. close( fd );
  8059. errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
  8060. errorText_ = errorStream_.str();
  8061. return FAILURE;
  8062. }
  8063. // Verify the sample rate setup worked.
  8064. if ( abs( srate - (int)sampleRate ) > 100 ) {
  8065. close( fd );
  8066. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
  8067. errorText_ = errorStream_.str();
  8068. return FAILURE;
  8069. }
  8070. stream_.sampleRate = sampleRate;
  8071. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
  8072. // We're doing duplex setup here.
  8073. stream_.deviceFormat[0] = stream_.deviceFormat[1];
  8074. stream_.nDeviceChannels[0] = deviceChannels;
  8075. }
  8076. // Set interleaving parameters.
  8077. stream_.userInterleaved = true;
  8078. stream_.deviceInterleaved[mode] = true;
  8079. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  8080. stream_.userInterleaved = false;
  8081. // Set flags for buffer conversion
  8082. stream_.doConvertBuffer[mode] = false;
  8083. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  8084. stream_.doConvertBuffer[mode] = true;
  8085. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  8086. stream_.doConvertBuffer[mode] = true;
  8087. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  8088. stream_.nUserChannels[mode] > 1 )
  8089. stream_.doConvertBuffer[mode] = true;
  8090. // Allocate the stream handles if necessary and then save.
  8091. if ( stream_.apiHandle == 0 ) {
  8092. try {
  8093. handle = new OssHandle;
  8094. }
  8095. catch ( std::bad_alloc& ) {
  8096. errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
  8097. goto error;
  8098. }
  8099. if ( pthread_cond_init( &handle->runnable, NULL ) ) {
  8100. errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
  8101. goto error;
  8102. }
  8103. stream_.apiHandle = (void *) handle;
  8104. }
  8105. else {
  8106. handle = (OssHandle *) stream_.apiHandle;
  8107. }
  8108. handle->id[mode] = fd;
  8109. // Allocate necessary internal buffers.
  8110. unsigned long bufferBytes;
  8111. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  8112. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  8113. if ( stream_.userBuffer[mode] == NULL ) {
  8114. errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
  8115. goto error;
  8116. }
  8117. if ( stream_.doConvertBuffer[mode] ) {
  8118. bool makeBuffer = true;
  8119. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  8120. if ( mode == INPUT ) {
  8121. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  8122. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  8123. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  8124. }
  8125. }
  8126. if ( makeBuffer ) {
  8127. bufferBytes *= *bufferSize;
  8128. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  8129. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  8130. if ( stream_.deviceBuffer == NULL ) {
  8131. errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
  8132. goto error;
  8133. }
  8134. }
  8135. }
  8136. stream_.device[mode] = device;
  8137. stream_.state = STREAM_STOPPED;
  8138. // Setup the buffer conversion information structure.
  8139. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  8140. // Setup thread if necessary.
  8141. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  8142. // We had already set up an output stream.
  8143. stream_.mode = DUPLEX;
  8144. if ( stream_.device[0] == device ) handle->id[0] = fd;
  8145. }
  8146. else {
  8147. stream_.mode = mode;
  8148. // Setup callback thread.
  8149. stream_.callbackInfo.object = (void *) this;
  8150. // Set the thread attributes for joinable and realtime scheduling
  8151. // priority. The higher priority will only take affect if the
  8152. // program is run as root or suid.
  8153. pthread_attr_t attr;
  8154. pthread_attr_init( &attr );
  8155. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  8156. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  8157. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  8158. stream_.callbackInfo.doRealtime = true;
  8159. struct sched_param param;
  8160. int priority = options->priority;
  8161. int min = sched_get_priority_min( SCHED_RR );
  8162. int max = sched_get_priority_max( SCHED_RR );
  8163. if ( priority < min ) priority = min;
  8164. else if ( priority > max ) priority = max;
  8165. param.sched_priority = priority;
  8166. // Set the policy BEFORE the priority. Otherwise it fails.
  8167. pthread_attr_setschedpolicy(&attr, SCHED_RR);
  8168. pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
  8169. // This is definitely required. Otherwise it fails.
  8170. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
  8171. pthread_attr_setschedparam(&attr, &param);
  8172. }
  8173. else
  8174. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  8175. #else
  8176. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  8177. #endif
  8178. stream_.callbackInfo.isRunning = true;
  8179. result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
  8180. pthread_attr_destroy( &attr );
  8181. if ( result ) {
  8182. // Failed. Try instead with default attributes.
  8183. result = pthread_create( &stream_.callbackInfo.thread, NULL, ossCallbackHandler, &stream_.callbackInfo );
  8184. if ( result ) {
  8185. stream_.callbackInfo.isRunning = false;
  8186. errorText_ = "RtApiOss::error creating callback thread!";
  8187. goto error;
  8188. }
  8189. }
  8190. }
  8191. return SUCCESS;
  8192. error:
  8193. if ( handle ) {
  8194. pthread_cond_destroy( &handle->runnable );
  8195. if ( handle->id[0] ) close( handle->id[0] );
  8196. if ( handle->id[1] ) close( handle->id[1] );
  8197. delete handle;
  8198. stream_.apiHandle = 0;
  8199. }
  8200. for ( int i=0; i<2; i++ ) {
  8201. if ( stream_.userBuffer[i] ) {
  8202. free( stream_.userBuffer[i] );
  8203. stream_.userBuffer[i] = 0;
  8204. }
  8205. }
  8206. if ( stream_.deviceBuffer ) {
  8207. free( stream_.deviceBuffer );
  8208. stream_.deviceBuffer = 0;
  8209. }
  8210. stream_.state = STREAM_CLOSED;
  8211. return FAILURE;
  8212. }
  8213. void RtApiOss :: closeStream()
  8214. {
  8215. if ( stream_.state == STREAM_CLOSED ) {
  8216. errorText_ = "RtApiOss::closeStream(): no open stream to close!";
  8217. error( RtAudioError::WARNING );
  8218. return;
  8219. }
  8220. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8221. stream_.callbackInfo.isRunning = false;
  8222. MUTEX_LOCK( &stream_.mutex );
  8223. if ( stream_.state == STREAM_STOPPED )
  8224. pthread_cond_signal( &handle->runnable );
  8225. MUTEX_UNLOCK( &stream_.mutex );
  8226. pthread_join( stream_.callbackInfo.thread, NULL );
  8227. if ( stream_.state == STREAM_RUNNING ) {
  8228. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  8229. ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8230. else
  8231. ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8232. stream_.state = STREAM_STOPPED;
  8233. }
  8234. if ( handle ) {
  8235. pthread_cond_destroy( &handle->runnable );
  8236. if ( handle->id[0] ) close( handle->id[0] );
  8237. if ( handle->id[1] ) close( handle->id[1] );
  8238. delete handle;
  8239. stream_.apiHandle = 0;
  8240. }
  8241. for ( int i=0; i<2; i++ ) {
  8242. if ( stream_.userBuffer[i] ) {
  8243. free( stream_.userBuffer[i] );
  8244. stream_.userBuffer[i] = 0;
  8245. }
  8246. }
  8247. if ( stream_.deviceBuffer ) {
  8248. free( stream_.deviceBuffer );
  8249. stream_.deviceBuffer = 0;
  8250. }
  8251. stream_.mode = UNINITIALIZED;
  8252. stream_.state = STREAM_CLOSED;
  8253. }
  8254. void RtApiOss :: startStream()
  8255. {
  8256. verifyStream();
  8257. if ( stream_.state == STREAM_RUNNING ) {
  8258. errorText_ = "RtApiOss::startStream(): the stream is already running!";
  8259. error( RtAudioError::WARNING );
  8260. return;
  8261. }
  8262. MUTEX_LOCK( &stream_.mutex );
  8263. #if defined( HAVE_GETTIMEOFDAY )
  8264. gettimeofday( &stream_.lastTickTimestamp, NULL );
  8265. #endif
  8266. stream_.state = STREAM_RUNNING;
  8267. // No need to do anything else here ... OSS automatically starts
  8268. // when fed samples.
  8269. MUTEX_UNLOCK( &stream_.mutex );
  8270. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8271. pthread_cond_signal( &handle->runnable );
  8272. }
  8273. void RtApiOss :: stopStream()
  8274. {
  8275. verifyStream();
  8276. if ( stream_.state == STREAM_STOPPED ) {
  8277. errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
  8278. error( RtAudioError::WARNING );
  8279. return;
  8280. }
  8281. MUTEX_LOCK( &stream_.mutex );
  8282. // The state might change while waiting on a mutex.
  8283. if ( stream_.state == STREAM_STOPPED ) {
  8284. MUTEX_UNLOCK( &stream_.mutex );
  8285. return;
  8286. }
  8287. int result = 0;
  8288. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8289. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8290. // Flush the output with zeros a few times.
  8291. char *buffer;
  8292. int samples;
  8293. RtAudioFormat format;
  8294. if ( stream_.doConvertBuffer[0] ) {
  8295. buffer = stream_.deviceBuffer;
  8296. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  8297. format = stream_.deviceFormat[0];
  8298. }
  8299. else {
  8300. buffer = stream_.userBuffer[0];
  8301. samples = stream_.bufferSize * stream_.nUserChannels[0];
  8302. format = stream_.userFormat;
  8303. }
  8304. memset( buffer, 0, samples * formatBytes(format) );
  8305. for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
  8306. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8307. if ( result == -1 ) {
  8308. errorText_ = "RtApiOss::stopStream: audio write error.";
  8309. error( RtAudioError::WARNING );
  8310. }
  8311. }
  8312. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8313. if ( result == -1 ) {
  8314. errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  8315. errorText_ = errorStream_.str();
  8316. goto unlock;
  8317. }
  8318. handle->triggered = false;
  8319. }
  8320. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  8321. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8322. if ( result == -1 ) {
  8323. errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  8324. errorText_ = errorStream_.str();
  8325. goto unlock;
  8326. }
  8327. }
  8328. unlock:
  8329. stream_.state = STREAM_STOPPED;
  8330. MUTEX_UNLOCK( &stream_.mutex );
  8331. if ( result != -1 ) return;
  8332. error( RtAudioError::SYSTEM_ERROR );
  8333. }
  8334. void RtApiOss :: abortStream()
  8335. {
  8336. verifyStream();
  8337. if ( stream_.state == STREAM_STOPPED ) {
  8338. errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
  8339. error( RtAudioError::WARNING );
  8340. return;
  8341. }
  8342. MUTEX_LOCK( &stream_.mutex );
  8343. // The state might change while waiting on a mutex.
  8344. if ( stream_.state == STREAM_STOPPED ) {
  8345. MUTEX_UNLOCK( &stream_.mutex );
  8346. return;
  8347. }
  8348. int result = 0;
  8349. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8350. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8351. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8352. if ( result == -1 ) {
  8353. errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  8354. errorText_ = errorStream_.str();
  8355. goto unlock;
  8356. }
  8357. handle->triggered = false;
  8358. }
  8359. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  8360. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8361. if ( result == -1 ) {
  8362. errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  8363. errorText_ = errorStream_.str();
  8364. goto unlock;
  8365. }
  8366. }
  8367. unlock:
  8368. stream_.state = STREAM_STOPPED;
  8369. MUTEX_UNLOCK( &stream_.mutex );
  8370. if ( result != -1 ) return;
  8371. error( RtAudioError::SYSTEM_ERROR );
  8372. }
  8373. void RtApiOss :: callbackEvent()
  8374. {
  8375. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8376. if ( stream_.state == STREAM_STOPPED ) {
  8377. MUTEX_LOCK( &stream_.mutex );
  8378. pthread_cond_wait( &handle->runnable, &stream_.mutex );
  8379. if ( stream_.state != STREAM_RUNNING ) {
  8380. MUTEX_UNLOCK( &stream_.mutex );
  8381. return;
  8382. }
  8383. MUTEX_UNLOCK( &stream_.mutex );
  8384. }
  8385. if ( stream_.state == STREAM_CLOSED ) {
  8386. errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
  8387. error( RtAudioError::WARNING );
  8388. return;
  8389. }
  8390. // Invoke user callback to get fresh output data.
  8391. int doStopStream = 0;
  8392. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  8393. double streamTime = getStreamTime();
  8394. RtAudioStreamStatus status = 0;
  8395. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  8396. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  8397. handle->xrun[0] = false;
  8398. }
  8399. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  8400. status |= RTAUDIO_INPUT_OVERFLOW;
  8401. handle->xrun[1] = false;
  8402. }
  8403. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  8404. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  8405. if ( doStopStream == 2 ) {
  8406. this->abortStream();
  8407. return;
  8408. }
  8409. MUTEX_LOCK( &stream_.mutex );
  8410. // The state might change while waiting on a mutex.
  8411. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  8412. int result;
  8413. char *buffer;
  8414. int samples;
  8415. RtAudioFormat format;
  8416. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8417. // Setup parameters and do buffer conversion if necessary.
  8418. if ( stream_.doConvertBuffer[0] ) {
  8419. buffer = stream_.deviceBuffer;
  8420. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  8421. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  8422. format = stream_.deviceFormat[0];
  8423. }
  8424. else {
  8425. buffer = stream_.userBuffer[0];
  8426. samples = stream_.bufferSize * stream_.nUserChannels[0];
  8427. format = stream_.userFormat;
  8428. }
  8429. // Do byte swapping if necessary.
  8430. if ( stream_.doByteSwap[0] )
  8431. byteSwapBuffer( buffer, samples, format );
  8432. if ( stream_.mode == DUPLEX && handle->triggered == false ) {
  8433. int trig = 0;
  8434. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8435. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8436. trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
  8437. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8438. handle->triggered = true;
  8439. }
  8440. else
  8441. // Write samples to device.
  8442. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8443. if ( result == -1 ) {
  8444. // We'll assume this is an underrun, though there isn't a
  8445. // specific means for determining that.
  8446. handle->xrun[0] = true;
  8447. errorText_ = "RtApiOss::callbackEvent: audio write error.";
  8448. error( RtAudioError::WARNING );
  8449. // Continue on to input section.
  8450. }
  8451. }
  8452. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  8453. // Setup parameters.
  8454. if ( stream_.doConvertBuffer[1] ) {
  8455. buffer = stream_.deviceBuffer;
  8456. samples = stream_.bufferSize * stream_.nDeviceChannels[1];
  8457. format = stream_.deviceFormat[1];
  8458. }
  8459. else {
  8460. buffer = stream_.userBuffer[1];
  8461. samples = stream_.bufferSize * stream_.nUserChannels[1];
  8462. format = stream_.userFormat;
  8463. }
  8464. // Read samples from device.
  8465. result = read( handle->id[1], buffer, samples * formatBytes(format) );
  8466. if ( result == -1 ) {
  8467. // We'll assume this is an overrun, though there isn't a
  8468. // specific means for determining that.
  8469. handle->xrun[1] = true;
  8470. errorText_ = "RtApiOss::callbackEvent: audio read error.";
  8471. error( RtAudioError::WARNING );
  8472. goto unlock;
  8473. }
  8474. // Do byte swapping if necessary.
  8475. if ( stream_.doByteSwap[1] )
  8476. byteSwapBuffer( buffer, samples, format );
  8477. // Do buffer conversion if necessary.
  8478. if ( stream_.doConvertBuffer[1] )
  8479. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  8480. }
  8481. unlock:
  8482. MUTEX_UNLOCK( &stream_.mutex );
  8483. RtApi::tickStreamTime();
  8484. if ( doStopStream == 1 ) this->stopStream();
  8485. }
  8486. static void *ossCallbackHandler( void *ptr )
  8487. {
  8488. CallbackInfo *info = (CallbackInfo *) ptr;
  8489. RtApiOss *object = (RtApiOss *) info->object;
  8490. bool *isRunning = &info->isRunning;
  8491. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  8492. if (info->doRealtime) {
  8493. std::cerr << "RtAudio oss: " <<
  8494. (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
  8495. "running realtime scheduling" << std::endl;
  8496. }
  8497. #endif
  8498. while ( *isRunning == true ) {
  8499. pthread_testcancel();
  8500. object->callbackEvent();
  8501. }
  8502. pthread_exit( NULL );
  8503. }
  8504. //******************** End of __LINUX_OSS__ *********************//
  8505. #endif
  8506. // *************************************************** //
  8507. //
  8508. // Protected common (OS-independent) RtAudio methods.
  8509. //
  8510. // *************************************************** //
  8511. // This method can be modified to control the behavior of error
  8512. // message printing.
  8513. void RtApi :: error( RtAudioError::Type type )
  8514. {
  8515. errorStream_.str(""); // clear the ostringstream
  8516. RtAudioErrorCallback errorCallback = (RtAudioErrorCallback) stream_.callbackInfo.errorCallback;
  8517. if ( errorCallback ) {
  8518. // abortStream() can generate new error messages. Ignore them. Just keep original one.
  8519. if ( firstErrorOccurred_ )
  8520. return;
  8521. firstErrorOccurred_ = true;
  8522. const std::string errorMessage = errorText_;
  8523. if ( type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED) {
  8524. stream_.callbackInfo.isRunning = false; // exit from the thread
  8525. abortStream();
  8526. }
  8527. errorCallback( type, errorMessage );
  8528. firstErrorOccurred_ = false;
  8529. return;
  8530. }
  8531. if ( type == RtAudioError::WARNING && showWarnings_ == true )
  8532. std::cerr << '\n' << errorText_ << "\n\n";
  8533. else if ( type != RtAudioError::WARNING )
  8534. throw( RtAudioError( errorText_, type ) );
  8535. }
  8536. void RtApi :: verifyStream()
  8537. {
  8538. if ( stream_.state == STREAM_CLOSED ) {
  8539. errorText_ = "RtApi:: a stream is not open!";
  8540. error( RtAudioError::INVALID_USE );
  8541. }
  8542. }
  8543. void RtApi :: clearStreamInfo()
  8544. {
  8545. stream_.mode = UNINITIALIZED;
  8546. stream_.state = STREAM_CLOSED;
  8547. stream_.sampleRate = 0;
  8548. stream_.bufferSize = 0;
  8549. stream_.nBuffers = 0;
  8550. stream_.userFormat = 0;
  8551. stream_.userInterleaved = true;
  8552. stream_.streamTime = 0.0;
  8553. stream_.apiHandle = 0;
  8554. stream_.deviceBuffer = 0;
  8555. stream_.callbackInfo.callback = 0;
  8556. stream_.callbackInfo.userData = 0;
  8557. stream_.callbackInfo.isRunning = false;
  8558. stream_.callbackInfo.errorCallback = 0;
  8559. for ( int i=0; i<2; i++ ) {
  8560. stream_.device[i] = 11111;
  8561. stream_.doConvertBuffer[i] = false;
  8562. stream_.deviceInterleaved[i] = true;
  8563. stream_.doByteSwap[i] = false;
  8564. stream_.nUserChannels[i] = 0;
  8565. stream_.nDeviceChannels[i] = 0;
  8566. stream_.channelOffset[i] = 0;
  8567. stream_.deviceFormat[i] = 0;
  8568. stream_.latency[i] = 0;
  8569. stream_.userBuffer[i] = 0;
  8570. stream_.convertInfo[i].channels = 0;
  8571. stream_.convertInfo[i].inJump = 0;
  8572. stream_.convertInfo[i].outJump = 0;
  8573. stream_.convertInfo[i].inFormat = 0;
  8574. stream_.convertInfo[i].outFormat = 0;
  8575. stream_.convertInfo[i].inOffset.clear();
  8576. stream_.convertInfo[i].outOffset.clear();
  8577. }
  8578. }
  8579. unsigned int RtApi :: formatBytes( RtAudioFormat format )
  8580. {
  8581. if ( format == RTAUDIO_SINT16 )
  8582. return 2;
  8583. else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )
  8584. return 4;
  8585. else if ( format == RTAUDIO_FLOAT64 )
  8586. return 8;
  8587. else if ( format == RTAUDIO_SINT24 )
  8588. return 3;
  8589. else if ( format == RTAUDIO_SINT8 )
  8590. return 1;
  8591. errorText_ = "RtApi::formatBytes: undefined format.";
  8592. error( RtAudioError::WARNING );
  8593. return 0;
  8594. }
  8595. void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
  8596. {
  8597. if ( mode == INPUT ) { // convert device to user buffer
  8598. stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
  8599. stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
  8600. stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
  8601. stream_.convertInfo[mode].outFormat = stream_.userFormat;
  8602. }
  8603. else { // convert user to device buffer
  8604. stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
  8605. stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
  8606. stream_.convertInfo[mode].inFormat = stream_.userFormat;
  8607. stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
  8608. }
  8609. if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
  8610. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
  8611. else
  8612. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
  8613. // Set up the interleave/deinterleave offsets.
  8614. if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
  8615. if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
  8616. ( mode == INPUT && stream_.userInterleaved ) ) {
  8617. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8618. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8619. stream_.convertInfo[mode].outOffset.push_back( k );
  8620. stream_.convertInfo[mode].inJump = 1;
  8621. }
  8622. }
  8623. else {
  8624. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8625. stream_.convertInfo[mode].inOffset.push_back( k );
  8626. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8627. stream_.convertInfo[mode].outJump = 1;
  8628. }
  8629. }
  8630. }
  8631. else { // no (de)interleaving
  8632. if ( stream_.userInterleaved ) {
  8633. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8634. stream_.convertInfo[mode].inOffset.push_back( k );
  8635. stream_.convertInfo[mode].outOffset.push_back( k );
  8636. }
  8637. }
  8638. else {
  8639. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8640. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8641. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8642. stream_.convertInfo[mode].inJump = 1;
  8643. stream_.convertInfo[mode].outJump = 1;
  8644. }
  8645. }
  8646. }
  8647. // Add channel offset.
  8648. if ( firstChannel > 0 ) {
  8649. if ( stream_.deviceInterleaved[mode] ) {
  8650. if ( mode == OUTPUT ) {
  8651. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8652. stream_.convertInfo[mode].outOffset[k] += firstChannel;
  8653. }
  8654. else {
  8655. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8656. stream_.convertInfo[mode].inOffset[k] += firstChannel;
  8657. }
  8658. }
  8659. else {
  8660. if ( mode == OUTPUT ) {
  8661. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8662. stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
  8663. }
  8664. else {
  8665. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8666. stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize );
  8667. }
  8668. }
  8669. }
  8670. }
  8671. void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
  8672. {
  8673. // This function does format conversion, input/output channel compensation, and
  8674. // data interleaving/deinterleaving. 24-bit integers are assumed to occupy
  8675. // the lower three bytes of a 32-bit integer.
  8676. // Clear our device buffer when in/out duplex device channels are different
  8677. if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
  8678. ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
  8679. memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
  8680. int j;
  8681. if (info.outFormat == RTAUDIO_FLOAT64) {
  8682. Float64 scale;
  8683. Float64 *out = (Float64 *)outBuffer;
  8684. if (info.inFormat == RTAUDIO_SINT8) {
  8685. signed char *in = (signed char *)inBuffer;
  8686. scale = 1.0 / 127.5;
  8687. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8688. for (j=0; j<info.channels; j++) {
  8689. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8690. out[info.outOffset[j]] += 0.5;
  8691. out[info.outOffset[j]] *= scale;
  8692. }
  8693. in += info.inJump;
  8694. out += info.outJump;
  8695. }
  8696. }
  8697. else if (info.inFormat == RTAUDIO_SINT16) {
  8698. Int16 *in = (Int16 *)inBuffer;
  8699. scale = 1.0 / 32767.5;
  8700. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8701. for (j=0; j<info.channels; j++) {
  8702. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8703. out[info.outOffset[j]] += 0.5;
  8704. out[info.outOffset[j]] *= scale;
  8705. }
  8706. in += info.inJump;
  8707. out += info.outJump;
  8708. }
  8709. }
  8710. else if (info.inFormat == RTAUDIO_SINT24) {
  8711. Int24 *in = (Int24 *)inBuffer;
  8712. scale = 1.0 / 8388607.5;
  8713. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8714. for (j=0; j<info.channels; j++) {
  8715. out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());
  8716. out[info.outOffset[j]] += 0.5;
  8717. out[info.outOffset[j]] *= scale;
  8718. }
  8719. in += info.inJump;
  8720. out += info.outJump;
  8721. }
  8722. }
  8723. else if (info.inFormat == RTAUDIO_SINT32) {
  8724. Int32 *in = (Int32 *)inBuffer;
  8725. scale = 1.0 / 2147483647.5;
  8726. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8727. for (j=0; j<info.channels; j++) {
  8728. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8729. out[info.outOffset[j]] += 0.5;
  8730. out[info.outOffset[j]] *= scale;
  8731. }
  8732. in += info.inJump;
  8733. out += info.outJump;
  8734. }
  8735. }
  8736. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8737. Float32 *in = (Float32 *)inBuffer;
  8738. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8739. for (j=0; j<info.channels; j++) {
  8740. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8741. }
  8742. in += info.inJump;
  8743. out += info.outJump;
  8744. }
  8745. }
  8746. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8747. // Channel compensation and/or (de)interleaving only.
  8748. Float64 *in = (Float64 *)inBuffer;
  8749. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8750. for (j=0; j<info.channels; j++) {
  8751. out[info.outOffset[j]] = in[info.inOffset[j]];
  8752. }
  8753. in += info.inJump;
  8754. out += info.outJump;
  8755. }
  8756. }
  8757. }
  8758. else if (info.outFormat == RTAUDIO_FLOAT32) {
  8759. Float32 scale;
  8760. Float32 *out = (Float32 *)outBuffer;
  8761. if (info.inFormat == RTAUDIO_SINT8) {
  8762. signed char *in = (signed char *)inBuffer;
  8763. scale = (Float32) ( 1.0 / 127.5 );
  8764. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8765. for (j=0; j<info.channels; j++) {
  8766. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8767. out[info.outOffset[j]] += 0.5;
  8768. out[info.outOffset[j]] *= scale;
  8769. }
  8770. in += info.inJump;
  8771. out += info.outJump;
  8772. }
  8773. }
  8774. else if (info.inFormat == RTAUDIO_SINT16) {
  8775. Int16 *in = (Int16 *)inBuffer;
  8776. scale = (Float32) ( 1.0 / 32767.5 );
  8777. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8778. for (j=0; j<info.channels; j++) {
  8779. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8780. out[info.outOffset[j]] += 0.5;
  8781. out[info.outOffset[j]] *= scale;
  8782. }
  8783. in += info.inJump;
  8784. out += info.outJump;
  8785. }
  8786. }
  8787. else if (info.inFormat == RTAUDIO_SINT24) {
  8788. Int24 *in = (Int24 *)inBuffer;
  8789. scale = (Float32) ( 1.0 / 8388607.5 );
  8790. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8791. for (j=0; j<info.channels; j++) {
  8792. out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());
  8793. out[info.outOffset[j]] += 0.5;
  8794. out[info.outOffset[j]] *= scale;
  8795. }
  8796. in += info.inJump;
  8797. out += info.outJump;
  8798. }
  8799. }
  8800. else if (info.inFormat == RTAUDIO_SINT32) {
  8801. Int32 *in = (Int32 *)inBuffer;
  8802. scale = (Float32) ( 1.0 / 2147483647.5 );
  8803. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8804. for (j=0; j<info.channels; j++) {
  8805. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8806. out[info.outOffset[j]] += 0.5;
  8807. out[info.outOffset[j]] *= scale;
  8808. }
  8809. in += info.inJump;
  8810. out += info.outJump;
  8811. }
  8812. }
  8813. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8814. // Channel compensation and/or (de)interleaving only.
  8815. Float32 *in = (Float32 *)inBuffer;
  8816. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8817. for (j=0; j<info.channels; j++) {
  8818. out[info.outOffset[j]] = in[info.inOffset[j]];
  8819. }
  8820. in += info.inJump;
  8821. out += info.outJump;
  8822. }
  8823. }
  8824. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8825. Float64 *in = (Float64 *)inBuffer;
  8826. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8827. for (j=0; j<info.channels; j++) {
  8828. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8829. }
  8830. in += info.inJump;
  8831. out += info.outJump;
  8832. }
  8833. }
  8834. }
  8835. else if (info.outFormat == RTAUDIO_SINT32) {
  8836. Int32 *out = (Int32 *)outBuffer;
  8837. if (info.inFormat == RTAUDIO_SINT8) {
  8838. signed char *in = (signed char *)inBuffer;
  8839. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8840. for (j=0; j<info.channels; j++) {
  8841. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8842. out[info.outOffset[j]] <<= 24;
  8843. }
  8844. in += info.inJump;
  8845. out += info.outJump;
  8846. }
  8847. }
  8848. else if (info.inFormat == RTAUDIO_SINT16) {
  8849. Int16 *in = (Int16 *)inBuffer;
  8850. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8851. for (j=0; j<info.channels; j++) {
  8852. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8853. out[info.outOffset[j]] <<= 16;
  8854. }
  8855. in += info.inJump;
  8856. out += info.outJump;
  8857. }
  8858. }
  8859. else if (info.inFormat == RTAUDIO_SINT24) {
  8860. Int24 *in = (Int24 *)inBuffer;
  8861. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8862. for (j=0; j<info.channels; j++) {
  8863. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();
  8864. out[info.outOffset[j]] <<= 8;
  8865. }
  8866. in += info.inJump;
  8867. out += info.outJump;
  8868. }
  8869. }
  8870. else if (info.inFormat == RTAUDIO_SINT32) {
  8871. // Channel compensation and/or (de)interleaving only.
  8872. Int32 *in = (Int32 *)inBuffer;
  8873. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8874. for (j=0; j<info.channels; j++) {
  8875. out[info.outOffset[j]] = in[info.inOffset[j]];
  8876. }
  8877. in += info.inJump;
  8878. out += info.outJump;
  8879. }
  8880. }
  8881. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8882. Float32 *in = (Float32 *)inBuffer;
  8883. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8884. for (j=0; j<info.channels; j++) {
  8885. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8886. }
  8887. in += info.inJump;
  8888. out += info.outJump;
  8889. }
  8890. }
  8891. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8892. Float64 *in = (Float64 *)inBuffer;
  8893. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8894. for (j=0; j<info.channels; j++) {
  8895. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8896. }
  8897. in += info.inJump;
  8898. out += info.outJump;
  8899. }
  8900. }
  8901. }
  8902. else if (info.outFormat == RTAUDIO_SINT24) {
  8903. Int24 *out = (Int24 *)outBuffer;
  8904. if (info.inFormat == RTAUDIO_SINT8) {
  8905. signed char *in = (signed char *)inBuffer;
  8906. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8907. for (j=0; j<info.channels; j++) {
  8908. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);
  8909. //out[info.outOffset[j]] <<= 16;
  8910. }
  8911. in += info.inJump;
  8912. out += info.outJump;
  8913. }
  8914. }
  8915. else if (info.inFormat == RTAUDIO_SINT16) {
  8916. Int16 *in = (Int16 *)inBuffer;
  8917. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8918. for (j=0; j<info.channels; j++) {
  8919. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);
  8920. //out[info.outOffset[j]] <<= 8;
  8921. }
  8922. in += info.inJump;
  8923. out += info.outJump;
  8924. }
  8925. }
  8926. else if (info.inFormat == RTAUDIO_SINT24) {
  8927. // Channel compensation and/or (de)interleaving only.
  8928. Int24 *in = (Int24 *)inBuffer;
  8929. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8930. for (j=0; j<info.channels; j++) {
  8931. out[info.outOffset[j]] = in[info.inOffset[j]];
  8932. }
  8933. in += info.inJump;
  8934. out += info.outJump;
  8935. }
  8936. }
  8937. else if (info.inFormat == RTAUDIO_SINT32) {
  8938. Int32 *in = (Int32 *)inBuffer;
  8939. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8940. for (j=0; j<info.channels; j++) {
  8941. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);
  8942. //out[info.outOffset[j]] >>= 8;
  8943. }
  8944. in += info.inJump;
  8945. out += info.outJump;
  8946. }
  8947. }
  8948. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8949. Float32 *in = (Float32 *)inBuffer;
  8950. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8951. for (j=0; j<info.channels; j++) {
  8952. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8953. }
  8954. in += info.inJump;
  8955. out += info.outJump;
  8956. }
  8957. }
  8958. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8959. Float64 *in = (Float64 *)inBuffer;
  8960. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8961. for (j=0; j<info.channels; j++) {
  8962. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8963. }
  8964. in += info.inJump;
  8965. out += info.outJump;
  8966. }
  8967. }
  8968. }
  8969. else if (info.outFormat == RTAUDIO_SINT16) {
  8970. Int16 *out = (Int16 *)outBuffer;
  8971. if (info.inFormat == RTAUDIO_SINT8) {
  8972. signed char *in = (signed char *)inBuffer;
  8973. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8974. for (j=0; j<info.channels; j++) {
  8975. out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
  8976. out[info.outOffset[j]] <<= 8;
  8977. }
  8978. in += info.inJump;
  8979. out += info.outJump;
  8980. }
  8981. }
  8982. else if (info.inFormat == RTAUDIO_SINT16) {
  8983. // Channel compensation and/or (de)interleaving only.
  8984. Int16 *in = (Int16 *)inBuffer;
  8985. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8986. for (j=0; j<info.channels; j++) {
  8987. out[info.outOffset[j]] = in[info.inOffset[j]];
  8988. }
  8989. in += info.inJump;
  8990. out += info.outJump;
  8991. }
  8992. }
  8993. else if (info.inFormat == RTAUDIO_SINT24) {
  8994. Int24 *in = (Int24 *)inBuffer;
  8995. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8996. for (j=0; j<info.channels; j++) {
  8997. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);
  8998. }
  8999. in += info.inJump;
  9000. out += info.outJump;
  9001. }
  9002. }
  9003. else if (info.inFormat == RTAUDIO_SINT32) {
  9004. Int32 *in = (Int32 *)inBuffer;
  9005. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9006. for (j=0; j<info.channels; j++) {
  9007. out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
  9008. }
  9009. in += info.inJump;
  9010. out += info.outJump;
  9011. }
  9012. }
  9013. else if (info.inFormat == RTAUDIO_FLOAT32) {
  9014. Float32 *in = (Float32 *)inBuffer;
  9015. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9016. for (j=0; j<info.channels; j++) {
  9017. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  9018. }
  9019. in += info.inJump;
  9020. out += info.outJump;
  9021. }
  9022. }
  9023. else if (info.inFormat == RTAUDIO_FLOAT64) {
  9024. Float64 *in = (Float64 *)inBuffer;
  9025. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9026. for (j=0; j<info.channels; j++) {
  9027. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  9028. }
  9029. in += info.inJump;
  9030. out += info.outJump;
  9031. }
  9032. }
  9033. }
  9034. else if (info.outFormat == RTAUDIO_SINT8) {
  9035. signed char *out = (signed char *)outBuffer;
  9036. if (info.inFormat == RTAUDIO_SINT8) {
  9037. // Channel compensation and/or (de)interleaving only.
  9038. signed char *in = (signed char *)inBuffer;
  9039. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9040. for (j=0; j<info.channels; j++) {
  9041. out[info.outOffset[j]] = in[info.inOffset[j]];
  9042. }
  9043. in += info.inJump;
  9044. out += info.outJump;
  9045. }
  9046. }
  9047. if (info.inFormat == RTAUDIO_SINT16) {
  9048. Int16 *in = (Int16 *)inBuffer;
  9049. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9050. for (j=0; j<info.channels; j++) {
  9051. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
  9052. }
  9053. in += info.inJump;
  9054. out += info.outJump;
  9055. }
  9056. }
  9057. else if (info.inFormat == RTAUDIO_SINT24) {
  9058. Int24 *in = (Int24 *)inBuffer;
  9059. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9060. for (j=0; j<info.channels; j++) {
  9061. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);
  9062. }
  9063. in += info.inJump;
  9064. out += info.outJump;
  9065. }
  9066. }
  9067. else if (info.inFormat == RTAUDIO_SINT32) {
  9068. Int32 *in = (Int32 *)inBuffer;
  9069. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9070. for (j=0; j<info.channels; j++) {
  9071. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
  9072. }
  9073. in += info.inJump;
  9074. out += info.outJump;
  9075. }
  9076. }
  9077. else if (info.inFormat == RTAUDIO_FLOAT32) {
  9078. Float32 *in = (Float32 *)inBuffer;
  9079. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9080. for (j=0; j<info.channels; j++) {
  9081. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  9082. }
  9083. in += info.inJump;
  9084. out += info.outJump;
  9085. }
  9086. }
  9087. else if (info.inFormat == RTAUDIO_FLOAT64) {
  9088. Float64 *in = (Float64 *)inBuffer;
  9089. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9090. for (j=0; j<info.channels; j++) {
  9091. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  9092. }
  9093. in += info.inJump;
  9094. out += info.outJump;
  9095. }
  9096. }
  9097. }
  9098. }
  9099. //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
  9100. //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
  9101. //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
  9102. void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
  9103. {
  9104. char val;
  9105. char *ptr;
  9106. ptr = buffer;
  9107. if ( format == RTAUDIO_SINT16 ) {
  9108. for ( unsigned int i=0; i<samples; i++ ) {
  9109. // Swap 1st and 2nd bytes.
  9110. val = *(ptr);
  9111. *(ptr) = *(ptr+1);
  9112. *(ptr+1) = val;
  9113. // Increment 2 bytes.
  9114. ptr += 2;
  9115. }
  9116. }
  9117. else if ( format == RTAUDIO_SINT32 ||
  9118. format == RTAUDIO_FLOAT32 ) {
  9119. for ( unsigned int i=0; i<samples; i++ ) {
  9120. // Swap 1st and 4th bytes.
  9121. val = *(ptr);
  9122. *(ptr) = *(ptr+3);
  9123. *(ptr+3) = val;
  9124. // Swap 2nd and 3rd bytes.
  9125. ptr += 1;
  9126. val = *(ptr);
  9127. *(ptr) = *(ptr+1);
  9128. *(ptr+1) = val;
  9129. // Increment 3 more bytes.
  9130. ptr += 3;
  9131. }
  9132. }
  9133. else if ( format == RTAUDIO_SINT24 ) {
  9134. for ( unsigned int i=0; i<samples; i++ ) {
  9135. // Swap 1st and 3rd bytes.
  9136. val = *(ptr);
  9137. *(ptr) = *(ptr+2);
  9138. *(ptr+2) = val;
  9139. // Increment 2 more bytes.
  9140. ptr += 2;
  9141. }
  9142. }
  9143. else if ( format == RTAUDIO_FLOAT64 ) {
  9144. for ( unsigned int i=0; i<samples; i++ ) {
  9145. // Swap 1st and 8th bytes
  9146. val = *(ptr);
  9147. *(ptr) = *(ptr+7);
  9148. *(ptr+7) = val;
  9149. // Swap 2nd and 7th bytes
  9150. ptr += 1;
  9151. val = *(ptr);
  9152. *(ptr) = *(ptr+5);
  9153. *(ptr+5) = val;
  9154. // Swap 3rd and 6th bytes
  9155. ptr += 1;
  9156. val = *(ptr);
  9157. *(ptr) = *(ptr+3);
  9158. *(ptr+3) = val;
  9159. // Swap 4th and 5th bytes
  9160. ptr += 1;
  9161. val = *(ptr);
  9162. *(ptr) = *(ptr+1);
  9163. *(ptr+1) = val;
  9164. // Increment 5 more bytes.
  9165. ptr += 5;
  9166. }
  9167. }
  9168. }
  9169. // Indentation settings for Vim and Emacs
  9170. //
  9171. // Local Variables:
  9172. // c-basic-offset: 2
  9173. // indent-tabs-mode: nil
  9174. // End:
  9175. //
  9176. // vim: et sts=2 sw=2