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.

10665 lines
365KB

  1. /************************************************************************/
  2. /*! \class RtAudio
  3. \brief Realtime audio i/o C++ classes.
  4. RtAudio provides a common API (Application Programming Interface)
  5. for realtime audio input/output across Linux (native ALSA, Jack,
  6. and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
  7. (DirectSound, ASIO and WASAPI) operating systems.
  8. RtAudio GitHub site: https://github.com/thestk/rtaudio
  9. RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
  10. RtAudio: realtime audio i/o C++ classes
  11. Copyright (c) 2001-2019 Gary P. Scavone
  12. Permission is hereby granted, free of charge, to any person
  13. obtaining a copy of this software and associated documentation files
  14. (the "Software"), to deal in the Software without restriction,
  15. including without limitation the rights to use, copy, modify, merge,
  16. publish, distribute, sublicense, and/or sell copies of the Software,
  17. and to permit persons to whom the Software is furnished to do so,
  18. subject to the following conditions:
  19. The above copyright notice and this permission notice shall be
  20. included in all copies or substantial portions of the Software.
  21. Any person wishing to distribute modifications to the Software is
  22. asked to send the modifications to the original developer so that
  23. they can be incorporated into the canonical version. This is,
  24. however, not a binding provision of this license.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  28. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  29. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  30. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. /************************************************************************/
  34. // RtAudio: Version 5.1.0
  35. #include "RtAudio.h"
  36. #include <iostream>
  37. #include <cstdlib>
  38. #include <cstring>
  39. #include <climits>
  40. #include <cmath>
  41. #include <algorithm>
  42. // Static variable definitions.
  43. const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
  44. const unsigned int RtApi::SAMPLE_RATES[] = {
  45. 4000, 5512, 8000, 9600, 11025, 16000, 22050,
  46. 32000, 44100, 48000, 88200, 96000, 176400, 192000
  47. };
  48. #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
  49. #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
  50. #define MUTEX_DESTROY(A) DeleteCriticalSection(A)
  51. #define MUTEX_LOCK(A) EnterCriticalSection(A)
  52. #define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
  53. #include "tchar.h"
  54. static std::string convertCharPointerToStdString(const char *text)
  55. {
  56. return std::string(text);
  57. }
  58. static std::string convertCharPointerToStdString(const wchar_t *text)
  59. {
  60. int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);
  61. std::string s( length-1, '\0' );
  62. WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);
  63. return s;
  64. }
  65. #elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
  66. // pthread API
  67. #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
  68. #define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
  69. #define MUTEX_LOCK(A) pthread_mutex_lock(A)
  70. #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
  71. #else
  72. #define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions
  73. #define MUTEX_DESTROY(A) abs(*A) // dummy definitions
  74. #endif
  75. // *************************************************** //
  76. //
  77. // RtAudio definitions.
  78. //
  79. // *************************************************** //
  80. std::string RtAudio :: getVersion( void )
  81. {
  82. return RTAUDIO_VERSION;
  83. }
  84. // Define API names and display names.
  85. // Must be in same order as API enum.
  86. extern "C" {
  87. const char* rtaudio_api_names[][2] = {
  88. { "unspecified" , "Unknown" },
  89. { "alsa" , "ALSA" },
  90. { "pulse" , "Pulse" },
  91. { "oss" , "OpenSoundSystem" },
  92. { "jack" , "Jack" },
  93. { "core" , "CoreAudio" },
  94. { "wasapi" , "WASAPI" },
  95. { "asio" , "ASIO" },
  96. { "ds" , "DirectSound" },
  97. { "dummy" , "Dummy" },
  98. };
  99. const unsigned int rtaudio_num_api_names =
  100. sizeof(rtaudio_api_names)/sizeof(rtaudio_api_names[0]);
  101. // The order here will control the order of RtAudio's API search in
  102. // the constructor.
  103. extern "C" const RtAudio::Api rtaudio_compiled_apis[] = {
  104. #if defined(__UNIX_JACK__)
  105. RtAudio::UNIX_JACK,
  106. #endif
  107. #if defined(__LINUX_PULSE__)
  108. RtAudio::LINUX_PULSE,
  109. #endif
  110. #if defined(__LINUX_ALSA__)
  111. RtAudio::LINUX_ALSA,
  112. #endif
  113. #if defined(__LINUX_OSS__)
  114. RtAudio::LINUX_OSS,
  115. #endif
  116. #if defined(__WINDOWS_ASIO__)
  117. RtAudio::WINDOWS_ASIO,
  118. #endif
  119. #if defined(__WINDOWS_WASAPI__)
  120. RtAudio::WINDOWS_WASAPI,
  121. #endif
  122. #if defined(__WINDOWS_DS__)
  123. RtAudio::WINDOWS_DS,
  124. #endif
  125. #if defined(__MACOSX_CORE__)
  126. RtAudio::MACOSX_CORE,
  127. #endif
  128. #if defined(__RTAUDIO_DUMMY__)
  129. RtAudio::RTAUDIO_DUMMY,
  130. #endif
  131. RtAudio::UNSPECIFIED,
  132. };
  133. extern "C" const unsigned int rtaudio_num_compiled_apis =
  134. sizeof(rtaudio_compiled_apis)/sizeof(rtaudio_compiled_apis[0])-1;
  135. }
  136. // This is a compile-time check that rtaudio_num_api_names == RtAudio::NUM_APIS.
  137. // If the build breaks here, check that they match.
  138. template<bool b> class StaticAssert { private: StaticAssert() {} };
  139. template<> class StaticAssert<true>{ public: StaticAssert() {} };
  140. class StaticAssertions { StaticAssertions() {
  141. StaticAssert<rtaudio_num_api_names == RtAudio::NUM_APIS>();
  142. }};
  143. void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis )
  144. {
  145. apis = std::vector<RtAudio::Api>(rtaudio_compiled_apis,
  146. rtaudio_compiled_apis + rtaudio_num_compiled_apis);
  147. }
  148. std::string RtAudio :: getApiName( RtAudio::Api api )
  149. {
  150. if (api < 0 || api >= RtAudio::NUM_APIS)
  151. return "";
  152. return rtaudio_api_names[api][0];
  153. }
  154. std::string RtAudio :: getApiDisplayName( RtAudio::Api api )
  155. {
  156. if (api < 0 || api >= RtAudio::NUM_APIS)
  157. return "Unknown";
  158. return rtaudio_api_names[api][1];
  159. }
  160. RtAudio::Api RtAudio :: getCompiledApiByName( const std::string &name )
  161. {
  162. unsigned int i=0;
  163. for (i = 0; i < rtaudio_num_compiled_apis; ++i)
  164. if (name == rtaudio_api_names[rtaudio_compiled_apis[i]][0])
  165. return rtaudio_compiled_apis[i];
  166. return RtAudio::UNSPECIFIED;
  167. }
  168. void RtAudio :: openRtApi( RtAudio::Api api )
  169. {
  170. if ( rtapi_ )
  171. delete rtapi_;
  172. rtapi_ = 0;
  173. #if defined(__UNIX_JACK__)
  174. if ( api == UNIX_JACK )
  175. rtapi_ = new RtApiJack();
  176. #endif
  177. #if defined(__LINUX_ALSA__)
  178. if ( api == LINUX_ALSA )
  179. rtapi_ = new RtApiAlsa();
  180. #endif
  181. #if defined(__LINUX_PULSE__)
  182. if ( api == LINUX_PULSE )
  183. rtapi_ = new RtApiPulse();
  184. #endif
  185. #if defined(__LINUX_OSS__)
  186. if ( api == LINUX_OSS )
  187. rtapi_ = new RtApiOss();
  188. #endif
  189. #if defined(__WINDOWS_ASIO__)
  190. if ( api == WINDOWS_ASIO )
  191. rtapi_ = new RtApiAsio();
  192. #endif
  193. #if defined(__WINDOWS_WASAPI__)
  194. if ( api == WINDOWS_WASAPI )
  195. rtapi_ = new RtApiWasapi();
  196. #endif
  197. #if defined(__WINDOWS_DS__)
  198. if ( api == WINDOWS_DS )
  199. rtapi_ = new RtApiDs();
  200. #endif
  201. #if defined(__MACOSX_CORE__)
  202. if ( api == MACOSX_CORE )
  203. rtapi_ = new RtApiCore();
  204. #endif
  205. #if defined(__RTAUDIO_DUMMY__)
  206. if ( api == RTAUDIO_DUMMY )
  207. rtapi_ = new RtApiDummy();
  208. #endif
  209. }
  210. RtAudio :: RtAudio( RtAudio::Api api )
  211. {
  212. rtapi_ = 0;
  213. if ( api != UNSPECIFIED ) {
  214. // Attempt to open the specified API.
  215. openRtApi( api );
  216. if ( rtapi_ ) return;
  217. // No compiled support for specified API value. Issue a debug
  218. // warning and continue as if no API was specified.
  219. std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;
  220. }
  221. // Iterate through the compiled APIs and return as soon as we find
  222. // one with at least one device or we reach the end of the list.
  223. std::vector< RtAudio::Api > apis;
  224. getCompiledApi( apis );
  225. for ( unsigned int i=0; i<apis.size(); i++ ) {
  226. openRtApi( apis[i] );
  227. if ( rtapi_ && rtapi_->getDeviceCount() ) break;
  228. }
  229. if ( rtapi_ ) return;
  230. // It should not be possible to get here because the preprocessor
  231. // definition __RTAUDIO_DUMMY__ is automatically defined if no
  232. // API-specific definitions are passed to the compiler. But just in
  233. // case something weird happens, we'll thow an error.
  234. std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";
  235. throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );
  236. }
  237. RtAudio :: ~RtAudio()
  238. {
  239. if ( rtapi_ )
  240. delete rtapi_;
  241. }
  242. void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
  243. RtAudio::StreamParameters *inputParameters,
  244. RtAudioFormat format, unsigned int sampleRate,
  245. unsigned int *bufferFrames,
  246. RtAudioCallback callback, void *userData,
  247. RtAudio::StreamOptions *options,
  248. RtAudioErrorCallback errorCallback )
  249. {
  250. return rtapi_->openStream( outputParameters, inputParameters, format,
  251. sampleRate, bufferFrames, callback,
  252. userData, options, errorCallback );
  253. }
  254. // *************************************************** //
  255. //
  256. // Public RtApi definitions (see end of file for
  257. // private or protected utility functions).
  258. //
  259. // *************************************************** //
  260. RtApi :: RtApi()
  261. {
  262. stream_.state = STREAM_CLOSED;
  263. stream_.mode = UNINITIALIZED;
  264. stream_.apiHandle = 0;
  265. stream_.userBuffer[0] = 0;
  266. stream_.userBuffer[1] = 0;
  267. MUTEX_INITIALIZE( &stream_.mutex );
  268. showWarnings_ = true;
  269. firstErrorOccurred_ = false;
  270. }
  271. RtApi :: ~RtApi()
  272. {
  273. MUTEX_DESTROY( &stream_.mutex );
  274. }
  275. void RtApi :: openStream( RtAudio::StreamParameters *oParams,
  276. RtAudio::StreamParameters *iParams,
  277. RtAudioFormat format, unsigned int sampleRate,
  278. unsigned int *bufferFrames,
  279. RtAudioCallback callback, void *userData,
  280. RtAudio::StreamOptions *options,
  281. RtAudioErrorCallback errorCallback )
  282. {
  283. if ( stream_.state != STREAM_CLOSED ) {
  284. errorText_ = "RtApi::openStream: a stream is already open!";
  285. error( RtAudioError::INVALID_USE );
  286. return;
  287. }
  288. // Clear stream information potentially left from a previously open stream.
  289. clearStreamInfo();
  290. if ( oParams && oParams->nChannels < 1 ) {
  291. errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
  292. error( RtAudioError::INVALID_USE );
  293. return;
  294. }
  295. if ( iParams && iParams->nChannels < 1 ) {
  296. errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
  297. error( RtAudioError::INVALID_USE );
  298. return;
  299. }
  300. if ( oParams == NULL && iParams == NULL ) {
  301. errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
  302. error( RtAudioError::INVALID_USE );
  303. return;
  304. }
  305. if ( formatBytes(format) == 0 ) {
  306. errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
  307. error( RtAudioError::INVALID_USE );
  308. return;
  309. }
  310. unsigned int nDevices = getDeviceCount();
  311. unsigned int oChannels = 0;
  312. if ( oParams ) {
  313. oChannels = oParams->nChannels;
  314. if ( oParams->deviceId >= nDevices ) {
  315. errorText_ = "RtApi::openStream: output device parameter value is invalid.";
  316. error( RtAudioError::INVALID_USE );
  317. return;
  318. }
  319. }
  320. unsigned int iChannels = 0;
  321. if ( iParams ) {
  322. iChannels = iParams->nChannels;
  323. if ( iParams->deviceId >= nDevices ) {
  324. errorText_ = "RtApi::openStream: input device parameter value is invalid.";
  325. error( RtAudioError::INVALID_USE );
  326. return;
  327. }
  328. }
  329. bool result;
  330. if ( oChannels > 0 ) {
  331. result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
  332. sampleRate, format, bufferFrames, options );
  333. if ( result == false ) {
  334. error( RtAudioError::SYSTEM_ERROR );
  335. return;
  336. }
  337. }
  338. if ( iChannels > 0 ) {
  339. result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
  340. sampleRate, format, bufferFrames, options );
  341. if ( result == false ) {
  342. if ( oChannels > 0 ) closeStream();
  343. error( RtAudioError::SYSTEM_ERROR );
  344. return;
  345. }
  346. }
  347. stream_.callbackInfo.callback = (void *) callback;
  348. stream_.callbackInfo.userData = userData;
  349. stream_.callbackInfo.errorCallback = (void *) errorCallback;
  350. if ( options ) options->numberOfBuffers = stream_.nBuffers;
  351. stream_.state = STREAM_STOPPED;
  352. }
  353. unsigned int RtApi :: getDefaultInputDevice( void )
  354. {
  355. // Should be implemented in subclasses if possible.
  356. return 0;
  357. }
  358. unsigned int RtApi :: getDefaultOutputDevice( void )
  359. {
  360. // Should be implemented in subclasses if possible.
  361. return 0;
  362. }
  363. void RtApi :: closeStream( void )
  364. {
  365. // MUST be implemented in subclasses!
  366. return;
  367. }
  368. bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
  369. unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
  370. RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
  371. RtAudio::StreamOptions * /*options*/ )
  372. {
  373. // MUST be implemented in subclasses!
  374. return FAILURE;
  375. }
  376. void RtApi :: tickStreamTime( void )
  377. {
  378. // Subclasses that do not provide their own implementation of
  379. // getStreamTime should call this function once per buffer I/O to
  380. // provide basic stream time support.
  381. stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
  382. #if defined( HAVE_GETTIMEOFDAY )
  383. gettimeofday( &stream_.lastTickTimestamp, NULL );
  384. #endif
  385. }
  386. long RtApi :: getStreamLatency( void )
  387. {
  388. verifyStream();
  389. long totalLatency = 0;
  390. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  391. totalLatency = stream_.latency[0];
  392. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  393. totalLatency += stream_.latency[1];
  394. return totalLatency;
  395. }
  396. double RtApi :: getStreamTime( void )
  397. {
  398. verifyStream();
  399. #if defined( HAVE_GETTIMEOFDAY )
  400. // Return a very accurate estimate of the stream time by
  401. // adding in the elapsed time since the last tick.
  402. struct timeval then;
  403. struct timeval now;
  404. if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
  405. return stream_.streamTime;
  406. gettimeofday( &now, NULL );
  407. then = stream_.lastTickTimestamp;
  408. return stream_.streamTime +
  409. ((now.tv_sec + 0.000001 * now.tv_usec) -
  410. (then.tv_sec + 0.000001 * then.tv_usec));
  411. #else
  412. return stream_.streamTime;
  413. #endif
  414. }
  415. void RtApi :: setStreamTime( double time )
  416. {
  417. verifyStream();
  418. if ( time >= 0.0 )
  419. stream_.streamTime = time;
  420. #if defined( HAVE_GETTIMEOFDAY )
  421. gettimeofday( &stream_.lastTickTimestamp, NULL );
  422. #endif
  423. }
  424. unsigned int RtApi :: getStreamSampleRate( void )
  425. {
  426. verifyStream();
  427. return stream_.sampleRate;
  428. }
  429. // *************************************************** //
  430. //
  431. // OS/API-specific methods.
  432. //
  433. // *************************************************** //
  434. #if defined(__MACOSX_CORE__)
  435. // The OS X CoreAudio API is designed to use a separate callback
  436. // procedure for each of its audio devices. A single RtAudio duplex
  437. // stream using two different devices is supported here, though it
  438. // cannot be guaranteed to always behave correctly because we cannot
  439. // synchronize these two callbacks.
  440. //
  441. // A property listener is installed for over/underrun information.
  442. // However, no functionality is currently provided to allow property
  443. // listeners to trigger user handlers because it is unclear what could
  444. // be done if a critical stream parameter (buffer size, sample rate,
  445. // device disconnect) notification arrived. The listeners entail
  446. // quite a bit of extra code and most likely, a user program wouldn't
  447. // be prepared for the result anyway. However, we do provide a flag
  448. // to the client callback function to inform of an over/underrun.
  449. // A structure to hold various information related to the CoreAudio API
  450. // implementation.
  451. struct CoreHandle {
  452. AudioDeviceID id[2]; // device ids
  453. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  454. AudioDeviceIOProcID procId[2];
  455. #endif
  456. UInt32 iStream[2]; // device stream index (or first if using multiple)
  457. UInt32 nStreams[2]; // number of streams to use
  458. bool xrun[2];
  459. char *deviceBuffer;
  460. pthread_cond_t condition;
  461. int drainCounter; // Tracks callback counts when draining
  462. bool internalDrain; // Indicates if stop is initiated from callback or not.
  463. CoreHandle()
  464. :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  465. };
  466. RtApiCore:: RtApiCore()
  467. {
  468. #if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )
  469. // This is a largely undocumented but absolutely necessary
  470. // requirement starting with OS-X 10.6. If not called, queries and
  471. // updates to various audio device properties are not handled
  472. // correctly.
  473. CFRunLoopRef theRunLoop = NULL;
  474. AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,
  475. kAudioObjectPropertyScopeGlobal,
  476. kAudioObjectPropertyElementMaster };
  477. OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  478. if ( result != noErr ) {
  479. errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
  480. error( RtAudioError::WARNING );
  481. }
  482. #endif
  483. }
  484. RtApiCore :: ~RtApiCore()
  485. {
  486. // The subclass destructor gets called before the base class
  487. // destructor, so close an existing stream before deallocating
  488. // apiDeviceId memory.
  489. if ( stream_.state != STREAM_CLOSED ) closeStream();
  490. }
  491. unsigned int RtApiCore :: getDeviceCount( void )
  492. {
  493. // Find out how many audio devices there are, if any.
  494. UInt32 dataSize;
  495. AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  496. OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );
  497. if ( result != noErr ) {
  498. errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
  499. error( RtAudioError::WARNING );
  500. return 0;
  501. }
  502. return dataSize / sizeof( AudioDeviceID );
  503. }
  504. unsigned int RtApiCore :: getDefaultInputDevice( void )
  505. {
  506. unsigned int nDevices = getDeviceCount();
  507. if ( nDevices <= 1 ) return 0;
  508. AudioDeviceID id;
  509. UInt32 dataSize = sizeof( AudioDeviceID );
  510. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  511. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  512. if ( result != noErr ) {
  513. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
  514. error( RtAudioError::WARNING );
  515. return 0;
  516. }
  517. dataSize *= nDevices;
  518. AudioDeviceID deviceList[ nDevices ];
  519. property.mSelector = kAudioHardwarePropertyDevices;
  520. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  521. if ( result != noErr ) {
  522. errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
  523. error( RtAudioError::WARNING );
  524. return 0;
  525. }
  526. for ( unsigned int i=0; i<nDevices; i++ )
  527. if ( id == deviceList[i] ) return i;
  528. errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
  529. error( RtAudioError::WARNING );
  530. return 0;
  531. }
  532. unsigned int RtApiCore :: getDefaultOutputDevice( void )
  533. {
  534. unsigned int nDevices = getDeviceCount();
  535. if ( nDevices <= 1 ) return 0;
  536. AudioDeviceID id;
  537. UInt32 dataSize = sizeof( AudioDeviceID );
  538. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  539. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
  540. if ( result != noErr ) {
  541. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
  542. error( RtAudioError::WARNING );
  543. return 0;
  544. }
  545. dataSize = sizeof( AudioDeviceID ) * nDevices;
  546. AudioDeviceID deviceList[ nDevices ];
  547. property.mSelector = kAudioHardwarePropertyDevices;
  548. result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
  549. if ( result != noErr ) {
  550. errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
  551. error( RtAudioError::WARNING );
  552. return 0;
  553. }
  554. for ( unsigned int i=0; i<nDevices; i++ )
  555. if ( id == deviceList[i] ) return i;
  556. errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
  557. error( RtAudioError::WARNING );
  558. return 0;
  559. }
  560. RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
  561. {
  562. RtAudio::DeviceInfo info;
  563. info.probed = false;
  564. // Get device ID
  565. unsigned int nDevices = getDeviceCount();
  566. if ( nDevices == 0 ) {
  567. errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
  568. error( RtAudioError::INVALID_USE );
  569. return info;
  570. }
  571. if ( device >= nDevices ) {
  572. errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
  573. error( RtAudioError::INVALID_USE );
  574. return info;
  575. }
  576. AudioDeviceID deviceList[ nDevices ];
  577. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  578. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  579. kAudioObjectPropertyScopeGlobal,
  580. kAudioObjectPropertyElementMaster };
  581. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  582. 0, NULL, &dataSize, (void *) &deviceList );
  583. if ( result != noErr ) {
  584. errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
  585. error( RtAudioError::WARNING );
  586. return info;
  587. }
  588. AudioDeviceID id = deviceList[ device ];
  589. // Get the device name.
  590. info.name.erase();
  591. CFStringRef cfname;
  592. dataSize = sizeof( CFStringRef );
  593. property.mSelector = kAudioObjectPropertyManufacturer;
  594. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  595. if ( result != noErr ) {
  596. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
  597. errorText_ = errorStream_.str();
  598. error( RtAudioError::WARNING );
  599. return info;
  600. }
  601. //const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  602. int length = CFStringGetLength(cfname);
  603. char *mname = (char *)malloc(length * 3 + 1);
  604. #if defined( UNICODE ) || defined( _UNICODE )
  605. CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
  606. #else
  607. CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
  608. #endif
  609. info.name.append( (const char *)mname, strlen(mname) );
  610. info.name.append( ": " );
  611. CFRelease( cfname );
  612. free(mname);
  613. property.mSelector = kAudioObjectPropertyName;
  614. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
  615. if ( result != noErr ) {
  616. errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
  617. errorText_ = errorStream_.str();
  618. error( RtAudioError::WARNING );
  619. return info;
  620. }
  621. //const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
  622. length = CFStringGetLength(cfname);
  623. char *name = (char *)malloc(length * 3 + 1);
  624. #if defined( UNICODE ) || defined( _UNICODE )
  625. CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
  626. #else
  627. CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
  628. #endif
  629. info.name.append( (const char *)name, strlen(name) );
  630. CFRelease( cfname );
  631. free(name);
  632. // Get the output stream "configuration".
  633. AudioBufferList *bufferList = nil;
  634. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  635. property.mScope = kAudioDevicePropertyScopeOutput;
  636. // property.mElement = kAudioObjectPropertyElementWildcard;
  637. dataSize = 0;
  638. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  639. if ( result != noErr || dataSize == 0 ) {
  640. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";
  641. errorText_ = errorStream_.str();
  642. error( RtAudioError::WARNING );
  643. return info;
  644. }
  645. // Allocate the AudioBufferList.
  646. bufferList = (AudioBufferList *) malloc( dataSize );
  647. if ( bufferList == NULL ) {
  648. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
  649. error( RtAudioError::WARNING );
  650. return info;
  651. }
  652. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  653. if ( result != noErr || dataSize == 0 ) {
  654. free( bufferList );
  655. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";
  656. errorText_ = errorStream_.str();
  657. error( RtAudioError::WARNING );
  658. return info;
  659. }
  660. // Get output channel information.
  661. unsigned int i, nStreams = bufferList->mNumberBuffers;
  662. for ( i=0; i<nStreams; i++ )
  663. info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
  664. free( bufferList );
  665. // Get the input stream "configuration".
  666. property.mScope = kAudioDevicePropertyScopeInput;
  667. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  668. if ( result != noErr || dataSize == 0 ) {
  669. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";
  670. errorText_ = errorStream_.str();
  671. error( RtAudioError::WARNING );
  672. return info;
  673. }
  674. // Allocate the AudioBufferList.
  675. bufferList = (AudioBufferList *) malloc( dataSize );
  676. if ( bufferList == NULL ) {
  677. errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
  678. error( RtAudioError::WARNING );
  679. return info;
  680. }
  681. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  682. if (result != noErr || dataSize == 0) {
  683. free( bufferList );
  684. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";
  685. errorText_ = errorStream_.str();
  686. error( RtAudioError::WARNING );
  687. return info;
  688. }
  689. // Get input channel information.
  690. nStreams = bufferList->mNumberBuffers;
  691. for ( i=0; i<nStreams; i++ )
  692. info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
  693. free( bufferList );
  694. // If device opens for both playback and capture, we determine the channels.
  695. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  696. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  697. // Probe the device sample rates.
  698. bool isInput = false;
  699. if ( info.outputChannels == 0 ) isInput = true;
  700. // Determine the supported sample rates.
  701. property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  702. if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;
  703. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  704. if ( result != kAudioHardwareNoError || dataSize == 0 ) {
  705. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
  706. errorText_ = errorStream_.str();
  707. error( RtAudioError::WARNING );
  708. return info;
  709. }
  710. UInt32 nRanges = dataSize / sizeof( AudioValueRange );
  711. AudioValueRange rangeList[ nRanges ];
  712. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );
  713. if ( result != kAudioHardwareNoError ) {
  714. errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
  715. errorText_ = errorStream_.str();
  716. error( RtAudioError::WARNING );
  717. return info;
  718. }
  719. // The sample rate reporting mechanism is a bit of a mystery. It
  720. // seems that it can either return individual rates or a range of
  721. // rates. I assume that if the min / max range values are the same,
  722. // then that represents a single supported rate and if the min / max
  723. // range values are different, the device supports an arbitrary
  724. // range of values (though there might be multiple ranges, so we'll
  725. // use the most conservative range).
  726. Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
  727. bool haveValueRange = false;
  728. info.sampleRates.clear();
  729. for ( UInt32 i=0; i<nRanges; i++ ) {
  730. if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {
  731. unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;
  732. info.sampleRates.push_back( tmpSr );
  733. if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )
  734. info.preferredSampleRate = tmpSr;
  735. } else {
  736. haveValueRange = true;
  737. if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;
  738. if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;
  739. }
  740. }
  741. if ( haveValueRange ) {
  742. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  743. if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {
  744. info.sampleRates.push_back( SAMPLE_RATES[k] );
  745. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  746. info.preferredSampleRate = SAMPLE_RATES[k];
  747. }
  748. }
  749. }
  750. // Sort and remove any redundant values
  751. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  752. info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );
  753. if ( info.sampleRates.size() == 0 ) {
  754. errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
  755. errorText_ = errorStream_.str();
  756. error( RtAudioError::WARNING );
  757. return info;
  758. }
  759. // CoreAudio always uses 32-bit floating point data for PCM streams.
  760. // Thus, any other "physical" formats supported by the device are of
  761. // no interest to the client.
  762. info.nativeFormats = RTAUDIO_FLOAT32;
  763. if ( info.outputChannels > 0 )
  764. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  765. if ( info.inputChannels > 0 )
  766. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  767. info.probed = true;
  768. return info;
  769. }
  770. static OSStatus callbackHandler( AudioDeviceID inDevice,
  771. const AudioTimeStamp* /*inNow*/,
  772. const AudioBufferList* inInputData,
  773. const AudioTimeStamp* /*inInputTime*/,
  774. AudioBufferList* outOutputData,
  775. const AudioTimeStamp* /*inOutputTime*/,
  776. void* infoPointer )
  777. {
  778. CallbackInfo *info = (CallbackInfo *) infoPointer;
  779. RtApiCore *object = (RtApiCore *) info->object;
  780. if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
  781. return kAudioHardwareUnspecifiedError;
  782. else
  783. return kAudioHardwareNoError;
  784. }
  785. static OSStatus xrunListener( AudioObjectID /*inDevice*/,
  786. UInt32 nAddresses,
  787. const AudioObjectPropertyAddress properties[],
  788. void* handlePointer )
  789. {
  790. CoreHandle *handle = (CoreHandle *) handlePointer;
  791. for ( UInt32 i=0; i<nAddresses; i++ ) {
  792. if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {
  793. if ( properties[i].mScope == kAudioDevicePropertyScopeInput )
  794. handle->xrun[1] = true;
  795. else
  796. handle->xrun[0] = true;
  797. }
  798. }
  799. return kAudioHardwareNoError;
  800. }
  801. static OSStatus rateListener( AudioObjectID inDevice,
  802. UInt32 /*nAddresses*/,
  803. const AudioObjectPropertyAddress /*properties*/[],
  804. void* ratePointer )
  805. {
  806. Float64 *rate = (Float64 *) ratePointer;
  807. UInt32 dataSize = sizeof( Float64 );
  808. AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,
  809. kAudioObjectPropertyScopeGlobal,
  810. kAudioObjectPropertyElementMaster };
  811. AudioObjectGetPropertyData( inDevice, &property, 0, NULL, &dataSize, rate );
  812. return kAudioHardwareNoError;
  813. }
  814. bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  815. unsigned int firstChannel, unsigned int sampleRate,
  816. RtAudioFormat format, unsigned int *bufferSize,
  817. RtAudio::StreamOptions *options )
  818. {
  819. // Get device ID
  820. unsigned int nDevices = getDeviceCount();
  821. if ( nDevices == 0 ) {
  822. // This should not happen because a check is made before this function is called.
  823. errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
  824. return FAILURE;
  825. }
  826. if ( device >= nDevices ) {
  827. // This should not happen because a check is made before this function is called.
  828. errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
  829. return FAILURE;
  830. }
  831. AudioDeviceID deviceList[ nDevices ];
  832. UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
  833. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  834. kAudioObjectPropertyScopeGlobal,
  835. kAudioObjectPropertyElementMaster };
  836. OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
  837. 0, NULL, &dataSize, (void *) &deviceList );
  838. if ( result != noErr ) {
  839. errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
  840. return FAILURE;
  841. }
  842. AudioDeviceID id = deviceList[ device ];
  843. // Setup for stream mode.
  844. bool isInput = false;
  845. if ( mode == INPUT ) {
  846. isInput = true;
  847. property.mScope = kAudioDevicePropertyScopeInput;
  848. }
  849. else
  850. property.mScope = kAudioDevicePropertyScopeOutput;
  851. // Get the stream "configuration".
  852. AudioBufferList *bufferList = nil;
  853. dataSize = 0;
  854. property.mSelector = kAudioDevicePropertyStreamConfiguration;
  855. result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
  856. if ( result != noErr || dataSize == 0 ) {
  857. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";
  858. errorText_ = errorStream_.str();
  859. return FAILURE;
  860. }
  861. // Allocate the AudioBufferList.
  862. bufferList = (AudioBufferList *) malloc( dataSize );
  863. if ( bufferList == NULL ) {
  864. errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";
  865. return FAILURE;
  866. }
  867. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
  868. if (result != noErr || dataSize == 0) {
  869. free( bufferList );
  870. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";
  871. errorText_ = errorStream_.str();
  872. return FAILURE;
  873. }
  874. // Search for one or more streams that contain the desired number of
  875. // channels. CoreAudio devices can have an arbitrary number of
  876. // streams and each stream can have an arbitrary number of channels.
  877. // For each stream, a single buffer of interleaved samples is
  878. // provided. RtAudio prefers the use of one stream of interleaved
  879. // data or multiple consecutive single-channel streams. However, we
  880. // now support multiple consecutive multi-channel streams of
  881. // interleaved data as well.
  882. UInt32 iStream, offsetCounter = firstChannel;
  883. UInt32 nStreams = bufferList->mNumberBuffers;
  884. bool monoMode = false;
  885. bool foundStream = false;
  886. // First check that the device supports the requested number of
  887. // channels.
  888. UInt32 deviceChannels = 0;
  889. for ( iStream=0; iStream<nStreams; iStream++ )
  890. deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;
  891. if ( deviceChannels < ( channels + firstChannel ) ) {
  892. free( bufferList );
  893. errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";
  894. errorText_ = errorStream_.str();
  895. return FAILURE;
  896. }
  897. // Look for a single stream meeting our needs.
  898. UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;
  899. for ( iStream=0; iStream<nStreams; iStream++ ) {
  900. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  901. if ( streamChannels >= channels + offsetCounter ) {
  902. firstStream = iStream;
  903. channelOffset = offsetCounter;
  904. foundStream = true;
  905. break;
  906. }
  907. if ( streamChannels > offsetCounter ) break;
  908. offsetCounter -= streamChannels;
  909. }
  910. // If we didn't find a single stream above, then we should be able
  911. // to meet the channel specification with multiple streams.
  912. if ( foundStream == false ) {
  913. monoMode = true;
  914. offsetCounter = firstChannel;
  915. for ( iStream=0; iStream<nStreams; iStream++ ) {
  916. streamChannels = bufferList->mBuffers[iStream].mNumberChannels;
  917. if ( streamChannels > offsetCounter ) break;
  918. offsetCounter -= streamChannels;
  919. }
  920. firstStream = iStream;
  921. channelOffset = offsetCounter;
  922. Int32 channelCounter = channels + offsetCounter - streamChannels;
  923. if ( streamChannels > 1 ) monoMode = false;
  924. while ( channelCounter > 0 ) {
  925. streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;
  926. if ( streamChannels > 1 ) monoMode = false;
  927. channelCounter -= streamChannels;
  928. streamCount++;
  929. }
  930. }
  931. free( bufferList );
  932. // Determine the buffer size.
  933. AudioValueRange bufferRange;
  934. dataSize = sizeof( AudioValueRange );
  935. property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  936. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange );
  937. if ( result != noErr ) {
  938. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ").";
  939. errorText_ = errorStream_.str();
  940. return FAILURE;
  941. }
  942. if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  943. else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMaximum;
  944. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned long) bufferRange.mMinimum;
  945. // Set the buffer size. For multiple streams, I'm assuming we only
  946. // need to make this setting for the master channel.
  947. UInt32 theSize = (UInt32) *bufferSize;
  948. dataSize = sizeof( UInt32 );
  949. property.mSelector = kAudioDevicePropertyBufferFrameSize;
  950. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize );
  951. if ( result != noErr ) {
  952. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ").";
  953. errorText_ = errorStream_.str();
  954. return FAILURE;
  955. }
  956. // If attempting to setup a duplex stream, the bufferSize parameter
  957. // MUST be the same in both directions!
  958. *bufferSize = theSize;
  959. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  960. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";
  961. errorText_ = errorStream_.str();
  962. return FAILURE;
  963. }
  964. stream_.bufferSize = *bufferSize;
  965. stream_.nBuffers = 1;
  966. // Try to set "hog" mode ... it's not clear to me this is working.
  967. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) {
  968. pid_t hog_pid;
  969. dataSize = sizeof( hog_pid );
  970. property.mSelector = kAudioDevicePropertyHogMode;
  971. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid );
  972. if ( result != noErr ) {
  973. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!";
  974. errorText_ = errorStream_.str();
  975. return FAILURE;
  976. }
  977. if ( hog_pid != getpid() ) {
  978. hog_pid = getpid();
  979. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid );
  980. if ( result != noErr ) {
  981. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";
  982. errorText_ = errorStream_.str();
  983. return FAILURE;
  984. }
  985. }
  986. }
  987. // Check and if necessary, change the sample rate for the device.
  988. Float64 nominalRate;
  989. dataSize = sizeof( Float64 );
  990. property.mSelector = kAudioDevicePropertyNominalSampleRate;
  991. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );
  992. if ( result != noErr ) {
  993. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";
  994. errorText_ = errorStream_.str();
  995. return FAILURE;
  996. }
  997. // Only change the sample rate if off by more than 1 Hz.
  998. if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) {
  999. // Set a property listener for the sample rate change
  1000. Float64 reportedRate = 0.0;
  1001. AudioObjectPropertyAddress tmp = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  1002. result = AudioObjectAddPropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1003. if ( result != noErr ) {
  1004. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate property listener for device (" << device << ").";
  1005. errorText_ = errorStream_.str();
  1006. return FAILURE;
  1007. }
  1008. nominalRate = (Float64) sampleRate;
  1009. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );
  1010. if ( result != noErr ) {
  1011. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1012. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ").";
  1013. errorText_ = errorStream_.str();
  1014. return FAILURE;
  1015. }
  1016. // Now wait until the reported nominal rate is what we just set.
  1017. UInt32 microCounter = 0;
  1018. while ( reportedRate != nominalRate ) {
  1019. microCounter += 5000;
  1020. if ( microCounter > 5000000 ) break;
  1021. usleep( 5000 );
  1022. }
  1023. // Remove the property listener.
  1024. AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );
  1025. if ( microCounter > 5000000 ) {
  1026. errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ").";
  1027. errorText_ = errorStream_.str();
  1028. return FAILURE;
  1029. }
  1030. }
  1031. // Now set the stream format for all streams. Also, check the
  1032. // physical format of the device and change that if necessary.
  1033. AudioStreamBasicDescription description;
  1034. dataSize = sizeof( AudioStreamBasicDescription );
  1035. property.mSelector = kAudioStreamPropertyVirtualFormat;
  1036. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  1037. if ( result != noErr ) {
  1038. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ").";
  1039. errorText_ = errorStream_.str();
  1040. return FAILURE;
  1041. }
  1042. // Set the sample rate and data format id. However, only make the
  1043. // change if the sample rate is not within 1.0 of the desired
  1044. // rate and the format is not linear pcm.
  1045. bool updateFormat = false;
  1046. if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) {
  1047. description.mSampleRate = (Float64) sampleRate;
  1048. updateFormat = true;
  1049. }
  1050. if ( description.mFormatID != kAudioFormatLinearPCM ) {
  1051. description.mFormatID = kAudioFormatLinearPCM;
  1052. updateFormat = true;
  1053. }
  1054. if ( updateFormat ) {
  1055. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description );
  1056. if ( result != noErr ) {
  1057. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ").";
  1058. errorText_ = errorStream_.str();
  1059. return FAILURE;
  1060. }
  1061. }
  1062. // Now check the physical format.
  1063. property.mSelector = kAudioStreamPropertyPhysicalFormat;
  1064. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );
  1065. if ( result != noErr ) {
  1066. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ").";
  1067. errorText_ = errorStream_.str();
  1068. return FAILURE;
  1069. }
  1070. //std::cout << "Current physical stream format:" << std::endl;
  1071. //std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl;
  1072. //std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1073. //std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl;
  1074. //std::cout << " sample rate = " << description.mSampleRate << std::endl;
  1075. if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) {
  1076. description.mFormatID = kAudioFormatLinearPCM;
  1077. //description.mSampleRate = (Float64) sampleRate;
  1078. AudioStreamBasicDescription testDescription = description;
  1079. UInt32 formatFlags;
  1080. // We'll try higher bit rates first and then work our way down.
  1081. std::vector< std::pair<UInt32, UInt32> > physicalFormats;
  1082. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;
  1083. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1084. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1085. physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );
  1086. physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) ); // 24-bit packed
  1087. formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh );
  1088. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low
  1089. formatFlags |= kAudioFormatFlagIsAlignedHigh;
  1090. physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high
  1091. formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;
  1092. physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) );
  1093. physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) );
  1094. bool setPhysicalFormat = false;
  1095. for( unsigned int i=0; i<physicalFormats.size(); i++ ) {
  1096. testDescription = description;
  1097. testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first;
  1098. testDescription.mFormatFlags = physicalFormats[i].second;
  1099. if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) )
  1100. testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame;
  1101. else
  1102. testDescription.mBytesPerFrame = testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame;
  1103. testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;
  1104. result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription );
  1105. if ( result == noErr ) {
  1106. setPhysicalFormat = true;
  1107. //std::cout << "Updated physical stream format:" << std::endl;
  1108. //std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;
  1109. //std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;
  1110. //std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;
  1111. //std::cout << " sample rate = " << testDescription.mSampleRate << std::endl;
  1112. break;
  1113. }
  1114. }
  1115. if ( !setPhysicalFormat ) {
  1116. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ").";
  1117. errorText_ = errorStream_.str();
  1118. return FAILURE;
  1119. }
  1120. } // done setting virtual/physical formats.
  1121. // Get the stream / device latency.
  1122. UInt32 latency;
  1123. dataSize = sizeof( UInt32 );
  1124. property.mSelector = kAudioDevicePropertyLatency;
  1125. if ( AudioObjectHasProperty( id, &property ) == true ) {
  1126. result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency );
  1127. if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;
  1128. else {
  1129. errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";
  1130. errorText_ = errorStream_.str();
  1131. error( RtAudioError::WARNING );
  1132. }
  1133. }
  1134. // Byte-swapping: According to AudioHardware.h, the stream data will
  1135. // always be presented in native-endian format, so we should never
  1136. // need to byte swap.
  1137. stream_.doByteSwap[mode] = false;
  1138. // From the CoreAudio documentation, PCM data must be supplied as
  1139. // 32-bit floats.
  1140. stream_.userFormat = format;
  1141. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  1142. if ( streamCount == 1 )
  1143. stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
  1144. else // multiple streams
  1145. stream_.nDeviceChannels[mode] = channels;
  1146. stream_.nUserChannels[mode] = channels;
  1147. stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream
  1148. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  1149. else stream_.userInterleaved = true;
  1150. stream_.deviceInterleaved[mode] = true;
  1151. if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;
  1152. // Set flags for buffer conversion.
  1153. stream_.doConvertBuffer[mode] = false;
  1154. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  1155. stream_.doConvertBuffer[mode] = true;
  1156. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  1157. stream_.doConvertBuffer[mode] = true;
  1158. if ( streamCount == 1 ) {
  1159. if ( stream_.nUserChannels[mode] > 1 &&
  1160. stream_.userInterleaved != stream_.deviceInterleaved[mode] )
  1161. stream_.doConvertBuffer[mode] = true;
  1162. }
  1163. else if ( monoMode && stream_.userInterleaved )
  1164. stream_.doConvertBuffer[mode] = true;
  1165. // Allocate our CoreHandle structure for the stream.
  1166. CoreHandle *handle = 0;
  1167. if ( stream_.apiHandle == 0 ) {
  1168. try {
  1169. handle = new CoreHandle;
  1170. }
  1171. catch ( std::bad_alloc& ) {
  1172. errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";
  1173. goto error;
  1174. }
  1175. if ( pthread_cond_init( &handle->condition, NULL ) ) {
  1176. errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";
  1177. goto error;
  1178. }
  1179. stream_.apiHandle = (void *) handle;
  1180. }
  1181. else
  1182. handle = (CoreHandle *) stream_.apiHandle;
  1183. handle->iStream[mode] = firstStream;
  1184. handle->nStreams[mode] = streamCount;
  1185. handle->id[mode] = id;
  1186. // Allocate necessary internal buffers.
  1187. unsigned long bufferBytes;
  1188. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  1189. // stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  1190. stream_.userBuffer[mode] = (char *) malloc( bufferBytes * sizeof(char) );
  1191. memset( stream_.userBuffer[mode], 0, bufferBytes * sizeof(char) );
  1192. if ( stream_.userBuffer[mode] == NULL ) {
  1193. errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";
  1194. goto error;
  1195. }
  1196. // If possible, we will make use of the CoreAudio stream buffers as
  1197. // "device buffers". However, we can't do this if using multiple
  1198. // streams.
  1199. if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {
  1200. bool makeBuffer = true;
  1201. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  1202. if ( mode == INPUT ) {
  1203. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  1204. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  1205. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  1206. }
  1207. }
  1208. if ( makeBuffer ) {
  1209. bufferBytes *= *bufferSize;
  1210. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  1211. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  1212. if ( stream_.deviceBuffer == NULL ) {
  1213. errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";
  1214. goto error;
  1215. }
  1216. }
  1217. }
  1218. stream_.sampleRate = sampleRate;
  1219. stream_.device[mode] = device;
  1220. stream_.state = STREAM_STOPPED;
  1221. stream_.callbackInfo.object = (void *) this;
  1222. // Setup the buffer conversion information structure.
  1223. if ( stream_.doConvertBuffer[mode] ) {
  1224. if ( streamCount > 1 ) setConvertInfo( mode, 0 );
  1225. else setConvertInfo( mode, channelOffset );
  1226. }
  1227. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device )
  1228. // Only one callback procedure per device.
  1229. stream_.mode = DUPLEX;
  1230. else {
  1231. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1232. result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );
  1233. #else
  1234. // deprecated in favor of AudioDeviceCreateIOProcID()
  1235. result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
  1236. #endif
  1237. if ( result != noErr ) {
  1238. errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";
  1239. errorText_ = errorStream_.str();
  1240. goto error;
  1241. }
  1242. if ( stream_.mode == OUTPUT && mode == INPUT )
  1243. stream_.mode = DUPLEX;
  1244. else
  1245. stream_.mode = mode;
  1246. }
  1247. // Setup the device property listener for over/underload.
  1248. property.mSelector = kAudioDeviceProcessorOverload;
  1249. property.mScope = kAudioObjectPropertyScopeGlobal;
  1250. result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );
  1251. return SUCCESS;
  1252. error:
  1253. if ( handle ) {
  1254. pthread_cond_destroy( &handle->condition );
  1255. delete handle;
  1256. stream_.apiHandle = 0;
  1257. }
  1258. for ( int i=0; i<2; i++ ) {
  1259. if ( stream_.userBuffer[i] ) {
  1260. free( stream_.userBuffer[i] );
  1261. stream_.userBuffer[i] = 0;
  1262. }
  1263. }
  1264. if ( stream_.deviceBuffer ) {
  1265. free( stream_.deviceBuffer );
  1266. stream_.deviceBuffer = 0;
  1267. }
  1268. stream_.state = STREAM_CLOSED;
  1269. return FAILURE;
  1270. }
  1271. void RtApiCore :: closeStream( void )
  1272. {
  1273. if ( stream_.state == STREAM_CLOSED ) {
  1274. errorText_ = "RtApiCore::closeStream(): no open stream to close!";
  1275. error( RtAudioError::WARNING );
  1276. return;
  1277. }
  1278. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1279. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1280. if (handle) {
  1281. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1282. kAudioObjectPropertyScopeGlobal,
  1283. kAudioObjectPropertyElementMaster };
  1284. property.mSelector = kAudioDeviceProcessorOverload;
  1285. property.mScope = kAudioObjectPropertyScopeGlobal;
  1286. if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {
  1287. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1288. error( RtAudioError::WARNING );
  1289. }
  1290. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1291. if ( stream_.state == STREAM_RUNNING )
  1292. AudioDeviceStop( handle->id[0], handle->procId[0] );
  1293. AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );
  1294. #else // deprecated behaviour
  1295. if ( stream_.state == STREAM_RUNNING )
  1296. AudioDeviceStop( handle->id[0], callbackHandler );
  1297. AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );
  1298. #endif
  1299. }
  1300. }
  1301. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1302. if (handle) {
  1303. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
  1304. kAudioObjectPropertyScopeGlobal,
  1305. kAudioObjectPropertyElementMaster };
  1306. property.mSelector = kAudioDeviceProcessorOverload;
  1307. property.mScope = kAudioObjectPropertyScopeGlobal;
  1308. if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {
  1309. errorText_ = "RtApiCore::closeStream(): error removing property listener!";
  1310. error( RtAudioError::WARNING );
  1311. }
  1312. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1313. if ( stream_.state == STREAM_RUNNING )
  1314. AudioDeviceStop( handle->id[1], handle->procId[1] );
  1315. AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );
  1316. #else // deprecated behaviour
  1317. if ( stream_.state == STREAM_RUNNING )
  1318. AudioDeviceStop( handle->id[1], callbackHandler );
  1319. AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );
  1320. #endif
  1321. }
  1322. }
  1323. for ( int i=0; i<2; i++ ) {
  1324. if ( stream_.userBuffer[i] ) {
  1325. free( stream_.userBuffer[i] );
  1326. stream_.userBuffer[i] = 0;
  1327. }
  1328. }
  1329. if ( stream_.deviceBuffer ) {
  1330. free( stream_.deviceBuffer );
  1331. stream_.deviceBuffer = 0;
  1332. }
  1333. // Destroy pthread condition variable.
  1334. pthread_cond_destroy( &handle->condition );
  1335. delete handle;
  1336. stream_.apiHandle = 0;
  1337. stream_.mode = UNINITIALIZED;
  1338. stream_.state = STREAM_CLOSED;
  1339. }
  1340. void RtApiCore :: startStream( void )
  1341. {
  1342. verifyStream();
  1343. if ( stream_.state == STREAM_RUNNING ) {
  1344. errorText_ = "RtApiCore::startStream(): the stream is already running!";
  1345. error( RtAudioError::WARNING );
  1346. return;
  1347. }
  1348. #if defined( HAVE_GETTIMEOFDAY )
  1349. gettimeofday( &stream_.lastTickTimestamp, NULL );
  1350. #endif
  1351. OSStatus result = noErr;
  1352. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1353. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1354. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1355. result = AudioDeviceStart( handle->id[0], handle->procId[0] );
  1356. #else // deprecated behaviour
  1357. result = AudioDeviceStart( handle->id[0], callbackHandler );
  1358. #endif
  1359. if ( result != noErr ) {
  1360. errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ").";
  1361. errorText_ = errorStream_.str();
  1362. goto unlock;
  1363. }
  1364. }
  1365. if ( stream_.mode == INPUT ||
  1366. ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1367. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1368. result = AudioDeviceStart( handle->id[1], handle->procId[1] );
  1369. #else // deprecated behaviour
  1370. result = AudioDeviceStart( handle->id[1], callbackHandler );
  1371. #endif
  1372. if ( result != noErr ) {
  1373. errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";
  1374. errorText_ = errorStream_.str();
  1375. goto unlock;
  1376. }
  1377. }
  1378. handle->drainCounter = 0;
  1379. handle->internalDrain = false;
  1380. stream_.state = STREAM_RUNNING;
  1381. unlock:
  1382. if ( result == noErr ) return;
  1383. error( RtAudioError::SYSTEM_ERROR );
  1384. }
  1385. void RtApiCore :: stopStream( void )
  1386. {
  1387. verifyStream();
  1388. if ( stream_.state == STREAM_STOPPED ) {
  1389. errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";
  1390. error( RtAudioError::WARNING );
  1391. return;
  1392. }
  1393. OSStatus result = noErr;
  1394. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1395. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  1396. if ( handle->drainCounter == 0 ) {
  1397. handle->drainCounter = 2;
  1398. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  1399. }
  1400. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1401. result = AudioDeviceStop( handle->id[0], handle->procId[0] );
  1402. #else // deprecated behaviour
  1403. result = AudioDeviceStop( handle->id[0], callbackHandler );
  1404. #endif
  1405. if ( result != noErr ) {
  1406. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";
  1407. errorText_ = errorStream_.str();
  1408. goto unlock;
  1409. }
  1410. }
  1411. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {
  1412. #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
  1413. result = AudioDeviceStop( handle->id[0], handle->procId[1] );
  1414. #else // deprecated behaviour
  1415. result = AudioDeviceStop( handle->id[1], callbackHandler );
  1416. #endif
  1417. if ( result != noErr ) {
  1418. errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";
  1419. errorText_ = errorStream_.str();
  1420. goto unlock;
  1421. }
  1422. }
  1423. stream_.state = STREAM_STOPPED;
  1424. unlock:
  1425. if ( result == noErr ) return;
  1426. error( RtAudioError::SYSTEM_ERROR );
  1427. }
  1428. void RtApiCore :: abortStream( void )
  1429. {
  1430. verifyStream();
  1431. if ( stream_.state == STREAM_STOPPED ) {
  1432. errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";
  1433. error( RtAudioError::WARNING );
  1434. return;
  1435. }
  1436. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1437. handle->drainCounter = 2;
  1438. stopStream();
  1439. }
  1440. // This function will be called by a spawned thread when the user
  1441. // callback function signals that the stream should be stopped or
  1442. // aborted. It is better to handle it this way because the
  1443. // callbackEvent() function probably should return before the AudioDeviceStop()
  1444. // function is called.
  1445. static void *coreStopStream( void *ptr )
  1446. {
  1447. CallbackInfo *info = (CallbackInfo *) ptr;
  1448. RtApiCore *object = (RtApiCore *) info->object;
  1449. object->stopStream();
  1450. pthread_exit( NULL );
  1451. }
  1452. bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
  1453. const AudioBufferList *inBufferList,
  1454. const AudioBufferList *outBufferList )
  1455. {
  1456. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  1457. if ( stream_.state == STREAM_CLOSED ) {
  1458. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  1459. error( RtAudioError::WARNING );
  1460. return FAILURE;
  1461. }
  1462. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  1463. CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
  1464. // Check if we were draining the stream and signal is finished.
  1465. if ( handle->drainCounter > 3 ) {
  1466. ThreadHandle threadId;
  1467. stream_.state = STREAM_STOPPING;
  1468. if ( handle->internalDrain == true )
  1469. pthread_create( &threadId, NULL, coreStopStream, info );
  1470. else // external call to stopStream()
  1471. pthread_cond_signal( &handle->condition );
  1472. return SUCCESS;
  1473. }
  1474. AudioDeviceID outputDevice = handle->id[0];
  1475. // Invoke user callback to get fresh output data UNLESS we are
  1476. // draining stream or duplex mode AND the input/output devices are
  1477. // different AND this function is called for the input device.
  1478. if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {
  1479. RtAudioCallback callback = (RtAudioCallback) info->callback;
  1480. double streamTime = getStreamTime();
  1481. RtAudioStreamStatus status = 0;
  1482. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  1483. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  1484. handle->xrun[0] = false;
  1485. }
  1486. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  1487. status |= RTAUDIO_INPUT_OVERFLOW;
  1488. handle->xrun[1] = false;
  1489. }
  1490. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  1491. stream_.bufferSize, streamTime, status, info->userData );
  1492. if ( cbReturnValue == 2 ) {
  1493. stream_.state = STREAM_STOPPING;
  1494. handle->drainCounter = 2;
  1495. abortStream();
  1496. return SUCCESS;
  1497. }
  1498. else if ( cbReturnValue == 1 ) {
  1499. handle->drainCounter = 1;
  1500. handle->internalDrain = true;
  1501. }
  1502. }
  1503. if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {
  1504. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  1505. if ( handle->nStreams[0] == 1 ) {
  1506. memset( outBufferList->mBuffers[handle->iStream[0]].mData,
  1507. 0,
  1508. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1509. }
  1510. else { // fill multiple streams with zeros
  1511. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1512. memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1513. 0,
  1514. outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );
  1515. }
  1516. }
  1517. }
  1518. else if ( handle->nStreams[0] == 1 ) {
  1519. if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer
  1520. convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,
  1521. stream_.userBuffer[0], stream_.convertInfo[0] );
  1522. }
  1523. else { // copy from user buffer
  1524. memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,
  1525. stream_.userBuffer[0],
  1526. outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );
  1527. }
  1528. }
  1529. else { // fill multiple streams
  1530. Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];
  1531. if ( stream_.doConvertBuffer[0] ) {
  1532. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  1533. inBuffer = (Float32 *) stream_.deviceBuffer;
  1534. }
  1535. if ( stream_.deviceInterleaved[0] == false ) { // mono mode
  1536. UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;
  1537. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  1538. memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,
  1539. (void *)&inBuffer[i*stream_.bufferSize], bufferBytes );
  1540. }
  1541. }
  1542. else { // fill multiple multi-channel streams with interleaved data
  1543. UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;
  1544. Float32 *out, *in;
  1545. bool inInterleaved = ( stream_.userInterleaved ) ? true : false;
  1546. UInt32 inChannels = stream_.nUserChannels[0];
  1547. if ( stream_.doConvertBuffer[0] ) {
  1548. inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1549. inChannels = stream_.nDeviceChannels[0];
  1550. }
  1551. if ( inInterleaved ) inOffset = 1;
  1552. else inOffset = stream_.bufferSize;
  1553. channelsLeft = inChannels;
  1554. for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {
  1555. in = inBuffer;
  1556. out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;
  1557. streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;
  1558. outJump = 0;
  1559. // Account for possible channel offset in first stream
  1560. if ( i == 0 && stream_.channelOffset[0] > 0 ) {
  1561. streamChannels -= stream_.channelOffset[0];
  1562. outJump = stream_.channelOffset[0];
  1563. out += outJump;
  1564. }
  1565. // Account for possible unfilled channels at end of the last stream
  1566. if ( streamChannels > channelsLeft ) {
  1567. outJump = streamChannels - channelsLeft;
  1568. streamChannels = channelsLeft;
  1569. }
  1570. // Determine input buffer offsets and skips
  1571. if ( inInterleaved ) {
  1572. inJump = inChannels;
  1573. in += inChannels - channelsLeft;
  1574. }
  1575. else {
  1576. inJump = 1;
  1577. in += (inChannels - channelsLeft) * inOffset;
  1578. }
  1579. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1580. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1581. *out++ = in[j*inOffset];
  1582. }
  1583. out += outJump;
  1584. in += inJump;
  1585. }
  1586. channelsLeft -= streamChannels;
  1587. }
  1588. }
  1589. }
  1590. }
  1591. // Don't bother draining input
  1592. if ( handle->drainCounter ) {
  1593. handle->drainCounter++;
  1594. goto unlock;
  1595. }
  1596. AudioDeviceID inputDevice;
  1597. inputDevice = handle->id[1];
  1598. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {
  1599. if ( handle->nStreams[1] == 1 ) {
  1600. if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer
  1601. convertBuffer( stream_.userBuffer[1],
  1602. (char *) inBufferList->mBuffers[handle->iStream[1]].mData,
  1603. stream_.convertInfo[1] );
  1604. }
  1605. else { // copy to user buffer
  1606. memcpy( stream_.userBuffer[1],
  1607. inBufferList->mBuffers[handle->iStream[1]].mData,
  1608. inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );
  1609. }
  1610. }
  1611. else { // read from multiple streams
  1612. Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];
  1613. if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;
  1614. if ( stream_.deviceInterleaved[1] == false ) { // mono mode
  1615. UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;
  1616. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  1617. memcpy( (void *)&outBuffer[i*stream_.bufferSize],
  1618. inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );
  1619. }
  1620. }
  1621. else { // read from multiple multi-channel streams
  1622. UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;
  1623. Float32 *out, *in;
  1624. bool outInterleaved = ( stream_.userInterleaved ) ? true : false;
  1625. UInt32 outChannels = stream_.nUserChannels[1];
  1626. if ( stream_.doConvertBuffer[1] ) {
  1627. outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode
  1628. outChannels = stream_.nDeviceChannels[1];
  1629. }
  1630. if ( outInterleaved ) outOffset = 1;
  1631. else outOffset = stream_.bufferSize;
  1632. channelsLeft = outChannels;
  1633. for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {
  1634. out = outBuffer;
  1635. in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;
  1636. streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;
  1637. inJump = 0;
  1638. // Account for possible channel offset in first stream
  1639. if ( i == 0 && stream_.channelOffset[1] > 0 ) {
  1640. streamChannels -= stream_.channelOffset[1];
  1641. inJump = stream_.channelOffset[1];
  1642. in += inJump;
  1643. }
  1644. // Account for possible unread channels at end of the last stream
  1645. if ( streamChannels > channelsLeft ) {
  1646. inJump = streamChannels - channelsLeft;
  1647. streamChannels = channelsLeft;
  1648. }
  1649. // Determine output buffer offsets and skips
  1650. if ( outInterleaved ) {
  1651. outJump = outChannels;
  1652. out += outChannels - channelsLeft;
  1653. }
  1654. else {
  1655. outJump = 1;
  1656. out += (outChannels - channelsLeft) * outOffset;
  1657. }
  1658. for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {
  1659. for ( unsigned int j=0; j<streamChannels; j++ ) {
  1660. out[j*outOffset] = *in++;
  1661. }
  1662. out += outJump;
  1663. in += inJump;
  1664. }
  1665. channelsLeft -= streamChannels;
  1666. }
  1667. }
  1668. if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer
  1669. convertBuffer( stream_.userBuffer[1],
  1670. stream_.deviceBuffer,
  1671. stream_.convertInfo[1] );
  1672. }
  1673. }
  1674. }
  1675. unlock:
  1676. //MUTEX_UNLOCK( &stream_.mutex );
  1677. // Make sure to only tick duplex stream time once if using two devices
  1678. if ( stream_.mode != DUPLEX || (stream_.mode == DUPLEX && handle->id[0] != handle->id[1] && deviceId == handle->id[0] ) )
  1679. RtApi::tickStreamTime();
  1680. return SUCCESS;
  1681. }
  1682. const char* RtApiCore :: getErrorCode( OSStatus code )
  1683. {
  1684. switch( code ) {
  1685. case kAudioHardwareNotRunningError:
  1686. return "kAudioHardwareNotRunningError";
  1687. case kAudioHardwareUnspecifiedError:
  1688. return "kAudioHardwareUnspecifiedError";
  1689. case kAudioHardwareUnknownPropertyError:
  1690. return "kAudioHardwareUnknownPropertyError";
  1691. case kAudioHardwareBadPropertySizeError:
  1692. return "kAudioHardwareBadPropertySizeError";
  1693. case kAudioHardwareIllegalOperationError:
  1694. return "kAudioHardwareIllegalOperationError";
  1695. case kAudioHardwareBadObjectError:
  1696. return "kAudioHardwareBadObjectError";
  1697. case kAudioHardwareBadDeviceError:
  1698. return "kAudioHardwareBadDeviceError";
  1699. case kAudioHardwareBadStreamError:
  1700. return "kAudioHardwareBadStreamError";
  1701. case kAudioHardwareUnsupportedOperationError:
  1702. return "kAudioHardwareUnsupportedOperationError";
  1703. case kAudioDeviceUnsupportedFormatError:
  1704. return "kAudioDeviceUnsupportedFormatError";
  1705. case kAudioDevicePermissionsError:
  1706. return "kAudioDevicePermissionsError";
  1707. default:
  1708. return "CoreAudio unknown error";
  1709. }
  1710. }
  1711. //******************** End of __MACOSX_CORE__ *********************//
  1712. #endif
  1713. #if defined(__UNIX_JACK__)
  1714. // JACK is a low-latency audio server, originally written for the
  1715. // GNU/Linux operating system and now also ported to OS-X. It can
  1716. // connect a number of different applications to an audio device, as
  1717. // well as allowing them to share audio between themselves.
  1718. //
  1719. // When using JACK with RtAudio, "devices" refer to JACK clients that
  1720. // have ports connected to the server. The JACK server is typically
  1721. // started in a terminal as follows:
  1722. //
  1723. // .jackd -d alsa -d hw:0
  1724. //
  1725. // or through an interface program such as qjackctl. Many of the
  1726. // parameters normally set for a stream are fixed by the JACK server
  1727. // and can be specified when the JACK server is started. In
  1728. // particular,
  1729. //
  1730. // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
  1731. //
  1732. // specifies a sample rate of 44100 Hz, a buffer size of 512 sample
  1733. // frames, and number of buffers = 4. Once the server is running, it
  1734. // is not possible to override these values. If the values are not
  1735. // specified in the command-line, the JACK server uses default values.
  1736. //
  1737. // The JACK server does not have to be running when an instance of
  1738. // RtApiJack is created, though the function getDeviceCount() will
  1739. // report 0 devices found until JACK has been started. When no
  1740. // devices are available (i.e., the JACK server is not running), a
  1741. // stream cannot be opened.
  1742. #include <jack/jack.h>
  1743. #include <unistd.h>
  1744. #include <cstdio>
  1745. // A structure to hold various information related to the Jack API
  1746. // implementation.
  1747. struct JackHandle {
  1748. jack_client_t *client;
  1749. jack_port_t **ports[2];
  1750. std::string deviceName[2];
  1751. bool xrun[2];
  1752. pthread_cond_t condition;
  1753. int drainCounter; // Tracks callback counts when draining
  1754. bool internalDrain; // Indicates if stop is initiated from callback or not.
  1755. JackHandle()
  1756. :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
  1757. };
  1758. #if !defined(__RTAUDIO_DEBUG__)
  1759. static void jackSilentError( const char * ) {};
  1760. #endif
  1761. RtApiJack :: RtApiJack()
  1762. :shouldAutoconnect_(true) {
  1763. // Nothing to do here.
  1764. #if !defined(__RTAUDIO_DEBUG__)
  1765. // Turn off Jack's internal error reporting.
  1766. jack_set_error_function( &jackSilentError );
  1767. #endif
  1768. }
  1769. RtApiJack :: ~RtApiJack()
  1770. {
  1771. if ( stream_.state != STREAM_CLOSED ) closeStream();
  1772. }
  1773. unsigned int RtApiJack :: getDeviceCount( void )
  1774. {
  1775. // See if we can become a jack client.
  1776. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1777. jack_status_t *status = NULL;
  1778. jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );
  1779. if ( client == 0 ) return 0;
  1780. const char **ports;
  1781. std::string port, previousPort;
  1782. unsigned int nChannels = 0, nDevices = 0;
  1783. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1784. if ( ports ) {
  1785. // Parse the port names up to the first colon (:).
  1786. size_t iColon = 0;
  1787. do {
  1788. port = (char *) ports[ nChannels ];
  1789. iColon = port.find(":");
  1790. if ( iColon != std::string::npos ) {
  1791. port = port.substr( 0, iColon + 1 );
  1792. if ( port != previousPort ) {
  1793. nDevices++;
  1794. previousPort = port;
  1795. }
  1796. }
  1797. } while ( ports[++nChannels] );
  1798. free( ports );
  1799. }
  1800. jack_client_close( client );
  1801. return nDevices;
  1802. }
  1803. RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
  1804. {
  1805. RtAudio::DeviceInfo info;
  1806. info.probed = false;
  1807. jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption
  1808. jack_status_t *status = NULL;
  1809. jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );
  1810. if ( client == 0 ) {
  1811. errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
  1812. error( RtAudioError::WARNING );
  1813. return info;
  1814. }
  1815. const char **ports;
  1816. std::string port, previousPort;
  1817. unsigned int nPorts = 0, nDevices = 0;
  1818. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1819. if ( ports ) {
  1820. // Parse the port names up to the first colon (:).
  1821. size_t iColon = 0;
  1822. do {
  1823. port = (char *) ports[ nPorts ];
  1824. iColon = port.find(":");
  1825. if ( iColon != std::string::npos ) {
  1826. port = port.substr( 0, iColon );
  1827. if ( port != previousPort ) {
  1828. if ( nDevices == device ) info.name = port;
  1829. nDevices++;
  1830. previousPort = port;
  1831. }
  1832. }
  1833. } while ( ports[++nPorts] );
  1834. free( ports );
  1835. }
  1836. if ( device >= nDevices ) {
  1837. jack_client_close( client );
  1838. errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
  1839. error( RtAudioError::INVALID_USE );
  1840. return info;
  1841. }
  1842. // Get the current jack server sample rate.
  1843. info.sampleRates.clear();
  1844. info.preferredSampleRate = jack_get_sample_rate( client );
  1845. info.sampleRates.push_back( info.preferredSampleRate );
  1846. // Count the available ports containing the client name as device
  1847. // channels. Jack "input ports" equal RtAudio output channels.
  1848. unsigned int nChannels = 0;
  1849. ports = jack_get_ports( client, info.name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput );
  1850. if ( ports ) {
  1851. while ( ports[ nChannels ] ) nChannels++;
  1852. free( ports );
  1853. info.outputChannels = nChannels;
  1854. }
  1855. // Jack "output ports" equal RtAudio input channels.
  1856. nChannels = 0;
  1857. ports = jack_get_ports( client, info.name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
  1858. if ( ports ) {
  1859. while ( ports[ nChannels ] ) nChannels++;
  1860. free( ports );
  1861. info.inputChannels = nChannels;
  1862. }
  1863. if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
  1864. jack_client_close(client);
  1865. errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
  1866. error( RtAudioError::WARNING );
  1867. return info;
  1868. }
  1869. // If device opens for both playback and capture, we determine the channels.
  1870. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  1871. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  1872. // Jack always uses 32-bit floats.
  1873. info.nativeFormats = RTAUDIO_FLOAT32;
  1874. // Jack doesn't provide default devices so we'll use the first available one.
  1875. if ( device == 0 && info.outputChannels > 0 )
  1876. info.isDefaultOutput = true;
  1877. if ( device == 0 && info.inputChannels > 0 )
  1878. info.isDefaultInput = true;
  1879. jack_client_close(client);
  1880. info.probed = true;
  1881. return info;
  1882. }
  1883. static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
  1884. {
  1885. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1886. RtApiJack *object = (RtApiJack *) info->object;
  1887. if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
  1888. return 0;
  1889. }
  1890. // This function will be called by a spawned thread when the Jack
  1891. // server signals that it is shutting down. It is necessary to handle
  1892. // it this way because the jackShutdown() function must return before
  1893. // the jack_deactivate() function (in closeStream()) will return.
  1894. static void *jackCloseStream( void *ptr )
  1895. {
  1896. CallbackInfo *info = (CallbackInfo *) ptr;
  1897. RtApiJack *object = (RtApiJack *) info->object;
  1898. object->closeStream();
  1899. pthread_exit( NULL );
  1900. }
  1901. static void jackShutdown( void *infoPointer )
  1902. {
  1903. CallbackInfo *info = (CallbackInfo *) infoPointer;
  1904. RtApiJack *object = (RtApiJack *) info->object;
  1905. // Check current stream state. If stopped, then we'll assume this
  1906. // was called as a result of a call to RtApiJack::stopStream (the
  1907. // deactivation of a client handle causes this function to be called).
  1908. // If not, we'll assume the Jack server is shutting down or some
  1909. // other problem occurred and we should close the stream.
  1910. if ( object->isStreamRunning() == false ) return;
  1911. ThreadHandle threadId;
  1912. pthread_create( &threadId, NULL, jackCloseStream, info );
  1913. std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
  1914. }
  1915. static int jackXrun( void *infoPointer )
  1916. {
  1917. JackHandle *handle = *((JackHandle **) infoPointer);
  1918. if ( handle->ports[0] ) handle->xrun[0] = true;
  1919. if ( handle->ports[1] ) handle->xrun[1] = true;
  1920. return 0;
  1921. }
  1922. bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  1923. unsigned int firstChannel, unsigned int sampleRate,
  1924. RtAudioFormat format, unsigned int *bufferSize,
  1925. RtAudio::StreamOptions *options )
  1926. {
  1927. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  1928. // Look for jack server and try to become a client (only do once per stream).
  1929. jack_client_t *client = 0;
  1930. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
  1931. jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption;
  1932. jack_status_t *status = NULL;
  1933. if ( options && !options->streamName.empty() )
  1934. client = jack_client_open( options->streamName.c_str(), jackoptions, status );
  1935. else
  1936. client = jack_client_open( "RtApiJack", jackoptions, status );
  1937. if ( client == 0 ) {
  1938. errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
  1939. error( RtAudioError::WARNING );
  1940. return FAILURE;
  1941. }
  1942. }
  1943. else {
  1944. // The handle must have been created on an earlier pass.
  1945. client = handle->client;
  1946. }
  1947. const char **ports;
  1948. std::string port, previousPort, deviceName;
  1949. unsigned int nPorts = 0, nDevices = 0;
  1950. ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 );
  1951. if ( ports ) {
  1952. // Parse the port names up to the first colon (:).
  1953. size_t iColon = 0;
  1954. do {
  1955. port = (char *) ports[ nPorts ];
  1956. iColon = port.find(":");
  1957. if ( iColon != std::string::npos ) {
  1958. port = port.substr( 0, iColon );
  1959. if ( port != previousPort ) {
  1960. if ( nDevices == device ) deviceName = port;
  1961. nDevices++;
  1962. previousPort = port;
  1963. }
  1964. }
  1965. } while ( ports[++nPorts] );
  1966. free( ports );
  1967. }
  1968. if ( device >= nDevices ) {
  1969. errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
  1970. return FAILURE;
  1971. }
  1972. unsigned long flag = JackPortIsInput;
  1973. if ( mode == INPUT ) flag = JackPortIsOutput;
  1974. if ( ! (options && (options->flags & RTAUDIO_JACK_DONT_CONNECT)) ) {
  1975. // Count the available ports containing the client name as device
  1976. // channels. Jack "input ports" equal RtAudio output channels.
  1977. unsigned int nChannels = 0;
  1978. ports = jack_get_ports( client, deviceName.c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
  1979. if ( ports ) {
  1980. while ( ports[ nChannels ] ) nChannels++;
  1981. free( ports );
  1982. }
  1983. // Compare the jack ports for specified client to the requested number of channels.
  1984. if ( nChannels < (channels + firstChannel) ) {
  1985. errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
  1986. errorText_ = errorStream_.str();
  1987. return FAILURE;
  1988. }
  1989. }
  1990. // Check the jack server sample rate.
  1991. unsigned int jackRate = jack_get_sample_rate( client );
  1992. if ( sampleRate != jackRate ) {
  1993. jack_client_close( client );
  1994. errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
  1995. errorText_ = errorStream_.str();
  1996. return FAILURE;
  1997. }
  1998. stream_.sampleRate = jackRate;
  1999. // Get the latency of the JACK port.
  2000. ports = jack_get_ports( client, deviceName.c_str(), JACK_DEFAULT_AUDIO_TYPE, flag );
  2001. if ( ports[ firstChannel ] ) {
  2002. // Added by Ge Wang
  2003. jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);
  2004. // the range (usually the min and max are equal)
  2005. jack_latency_range_t latrange; latrange.min = latrange.max = 0;
  2006. // get the latency range
  2007. jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );
  2008. // be optimistic, use the min!
  2009. stream_.latency[mode] = latrange.min;
  2010. //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
  2011. }
  2012. free( ports );
  2013. // The jack server always uses 32-bit floating-point data.
  2014. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2015. stream_.userFormat = format;
  2016. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2017. else stream_.userInterleaved = true;
  2018. // Jack always uses non-interleaved buffers.
  2019. stream_.deviceInterleaved[mode] = false;
  2020. // Jack always provides host byte-ordered data.
  2021. stream_.doByteSwap[mode] = false;
  2022. // Get the buffer size. The buffer size and number of buffers
  2023. // (periods) is set when the jack server is started.
  2024. stream_.bufferSize = (int) jack_get_buffer_size( client );
  2025. *bufferSize = stream_.bufferSize;
  2026. stream_.nDeviceChannels[mode] = channels;
  2027. stream_.nUserChannels[mode] = channels;
  2028. // Set flags for buffer conversion.
  2029. stream_.doConvertBuffer[mode] = false;
  2030. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2031. stream_.doConvertBuffer[mode] = true;
  2032. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2033. stream_.nUserChannels[mode] > 1 )
  2034. stream_.doConvertBuffer[mode] = true;
  2035. // Allocate our JackHandle structure for the stream.
  2036. if ( handle == 0 ) {
  2037. try {
  2038. handle = new JackHandle;
  2039. }
  2040. catch ( std::bad_alloc& ) {
  2041. errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
  2042. goto error;
  2043. }
  2044. if ( pthread_cond_init(&handle->condition, NULL) ) {
  2045. errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
  2046. goto error;
  2047. }
  2048. stream_.apiHandle = (void *) handle;
  2049. handle->client = client;
  2050. }
  2051. handle->deviceName[mode] = deviceName;
  2052. // Allocate necessary internal buffers.
  2053. unsigned long bufferBytes;
  2054. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2055. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2056. if ( stream_.userBuffer[mode] == NULL ) {
  2057. errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
  2058. goto error;
  2059. }
  2060. if ( stream_.doConvertBuffer[mode] ) {
  2061. bool makeBuffer = true;
  2062. if ( mode == OUTPUT )
  2063. bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2064. else { // mode == INPUT
  2065. bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
  2066. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  2067. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
  2068. if ( bufferBytes < bytesOut ) makeBuffer = false;
  2069. }
  2070. }
  2071. if ( makeBuffer ) {
  2072. bufferBytes *= *bufferSize;
  2073. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2074. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2075. if ( stream_.deviceBuffer == NULL ) {
  2076. errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
  2077. goto error;
  2078. }
  2079. }
  2080. }
  2081. // Allocate memory for the Jack ports (channels) identifiers.
  2082. handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
  2083. if ( handle->ports[mode] == NULL ) {
  2084. errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
  2085. goto error;
  2086. }
  2087. stream_.device[mode] = device;
  2088. stream_.channelOffset[mode] = firstChannel;
  2089. stream_.state = STREAM_STOPPED;
  2090. stream_.callbackInfo.object = (void *) this;
  2091. if ( stream_.mode == OUTPUT && mode == INPUT )
  2092. // We had already set up the stream for output.
  2093. stream_.mode = DUPLEX;
  2094. else {
  2095. stream_.mode = mode;
  2096. jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
  2097. jack_set_xrun_callback( handle->client, jackXrun, (void *) &stream_.apiHandle );
  2098. jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
  2099. }
  2100. // Register our ports.
  2101. char label[64];
  2102. if ( mode == OUTPUT ) {
  2103. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2104. snprintf( label, 64, "outport %d", i );
  2105. handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
  2106. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
  2107. }
  2108. }
  2109. else {
  2110. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2111. snprintf( label, 64, "inport %d", i );
  2112. handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
  2113. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
  2114. }
  2115. }
  2116. // Setup the buffer conversion information structure. We don't use
  2117. // buffers to do channel offsets, so we override that parameter
  2118. // here.
  2119. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2120. if ( options && options->flags & RTAUDIO_JACK_DONT_CONNECT ) shouldAutoconnect_ = false;
  2121. return SUCCESS;
  2122. error:
  2123. if ( handle ) {
  2124. pthread_cond_destroy( &handle->condition );
  2125. jack_client_close( handle->client );
  2126. if ( handle->ports[0] ) free( handle->ports[0] );
  2127. if ( handle->ports[1] ) free( handle->ports[1] );
  2128. delete handle;
  2129. stream_.apiHandle = 0;
  2130. }
  2131. for ( int i=0; i<2; i++ ) {
  2132. if ( stream_.userBuffer[i] ) {
  2133. free( stream_.userBuffer[i] );
  2134. stream_.userBuffer[i] = 0;
  2135. }
  2136. }
  2137. if ( stream_.deviceBuffer ) {
  2138. free( stream_.deviceBuffer );
  2139. stream_.deviceBuffer = 0;
  2140. }
  2141. return FAILURE;
  2142. }
  2143. void RtApiJack :: closeStream( void )
  2144. {
  2145. if ( stream_.state == STREAM_CLOSED ) {
  2146. errorText_ = "RtApiJack::closeStream(): no open stream to close!";
  2147. error( RtAudioError::WARNING );
  2148. return;
  2149. }
  2150. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2151. if ( handle ) {
  2152. if ( stream_.state == STREAM_RUNNING )
  2153. jack_deactivate( handle->client );
  2154. jack_client_close( handle->client );
  2155. }
  2156. if ( handle ) {
  2157. if ( handle->ports[0] ) free( handle->ports[0] );
  2158. if ( handle->ports[1] ) free( handle->ports[1] );
  2159. pthread_cond_destroy( &handle->condition );
  2160. delete handle;
  2161. stream_.apiHandle = 0;
  2162. }
  2163. for ( int i=0; i<2; i++ ) {
  2164. if ( stream_.userBuffer[i] ) {
  2165. free( stream_.userBuffer[i] );
  2166. stream_.userBuffer[i] = 0;
  2167. }
  2168. }
  2169. if ( stream_.deviceBuffer ) {
  2170. free( stream_.deviceBuffer );
  2171. stream_.deviceBuffer = 0;
  2172. }
  2173. stream_.mode = UNINITIALIZED;
  2174. stream_.state = STREAM_CLOSED;
  2175. }
  2176. void RtApiJack :: startStream( void )
  2177. {
  2178. verifyStream();
  2179. if ( stream_.state == STREAM_RUNNING ) {
  2180. errorText_ = "RtApiJack::startStream(): the stream is already running!";
  2181. error( RtAudioError::WARNING );
  2182. return;
  2183. }
  2184. #if defined( HAVE_GETTIMEOFDAY )
  2185. gettimeofday( &stream_.lastTickTimestamp, NULL );
  2186. #endif
  2187. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2188. int result = jack_activate( handle->client );
  2189. if ( result ) {
  2190. errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
  2191. goto unlock;
  2192. }
  2193. const char **ports;
  2194. // Get the list of available ports.
  2195. if ( shouldAutoconnect_ && (stream_.mode == OUTPUT || stream_.mode == DUPLEX) ) {
  2196. result = 1;
  2197. ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput);
  2198. if ( ports == NULL) {
  2199. errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
  2200. goto unlock;
  2201. }
  2202. // Now make the port connections. Since RtAudio wasn't designed to
  2203. // allow the user to select particular channels of a device, we'll
  2204. // just open the first "nChannels" ports with offset.
  2205. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2206. result = 1;
  2207. if ( ports[ stream_.channelOffset[0] + i ] )
  2208. result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
  2209. if ( result ) {
  2210. free( ports );
  2211. errorText_ = "RtApiJack::startStream(): error connecting output ports!";
  2212. goto unlock;
  2213. }
  2214. }
  2215. free(ports);
  2216. }
  2217. if ( shouldAutoconnect_ && (stream_.mode == INPUT || stream_.mode == DUPLEX) ) {
  2218. result = 1;
  2219. ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput );
  2220. if ( ports == NULL) {
  2221. errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
  2222. goto unlock;
  2223. }
  2224. // Now make the port connections. See note above.
  2225. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2226. result = 1;
  2227. if ( ports[ stream_.channelOffset[1] + i ] )
  2228. result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
  2229. if ( result ) {
  2230. free( ports );
  2231. errorText_ = "RtApiJack::startStream(): error connecting input ports!";
  2232. goto unlock;
  2233. }
  2234. }
  2235. free(ports);
  2236. }
  2237. handle->drainCounter = 0;
  2238. handle->internalDrain = false;
  2239. stream_.state = STREAM_RUNNING;
  2240. unlock:
  2241. if ( result == 0 ) return;
  2242. error( RtAudioError::SYSTEM_ERROR );
  2243. }
  2244. void RtApiJack :: stopStream( void )
  2245. {
  2246. verifyStream();
  2247. if ( stream_.state == STREAM_STOPPED ) {
  2248. errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
  2249. error( RtAudioError::WARNING );
  2250. return;
  2251. }
  2252. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2253. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2254. if ( handle->drainCounter == 0 ) {
  2255. handle->drainCounter = 2;
  2256. pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
  2257. }
  2258. }
  2259. jack_deactivate( handle->client );
  2260. stream_.state = STREAM_STOPPED;
  2261. }
  2262. void RtApiJack :: abortStream( void )
  2263. {
  2264. verifyStream();
  2265. if ( stream_.state == STREAM_STOPPED ) {
  2266. errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
  2267. error( RtAudioError::WARNING );
  2268. return;
  2269. }
  2270. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2271. handle->drainCounter = 2;
  2272. stopStream();
  2273. }
  2274. // This function will be called by a spawned thread when the user
  2275. // callback function signals that the stream should be stopped or
  2276. // aborted. It is necessary to handle it this way because the
  2277. // callbackEvent() function must return before the jack_deactivate()
  2278. // function will return.
  2279. static void *jackStopStream( void *ptr )
  2280. {
  2281. CallbackInfo *info = (CallbackInfo *) ptr;
  2282. RtApiJack *object = (RtApiJack *) info->object;
  2283. object->stopStream();
  2284. pthread_exit( NULL );
  2285. }
  2286. bool RtApiJack :: callbackEvent( unsigned long nframes )
  2287. {
  2288. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  2289. if ( stream_.state == STREAM_CLOSED ) {
  2290. errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
  2291. error( RtAudioError::WARNING );
  2292. return FAILURE;
  2293. }
  2294. if ( stream_.bufferSize != nframes ) {
  2295. errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
  2296. error( RtAudioError::WARNING );
  2297. return FAILURE;
  2298. }
  2299. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  2300. JackHandle *handle = (JackHandle *) stream_.apiHandle;
  2301. // Check if we were draining the stream and signal is finished.
  2302. if ( handle->drainCounter > 3 ) {
  2303. ThreadHandle threadId;
  2304. stream_.state = STREAM_STOPPING;
  2305. if ( handle->internalDrain == true )
  2306. pthread_create( &threadId, NULL, jackStopStream, info );
  2307. else
  2308. pthread_cond_signal( &handle->condition );
  2309. return SUCCESS;
  2310. }
  2311. // Invoke user callback first, to get fresh output data.
  2312. if ( handle->drainCounter == 0 ) {
  2313. RtAudioCallback callback = (RtAudioCallback) info->callback;
  2314. double streamTime = getStreamTime();
  2315. RtAudioStreamStatus status = 0;
  2316. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  2317. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  2318. handle->xrun[0] = false;
  2319. }
  2320. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  2321. status |= RTAUDIO_INPUT_OVERFLOW;
  2322. handle->xrun[1] = false;
  2323. }
  2324. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  2325. stream_.bufferSize, streamTime, status, info->userData );
  2326. if ( cbReturnValue == 2 ) {
  2327. stream_.state = STREAM_STOPPING;
  2328. handle->drainCounter = 2;
  2329. ThreadHandle id;
  2330. pthread_create( &id, NULL, jackStopStream, info );
  2331. return SUCCESS;
  2332. }
  2333. else if ( cbReturnValue == 1 ) {
  2334. handle->drainCounter = 1;
  2335. handle->internalDrain = true;
  2336. }
  2337. }
  2338. jack_default_audio_sample_t *jackbuffer;
  2339. unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
  2340. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2341. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  2342. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2343. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2344. memset( jackbuffer, 0, bufferBytes );
  2345. }
  2346. }
  2347. else if ( stream_.doConvertBuffer[0] ) {
  2348. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  2349. for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
  2350. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2351. memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
  2352. }
  2353. }
  2354. else { // no buffer conversion
  2355. for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
  2356. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
  2357. memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
  2358. }
  2359. }
  2360. }
  2361. // Don't bother draining input
  2362. if ( handle->drainCounter ) {
  2363. handle->drainCounter++;
  2364. goto unlock;
  2365. }
  2366. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  2367. if ( stream_.doConvertBuffer[1] ) {
  2368. for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
  2369. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2370. memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
  2371. }
  2372. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  2373. }
  2374. else { // no buffer conversion
  2375. for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
  2376. jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
  2377. memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
  2378. }
  2379. }
  2380. }
  2381. unlock:
  2382. RtApi::tickStreamTime();
  2383. return SUCCESS;
  2384. }
  2385. //******************** End of __UNIX_JACK__ *********************//
  2386. #endif
  2387. #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
  2388. // The ASIO API is designed around a callback scheme, so this
  2389. // implementation is similar to that used for OS-X CoreAudio and Linux
  2390. // Jack. The primary constraint with ASIO is that it only allows
  2391. // access to a single driver at a time. Thus, it is not possible to
  2392. // have more than one simultaneous RtAudio stream.
  2393. //
  2394. // This implementation also requires a number of external ASIO files
  2395. // and a few global variables. The ASIO callback scheme does not
  2396. // allow for the passing of user data, so we must create a global
  2397. // pointer to our callbackInfo structure.
  2398. //
  2399. // On unix systems, we make use of a pthread condition variable.
  2400. // Since there is no equivalent in Windows, I hacked something based
  2401. // on information found in
  2402. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
  2403. #include "asiosys.h"
  2404. #include "asio.h"
  2405. #include "iasiothiscallresolver.h"
  2406. #include "asiodrivers.h"
  2407. #include <cmath>
  2408. static AsioDrivers drivers;
  2409. static ASIOCallbacks asioCallbacks;
  2410. static ASIODriverInfo driverInfo;
  2411. static CallbackInfo *asioCallbackInfo;
  2412. static bool asioXRun;
  2413. struct AsioHandle {
  2414. int drainCounter; // Tracks callback counts when draining
  2415. bool internalDrain; // Indicates if stop is initiated from callback or not.
  2416. ASIOBufferInfo *bufferInfos;
  2417. HANDLE condition;
  2418. AsioHandle()
  2419. :drainCounter(0), internalDrain(false), bufferInfos(0) {}
  2420. };
  2421. // Function declarations (definitions at end of section)
  2422. static const char* getAsioErrorString( ASIOError result );
  2423. static void sampleRateChanged( ASIOSampleRate sRate );
  2424. static long asioMessages( long selector, long value, void* message, double* opt );
  2425. RtApiAsio :: RtApiAsio()
  2426. {
  2427. // ASIO cannot run on a multi-threaded appartment. You can call
  2428. // CoInitialize beforehand, but it must be for appartment threading
  2429. // (in which case, CoInitilialize will return S_FALSE here).
  2430. coInitialized_ = false;
  2431. HRESULT hr = CoInitialize( NULL );
  2432. if ( FAILED(hr) ) {
  2433. errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
  2434. error( RtAudioError::WARNING );
  2435. }
  2436. coInitialized_ = true;
  2437. drivers.removeCurrentDriver();
  2438. driverInfo.asioVersion = 2;
  2439. // See note in DirectSound implementation about GetDesktopWindow().
  2440. driverInfo.sysRef = GetForegroundWindow();
  2441. }
  2442. RtApiAsio :: ~RtApiAsio()
  2443. {
  2444. if ( stream_.state != STREAM_CLOSED ) closeStream();
  2445. if ( coInitialized_ ) CoUninitialize();
  2446. }
  2447. unsigned int RtApiAsio :: getDeviceCount( void )
  2448. {
  2449. return (unsigned int) drivers.asioGetNumDev();
  2450. }
  2451. RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
  2452. {
  2453. RtAudio::DeviceInfo info;
  2454. info.probed = false;
  2455. // Get device ID
  2456. unsigned int nDevices = getDeviceCount();
  2457. if ( nDevices == 0 ) {
  2458. errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
  2459. error( RtAudioError::INVALID_USE );
  2460. return info;
  2461. }
  2462. if ( device >= nDevices ) {
  2463. errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
  2464. error( RtAudioError::INVALID_USE );
  2465. return info;
  2466. }
  2467. // If a stream is already open, we cannot probe other devices. Thus, use the saved results.
  2468. if ( stream_.state != STREAM_CLOSED ) {
  2469. if ( device >= devices_.size() ) {
  2470. errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
  2471. error( RtAudioError::WARNING );
  2472. return info;
  2473. }
  2474. return devices_[ device ];
  2475. }
  2476. char driverName[32];
  2477. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2478. if ( result != ASE_OK ) {
  2479. errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2480. errorText_ = errorStream_.str();
  2481. error( RtAudioError::WARNING );
  2482. return info;
  2483. }
  2484. info.name = driverName;
  2485. if ( !drivers.loadDriver( driverName ) ) {
  2486. errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
  2487. errorText_ = errorStream_.str();
  2488. error( RtAudioError::WARNING );
  2489. return info;
  2490. }
  2491. result = ASIOInit( &driverInfo );
  2492. if ( result != ASE_OK ) {
  2493. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2494. errorText_ = errorStream_.str();
  2495. error( RtAudioError::WARNING );
  2496. return info;
  2497. }
  2498. // Determine the device channel information.
  2499. long inputChannels, outputChannels;
  2500. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2501. if ( result != ASE_OK ) {
  2502. drivers.removeCurrentDriver();
  2503. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2504. errorText_ = errorStream_.str();
  2505. error( RtAudioError::WARNING );
  2506. return info;
  2507. }
  2508. info.outputChannels = outputChannels;
  2509. info.inputChannels = inputChannels;
  2510. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  2511. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  2512. // Determine the supported sample rates.
  2513. info.sampleRates.clear();
  2514. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  2515. result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
  2516. if ( result == ASE_OK ) {
  2517. info.sampleRates.push_back( SAMPLE_RATES[i] );
  2518. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  2519. info.preferredSampleRate = SAMPLE_RATES[i];
  2520. }
  2521. }
  2522. // Determine supported data types ... just check first channel and assume rest are the same.
  2523. ASIOChannelInfo channelInfo;
  2524. channelInfo.channel = 0;
  2525. channelInfo.isInput = true;
  2526. if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
  2527. result = ASIOGetChannelInfo( &channelInfo );
  2528. if ( result != ASE_OK ) {
  2529. drivers.removeCurrentDriver();
  2530. errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
  2531. errorText_ = errorStream_.str();
  2532. error( RtAudioError::WARNING );
  2533. return info;
  2534. }
  2535. info.nativeFormats = 0;
  2536. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
  2537. info.nativeFormats |= RTAUDIO_SINT16;
  2538. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
  2539. info.nativeFormats |= RTAUDIO_SINT32;
  2540. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
  2541. info.nativeFormats |= RTAUDIO_FLOAT32;
  2542. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
  2543. info.nativeFormats |= RTAUDIO_FLOAT64;
  2544. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )
  2545. info.nativeFormats |= RTAUDIO_SINT24;
  2546. if ( info.outputChannels > 0 )
  2547. if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
  2548. if ( info.inputChannels > 0 )
  2549. if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
  2550. info.probed = true;
  2551. drivers.removeCurrentDriver();
  2552. return info;
  2553. }
  2554. static void bufferSwitch( long index, ASIOBool /*processNow*/ )
  2555. {
  2556. RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
  2557. object->callbackEvent( index );
  2558. }
  2559. void RtApiAsio :: saveDeviceInfo( void )
  2560. {
  2561. devices_.clear();
  2562. unsigned int nDevices = getDeviceCount();
  2563. devices_.resize( nDevices );
  2564. for ( unsigned int i=0; i<nDevices; i++ )
  2565. devices_[i] = getDeviceInfo( i );
  2566. }
  2567. bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  2568. unsigned int firstChannel, unsigned int sampleRate,
  2569. RtAudioFormat format, unsigned int *bufferSize,
  2570. RtAudio::StreamOptions *options )
  2571. {////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2572. bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT;
  2573. // For ASIO, a duplex stream MUST use the same driver.
  2574. if ( isDuplexInput && stream_.device[0] != device ) {
  2575. errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
  2576. return FAILURE;
  2577. }
  2578. char driverName[32];
  2579. ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
  2580. if ( result != ASE_OK ) {
  2581. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
  2582. errorText_ = errorStream_.str();
  2583. return FAILURE;
  2584. }
  2585. // Only load the driver once for duplex stream.
  2586. if ( !isDuplexInput ) {
  2587. // The getDeviceInfo() function will not work when a stream is open
  2588. // because ASIO does not allow multiple devices to run at the same
  2589. // time. Thus, we'll probe the system before opening a stream and
  2590. // save the results for use by getDeviceInfo().
  2591. this->saveDeviceInfo();
  2592. if ( !drivers.loadDriver( driverName ) ) {
  2593. errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
  2594. errorText_ = errorStream_.str();
  2595. return FAILURE;
  2596. }
  2597. result = ASIOInit( &driverInfo );
  2598. if ( result != ASE_OK ) {
  2599. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
  2600. errorText_ = errorStream_.str();
  2601. return FAILURE;
  2602. }
  2603. }
  2604. // keep them before any "goto error", they are used for error cleanup + goto device boundary checks
  2605. bool buffersAllocated = false;
  2606. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2607. unsigned int nChannels;
  2608. // Check the device channel count.
  2609. long inputChannels, outputChannels;
  2610. result = ASIOGetChannels( &inputChannels, &outputChannels );
  2611. if ( result != ASE_OK ) {
  2612. errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
  2613. errorText_ = errorStream_.str();
  2614. goto error;
  2615. }
  2616. if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
  2617. ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
  2618. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
  2619. errorText_ = errorStream_.str();
  2620. goto error;
  2621. }
  2622. stream_.nDeviceChannels[mode] = channels;
  2623. stream_.nUserChannels[mode] = channels;
  2624. stream_.channelOffset[mode] = firstChannel;
  2625. // Verify the sample rate is supported.
  2626. result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
  2627. if ( result != ASE_OK ) {
  2628. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
  2629. errorText_ = errorStream_.str();
  2630. goto error;
  2631. }
  2632. // Get the current sample rate
  2633. ASIOSampleRate currentRate;
  2634. result = ASIOGetSampleRate( &currentRate );
  2635. if ( result != ASE_OK ) {
  2636. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
  2637. errorText_ = errorStream_.str();
  2638. goto error;
  2639. }
  2640. // Set the sample rate only if necessary
  2641. if ( currentRate != sampleRate ) {
  2642. result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
  2643. if ( result != ASE_OK ) {
  2644. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
  2645. errorText_ = errorStream_.str();
  2646. goto error;
  2647. }
  2648. }
  2649. // Determine the driver data type.
  2650. ASIOChannelInfo channelInfo;
  2651. channelInfo.channel = 0;
  2652. if ( mode == OUTPUT ) channelInfo.isInput = false;
  2653. else channelInfo.isInput = true;
  2654. result = ASIOGetChannelInfo( &channelInfo );
  2655. if ( result != ASE_OK ) {
  2656. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
  2657. errorText_ = errorStream_.str();
  2658. goto error;
  2659. }
  2660. // Assuming WINDOWS host is always little-endian.
  2661. stream_.doByteSwap[mode] = false;
  2662. stream_.userFormat = format;
  2663. stream_.deviceFormat[mode] = 0;
  2664. if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
  2665. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  2666. if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
  2667. }
  2668. else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
  2669. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  2670. if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
  2671. }
  2672. else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
  2673. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  2674. if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
  2675. }
  2676. else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
  2677. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  2678. if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
  2679. }
  2680. else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {
  2681. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  2682. if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;
  2683. }
  2684. if ( stream_.deviceFormat[mode] == 0 ) {
  2685. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
  2686. errorText_ = errorStream_.str();
  2687. goto error;
  2688. }
  2689. // Set the buffer size. For a duplex stream, this will end up
  2690. // setting the buffer size based on the input constraints, which
  2691. // should be ok.
  2692. long minSize, maxSize, preferSize, granularity;
  2693. result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
  2694. if ( result != ASE_OK ) {
  2695. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
  2696. errorText_ = errorStream_.str();
  2697. goto error;
  2698. }
  2699. if ( isDuplexInput ) {
  2700. // When this is the duplex input (output was opened before), then we have to use the same
  2701. // buffersize as the output, because it might use the preferred buffer size, which most
  2702. // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,
  2703. // So instead of throwing an error, make them equal. The caller uses the reference
  2704. // to the "bufferSize" param as usual to set up processing buffers.
  2705. *bufferSize = stream_.bufferSize;
  2706. } else {
  2707. if ( *bufferSize == 0 ) *bufferSize = preferSize;
  2708. else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2709. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2710. else if ( granularity == -1 ) {
  2711. // Make sure bufferSize is a power of two.
  2712. int log2_of_min_size = 0;
  2713. int log2_of_max_size = 0;
  2714. for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
  2715. if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
  2716. if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
  2717. }
  2718. long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
  2719. int min_delta_num = log2_of_min_size;
  2720. for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
  2721. long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
  2722. if (current_delta < min_delta) {
  2723. min_delta = current_delta;
  2724. min_delta_num = i;
  2725. }
  2726. }
  2727. *bufferSize = ( (unsigned int)1 << min_delta_num );
  2728. if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
  2729. else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
  2730. }
  2731. else if ( granularity != 0 ) {
  2732. // Set to an even multiple of granularity, rounding up.
  2733. *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
  2734. }
  2735. }
  2736. /*
  2737. // we don't use it anymore, see above!
  2738. // Just left it here for the case...
  2739. if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {
  2740. errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
  2741. goto error;
  2742. }
  2743. */
  2744. stream_.bufferSize = *bufferSize;
  2745. stream_.nBuffers = 2;
  2746. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  2747. else stream_.userInterleaved = true;
  2748. // ASIO always uses non-interleaved buffers.
  2749. stream_.deviceInterleaved[mode] = false;
  2750. // Allocate, if necessary, our AsioHandle structure for the stream.
  2751. if ( handle == 0 ) {
  2752. try {
  2753. handle = new AsioHandle;
  2754. }
  2755. catch ( std::bad_alloc& ) {
  2756. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
  2757. goto error;
  2758. }
  2759. handle->bufferInfos = 0;
  2760. // Create a manual-reset event.
  2761. handle->condition = CreateEvent( NULL, // no security
  2762. TRUE, // manual-reset
  2763. FALSE, // non-signaled initially
  2764. NULL ); // unnamed
  2765. stream_.apiHandle = (void *) handle;
  2766. }
  2767. // Create the ASIO internal buffers. Since RtAudio sets up input
  2768. // and output separately, we'll have to dispose of previously
  2769. // created output buffers for a duplex stream.
  2770. if ( mode == INPUT && stream_.mode == OUTPUT ) {
  2771. ASIODisposeBuffers();
  2772. if ( handle->bufferInfos ) free( handle->bufferInfos );
  2773. }
  2774. // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
  2775. unsigned int i;
  2776. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  2777. handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
  2778. if ( handle->bufferInfos == NULL ) {
  2779. errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
  2780. errorText_ = errorStream_.str();
  2781. goto error;
  2782. }
  2783. ASIOBufferInfo *infos;
  2784. infos = handle->bufferInfos;
  2785. for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
  2786. infos->isInput = ASIOFalse;
  2787. infos->channelNum = i + stream_.channelOffset[0];
  2788. infos->buffers[0] = infos->buffers[1] = 0;
  2789. }
  2790. for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
  2791. infos->isInput = ASIOTrue;
  2792. infos->channelNum = i + stream_.channelOffset[1];
  2793. infos->buffers[0] = infos->buffers[1] = 0;
  2794. }
  2795. // prepare for callbacks
  2796. stream_.sampleRate = sampleRate;
  2797. stream_.device[mode] = device;
  2798. stream_.mode = isDuplexInput ? DUPLEX : mode;
  2799. // store this class instance before registering callbacks, that are going to use it
  2800. asioCallbackInfo = &stream_.callbackInfo;
  2801. stream_.callbackInfo.object = (void *) this;
  2802. // Set up the ASIO callback structure and create the ASIO data buffers.
  2803. asioCallbacks.bufferSwitch = &bufferSwitch;
  2804. asioCallbacks.sampleRateDidChange = &sampleRateChanged;
  2805. asioCallbacks.asioMessage = &asioMessages;
  2806. asioCallbacks.bufferSwitchTimeInfo = NULL;
  2807. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2808. if ( result != ASE_OK ) {
  2809. // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges
  2810. // but only accept the preferred buffer size as parameter for ASIOCreateBuffers (e.g. Creative's ASIO driver).
  2811. // In that case, let's be naïve and try that instead.
  2812. *bufferSize = preferSize;
  2813. stream_.bufferSize = *bufferSize;
  2814. result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
  2815. }
  2816. if ( result != ASE_OK ) {
  2817. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
  2818. errorText_ = errorStream_.str();
  2819. goto error;
  2820. }
  2821. buffersAllocated = true;
  2822. stream_.state = STREAM_STOPPED;
  2823. // Set flags for buffer conversion.
  2824. stream_.doConvertBuffer[mode] = false;
  2825. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  2826. stream_.doConvertBuffer[mode] = true;
  2827. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  2828. stream_.nUserChannels[mode] > 1 )
  2829. stream_.doConvertBuffer[mode] = true;
  2830. // Allocate necessary internal buffers
  2831. unsigned long bufferBytes;
  2832. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  2833. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  2834. if ( stream_.userBuffer[mode] == NULL ) {
  2835. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
  2836. goto error;
  2837. }
  2838. if ( stream_.doConvertBuffer[mode] ) {
  2839. bool makeBuffer = true;
  2840. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  2841. if ( isDuplexInput && stream_.deviceBuffer ) {
  2842. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  2843. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  2844. }
  2845. if ( makeBuffer ) {
  2846. bufferBytes *= *bufferSize;
  2847. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  2848. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  2849. if ( stream_.deviceBuffer == NULL ) {
  2850. errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
  2851. goto error;
  2852. }
  2853. }
  2854. }
  2855. // Determine device latencies
  2856. long inputLatency, outputLatency;
  2857. result = ASIOGetLatencies( &inputLatency, &outputLatency );
  2858. if ( result != ASE_OK ) {
  2859. errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
  2860. errorText_ = errorStream_.str();
  2861. error( RtAudioError::WARNING); // warn but don't fail
  2862. }
  2863. else {
  2864. stream_.latency[0] = outputLatency;
  2865. stream_.latency[1] = inputLatency;
  2866. }
  2867. // Setup the buffer conversion information structure. We don't use
  2868. // buffers to do channel offsets, so we override that parameter
  2869. // here.
  2870. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
  2871. return SUCCESS;
  2872. error:
  2873. if ( !isDuplexInput ) {
  2874. // the cleanup for error in the duplex input, is done by RtApi::openStream
  2875. // So we clean up for single channel only
  2876. if ( buffersAllocated )
  2877. ASIODisposeBuffers();
  2878. drivers.removeCurrentDriver();
  2879. if ( handle ) {
  2880. CloseHandle( handle->condition );
  2881. if ( handle->bufferInfos )
  2882. free( handle->bufferInfos );
  2883. delete handle;
  2884. stream_.apiHandle = 0;
  2885. }
  2886. if ( stream_.userBuffer[mode] ) {
  2887. free( stream_.userBuffer[mode] );
  2888. stream_.userBuffer[mode] = 0;
  2889. }
  2890. if ( stream_.deviceBuffer ) {
  2891. free( stream_.deviceBuffer );
  2892. stream_.deviceBuffer = 0;
  2893. }
  2894. }
  2895. return FAILURE;
  2896. }////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2897. void RtApiAsio :: closeStream()
  2898. {
  2899. if ( stream_.state == STREAM_CLOSED ) {
  2900. errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
  2901. error( RtAudioError::WARNING );
  2902. return;
  2903. }
  2904. if ( stream_.state == STREAM_RUNNING ) {
  2905. stream_.state = STREAM_STOPPED;
  2906. ASIOStop();
  2907. }
  2908. ASIODisposeBuffers();
  2909. drivers.removeCurrentDriver();
  2910. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2911. if ( handle ) {
  2912. CloseHandle( handle->condition );
  2913. if ( handle->bufferInfos )
  2914. free( handle->bufferInfos );
  2915. delete handle;
  2916. stream_.apiHandle = 0;
  2917. }
  2918. for ( int i=0; i<2; i++ ) {
  2919. if ( stream_.userBuffer[i] ) {
  2920. free( stream_.userBuffer[i] );
  2921. stream_.userBuffer[i] = 0;
  2922. }
  2923. }
  2924. if ( stream_.deviceBuffer ) {
  2925. free( stream_.deviceBuffer );
  2926. stream_.deviceBuffer = 0;
  2927. }
  2928. stream_.mode = UNINITIALIZED;
  2929. stream_.state = STREAM_CLOSED;
  2930. }
  2931. bool stopThreadCalled = false;
  2932. void RtApiAsio :: startStream()
  2933. {
  2934. verifyStream();
  2935. if ( stream_.state == STREAM_RUNNING ) {
  2936. errorText_ = "RtApiAsio::startStream(): the stream is already running!";
  2937. error( RtAudioError::WARNING );
  2938. return;
  2939. }
  2940. #if defined( HAVE_GETTIMEOFDAY )
  2941. gettimeofday( &stream_.lastTickTimestamp, NULL );
  2942. #endif
  2943. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2944. ASIOError result = ASIOStart();
  2945. if ( result != ASE_OK ) {
  2946. errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
  2947. errorText_ = errorStream_.str();
  2948. goto unlock;
  2949. }
  2950. handle->drainCounter = 0;
  2951. handle->internalDrain = false;
  2952. ResetEvent( handle->condition );
  2953. stream_.state = STREAM_RUNNING;
  2954. asioXRun = false;
  2955. unlock:
  2956. stopThreadCalled = false;
  2957. if ( result == ASE_OK ) return;
  2958. error( RtAudioError::SYSTEM_ERROR );
  2959. }
  2960. void RtApiAsio :: stopStream()
  2961. {
  2962. verifyStream();
  2963. if ( stream_.state == STREAM_STOPPED ) {
  2964. errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
  2965. error( RtAudioError::WARNING );
  2966. return;
  2967. }
  2968. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2969. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  2970. if ( handle->drainCounter == 0 ) {
  2971. handle->drainCounter = 2;
  2972. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  2973. }
  2974. }
  2975. stream_.state = STREAM_STOPPED;
  2976. ASIOError result = ASIOStop();
  2977. if ( result != ASE_OK ) {
  2978. errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
  2979. errorText_ = errorStream_.str();
  2980. }
  2981. if ( result == ASE_OK ) return;
  2982. error( RtAudioError::SYSTEM_ERROR );
  2983. }
  2984. void RtApiAsio :: abortStream()
  2985. {
  2986. verifyStream();
  2987. if ( stream_.state == STREAM_STOPPED ) {
  2988. errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
  2989. error( RtAudioError::WARNING );
  2990. return;
  2991. }
  2992. // The following lines were commented-out because some behavior was
  2993. // noted where the device buffers need to be zeroed to avoid
  2994. // continuing sound, even when the device buffers are completely
  2995. // disposed. So now, calling abort is the same as calling stop.
  2996. // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  2997. // handle->drainCounter = 2;
  2998. stopStream();
  2999. }
  3000. // This function will be called by a spawned thread when the user
  3001. // callback function signals that the stream should be stopped or
  3002. // aborted. It is necessary to handle it this way because the
  3003. // callbackEvent() function must return before the ASIOStop()
  3004. // function will return.
  3005. static unsigned __stdcall asioStopStream( void *ptr )
  3006. {
  3007. CallbackInfo *info = (CallbackInfo *) ptr;
  3008. RtApiAsio *object = (RtApiAsio *) info->object;
  3009. object->stopStream();
  3010. _endthreadex( 0 );
  3011. return 0;
  3012. }
  3013. bool RtApiAsio :: callbackEvent( long bufferIndex )
  3014. {
  3015. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;
  3016. if ( stream_.state == STREAM_CLOSED ) {
  3017. errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
  3018. error( RtAudioError::WARNING );
  3019. return FAILURE;
  3020. }
  3021. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  3022. AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
  3023. // Check if we were draining the stream and signal if finished.
  3024. if ( handle->drainCounter > 3 ) {
  3025. stream_.state = STREAM_STOPPING;
  3026. if ( handle->internalDrain == false )
  3027. SetEvent( handle->condition );
  3028. else { // spawn a thread to stop the stream
  3029. unsigned threadId;
  3030. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  3031. &stream_.callbackInfo, 0, &threadId );
  3032. }
  3033. return SUCCESS;
  3034. }
  3035. // Invoke user callback to get fresh output data UNLESS we are
  3036. // draining stream.
  3037. if ( handle->drainCounter == 0 ) {
  3038. RtAudioCallback callback = (RtAudioCallback) info->callback;
  3039. double streamTime = getStreamTime();
  3040. RtAudioStreamStatus status = 0;
  3041. if ( stream_.mode != INPUT && asioXRun == true ) {
  3042. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  3043. asioXRun = false;
  3044. }
  3045. if ( stream_.mode != OUTPUT && asioXRun == true ) {
  3046. status |= RTAUDIO_INPUT_OVERFLOW;
  3047. asioXRun = false;
  3048. }
  3049. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  3050. stream_.bufferSize, streamTime, status, info->userData );
  3051. if ( cbReturnValue == 2 ) {
  3052. stream_.state = STREAM_STOPPING;
  3053. handle->drainCounter = 2;
  3054. unsigned threadId;
  3055. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,
  3056. &stream_.callbackInfo, 0, &threadId );
  3057. return SUCCESS;
  3058. }
  3059. else if ( cbReturnValue == 1 ) {
  3060. handle->drainCounter = 1;
  3061. handle->internalDrain = true;
  3062. }
  3063. }
  3064. unsigned int nChannels, bufferBytes, i, j;
  3065. nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
  3066. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  3067. bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
  3068. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  3069. for ( i=0, j=0; i<nChannels; i++ ) {
  3070. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3071. memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
  3072. }
  3073. }
  3074. else if ( stream_.doConvertBuffer[0] ) {
  3075. convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  3076. if ( stream_.doByteSwap[0] )
  3077. byteSwapBuffer( stream_.deviceBuffer,
  3078. stream_.bufferSize * stream_.nDeviceChannels[0],
  3079. stream_.deviceFormat[0] );
  3080. for ( i=0, j=0; i<nChannels; i++ ) {
  3081. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3082. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  3083. &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
  3084. }
  3085. }
  3086. else {
  3087. if ( stream_.doByteSwap[0] )
  3088. byteSwapBuffer( stream_.userBuffer[0],
  3089. stream_.bufferSize * stream_.nUserChannels[0],
  3090. stream_.userFormat );
  3091. for ( i=0, j=0; i<nChannels; i++ ) {
  3092. if ( handle->bufferInfos[i].isInput != ASIOTrue )
  3093. memcpy( handle->bufferInfos[i].buffers[bufferIndex],
  3094. &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
  3095. }
  3096. }
  3097. }
  3098. // Don't bother draining input
  3099. if ( handle->drainCounter ) {
  3100. handle->drainCounter++;
  3101. goto unlock;
  3102. }
  3103. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  3104. bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
  3105. if (stream_.doConvertBuffer[1]) {
  3106. // Always interleave ASIO input data.
  3107. for ( i=0, j=0; i<nChannels; i++ ) {
  3108. if ( handle->bufferInfos[i].isInput == ASIOTrue )
  3109. memcpy( &stream_.deviceBuffer[j++*bufferBytes],
  3110. handle->bufferInfos[i].buffers[bufferIndex],
  3111. bufferBytes );
  3112. }
  3113. if ( stream_.doByteSwap[1] )
  3114. byteSwapBuffer( stream_.deviceBuffer,
  3115. stream_.bufferSize * stream_.nDeviceChannels[1],
  3116. stream_.deviceFormat[1] );
  3117. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  3118. }
  3119. else {
  3120. for ( i=0, j=0; i<nChannels; i++ ) {
  3121. if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
  3122. memcpy( &stream_.userBuffer[1][bufferBytes*j++],
  3123. handle->bufferInfos[i].buffers[bufferIndex],
  3124. bufferBytes );
  3125. }
  3126. }
  3127. if ( stream_.doByteSwap[1] )
  3128. byteSwapBuffer( stream_.userBuffer[1],
  3129. stream_.bufferSize * stream_.nUserChannels[1],
  3130. stream_.userFormat );
  3131. }
  3132. }
  3133. unlock:
  3134. // The following call was suggested by Malte Clasen. While the API
  3135. // documentation indicates it should not be required, some device
  3136. // drivers apparently do not function correctly without it.
  3137. ASIOOutputReady();
  3138. RtApi::tickStreamTime();
  3139. return SUCCESS;
  3140. }
  3141. static void sampleRateChanged( ASIOSampleRate sRate )
  3142. {
  3143. // The ASIO documentation says that this usually only happens during
  3144. // external sync. Audio processing is not stopped by the driver,
  3145. // actual sample rate might not have even changed, maybe only the
  3146. // sample rate status of an AES/EBU or S/PDIF digital input at the
  3147. // audio device.
  3148. RtApi *object = (RtApi *) asioCallbackInfo->object;
  3149. try {
  3150. object->stopStream();
  3151. }
  3152. catch ( RtAudioError &exception ) {
  3153. std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
  3154. return;
  3155. }
  3156. std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
  3157. }
  3158. static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )
  3159. {
  3160. long ret = 0;
  3161. switch( selector ) {
  3162. case kAsioSelectorSupported:
  3163. if ( value == kAsioResetRequest
  3164. || value == kAsioEngineVersion
  3165. || value == kAsioResyncRequest
  3166. || value == kAsioLatenciesChanged
  3167. // The following three were added for ASIO 2.0, you don't
  3168. // necessarily have to support them.
  3169. || value == kAsioSupportsTimeInfo
  3170. || value == kAsioSupportsTimeCode
  3171. || value == kAsioSupportsInputMonitor)
  3172. ret = 1L;
  3173. break;
  3174. case kAsioResetRequest:
  3175. // Defer the task and perform the reset of the driver during the
  3176. // next "safe" situation. You cannot reset the driver right now,
  3177. // as this code is called from the driver. Reset the driver is
  3178. // done by completely destruct is. I.e. ASIOStop(),
  3179. // ASIODisposeBuffers(), Destruction Afterwards you initialize the
  3180. // driver again.
  3181. std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
  3182. ret = 1L;
  3183. break;
  3184. case kAsioResyncRequest:
  3185. // This informs the application that the driver encountered some
  3186. // non-fatal data loss. It is used for synchronization purposes
  3187. // of different media. Added mainly to work around the Win16Mutex
  3188. // problems in Windows 95/98 with the Windows Multimedia system,
  3189. // which could lose data because the Mutex was held too long by
  3190. // another thread. However a driver can issue it in other
  3191. // situations, too.
  3192. // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
  3193. asioXRun = true;
  3194. ret = 1L;
  3195. break;
  3196. case kAsioLatenciesChanged:
  3197. // This will inform the host application that the drivers were
  3198. // latencies changed. Beware, it this does not mean that the
  3199. // buffer sizes have changed! You might need to update internal
  3200. // delay data.
  3201. std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
  3202. ret = 1L;
  3203. break;
  3204. case kAsioEngineVersion:
  3205. // Return the supported ASIO version of the host application. If
  3206. // a host application does not implement this selector, ASIO 1.0
  3207. // is assumed by the driver.
  3208. ret = 2L;
  3209. break;
  3210. case kAsioSupportsTimeInfo:
  3211. // Informs the driver whether the
  3212. // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
  3213. // For compatibility with ASIO 1.0 drivers the host application
  3214. // should always support the "old" bufferSwitch method, too.
  3215. ret = 0;
  3216. break;
  3217. case kAsioSupportsTimeCode:
  3218. // Informs the driver whether application is interested in time
  3219. // code info. If an application does not need to know about time
  3220. // code, the driver has less work to do.
  3221. ret = 0;
  3222. break;
  3223. }
  3224. return ret;
  3225. }
  3226. static const char* getAsioErrorString( ASIOError result )
  3227. {
  3228. struct Messages
  3229. {
  3230. ASIOError value;
  3231. const char*message;
  3232. };
  3233. static const Messages m[] =
  3234. {
  3235. { ASE_NotPresent, "Hardware input or output is not present or available." },
  3236. { ASE_HWMalfunction, "Hardware is malfunctioning." },
  3237. { ASE_InvalidParameter, "Invalid input parameter." },
  3238. { ASE_InvalidMode, "Invalid mode." },
  3239. { ASE_SPNotAdvancing, "Sample position not advancing." },
  3240. { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." },
  3241. { ASE_NoMemory, "Not enough memory to complete the request." }
  3242. };
  3243. for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
  3244. if ( m[i].value == result ) return m[i].message;
  3245. return "Unknown error.";
  3246. }
  3247. //******************** End of __WINDOWS_ASIO__ *********************//
  3248. #endif
  3249. #if defined(__WINDOWS_WASAPI__) // Windows WASAPI API
  3250. // Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014
  3251. // - Introduces support for the Windows WASAPI API
  3252. // - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required
  3253. // - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface
  3254. // - Includes automatic internal conversion of sample rate and buffer size between hardware and the user
  3255. #ifndef INITGUID
  3256. #define INITGUID
  3257. #endif
  3258. #include <mfapi.h>
  3259. #include <mferror.h>
  3260. #include <mfplay.h>
  3261. #include <mftransform.h>
  3262. #include <wmcodecdsp.h>
  3263. #include <audioclient.h>
  3264. #include <avrt.h>
  3265. #include <mmdeviceapi.h>
  3266. #include <functiondiscoverykeys_devpkey.h>
  3267. #ifndef MF_E_TRANSFORM_NEED_MORE_INPUT
  3268. #define MF_E_TRANSFORM_NEED_MORE_INPUT _HRESULT_TYPEDEF_(0xc00d6d72)
  3269. #endif
  3270. #ifndef MFSTARTUP_NOSOCKET
  3271. #define MFSTARTUP_NOSOCKET 0x1
  3272. #endif
  3273. #ifdef _MSC_VER
  3274. #pragma comment( lib, "ksuser" )
  3275. #pragma comment( lib, "mfplat.lib" )
  3276. #pragma comment( lib, "mfuuid.lib" )
  3277. #pragma comment( lib, "wmcodecdspuuid" )
  3278. #endif
  3279. //=============================================================================
  3280. #define SAFE_RELEASE( objectPtr )\
  3281. if ( objectPtr )\
  3282. {\
  3283. objectPtr->Release();\
  3284. objectPtr = NULL;\
  3285. }
  3286. typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );
  3287. //-----------------------------------------------------------------------------
  3288. // WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.
  3289. // Therefore we must perform all necessary conversions to user buffers in order to satisfy these
  3290. // requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to
  3291. // provide intermediate storage for read / write synchronization.
  3292. class WasapiBuffer
  3293. {
  3294. public:
  3295. WasapiBuffer()
  3296. : buffer_( NULL ),
  3297. bufferSize_( 0 ),
  3298. inIndex_( 0 ),
  3299. outIndex_( 0 ) {}
  3300. ~WasapiBuffer() {
  3301. free( buffer_ );
  3302. }
  3303. // sets the length of the internal ring buffer
  3304. void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {
  3305. free( buffer_ );
  3306. buffer_ = ( char* ) calloc( bufferSize, formatBytes );
  3307. bufferSize_ = bufferSize;
  3308. inIndex_ = 0;
  3309. outIndex_ = 0;
  3310. }
  3311. // attempt to push a buffer into the ring buffer at the current "in" index
  3312. bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3313. {
  3314. if ( !buffer || // incoming buffer is NULL
  3315. bufferSize == 0 || // incoming buffer has no data
  3316. bufferSize > bufferSize_ ) // incoming buffer too large
  3317. {
  3318. return false;
  3319. }
  3320. unsigned int relOutIndex = outIndex_;
  3321. unsigned int inIndexEnd = inIndex_ + bufferSize;
  3322. if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {
  3323. relOutIndex += bufferSize_;
  3324. }
  3325. // the "IN" index CAN BEGIN at the "OUT" index
  3326. // the "IN" index CANNOT END at the "OUT" index
  3327. if ( inIndex_ < relOutIndex && inIndexEnd >= relOutIndex ) {
  3328. return false; // not enough space between "in" index and "out" index
  3329. }
  3330. // copy buffer from external to internal
  3331. int fromZeroSize = inIndex_ + bufferSize - bufferSize_;
  3332. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3333. int fromInSize = bufferSize - fromZeroSize;
  3334. switch( format )
  3335. {
  3336. case RTAUDIO_SINT8:
  3337. memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );
  3338. memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );
  3339. break;
  3340. case RTAUDIO_SINT16:
  3341. memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );
  3342. memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );
  3343. break;
  3344. case RTAUDIO_SINT24:
  3345. memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );
  3346. memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );
  3347. break;
  3348. case RTAUDIO_SINT32:
  3349. memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );
  3350. memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );
  3351. break;
  3352. case RTAUDIO_FLOAT32:
  3353. memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );
  3354. memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );
  3355. break;
  3356. case RTAUDIO_FLOAT64:
  3357. memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );
  3358. memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );
  3359. break;
  3360. }
  3361. // update "in" index
  3362. inIndex_ += bufferSize;
  3363. inIndex_ %= bufferSize_;
  3364. return true;
  3365. }
  3366. // attempt to pull a buffer from the ring buffer from the current "out" index
  3367. bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )
  3368. {
  3369. if ( !buffer || // incoming buffer is NULL
  3370. bufferSize == 0 || // incoming buffer has no data
  3371. bufferSize > bufferSize_ ) // incoming buffer too large
  3372. {
  3373. return false;
  3374. }
  3375. unsigned int relInIndex = inIndex_;
  3376. unsigned int outIndexEnd = outIndex_ + bufferSize;
  3377. if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {
  3378. relInIndex += bufferSize_;
  3379. }
  3380. // the "OUT" index CANNOT BEGIN at the "IN" index
  3381. // the "OUT" index CAN END at the "IN" index
  3382. if ( outIndex_ <= relInIndex && outIndexEnd > relInIndex ) {
  3383. return false; // not enough space between "out" index and "in" index
  3384. }
  3385. // copy buffer from internal to external
  3386. int fromZeroSize = outIndex_ + bufferSize - bufferSize_;
  3387. fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;
  3388. int fromOutSize = bufferSize - fromZeroSize;
  3389. switch( format )
  3390. {
  3391. case RTAUDIO_SINT8:
  3392. memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );
  3393. memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );
  3394. break;
  3395. case RTAUDIO_SINT16:
  3396. memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );
  3397. memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );
  3398. break;
  3399. case RTAUDIO_SINT24:
  3400. memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );
  3401. memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );
  3402. break;
  3403. case RTAUDIO_SINT32:
  3404. memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );
  3405. memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );
  3406. break;
  3407. case RTAUDIO_FLOAT32:
  3408. memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );
  3409. memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );
  3410. break;
  3411. case RTAUDIO_FLOAT64:
  3412. memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );
  3413. memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );
  3414. break;
  3415. }
  3416. // update "out" index
  3417. outIndex_ += bufferSize;
  3418. outIndex_ %= bufferSize_;
  3419. return true;
  3420. }
  3421. private:
  3422. char* buffer_;
  3423. unsigned int bufferSize_;
  3424. unsigned int inIndex_;
  3425. unsigned int outIndex_;
  3426. };
  3427. //-----------------------------------------------------------------------------
  3428. // In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate
  3429. // between HW and the user. The WasapiResampler class is used to perform this conversion between
  3430. // HwIn->UserIn and UserOut->HwOut during the stream callback loop.
  3431. class WasapiResampler
  3432. {
  3433. public:
  3434. WasapiResampler( bool isFloat, unsigned int bitsPerSample, unsigned int channelCount,
  3435. unsigned int inSampleRate, unsigned int outSampleRate )
  3436. : _bytesPerSample( bitsPerSample / 8 )
  3437. , _channelCount( channelCount )
  3438. , _sampleRatio( ( float ) outSampleRate / inSampleRate )
  3439. , _transformUnk( NULL )
  3440. , _transform( NULL )
  3441. , _mediaType( NULL )
  3442. , _inputMediaType( NULL )
  3443. , _outputMediaType( NULL )
  3444. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3445. , _resamplerProps( NULL )
  3446. #endif
  3447. {
  3448. // 1. Initialization
  3449. MFStartup( MF_VERSION, MFSTARTUP_NOSOCKET );
  3450. // 2. Create Resampler Transform Object
  3451. CoCreateInstance( CLSID_CResamplerMediaObject, NULL, CLSCTX_INPROC_SERVER,
  3452. IID_IUnknown, ( void** ) &_transformUnk );
  3453. _transformUnk->QueryInterface( IID_PPV_ARGS( &_transform ) );
  3454. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3455. _transformUnk->QueryInterface( IID_PPV_ARGS( &_resamplerProps ) );
  3456. _resamplerProps->SetHalfFilterLength( 60 ); // best conversion quality
  3457. #endif
  3458. // 3. Specify input / output format
  3459. MFCreateMediaType( &_mediaType );
  3460. _mediaType->SetGUID( MF_MT_MAJOR_TYPE, MFMediaType_Audio );
  3461. _mediaType->SetGUID( MF_MT_SUBTYPE, isFloat ? MFAudioFormat_Float : MFAudioFormat_PCM );
  3462. _mediaType->SetUINT32( MF_MT_AUDIO_NUM_CHANNELS, channelCount );
  3463. _mediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, inSampleRate );
  3464. _mediaType->SetUINT32( MF_MT_AUDIO_BLOCK_ALIGNMENT, _bytesPerSample * channelCount );
  3465. _mediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * inSampleRate );
  3466. _mediaType->SetUINT32( MF_MT_AUDIO_BITS_PER_SAMPLE, bitsPerSample );
  3467. _mediaType->SetUINT32( MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE );
  3468. MFCreateMediaType( &_inputMediaType );
  3469. _mediaType->CopyAllItems( _inputMediaType );
  3470. _transform->SetInputType( 0, _inputMediaType, 0 );
  3471. MFCreateMediaType( &_outputMediaType );
  3472. _mediaType->CopyAllItems( _outputMediaType );
  3473. _outputMediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, outSampleRate );
  3474. _outputMediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * outSampleRate );
  3475. _transform->SetOutputType( 0, _outputMediaType, 0 );
  3476. // 4. Send stream start messages to Resampler
  3477. _transform->ProcessMessage( MFT_MESSAGE_COMMAND_FLUSH, 0 );
  3478. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0 );
  3479. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0 );
  3480. }
  3481. ~WasapiResampler()
  3482. {
  3483. // 8. Send stream stop messages to Resampler
  3484. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0 );
  3485. _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_STREAMING, 0 );
  3486. // 9. Cleanup
  3487. MFShutdown();
  3488. SAFE_RELEASE( _transformUnk );
  3489. SAFE_RELEASE( _transform );
  3490. SAFE_RELEASE( _mediaType );
  3491. SAFE_RELEASE( _inputMediaType );
  3492. SAFE_RELEASE( _outputMediaType );
  3493. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3494. SAFE_RELEASE( _resamplerProps );
  3495. #endif
  3496. }
  3497. void Convert( char* outBuffer, const char* inBuffer, unsigned int inSampleCount, unsigned int& outSampleCount )
  3498. {
  3499. unsigned int inputBufferSize = _bytesPerSample * _channelCount * inSampleCount;
  3500. if ( _sampleRatio == 1 )
  3501. {
  3502. // no sample rate conversion required
  3503. memcpy( outBuffer, inBuffer, inputBufferSize );
  3504. outSampleCount = inSampleCount;
  3505. return;
  3506. }
  3507. unsigned int outputBufferSize = ( unsigned int ) ceilf( inputBufferSize * _sampleRatio ) + ( _bytesPerSample * _channelCount );
  3508. IMFMediaBuffer* rInBuffer;
  3509. IMFSample* rInSample;
  3510. BYTE* rInByteBuffer = NULL;
  3511. // 5. Create Sample object from input data
  3512. MFCreateMemoryBuffer( inputBufferSize, &rInBuffer );
  3513. rInBuffer->Lock( &rInByteBuffer, NULL, NULL );
  3514. memcpy( rInByteBuffer, inBuffer, inputBufferSize );
  3515. rInBuffer->Unlock();
  3516. rInByteBuffer = NULL;
  3517. rInBuffer->SetCurrentLength( inputBufferSize );
  3518. MFCreateSample( &rInSample );
  3519. rInSample->AddBuffer( rInBuffer );
  3520. // 6. Pass input data to Resampler
  3521. _transform->ProcessInput( 0, rInSample, 0 );
  3522. SAFE_RELEASE( rInBuffer );
  3523. SAFE_RELEASE( rInSample );
  3524. // 7. Perform sample rate conversion
  3525. IMFMediaBuffer* rOutBuffer = NULL;
  3526. BYTE* rOutByteBuffer = NULL;
  3527. MFT_OUTPUT_DATA_BUFFER rOutDataBuffer;
  3528. DWORD rStatus;
  3529. DWORD rBytes = outputBufferSize; // maximum bytes accepted per ProcessOutput
  3530. // 7.1 Create Sample object for output data
  3531. memset( &rOutDataBuffer, 0, sizeof rOutDataBuffer );
  3532. MFCreateSample( &( rOutDataBuffer.pSample ) );
  3533. MFCreateMemoryBuffer( rBytes, &rOutBuffer );
  3534. rOutDataBuffer.pSample->AddBuffer( rOutBuffer );
  3535. rOutDataBuffer.dwStreamID = 0;
  3536. rOutDataBuffer.dwStatus = 0;
  3537. rOutDataBuffer.pEvents = NULL;
  3538. // 7.2 Get output data from Resampler
  3539. if ( _transform->ProcessOutput( 0, 1, &rOutDataBuffer, &rStatus ) == MF_E_TRANSFORM_NEED_MORE_INPUT )
  3540. {
  3541. outSampleCount = 0;
  3542. SAFE_RELEASE( rOutBuffer );
  3543. SAFE_RELEASE( rOutDataBuffer.pSample );
  3544. return;
  3545. }
  3546. // 7.3 Write output data to outBuffer
  3547. SAFE_RELEASE( rOutBuffer );
  3548. rOutDataBuffer.pSample->ConvertToContiguousBuffer( &rOutBuffer );
  3549. rOutBuffer->GetCurrentLength( &rBytes );
  3550. rOutBuffer->Lock( &rOutByteBuffer, NULL, NULL );
  3551. memcpy( outBuffer, rOutByteBuffer, rBytes );
  3552. rOutBuffer->Unlock();
  3553. rOutByteBuffer = NULL;
  3554. outSampleCount = rBytes / _bytesPerSample / _channelCount;
  3555. SAFE_RELEASE( rOutBuffer );
  3556. SAFE_RELEASE( rOutDataBuffer.pSample );
  3557. }
  3558. private:
  3559. unsigned int _bytesPerSample;
  3560. unsigned int _channelCount;
  3561. float _sampleRatio;
  3562. IUnknown* _transformUnk;
  3563. IMFTransform* _transform;
  3564. IMFMediaType* _mediaType;
  3565. IMFMediaType* _inputMediaType;
  3566. IMFMediaType* _outputMediaType;
  3567. #ifdef __IWMResamplerProps_FWD_DEFINED__
  3568. IWMResamplerProps* _resamplerProps;
  3569. #endif
  3570. };
  3571. //-----------------------------------------------------------------------------
  3572. // A structure to hold various information related to the WASAPI implementation.
  3573. struct WasapiHandle
  3574. {
  3575. IAudioClient* captureAudioClient;
  3576. IAudioClient* renderAudioClient;
  3577. IAudioCaptureClient* captureClient;
  3578. IAudioRenderClient* renderClient;
  3579. HANDLE captureEvent;
  3580. HANDLE renderEvent;
  3581. WasapiHandle()
  3582. : captureAudioClient( NULL ),
  3583. renderAudioClient( NULL ),
  3584. captureClient( NULL ),
  3585. renderClient( NULL ),
  3586. captureEvent( NULL ),
  3587. renderEvent( NULL ) {}
  3588. };
  3589. //=============================================================================
  3590. RtApiWasapi::RtApiWasapi()
  3591. : coInitialized_( false ), deviceEnumerator_( NULL )
  3592. {
  3593. // WASAPI can run either apartment or multi-threaded
  3594. HRESULT hr = CoInitialize( NULL );
  3595. if ( !FAILED( hr ) )
  3596. coInitialized_ = true;
  3597. // Instantiate device enumerator
  3598. hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
  3599. CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),
  3600. ( void** ) &deviceEnumerator_ );
  3601. // If this runs on an old Windows, it will fail. Ignore and proceed.
  3602. if ( FAILED( hr ) )
  3603. deviceEnumerator_ = NULL;
  3604. }
  3605. //-----------------------------------------------------------------------------
  3606. RtApiWasapi::~RtApiWasapi()
  3607. {
  3608. if ( stream_.state != STREAM_CLOSED )
  3609. closeStream();
  3610. SAFE_RELEASE( deviceEnumerator_ );
  3611. // If this object previously called CoInitialize()
  3612. if ( coInitialized_ )
  3613. CoUninitialize();
  3614. }
  3615. //=============================================================================
  3616. unsigned int RtApiWasapi::getDeviceCount( void )
  3617. {
  3618. unsigned int captureDeviceCount = 0;
  3619. unsigned int renderDeviceCount = 0;
  3620. IMMDeviceCollection* captureDevices = NULL;
  3621. IMMDeviceCollection* renderDevices = NULL;
  3622. if ( !deviceEnumerator_ )
  3623. return 0;
  3624. // Count capture devices
  3625. errorText_.clear();
  3626. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3627. if ( FAILED( hr ) ) {
  3628. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";
  3629. goto Exit;
  3630. }
  3631. hr = captureDevices->GetCount( &captureDeviceCount );
  3632. if ( FAILED( hr ) ) {
  3633. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";
  3634. goto Exit;
  3635. }
  3636. // Count render devices
  3637. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3638. if ( FAILED( hr ) ) {
  3639. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";
  3640. goto Exit;
  3641. }
  3642. hr = renderDevices->GetCount( &renderDeviceCount );
  3643. if ( FAILED( hr ) ) {
  3644. errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";
  3645. goto Exit;
  3646. }
  3647. Exit:
  3648. // release all references
  3649. SAFE_RELEASE( captureDevices );
  3650. SAFE_RELEASE( renderDevices );
  3651. if ( errorText_.empty() )
  3652. return captureDeviceCount + renderDeviceCount;
  3653. error( RtAudioError::DRIVER_ERROR );
  3654. return 0;
  3655. }
  3656. //-----------------------------------------------------------------------------
  3657. RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
  3658. {
  3659. RtAudio::DeviceInfo info;
  3660. unsigned int captureDeviceCount = 0;
  3661. unsigned int renderDeviceCount = 0;
  3662. std::string defaultDeviceName;
  3663. bool isCaptureDevice = false;
  3664. PROPVARIANT deviceNameProp;
  3665. PROPVARIANT defaultDeviceNameProp;
  3666. IMMDeviceCollection* captureDevices = NULL;
  3667. IMMDeviceCollection* renderDevices = NULL;
  3668. IMMDevice* devicePtr = NULL;
  3669. IMMDevice* defaultDevicePtr = NULL;
  3670. IAudioClient* audioClient = NULL;
  3671. IPropertyStore* devicePropStore = NULL;
  3672. IPropertyStore* defaultDevicePropStore = NULL;
  3673. WAVEFORMATEX* deviceFormat = NULL;
  3674. WAVEFORMATEX* closestMatchFormat = NULL;
  3675. // probed
  3676. info.probed = false;
  3677. // Count capture devices
  3678. errorText_.clear();
  3679. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3680. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3681. if ( FAILED( hr ) ) {
  3682. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";
  3683. goto Exit;
  3684. }
  3685. hr = captureDevices->GetCount( &captureDeviceCount );
  3686. if ( FAILED( hr ) ) {
  3687. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";
  3688. goto Exit;
  3689. }
  3690. // Count render devices
  3691. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  3692. if ( FAILED( hr ) ) {
  3693. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";
  3694. goto Exit;
  3695. }
  3696. hr = renderDevices->GetCount( &renderDeviceCount );
  3697. if ( FAILED( hr ) ) {
  3698. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";
  3699. goto Exit;
  3700. }
  3701. // validate device index
  3702. if ( device >= captureDeviceCount + renderDeviceCount ) {
  3703. errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";
  3704. errorType = RtAudioError::INVALID_USE;
  3705. goto Exit;
  3706. }
  3707. // determine whether index falls within capture or render devices
  3708. if ( device >= renderDeviceCount ) {
  3709. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  3710. if ( FAILED( hr ) ) {
  3711. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";
  3712. goto Exit;
  3713. }
  3714. isCaptureDevice = true;
  3715. }
  3716. else {
  3717. hr = renderDevices->Item( device, &devicePtr );
  3718. if ( FAILED( hr ) ) {
  3719. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";
  3720. goto Exit;
  3721. }
  3722. isCaptureDevice = false;
  3723. }
  3724. // get default device name
  3725. if ( isCaptureDevice ) {
  3726. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );
  3727. if ( FAILED( hr ) ) {
  3728. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";
  3729. goto Exit;
  3730. }
  3731. }
  3732. else {
  3733. hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );
  3734. if ( FAILED( hr ) ) {
  3735. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";
  3736. goto Exit;
  3737. }
  3738. }
  3739. hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );
  3740. if ( FAILED( hr ) ) {
  3741. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";
  3742. goto Exit;
  3743. }
  3744. PropVariantInit( &defaultDeviceNameProp );
  3745. hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );
  3746. if ( FAILED( hr ) ) {
  3747. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";
  3748. goto Exit;
  3749. }
  3750. defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);
  3751. // name
  3752. hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );
  3753. if ( FAILED( hr ) ) {
  3754. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";
  3755. goto Exit;
  3756. }
  3757. PropVariantInit( &deviceNameProp );
  3758. hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );
  3759. if ( FAILED( hr ) ) {
  3760. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";
  3761. goto Exit;
  3762. }
  3763. info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);
  3764. // is default
  3765. if ( isCaptureDevice ) {
  3766. info.isDefaultInput = info.name == defaultDeviceName;
  3767. info.isDefaultOutput = false;
  3768. }
  3769. else {
  3770. info.isDefaultInput = false;
  3771. info.isDefaultOutput = info.name == defaultDeviceName;
  3772. }
  3773. // channel count
  3774. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );
  3775. if ( FAILED( hr ) ) {
  3776. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";
  3777. goto Exit;
  3778. }
  3779. hr = audioClient->GetMixFormat( &deviceFormat );
  3780. if ( FAILED( hr ) ) {
  3781. errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";
  3782. goto Exit;
  3783. }
  3784. if ( isCaptureDevice ) {
  3785. info.inputChannels = deviceFormat->nChannels;
  3786. info.outputChannels = 0;
  3787. info.duplexChannels = 0;
  3788. }
  3789. else {
  3790. info.inputChannels = 0;
  3791. info.outputChannels = deviceFormat->nChannels;
  3792. info.duplexChannels = 0;
  3793. }
  3794. // sample rates
  3795. info.sampleRates.clear();
  3796. // allow support for all sample rates as we have a built-in sample rate converter
  3797. for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {
  3798. info.sampleRates.push_back( SAMPLE_RATES[i] );
  3799. }
  3800. info.preferredSampleRate = deviceFormat->nSamplesPerSec;
  3801. // native format
  3802. info.nativeFormats = 0;
  3803. if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
  3804. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3805. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )
  3806. {
  3807. if ( deviceFormat->wBitsPerSample == 32 ) {
  3808. info.nativeFormats |= RTAUDIO_FLOAT32;
  3809. }
  3810. else if ( deviceFormat->wBitsPerSample == 64 ) {
  3811. info.nativeFormats |= RTAUDIO_FLOAT64;
  3812. }
  3813. }
  3814. else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||
  3815. ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
  3816. ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )
  3817. {
  3818. if ( deviceFormat->wBitsPerSample == 8 ) {
  3819. info.nativeFormats |= RTAUDIO_SINT8;
  3820. }
  3821. else if ( deviceFormat->wBitsPerSample == 16 ) {
  3822. info.nativeFormats |= RTAUDIO_SINT16;
  3823. }
  3824. else if ( deviceFormat->wBitsPerSample == 24 ) {
  3825. info.nativeFormats |= RTAUDIO_SINT24;
  3826. }
  3827. else if ( deviceFormat->wBitsPerSample == 32 ) {
  3828. info.nativeFormats |= RTAUDIO_SINT32;
  3829. }
  3830. }
  3831. // probed
  3832. info.probed = true;
  3833. Exit:
  3834. // release all references
  3835. PropVariantClear( &deviceNameProp );
  3836. PropVariantClear( &defaultDeviceNameProp );
  3837. SAFE_RELEASE( captureDevices );
  3838. SAFE_RELEASE( renderDevices );
  3839. SAFE_RELEASE( devicePtr );
  3840. SAFE_RELEASE( defaultDevicePtr );
  3841. SAFE_RELEASE( audioClient );
  3842. SAFE_RELEASE( devicePropStore );
  3843. SAFE_RELEASE( defaultDevicePropStore );
  3844. CoTaskMemFree( deviceFormat );
  3845. CoTaskMemFree( closestMatchFormat );
  3846. if ( !errorText_.empty() )
  3847. error( errorType );
  3848. return info;
  3849. }
  3850. //-----------------------------------------------------------------------------
  3851. unsigned int RtApiWasapi::getDefaultOutputDevice( void )
  3852. {
  3853. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3854. if ( getDeviceInfo( i ).isDefaultOutput ) {
  3855. return i;
  3856. }
  3857. }
  3858. return 0;
  3859. }
  3860. //-----------------------------------------------------------------------------
  3861. unsigned int RtApiWasapi::getDefaultInputDevice( void )
  3862. {
  3863. for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {
  3864. if ( getDeviceInfo( i ).isDefaultInput ) {
  3865. return i;
  3866. }
  3867. }
  3868. return 0;
  3869. }
  3870. //-----------------------------------------------------------------------------
  3871. void RtApiWasapi::closeStream( void )
  3872. {
  3873. if ( stream_.state == STREAM_CLOSED ) {
  3874. errorText_ = "RtApiWasapi::closeStream: No open stream to close.";
  3875. error( RtAudioError::WARNING );
  3876. return;
  3877. }
  3878. if ( stream_.state != STREAM_STOPPED )
  3879. stopStream();
  3880. // clean up stream memory
  3881. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )
  3882. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )
  3883. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )
  3884. SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )
  3885. if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )
  3886. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );
  3887. if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )
  3888. CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );
  3889. delete ( WasapiHandle* ) stream_.apiHandle;
  3890. stream_.apiHandle = NULL;
  3891. for ( int i = 0; i < 2; i++ ) {
  3892. if ( stream_.userBuffer[i] ) {
  3893. free( stream_.userBuffer[i] );
  3894. stream_.userBuffer[i] = 0;
  3895. }
  3896. }
  3897. if ( stream_.deviceBuffer ) {
  3898. free( stream_.deviceBuffer );
  3899. stream_.deviceBuffer = 0;
  3900. }
  3901. // update stream state
  3902. stream_.state = STREAM_CLOSED;
  3903. }
  3904. //-----------------------------------------------------------------------------
  3905. void RtApiWasapi::startStream( void )
  3906. {
  3907. verifyStream();
  3908. if ( stream_.state == STREAM_RUNNING ) {
  3909. errorText_ = "RtApiWasapi::startStream: The stream is already running.";
  3910. error( RtAudioError::WARNING );
  3911. return;
  3912. }
  3913. #if defined( HAVE_GETTIMEOFDAY )
  3914. gettimeofday( &stream_.lastTickTimestamp, NULL );
  3915. #endif
  3916. // update stream state
  3917. stream_.state = STREAM_RUNNING;
  3918. // create WASAPI stream thread
  3919. stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );
  3920. if ( !stream_.callbackInfo.thread ) {
  3921. errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";
  3922. error( RtAudioError::THREAD_ERROR );
  3923. }
  3924. else {
  3925. SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );
  3926. ResumeThread( ( void* ) stream_.callbackInfo.thread );
  3927. }
  3928. }
  3929. //-----------------------------------------------------------------------------
  3930. void RtApiWasapi::stopStream( void )
  3931. {
  3932. verifyStream();
  3933. if ( stream_.state == STREAM_STOPPED ) {
  3934. errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";
  3935. error( RtAudioError::WARNING );
  3936. return;
  3937. }
  3938. // inform stream thread by setting stream state to STREAM_STOPPING
  3939. stream_.state = STREAM_STOPPING;
  3940. // wait until stream thread is stopped
  3941. while( stream_.state != STREAM_STOPPED ) {
  3942. Sleep( 1 );
  3943. }
  3944. // Wait for the last buffer to play before stopping.
  3945. Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );
  3946. // close thread handle
  3947. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3948. errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";
  3949. error( RtAudioError::THREAD_ERROR );
  3950. return;
  3951. }
  3952. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3953. }
  3954. //-----------------------------------------------------------------------------
  3955. void RtApiWasapi::abortStream( void )
  3956. {
  3957. verifyStream();
  3958. if ( stream_.state == STREAM_STOPPED ) {
  3959. errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";
  3960. error( RtAudioError::WARNING );
  3961. return;
  3962. }
  3963. // inform stream thread by setting stream state to STREAM_STOPPING
  3964. stream_.state = STREAM_STOPPING;
  3965. // wait until stream thread is stopped
  3966. while ( stream_.state != STREAM_STOPPED ) {
  3967. Sleep( 1 );
  3968. }
  3969. // close thread handle
  3970. if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {
  3971. errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";
  3972. error( RtAudioError::THREAD_ERROR );
  3973. return;
  3974. }
  3975. stream_.callbackInfo.thread = (ThreadHandle) NULL;
  3976. }
  3977. //-----------------------------------------------------------------------------
  3978. bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  3979. unsigned int firstChannel, unsigned int sampleRate,
  3980. RtAudioFormat format, unsigned int* bufferSize,
  3981. RtAudio::StreamOptions* options )
  3982. {
  3983. bool methodResult = FAILURE;
  3984. unsigned int captureDeviceCount = 0;
  3985. unsigned int renderDeviceCount = 0;
  3986. IMMDeviceCollection* captureDevices = NULL;
  3987. IMMDeviceCollection* renderDevices = NULL;
  3988. IMMDevice* devicePtr = NULL;
  3989. WAVEFORMATEX* deviceFormat = NULL;
  3990. unsigned int bufferBytes;
  3991. stream_.state = STREAM_STOPPED;
  3992. // create API Handle if not already created
  3993. if ( !stream_.apiHandle )
  3994. stream_.apiHandle = ( void* ) new WasapiHandle();
  3995. // Count capture devices
  3996. errorText_.clear();
  3997. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  3998. HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );
  3999. if ( FAILED( hr ) ) {
  4000. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";
  4001. goto Exit;
  4002. }
  4003. hr = captureDevices->GetCount( &captureDeviceCount );
  4004. if ( FAILED( hr ) ) {
  4005. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";
  4006. goto Exit;
  4007. }
  4008. // Count render devices
  4009. hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );
  4010. if ( FAILED( hr ) ) {
  4011. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";
  4012. goto Exit;
  4013. }
  4014. hr = renderDevices->GetCount( &renderDeviceCount );
  4015. if ( FAILED( hr ) ) {
  4016. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";
  4017. goto Exit;
  4018. }
  4019. // validate device index
  4020. if ( device >= captureDeviceCount + renderDeviceCount ) {
  4021. errorType = RtAudioError::INVALID_USE;
  4022. errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";
  4023. goto Exit;
  4024. }
  4025. // if device index falls within capture devices
  4026. if ( device >= renderDeviceCount ) {
  4027. if ( mode != INPUT ) {
  4028. errorType = RtAudioError::INVALID_USE;
  4029. errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";
  4030. goto Exit;
  4031. }
  4032. // retrieve captureAudioClient from devicePtr
  4033. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4034. hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );
  4035. if ( FAILED( hr ) ) {
  4036. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";
  4037. goto Exit;
  4038. }
  4039. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4040. NULL, ( void** ) &captureAudioClient );
  4041. if ( FAILED( hr ) ) {
  4042. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device audio client.";
  4043. goto Exit;
  4044. }
  4045. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  4046. if ( FAILED( hr ) ) {
  4047. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device mix format.";
  4048. goto Exit;
  4049. }
  4050. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4051. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4052. }
  4053. // if device index falls within render devices and is configured for loopback
  4054. if ( device < renderDeviceCount && mode == INPUT )
  4055. {
  4056. // if renderAudioClient is not initialised, initialise it now
  4057. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4058. if ( !renderAudioClient )
  4059. {
  4060. probeDeviceOpen( device, OUTPUT, channels, firstChannel, sampleRate, format, bufferSize, options );
  4061. }
  4062. // retrieve captureAudioClient from devicePtr
  4063. IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4064. hr = renderDevices->Item( device, &devicePtr );
  4065. if ( FAILED( hr ) ) {
  4066. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  4067. goto Exit;
  4068. }
  4069. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4070. NULL, ( void** ) &captureAudioClient );
  4071. if ( FAILED( hr ) ) {
  4072. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
  4073. goto Exit;
  4074. }
  4075. hr = captureAudioClient->GetMixFormat( &deviceFormat );
  4076. if ( FAILED( hr ) ) {
  4077. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
  4078. goto Exit;
  4079. }
  4080. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4081. captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4082. }
  4083. // if device index falls within render devices and is configured for output
  4084. if ( device < renderDeviceCount && mode == OUTPUT )
  4085. {
  4086. // if renderAudioClient is already initialised, don't initialise it again
  4087. IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4088. if ( renderAudioClient )
  4089. {
  4090. methodResult = SUCCESS;
  4091. goto Exit;
  4092. }
  4093. hr = renderDevices->Item( device, &devicePtr );
  4094. if ( FAILED( hr ) ) {
  4095. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";
  4096. goto Exit;
  4097. }
  4098. hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,
  4099. NULL, ( void** ) &renderAudioClient );
  4100. if ( FAILED( hr ) ) {
  4101. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client.";
  4102. goto Exit;
  4103. }
  4104. hr = renderAudioClient->GetMixFormat( &deviceFormat );
  4105. if ( FAILED( hr ) ) {
  4106. errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format.";
  4107. goto Exit;
  4108. }
  4109. stream_.nDeviceChannels[mode] = deviceFormat->nChannels;
  4110. renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );
  4111. }
  4112. // fill stream data
  4113. if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||
  4114. ( stream_.mode == INPUT && mode == OUTPUT ) ) {
  4115. stream_.mode = DUPLEX;
  4116. }
  4117. else {
  4118. stream_.mode = mode;
  4119. }
  4120. stream_.device[mode] = device;
  4121. stream_.doByteSwap[mode] = false;
  4122. stream_.sampleRate = sampleRate;
  4123. stream_.bufferSize = *bufferSize;
  4124. stream_.nBuffers = 1;
  4125. stream_.nUserChannels[mode] = channels;
  4126. stream_.channelOffset[mode] = firstChannel;
  4127. stream_.userFormat = format;
  4128. stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats;
  4129. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  4130. stream_.userInterleaved = false;
  4131. else
  4132. stream_.userInterleaved = true;
  4133. stream_.deviceInterleaved[mode] = true;
  4134. // Set flags for buffer conversion.
  4135. stream_.doConvertBuffer[mode] = false;
  4136. if ( stream_.userFormat != stream_.deviceFormat[mode] ||
  4137. stream_.nUserChannels[0] != stream_.nDeviceChannels[0] ||
  4138. stream_.nUserChannels[1] != stream_.nDeviceChannels[1] )
  4139. stream_.doConvertBuffer[mode] = true;
  4140. else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  4141. stream_.nUserChannels[mode] > 1 )
  4142. stream_.doConvertBuffer[mode] = true;
  4143. if ( stream_.doConvertBuffer[mode] )
  4144. setConvertInfo( mode, firstChannel );
  4145. // Allocate necessary internal buffers
  4146. bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );
  4147. stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );
  4148. if ( !stream_.userBuffer[mode] ) {
  4149. errorType = RtAudioError::MEMORY_ERROR;
  4150. errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";
  4151. goto Exit;
  4152. }
  4153. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )
  4154. stream_.callbackInfo.priority = 15;
  4155. else
  4156. stream_.callbackInfo.priority = 0;
  4157. ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback
  4158. ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode
  4159. methodResult = SUCCESS;
  4160. Exit:
  4161. //clean up
  4162. SAFE_RELEASE( captureDevices );
  4163. SAFE_RELEASE( renderDevices );
  4164. SAFE_RELEASE( devicePtr );
  4165. CoTaskMemFree( deviceFormat );
  4166. // if method failed, close the stream
  4167. if ( methodResult == FAILURE )
  4168. closeStream();
  4169. if ( !errorText_.empty() )
  4170. error( errorType );
  4171. return methodResult;
  4172. }
  4173. //=============================================================================
  4174. DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )
  4175. {
  4176. if ( wasapiPtr )
  4177. ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();
  4178. return 0;
  4179. }
  4180. DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )
  4181. {
  4182. if ( wasapiPtr )
  4183. ( ( RtApiWasapi* ) wasapiPtr )->stopStream();
  4184. return 0;
  4185. }
  4186. DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )
  4187. {
  4188. if ( wasapiPtr )
  4189. ( ( RtApiWasapi* ) wasapiPtr )->abortStream();
  4190. return 0;
  4191. }
  4192. //-----------------------------------------------------------------------------
  4193. void RtApiWasapi::wasapiThread()
  4194. {
  4195. // as this is a new thread, we must CoInitialize it
  4196. CoInitialize( NULL );
  4197. HRESULT hr;
  4198. IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;
  4199. IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;
  4200. IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;
  4201. IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;
  4202. HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;
  4203. HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;
  4204. WAVEFORMATEX* captureFormat = NULL;
  4205. WAVEFORMATEX* renderFormat = NULL;
  4206. float captureSrRatio = 0.0f;
  4207. float renderSrRatio = 0.0f;
  4208. WasapiBuffer captureBuffer;
  4209. WasapiBuffer renderBuffer;
  4210. WasapiResampler* captureResampler = NULL;
  4211. WasapiResampler* renderResampler = NULL;
  4212. // declare local stream variables
  4213. RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;
  4214. BYTE* streamBuffer = NULL;
  4215. DWORD captureFlags = 0;
  4216. unsigned int bufferFrameCount = 0;
  4217. unsigned int numFramesPadding = 0;
  4218. unsigned int convBufferSize = 0;
  4219. bool loopbackEnabled = stream_.device[INPUT] == stream_.device[OUTPUT];
  4220. bool callbackPushed = true;
  4221. bool callbackPulled = false;
  4222. bool callbackStopped = false;
  4223. int callbackResult = 0;
  4224. // convBuffer is used to store converted buffers between WASAPI and the user
  4225. char* convBuffer = NULL;
  4226. unsigned int convBuffSize = 0;
  4227. unsigned int deviceBuffSize = 0;
  4228. std::string errorText;
  4229. RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;
  4230. // Attempt to assign "Pro Audio" characteristic to thread
  4231. HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );
  4232. if ( AvrtDll ) {
  4233. DWORD taskIndex = 0;
  4234. TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr =
  4235. ( TAvSetMmThreadCharacteristicsPtr ) (void(*)()) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );
  4236. AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );
  4237. FreeLibrary( AvrtDll );
  4238. }
  4239. // start capture stream if applicable
  4240. if ( captureAudioClient ) {
  4241. hr = captureAudioClient->GetMixFormat( &captureFormat );
  4242. if ( FAILED( hr ) ) {
  4243. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4244. goto Exit;
  4245. }
  4246. // init captureResampler
  4247. captureResampler = new WasapiResampler( stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT64,
  4248. formatBytes( stream_.deviceFormat[INPUT] ) * 8, stream_.nDeviceChannels[INPUT],
  4249. captureFormat->nSamplesPerSec, stream_.sampleRate );
  4250. captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );
  4251. if ( !captureClient ) {
  4252. hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4253. loopbackEnabled ? AUDCLNT_STREAMFLAGS_LOOPBACK : AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4254. 0,
  4255. 0,
  4256. captureFormat,
  4257. NULL );
  4258. if ( FAILED( hr ) ) {
  4259. errorText = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";
  4260. goto Exit;
  4261. }
  4262. hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),
  4263. ( void** ) &captureClient );
  4264. if ( FAILED( hr ) ) {
  4265. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";
  4266. goto Exit;
  4267. }
  4268. // don't configure captureEvent if in loopback mode
  4269. if ( !loopbackEnabled )
  4270. {
  4271. // configure captureEvent to trigger on every available capture buffer
  4272. captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4273. if ( !captureEvent ) {
  4274. errorType = RtAudioError::SYSTEM_ERROR;
  4275. errorText = "RtApiWasapi::wasapiThread: Unable to create capture event.";
  4276. goto Exit;
  4277. }
  4278. hr = captureAudioClient->SetEventHandle( captureEvent );
  4279. if ( FAILED( hr ) ) {
  4280. errorText = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";
  4281. goto Exit;
  4282. }
  4283. ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;
  4284. }
  4285. ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;
  4286. // reset the capture stream
  4287. hr = captureAudioClient->Reset();
  4288. if ( FAILED( hr ) ) {
  4289. errorText = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";
  4290. goto Exit;
  4291. }
  4292. // start the capture stream
  4293. hr = captureAudioClient->Start();
  4294. if ( FAILED( hr ) ) {
  4295. errorText = "RtApiWasapi::wasapiThread: Unable to start capture stream.";
  4296. goto Exit;
  4297. }
  4298. }
  4299. unsigned int inBufferSize = 0;
  4300. hr = captureAudioClient->GetBufferSize( &inBufferSize );
  4301. if ( FAILED( hr ) ) {
  4302. errorText = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";
  4303. goto Exit;
  4304. }
  4305. // scale outBufferSize according to stream->user sample rate ratio
  4306. unsigned int outBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];
  4307. inBufferSize *= stream_.nDeviceChannels[INPUT];
  4308. // set captureBuffer size
  4309. captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );
  4310. }
  4311. // start render stream if applicable
  4312. if ( renderAudioClient ) {
  4313. hr = renderAudioClient->GetMixFormat( &renderFormat );
  4314. if ( FAILED( hr ) ) {
  4315. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";
  4316. goto Exit;
  4317. }
  4318. // init renderResampler
  4319. renderResampler = new WasapiResampler( stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT64,
  4320. formatBytes( stream_.deviceFormat[OUTPUT] ) * 8, stream_.nDeviceChannels[OUTPUT],
  4321. stream_.sampleRate, renderFormat->nSamplesPerSec );
  4322. renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );
  4323. if ( !renderClient ) {
  4324. hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,
  4325. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  4326. 0,
  4327. 0,
  4328. renderFormat,
  4329. NULL );
  4330. if ( FAILED( hr ) ) {
  4331. errorText = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";
  4332. goto Exit;
  4333. }
  4334. hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),
  4335. ( void** ) &renderClient );
  4336. if ( FAILED( hr ) ) {
  4337. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";
  4338. goto Exit;
  4339. }
  4340. // configure renderEvent to trigger on every available render buffer
  4341. renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  4342. if ( !renderEvent ) {
  4343. errorType = RtAudioError::SYSTEM_ERROR;
  4344. errorText = "RtApiWasapi::wasapiThread: Unable to create render event.";
  4345. goto Exit;
  4346. }
  4347. hr = renderAudioClient->SetEventHandle( renderEvent );
  4348. if ( FAILED( hr ) ) {
  4349. errorText = "RtApiWasapi::wasapiThread: Unable to set render event handle.";
  4350. goto Exit;
  4351. }
  4352. ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;
  4353. ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;
  4354. // reset the render stream
  4355. hr = renderAudioClient->Reset();
  4356. if ( FAILED( hr ) ) {
  4357. errorText = "RtApiWasapi::wasapiThread: Unable to reset render stream.";
  4358. goto Exit;
  4359. }
  4360. // start the render stream
  4361. hr = renderAudioClient->Start();
  4362. if ( FAILED( hr ) ) {
  4363. errorText = "RtApiWasapi::wasapiThread: Unable to start render stream.";
  4364. goto Exit;
  4365. }
  4366. }
  4367. unsigned int outBufferSize = 0;
  4368. hr = renderAudioClient->GetBufferSize( &outBufferSize );
  4369. if ( FAILED( hr ) ) {
  4370. errorText = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";
  4371. goto Exit;
  4372. }
  4373. // scale inBufferSize according to user->stream sample rate ratio
  4374. unsigned int inBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];
  4375. outBufferSize *= stream_.nDeviceChannels[OUTPUT];
  4376. // set renderBuffer size
  4377. renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4378. }
  4379. // malloc buffer memory
  4380. if ( stream_.mode == INPUT )
  4381. {
  4382. using namespace std; // for ceilf
  4383. convBuffSize = ( size_t ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4384. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4385. }
  4386. else if ( stream_.mode == OUTPUT )
  4387. {
  4388. convBuffSize = ( size_t ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4389. deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );
  4390. }
  4391. else if ( stream_.mode == DUPLEX )
  4392. {
  4393. convBuffSize = std::max( ( size_t ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4394. ( size_t ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4395. deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),
  4396. stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );
  4397. }
  4398. convBuffSize *= 2; // allow overflow for *SrRatio remainders
  4399. convBuffer = ( char* ) calloc( convBuffSize, 1 );
  4400. stream_.deviceBuffer = ( char* ) calloc( deviceBuffSize, 1 );
  4401. if ( !convBuffer || !stream_.deviceBuffer ) {
  4402. errorType = RtAudioError::MEMORY_ERROR;
  4403. errorText = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";
  4404. goto Exit;
  4405. }
  4406. // stream process loop
  4407. while ( stream_.state != STREAM_STOPPING ) {
  4408. if ( !callbackPulled ) {
  4409. // Callback Input
  4410. // ==============
  4411. // 1. Pull callback buffer from inputBuffer
  4412. // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count
  4413. // Convert callback buffer to user format
  4414. if ( captureAudioClient )
  4415. {
  4416. int samplesToPull = ( unsigned int ) floorf( stream_.bufferSize * captureSrRatio );
  4417. if ( captureSrRatio != 1 )
  4418. {
  4419. // account for remainders
  4420. samplesToPull--;
  4421. }
  4422. convBufferSize = 0;
  4423. while ( convBufferSize < stream_.bufferSize )
  4424. {
  4425. // Pull callback buffer from inputBuffer
  4426. callbackPulled = captureBuffer.pullBuffer( convBuffer,
  4427. samplesToPull * stream_.nDeviceChannels[INPUT],
  4428. stream_.deviceFormat[INPUT] );
  4429. if ( !callbackPulled )
  4430. {
  4431. break;
  4432. }
  4433. // Convert callback buffer to user sample rate
  4434. unsigned int deviceBufferOffset = convBufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );
  4435. unsigned int convSamples = 0;
  4436. captureResampler->Convert( stream_.deviceBuffer + deviceBufferOffset,
  4437. convBuffer,
  4438. samplesToPull,
  4439. convSamples );
  4440. convBufferSize += convSamples;
  4441. samplesToPull = 1; // now pull one sample at a time until we have stream_.bufferSize samples
  4442. }
  4443. if ( callbackPulled )
  4444. {
  4445. if ( stream_.doConvertBuffer[INPUT] ) {
  4446. // Convert callback buffer to user format
  4447. convertBuffer( stream_.userBuffer[INPUT],
  4448. stream_.deviceBuffer,
  4449. stream_.convertInfo[INPUT] );
  4450. }
  4451. else {
  4452. // no further conversion, simple copy deviceBuffer to userBuffer
  4453. memcpy( stream_.userBuffer[INPUT],
  4454. stream_.deviceBuffer,
  4455. stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );
  4456. }
  4457. }
  4458. }
  4459. else {
  4460. // if there is no capture stream, set callbackPulled flag
  4461. callbackPulled = true;
  4462. }
  4463. // Execute Callback
  4464. // ================
  4465. // 1. Execute user callback method
  4466. // 2. Handle return value from callback
  4467. // if callback has not requested the stream to stop
  4468. if ( callbackPulled && !callbackStopped ) {
  4469. // Execute user callback method
  4470. callbackResult = callback( stream_.userBuffer[OUTPUT],
  4471. stream_.userBuffer[INPUT],
  4472. stream_.bufferSize,
  4473. getStreamTime(),
  4474. captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,
  4475. stream_.callbackInfo.userData );
  4476. // tick stream time
  4477. RtApi::tickStreamTime();
  4478. // Handle return value from callback
  4479. if ( callbackResult == 1 ) {
  4480. // instantiate a thread to stop this thread
  4481. HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );
  4482. if ( !threadHandle ) {
  4483. errorType = RtAudioError::THREAD_ERROR;
  4484. errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";
  4485. goto Exit;
  4486. }
  4487. else if ( !CloseHandle( threadHandle ) ) {
  4488. errorType = RtAudioError::THREAD_ERROR;
  4489. errorText = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";
  4490. goto Exit;
  4491. }
  4492. callbackStopped = true;
  4493. }
  4494. else if ( callbackResult == 2 ) {
  4495. // instantiate a thread to stop this thread
  4496. HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );
  4497. if ( !threadHandle ) {
  4498. errorType = RtAudioError::THREAD_ERROR;
  4499. errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";
  4500. goto Exit;
  4501. }
  4502. else if ( !CloseHandle( threadHandle ) ) {
  4503. errorType = RtAudioError::THREAD_ERROR;
  4504. errorText = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";
  4505. goto Exit;
  4506. }
  4507. callbackStopped = true;
  4508. }
  4509. }
  4510. }
  4511. // Callback Output
  4512. // ===============
  4513. // 1. Convert callback buffer to stream format
  4514. // 2. Convert callback buffer to stream sample rate and channel count
  4515. // 3. Push callback buffer into outputBuffer
  4516. if ( renderAudioClient && callbackPulled )
  4517. {
  4518. // if the last call to renderBuffer.PushBuffer() was successful
  4519. if ( callbackPushed || convBufferSize == 0 )
  4520. {
  4521. if ( stream_.doConvertBuffer[OUTPUT] )
  4522. {
  4523. // Convert callback buffer to stream format
  4524. convertBuffer( stream_.deviceBuffer,
  4525. stream_.userBuffer[OUTPUT],
  4526. stream_.convertInfo[OUTPUT] );
  4527. }
  4528. else {
  4529. // no further conversion, simple copy userBuffer to deviceBuffer
  4530. memcpy( stream_.deviceBuffer,
  4531. stream_.userBuffer[OUTPUT],
  4532. stream_.bufferSize * stream_.nUserChannels[OUTPUT] * formatBytes( stream_.userFormat ) );
  4533. }
  4534. // Convert callback buffer to stream sample rate
  4535. renderResampler->Convert( convBuffer,
  4536. stream_.deviceBuffer,
  4537. stream_.bufferSize,
  4538. convBufferSize );
  4539. }
  4540. // Push callback buffer into outputBuffer
  4541. callbackPushed = renderBuffer.pushBuffer( convBuffer,
  4542. convBufferSize * stream_.nDeviceChannels[OUTPUT],
  4543. stream_.deviceFormat[OUTPUT] );
  4544. }
  4545. else {
  4546. // if there is no render stream, set callbackPushed flag
  4547. callbackPushed = true;
  4548. }
  4549. // Stream Capture
  4550. // ==============
  4551. // 1. Get capture buffer from stream
  4552. // 2. Push capture buffer into inputBuffer
  4553. // 3. If 2. was successful: Release capture buffer
  4554. if ( captureAudioClient ) {
  4555. // if the callback input buffer was not pulled from captureBuffer, wait for next capture event
  4556. if ( !callbackPulled ) {
  4557. WaitForSingleObject( loopbackEnabled ? renderEvent : captureEvent, INFINITE );
  4558. }
  4559. // Get capture buffer from stream
  4560. hr = captureClient->GetBuffer( &streamBuffer,
  4561. &bufferFrameCount,
  4562. &captureFlags, NULL, NULL );
  4563. if ( FAILED( hr ) ) {
  4564. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";
  4565. goto Exit;
  4566. }
  4567. if ( bufferFrameCount != 0 ) {
  4568. // Push capture buffer into inputBuffer
  4569. if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,
  4570. bufferFrameCount * stream_.nDeviceChannels[INPUT],
  4571. stream_.deviceFormat[INPUT] ) )
  4572. {
  4573. // Release capture buffer
  4574. hr = captureClient->ReleaseBuffer( bufferFrameCount );
  4575. if ( FAILED( hr ) ) {
  4576. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4577. goto Exit;
  4578. }
  4579. }
  4580. else
  4581. {
  4582. // Inform WASAPI that capture was unsuccessful
  4583. hr = captureClient->ReleaseBuffer( 0 );
  4584. if ( FAILED( hr ) ) {
  4585. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4586. goto Exit;
  4587. }
  4588. }
  4589. }
  4590. else
  4591. {
  4592. // Inform WASAPI that capture was unsuccessful
  4593. hr = captureClient->ReleaseBuffer( 0 );
  4594. if ( FAILED( hr ) ) {
  4595. errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";
  4596. goto Exit;
  4597. }
  4598. }
  4599. }
  4600. // Stream Render
  4601. // =============
  4602. // 1. Get render buffer from stream
  4603. // 2. Pull next buffer from outputBuffer
  4604. // 3. If 2. was successful: Fill render buffer with next buffer
  4605. // Release render buffer
  4606. if ( renderAudioClient ) {
  4607. // if the callback output buffer was not pushed to renderBuffer, wait for next render event
  4608. if ( callbackPulled && !callbackPushed ) {
  4609. WaitForSingleObject( renderEvent, INFINITE );
  4610. }
  4611. // Get render buffer from stream
  4612. hr = renderAudioClient->GetBufferSize( &bufferFrameCount );
  4613. if ( FAILED( hr ) ) {
  4614. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";
  4615. goto Exit;
  4616. }
  4617. hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );
  4618. if ( FAILED( hr ) ) {
  4619. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";
  4620. goto Exit;
  4621. }
  4622. bufferFrameCount -= numFramesPadding;
  4623. if ( bufferFrameCount != 0 ) {
  4624. hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );
  4625. if ( FAILED( hr ) ) {
  4626. errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";
  4627. goto Exit;
  4628. }
  4629. // Pull next buffer from outputBuffer
  4630. // Fill render buffer with next buffer
  4631. if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,
  4632. bufferFrameCount * stream_.nDeviceChannels[OUTPUT],
  4633. stream_.deviceFormat[OUTPUT] ) )
  4634. {
  4635. // Release render buffer
  4636. hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );
  4637. if ( FAILED( hr ) ) {
  4638. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4639. goto Exit;
  4640. }
  4641. }
  4642. else
  4643. {
  4644. // Inform WASAPI that render was unsuccessful
  4645. hr = renderClient->ReleaseBuffer( 0, 0 );
  4646. if ( FAILED( hr ) ) {
  4647. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4648. goto Exit;
  4649. }
  4650. }
  4651. }
  4652. else
  4653. {
  4654. // Inform WASAPI that render was unsuccessful
  4655. hr = renderClient->ReleaseBuffer( 0, 0 );
  4656. if ( FAILED( hr ) ) {
  4657. errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer.";
  4658. goto Exit;
  4659. }
  4660. }
  4661. }
  4662. // if the callback buffer was pushed renderBuffer reset callbackPulled flag
  4663. if ( callbackPushed ) {
  4664. // unsetting the callbackPulled flag lets the stream know that
  4665. // the audio device is ready for another callback output buffer.
  4666. callbackPulled = false;
  4667. }
  4668. }
  4669. Exit:
  4670. // clean up
  4671. CoTaskMemFree( captureFormat );
  4672. CoTaskMemFree( renderFormat );
  4673. free ( convBuffer );
  4674. delete renderResampler;
  4675. delete captureResampler;
  4676. CoUninitialize();
  4677. // update stream state
  4678. stream_.state = STREAM_STOPPED;
  4679. if ( !errorText.empty() )
  4680. {
  4681. errorText_ = errorText;
  4682. error( errorType );
  4683. }
  4684. }
  4685. //******************** End of __WINDOWS_WASAPI__ *********************//
  4686. #endif
  4687. #if defined(__WINDOWS_DS__) // Windows DirectSound API
  4688. // Modified by Robin Davies, October 2005
  4689. // - Improvements to DirectX pointer chasing.
  4690. // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
  4691. // - Auto-call CoInitialize for DSOUND and ASIO platforms.
  4692. // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
  4693. // Changed device query structure for RtAudio 4.0.7, January 2010
  4694. #include <windows.h>
  4695. #include <process.h>
  4696. #include <mmsystem.h>
  4697. #include <mmreg.h>
  4698. #include <dsound.h>
  4699. #include <assert.h>
  4700. #include <algorithm>
  4701. #if defined(__MINGW32__)
  4702. // missing from latest mingw winapi
  4703. #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
  4704. #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
  4705. #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
  4706. #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
  4707. #endif
  4708. #define MINIMUM_DEVICE_BUFFER_SIZE 32768
  4709. #ifdef _MSC_VER // if Microsoft Visual C++
  4710. #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
  4711. #endif
  4712. static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
  4713. {
  4714. if ( pointer > bufferSize ) pointer -= bufferSize;
  4715. if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
  4716. if ( pointer < earlierPointer ) pointer += bufferSize;
  4717. return pointer >= earlierPointer && pointer < laterPointer;
  4718. }
  4719. // A structure to hold various information related to the DirectSound
  4720. // API implementation.
  4721. struct DsHandle {
  4722. unsigned int drainCounter; // Tracks callback counts when draining
  4723. bool internalDrain; // Indicates if stop is initiated from callback or not.
  4724. void *id[2];
  4725. void *buffer[2];
  4726. bool xrun[2];
  4727. UINT bufferPointer[2];
  4728. DWORD dsBufferSize[2];
  4729. DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
  4730. HANDLE condition;
  4731. DsHandle()
  4732. :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; }
  4733. };
  4734. // Declarations for utility functions, callbacks, and structures
  4735. // specific to the DirectSound implementation.
  4736. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  4737. LPCTSTR description,
  4738. LPCTSTR module,
  4739. LPVOID lpContext );
  4740. static const char* getErrorString( int code );
  4741. static unsigned __stdcall callbackHandler( void *ptr );
  4742. struct DsDevice {
  4743. LPGUID id[2];
  4744. bool validId[2];
  4745. bool found;
  4746. std::string name;
  4747. DsDevice()
  4748. : found(false) { validId[0] = false; validId[1] = false; }
  4749. };
  4750. struct DsProbeData {
  4751. bool isInput;
  4752. std::vector<struct DsDevice>* dsDevices;
  4753. };
  4754. RtApiDs :: RtApiDs()
  4755. {
  4756. // Dsound will run both-threaded. If CoInitialize fails, then just
  4757. // accept whatever the mainline chose for a threading model.
  4758. coInitialized_ = false;
  4759. HRESULT hr = CoInitialize( NULL );
  4760. if ( !FAILED( hr ) ) coInitialized_ = true;
  4761. }
  4762. RtApiDs :: ~RtApiDs()
  4763. {
  4764. if ( stream_.state != STREAM_CLOSED ) closeStream();
  4765. if ( coInitialized_ ) CoUninitialize(); // balanced call.
  4766. }
  4767. // The DirectSound default output is always the first device.
  4768. unsigned int RtApiDs :: getDefaultOutputDevice( void )
  4769. {
  4770. return 0;
  4771. }
  4772. // The DirectSound default input is always the first input device,
  4773. // which is the first capture device enumerated.
  4774. unsigned int RtApiDs :: getDefaultInputDevice( void )
  4775. {
  4776. return 0;
  4777. }
  4778. unsigned int RtApiDs :: getDeviceCount( void )
  4779. {
  4780. // Set query flag for previously found devices to false, so that we
  4781. // can check for any devices that have disappeared.
  4782. for ( unsigned int i=0; i<dsDevices.size(); i++ )
  4783. dsDevices[i].found = false;
  4784. // Query DirectSound devices.
  4785. struct DsProbeData probeInfo;
  4786. probeInfo.isInput = false;
  4787. probeInfo.dsDevices = &dsDevices;
  4788. HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4789. if ( FAILED( result ) ) {
  4790. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
  4791. errorText_ = errorStream_.str();
  4792. error( RtAudioError::WARNING );
  4793. }
  4794. // Query DirectSoundCapture devices.
  4795. probeInfo.isInput = true;
  4796. result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );
  4797. if ( FAILED( result ) ) {
  4798. errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
  4799. errorText_ = errorStream_.str();
  4800. error( RtAudioError::WARNING );
  4801. }
  4802. // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).
  4803. for ( unsigned int i=0; i<dsDevices.size(); ) {
  4804. if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );
  4805. else i++;
  4806. }
  4807. return static_cast<unsigned int>(dsDevices.size());
  4808. }
  4809. RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
  4810. {
  4811. RtAudio::DeviceInfo info;
  4812. info.probed = false;
  4813. if ( dsDevices.size() == 0 ) {
  4814. // Force a query of all devices
  4815. getDeviceCount();
  4816. if ( dsDevices.size() == 0 ) {
  4817. errorText_ = "RtApiDs::getDeviceInfo: no devices found!";
  4818. error( RtAudioError::INVALID_USE );
  4819. return info;
  4820. }
  4821. }
  4822. if ( device >= dsDevices.size() ) {
  4823. errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";
  4824. error( RtAudioError::INVALID_USE );
  4825. return info;
  4826. }
  4827. HRESULT result;
  4828. if ( dsDevices[ device ].validId[0] == false ) goto probeInput;
  4829. LPDIRECTSOUND output;
  4830. DSCAPS outCaps;
  4831. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  4832. if ( FAILED( result ) ) {
  4833. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  4834. errorText_ = errorStream_.str();
  4835. error( RtAudioError::WARNING );
  4836. goto probeInput;
  4837. }
  4838. outCaps.dwSize = sizeof( outCaps );
  4839. result = output->GetCaps( &outCaps );
  4840. if ( FAILED( result ) ) {
  4841. output->Release();
  4842. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
  4843. errorText_ = errorStream_.str();
  4844. error( RtAudioError::WARNING );
  4845. goto probeInput;
  4846. }
  4847. // Get output channel information.
  4848. info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
  4849. // Get sample rate information.
  4850. info.sampleRates.clear();
  4851. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  4852. if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
  4853. SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {
  4854. info.sampleRates.push_back( SAMPLE_RATES[k] );
  4855. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  4856. info.preferredSampleRate = SAMPLE_RATES[k];
  4857. }
  4858. }
  4859. // Get format information.
  4860. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
  4861. if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
  4862. output->Release();
  4863. if ( getDefaultOutputDevice() == device )
  4864. info.isDefaultOutput = true;
  4865. if ( dsDevices[ device ].validId[1] == false ) {
  4866. info.name = dsDevices[ device ].name;
  4867. info.probed = true;
  4868. return info;
  4869. }
  4870. probeInput:
  4871. LPDIRECTSOUNDCAPTURE input;
  4872. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  4873. if ( FAILED( result ) ) {
  4874. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  4875. errorText_ = errorStream_.str();
  4876. error( RtAudioError::WARNING );
  4877. return info;
  4878. }
  4879. DSCCAPS inCaps;
  4880. inCaps.dwSize = sizeof( inCaps );
  4881. result = input->GetCaps( &inCaps );
  4882. if ( FAILED( result ) ) {
  4883. input->Release();
  4884. errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";
  4885. errorText_ = errorStream_.str();
  4886. error( RtAudioError::WARNING );
  4887. return info;
  4888. }
  4889. // Get input channel information.
  4890. info.inputChannels = inCaps.dwChannels;
  4891. // Get sample rate and format information.
  4892. std::vector<unsigned int> rates;
  4893. if ( inCaps.dwChannels >= 2 ) {
  4894. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4895. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4896. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4897. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4898. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4899. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4900. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4901. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4902. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4903. if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );
  4904. if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );
  4905. if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );
  4906. if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );
  4907. }
  4908. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4909. if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );
  4910. if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );
  4911. if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );
  4912. if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );
  4913. }
  4914. }
  4915. else if ( inCaps.dwChannels == 1 ) {
  4916. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4917. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4918. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4919. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
  4920. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4921. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4922. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4923. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
  4924. if ( info.nativeFormats & RTAUDIO_SINT16 ) {
  4925. if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );
  4926. if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );
  4927. if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );
  4928. if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );
  4929. }
  4930. else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
  4931. if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );
  4932. if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );
  4933. if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );
  4934. if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );
  4935. }
  4936. }
  4937. else info.inputChannels = 0; // technically, this would be an error
  4938. input->Release();
  4939. if ( info.inputChannels == 0 ) return info;
  4940. // Copy the supported rates to the info structure but avoid duplication.
  4941. bool found;
  4942. for ( unsigned int i=0; i<rates.size(); i++ ) {
  4943. found = false;
  4944. for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {
  4945. if ( rates[i] == info.sampleRates[j] ) {
  4946. found = true;
  4947. break;
  4948. }
  4949. }
  4950. if ( found == false ) info.sampleRates.push_back( rates[i] );
  4951. }
  4952. std::sort( info.sampleRates.begin(), info.sampleRates.end() );
  4953. // If device opens for both playback and capture, we determine the channels.
  4954. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  4955. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  4956. if ( device == 0 ) info.isDefaultInput = true;
  4957. // Copy name and return.
  4958. info.name = dsDevices[ device ].name;
  4959. info.probed = true;
  4960. return info;
  4961. }
  4962. bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  4963. unsigned int firstChannel, unsigned int sampleRate,
  4964. RtAudioFormat format, unsigned int *bufferSize,
  4965. RtAudio::StreamOptions *options )
  4966. {
  4967. if ( channels + firstChannel > 2 ) {
  4968. errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
  4969. return FAILURE;
  4970. }
  4971. size_t nDevices = dsDevices.size();
  4972. if ( nDevices == 0 ) {
  4973. // This should not happen because a check is made before this function is called.
  4974. errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";
  4975. return FAILURE;
  4976. }
  4977. if ( device >= nDevices ) {
  4978. // This should not happen because a check is made before this function is called.
  4979. errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";
  4980. return FAILURE;
  4981. }
  4982. if ( mode == OUTPUT ) {
  4983. if ( dsDevices[ device ].validId[0] == false ) {
  4984. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
  4985. errorText_ = errorStream_.str();
  4986. return FAILURE;
  4987. }
  4988. }
  4989. else { // mode == INPUT
  4990. if ( dsDevices[ device ].validId[1] == false ) {
  4991. errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
  4992. errorText_ = errorStream_.str();
  4993. return FAILURE;
  4994. }
  4995. }
  4996. // According to a note in PortAudio, using GetDesktopWindow()
  4997. // instead of GetForegroundWindow() is supposed to avoid problems
  4998. // that occur when the application's window is not the foreground
  4999. // window. Also, if the application window closes before the
  5000. // DirectSound buffer, DirectSound can crash. In the past, I had
  5001. // problems when using GetDesktopWindow() but it seems fine now
  5002. // (January 2010). I'll leave it commented here.
  5003. // HWND hWnd = GetForegroundWindow();
  5004. HWND hWnd = GetDesktopWindow();
  5005. // Check the numberOfBuffers parameter and limit the lowest value to
  5006. // two. This is a judgement call and a value of two is probably too
  5007. // low for capture, but it should work for playback.
  5008. int nBuffers = 0;
  5009. if ( options ) nBuffers = options->numberOfBuffers;
  5010. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
  5011. if ( nBuffers < 2 ) nBuffers = 3;
  5012. // Check the lower range of the user-specified buffer size and set
  5013. // (arbitrarily) to a lower bound of 32.
  5014. if ( *bufferSize < 32 ) *bufferSize = 32;
  5015. // Create the wave format structure. The data format setting will
  5016. // be determined later.
  5017. WAVEFORMATEX waveFormat;
  5018. ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
  5019. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  5020. waveFormat.nChannels = channels + firstChannel;
  5021. waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
  5022. // Determine the device buffer size. By default, we'll use the value
  5023. // defined above (32K), but we will grow it to make allowances for
  5024. // very large software buffer sizes.
  5025. DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;
  5026. DWORD dsPointerLeadTime = 0;
  5027. void *ohandle = 0, *bhandle = 0;
  5028. HRESULT result;
  5029. if ( mode == OUTPUT ) {
  5030. LPDIRECTSOUND output;
  5031. result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );
  5032. if ( FAILED( result ) ) {
  5033. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";
  5034. errorText_ = errorStream_.str();
  5035. return FAILURE;
  5036. }
  5037. DSCAPS outCaps;
  5038. outCaps.dwSize = sizeof( outCaps );
  5039. result = output->GetCaps( &outCaps );
  5040. if ( FAILED( result ) ) {
  5041. output->Release();
  5042. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";
  5043. errorText_ = errorStream_.str();
  5044. return FAILURE;
  5045. }
  5046. // Check channel information.
  5047. if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
  5048. errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";
  5049. errorText_ = errorStream_.str();
  5050. return FAILURE;
  5051. }
  5052. // Check format information. Use 16-bit format unless not
  5053. // supported or user requests 8-bit.
  5054. if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
  5055. !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
  5056. waveFormat.wBitsPerSample = 16;
  5057. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5058. }
  5059. else {
  5060. waveFormat.wBitsPerSample = 8;
  5061. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5062. }
  5063. stream_.userFormat = format;
  5064. // Update wave format structure and buffer information.
  5065. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  5066. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  5067. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  5068. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  5069. while ( dsPointerLeadTime * 2U > dsBufferSize )
  5070. dsBufferSize *= 2;
  5071. // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
  5072. // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
  5073. // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
  5074. result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
  5075. if ( FAILED( result ) ) {
  5076. output->Release();
  5077. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";
  5078. errorText_ = errorStream_.str();
  5079. return FAILURE;
  5080. }
  5081. // Even though we will write to the secondary buffer, we need to
  5082. // access the primary buffer to set the correct output format
  5083. // (since the default is 8-bit, 22 kHz!). Setup the DS primary
  5084. // buffer description.
  5085. DSBUFFERDESC bufferDescription;
  5086. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  5087. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  5088. bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  5089. // Obtain the primary buffer
  5090. LPDIRECTSOUNDBUFFER buffer;
  5091. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5092. if ( FAILED( result ) ) {
  5093. output->Release();
  5094. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";
  5095. errorText_ = errorStream_.str();
  5096. return FAILURE;
  5097. }
  5098. // Set the primary DS buffer sound format.
  5099. result = buffer->SetFormat( &waveFormat );
  5100. if ( FAILED( result ) ) {
  5101. output->Release();
  5102. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";
  5103. errorText_ = errorStream_.str();
  5104. return FAILURE;
  5105. }
  5106. // Setup the secondary DS buffer description.
  5107. ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
  5108. bufferDescription.dwSize = sizeof( DSBUFFERDESC );
  5109. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  5110. DSBCAPS_GLOBALFOCUS |
  5111. DSBCAPS_GETCURRENTPOSITION2 |
  5112. DSBCAPS_LOCHARDWARE ); // Force hardware mixing
  5113. bufferDescription.dwBufferBytes = dsBufferSize;
  5114. bufferDescription.lpwfxFormat = &waveFormat;
  5115. // Try to create the secondary DS buffer. If that doesn't work,
  5116. // try to use software mixing. Otherwise, there's a problem.
  5117. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5118. if ( FAILED( result ) ) {
  5119. bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
  5120. DSBCAPS_GLOBALFOCUS |
  5121. DSBCAPS_GETCURRENTPOSITION2 |
  5122. DSBCAPS_LOCSOFTWARE ); // Force software mixing
  5123. result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
  5124. if ( FAILED( result ) ) {
  5125. output->Release();
  5126. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";
  5127. errorText_ = errorStream_.str();
  5128. return FAILURE;
  5129. }
  5130. }
  5131. // Get the buffer size ... might be different from what we specified.
  5132. DSBCAPS dsbcaps;
  5133. dsbcaps.dwSize = sizeof( DSBCAPS );
  5134. result = buffer->GetCaps( &dsbcaps );
  5135. if ( FAILED( result ) ) {
  5136. output->Release();
  5137. buffer->Release();
  5138. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  5139. errorText_ = errorStream_.str();
  5140. return FAILURE;
  5141. }
  5142. dsBufferSize = dsbcaps.dwBufferBytes;
  5143. // Lock the DS buffer
  5144. LPVOID audioPtr;
  5145. DWORD dataLen;
  5146. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  5147. if ( FAILED( result ) ) {
  5148. output->Release();
  5149. buffer->Release();
  5150. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";
  5151. errorText_ = errorStream_.str();
  5152. return FAILURE;
  5153. }
  5154. // Zero the DS buffer
  5155. ZeroMemory( audioPtr, dataLen );
  5156. // Unlock the DS buffer
  5157. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5158. if ( FAILED( result ) ) {
  5159. output->Release();
  5160. buffer->Release();
  5161. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";
  5162. errorText_ = errorStream_.str();
  5163. return FAILURE;
  5164. }
  5165. ohandle = (void *) output;
  5166. bhandle = (void *) buffer;
  5167. }
  5168. if ( mode == INPUT ) {
  5169. LPDIRECTSOUNDCAPTURE input;
  5170. result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );
  5171. if ( FAILED( result ) ) {
  5172. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";
  5173. errorText_ = errorStream_.str();
  5174. return FAILURE;
  5175. }
  5176. DSCCAPS inCaps;
  5177. inCaps.dwSize = sizeof( inCaps );
  5178. result = input->GetCaps( &inCaps );
  5179. if ( FAILED( result ) ) {
  5180. input->Release();
  5181. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";
  5182. errorText_ = errorStream_.str();
  5183. return FAILURE;
  5184. }
  5185. // Check channel information.
  5186. if ( inCaps.dwChannels < channels + firstChannel ) {
  5187. errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
  5188. return FAILURE;
  5189. }
  5190. // Check format information. Use 16-bit format unless user
  5191. // requests 8-bit.
  5192. DWORD deviceFormats;
  5193. if ( channels + firstChannel == 2 ) {
  5194. deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
  5195. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5196. waveFormat.wBitsPerSample = 8;
  5197. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5198. }
  5199. else { // assume 16-bit is supported
  5200. waveFormat.wBitsPerSample = 16;
  5201. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5202. }
  5203. }
  5204. else { // channel == 1
  5205. deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
  5206. if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
  5207. waveFormat.wBitsPerSample = 8;
  5208. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  5209. }
  5210. else { // assume 16-bit is supported
  5211. waveFormat.wBitsPerSample = 16;
  5212. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  5213. }
  5214. }
  5215. stream_.userFormat = format;
  5216. // Update wave format structure and buffer information.
  5217. waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  5218. waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
  5219. dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
  5220. // If the user wants an even bigger buffer, increase the device buffer size accordingly.
  5221. while ( dsPointerLeadTime * 2U > dsBufferSize )
  5222. dsBufferSize *= 2;
  5223. // Setup the secondary DS buffer description.
  5224. DSCBUFFERDESC bufferDescription;
  5225. ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
  5226. bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
  5227. bufferDescription.dwFlags = 0;
  5228. bufferDescription.dwReserved = 0;
  5229. bufferDescription.dwBufferBytes = dsBufferSize;
  5230. bufferDescription.lpwfxFormat = &waveFormat;
  5231. // Create the capture buffer.
  5232. LPDIRECTSOUNDCAPTUREBUFFER buffer;
  5233. result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
  5234. if ( FAILED( result ) ) {
  5235. input->Release();
  5236. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";
  5237. errorText_ = errorStream_.str();
  5238. return FAILURE;
  5239. }
  5240. // Get the buffer size ... might be different from what we specified.
  5241. DSCBCAPS dscbcaps;
  5242. dscbcaps.dwSize = sizeof( DSCBCAPS );
  5243. result = buffer->GetCaps( &dscbcaps );
  5244. if ( FAILED( result ) ) {
  5245. input->Release();
  5246. buffer->Release();
  5247. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";
  5248. errorText_ = errorStream_.str();
  5249. return FAILURE;
  5250. }
  5251. dsBufferSize = dscbcaps.dwBufferBytes;
  5252. // NOTE: We could have a problem here if this is a duplex stream
  5253. // and the play and capture hardware buffer sizes are different
  5254. // (I'm actually not sure if that is a problem or not).
  5255. // Currently, we are not verifying that.
  5256. // Lock the capture buffer
  5257. LPVOID audioPtr;
  5258. DWORD dataLen;
  5259. result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );
  5260. if ( FAILED( result ) ) {
  5261. input->Release();
  5262. buffer->Release();
  5263. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";
  5264. errorText_ = errorStream_.str();
  5265. return FAILURE;
  5266. }
  5267. // Zero the buffer
  5268. ZeroMemory( audioPtr, dataLen );
  5269. // Unlock the buffer
  5270. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5271. if ( FAILED( result ) ) {
  5272. input->Release();
  5273. buffer->Release();
  5274. errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";
  5275. errorText_ = errorStream_.str();
  5276. return FAILURE;
  5277. }
  5278. ohandle = (void *) input;
  5279. bhandle = (void *) buffer;
  5280. }
  5281. // Set various stream parameters
  5282. DsHandle *handle = 0;
  5283. stream_.nDeviceChannels[mode] = channels + firstChannel;
  5284. stream_.nUserChannels[mode] = channels;
  5285. stream_.bufferSize = *bufferSize;
  5286. stream_.channelOffset[mode] = firstChannel;
  5287. stream_.deviceInterleaved[mode] = true;
  5288. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  5289. else stream_.userInterleaved = true;
  5290. // Set flag for buffer conversion
  5291. stream_.doConvertBuffer[mode] = false;
  5292. if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
  5293. stream_.doConvertBuffer[mode] = true;
  5294. if (stream_.userFormat != stream_.deviceFormat[mode])
  5295. stream_.doConvertBuffer[mode] = true;
  5296. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  5297. stream_.nUserChannels[mode] > 1 )
  5298. stream_.doConvertBuffer[mode] = true;
  5299. // Allocate necessary internal buffers
  5300. long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  5301. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  5302. if ( stream_.userBuffer[mode] == NULL ) {
  5303. errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
  5304. goto error;
  5305. }
  5306. if ( stream_.doConvertBuffer[mode] ) {
  5307. bool makeBuffer = true;
  5308. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  5309. if ( mode == INPUT ) {
  5310. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  5311. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  5312. if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
  5313. }
  5314. }
  5315. if ( makeBuffer ) {
  5316. bufferBytes *= *bufferSize;
  5317. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  5318. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  5319. if ( stream_.deviceBuffer == NULL ) {
  5320. errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
  5321. goto error;
  5322. }
  5323. }
  5324. }
  5325. // Allocate our DsHandle structures for the stream.
  5326. if ( stream_.apiHandle == 0 ) {
  5327. try {
  5328. handle = new DsHandle;
  5329. }
  5330. catch ( std::bad_alloc& ) {
  5331. errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
  5332. goto error;
  5333. }
  5334. // Create a manual-reset event.
  5335. handle->condition = CreateEvent( NULL, // no security
  5336. TRUE, // manual-reset
  5337. FALSE, // non-signaled initially
  5338. NULL ); // unnamed
  5339. stream_.apiHandle = (void *) handle;
  5340. }
  5341. else
  5342. handle = (DsHandle *) stream_.apiHandle;
  5343. handle->id[mode] = ohandle;
  5344. handle->buffer[mode] = bhandle;
  5345. handle->dsBufferSize[mode] = dsBufferSize;
  5346. handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
  5347. stream_.device[mode] = device;
  5348. stream_.state = STREAM_STOPPED;
  5349. if ( stream_.mode == OUTPUT && mode == INPUT )
  5350. // We had already set up an output stream.
  5351. stream_.mode = DUPLEX;
  5352. else
  5353. stream_.mode = mode;
  5354. stream_.nBuffers = nBuffers;
  5355. stream_.sampleRate = sampleRate;
  5356. // Setup the buffer conversion information structure.
  5357. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  5358. // Setup the callback thread.
  5359. if ( stream_.callbackInfo.isRunning == false ) {
  5360. unsigned threadId;
  5361. stream_.callbackInfo.isRunning = true;
  5362. stream_.callbackInfo.object = (void *) this;
  5363. stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
  5364. &stream_.callbackInfo, 0, &threadId );
  5365. if ( stream_.callbackInfo.thread == 0 ) {
  5366. errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
  5367. goto error;
  5368. }
  5369. // Boost DS thread priority
  5370. SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
  5371. }
  5372. return SUCCESS;
  5373. error:
  5374. if ( handle ) {
  5375. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5376. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5377. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5378. if ( buffer ) buffer->Release();
  5379. object->Release();
  5380. }
  5381. if ( handle->buffer[1] ) {
  5382. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5383. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5384. if ( buffer ) buffer->Release();
  5385. object->Release();
  5386. }
  5387. CloseHandle( handle->condition );
  5388. delete handle;
  5389. stream_.apiHandle = 0;
  5390. }
  5391. for ( int i=0; i<2; i++ ) {
  5392. if ( stream_.userBuffer[i] ) {
  5393. free( stream_.userBuffer[i] );
  5394. stream_.userBuffer[i] = 0;
  5395. }
  5396. }
  5397. if ( stream_.deviceBuffer ) {
  5398. free( stream_.deviceBuffer );
  5399. stream_.deviceBuffer = 0;
  5400. }
  5401. stream_.state = STREAM_CLOSED;
  5402. return FAILURE;
  5403. }
  5404. void RtApiDs :: closeStream()
  5405. {
  5406. if ( stream_.state == STREAM_CLOSED ) {
  5407. errorText_ = "RtApiDs::closeStream(): no open stream to close!";
  5408. error( RtAudioError::WARNING );
  5409. return;
  5410. }
  5411. // Stop the callback thread.
  5412. stream_.callbackInfo.isRunning = false;
  5413. WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
  5414. CloseHandle( (HANDLE) stream_.callbackInfo.thread );
  5415. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5416. if ( handle ) {
  5417. if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
  5418. LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
  5419. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5420. if ( buffer ) {
  5421. buffer->Stop();
  5422. buffer->Release();
  5423. }
  5424. object->Release();
  5425. }
  5426. if ( handle->buffer[1] ) {
  5427. LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
  5428. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5429. if ( buffer ) {
  5430. buffer->Stop();
  5431. buffer->Release();
  5432. }
  5433. object->Release();
  5434. }
  5435. CloseHandle( handle->condition );
  5436. delete handle;
  5437. stream_.apiHandle = 0;
  5438. }
  5439. for ( int i=0; i<2; i++ ) {
  5440. if ( stream_.userBuffer[i] ) {
  5441. free( stream_.userBuffer[i] );
  5442. stream_.userBuffer[i] = 0;
  5443. }
  5444. }
  5445. if ( stream_.deviceBuffer ) {
  5446. free( stream_.deviceBuffer );
  5447. stream_.deviceBuffer = 0;
  5448. }
  5449. stream_.mode = UNINITIALIZED;
  5450. stream_.state = STREAM_CLOSED;
  5451. }
  5452. void RtApiDs :: startStream()
  5453. {
  5454. verifyStream();
  5455. if ( stream_.state == STREAM_RUNNING ) {
  5456. errorText_ = "RtApiDs::startStream(): the stream is already running!";
  5457. error( RtAudioError::WARNING );
  5458. return;
  5459. }
  5460. #if defined( HAVE_GETTIMEOFDAY )
  5461. gettimeofday( &stream_.lastTickTimestamp, NULL );
  5462. #endif
  5463. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5464. // Increase scheduler frequency on lesser windows (a side-effect of
  5465. // increasing timer accuracy). On greater windows (Win2K or later),
  5466. // this is already in effect.
  5467. timeBeginPeriod( 1 );
  5468. buffersRolling = false;
  5469. duplexPrerollBytes = 0;
  5470. if ( stream_.mode == DUPLEX ) {
  5471. // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
  5472. duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
  5473. }
  5474. HRESULT result = 0;
  5475. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5476. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5477. result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
  5478. if ( FAILED( result ) ) {
  5479. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
  5480. errorText_ = errorStream_.str();
  5481. goto unlock;
  5482. }
  5483. }
  5484. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5485. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5486. result = buffer->Start( DSCBSTART_LOOPING );
  5487. if ( FAILED( result ) ) {
  5488. errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
  5489. errorText_ = errorStream_.str();
  5490. goto unlock;
  5491. }
  5492. }
  5493. handle->drainCounter = 0;
  5494. handle->internalDrain = false;
  5495. ResetEvent( handle->condition );
  5496. stream_.state = STREAM_RUNNING;
  5497. unlock:
  5498. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5499. }
  5500. void RtApiDs :: stopStream()
  5501. {
  5502. verifyStream();
  5503. if ( stream_.state == STREAM_STOPPED ) {
  5504. errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
  5505. error( RtAudioError::WARNING );
  5506. return;
  5507. }
  5508. HRESULT result = 0;
  5509. LPVOID audioPtr;
  5510. DWORD dataLen;
  5511. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5512. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5513. if ( handle->drainCounter == 0 ) {
  5514. handle->drainCounter = 2;
  5515. WaitForSingleObject( handle->condition, INFINITE ); // block until signaled
  5516. }
  5517. stream_.state = STREAM_STOPPED;
  5518. MUTEX_LOCK( &stream_.mutex );
  5519. // Stop the buffer and clear memory
  5520. LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5521. result = buffer->Stop();
  5522. if ( FAILED( result ) ) {
  5523. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";
  5524. errorText_ = errorStream_.str();
  5525. goto unlock;
  5526. }
  5527. // Lock the buffer and clear it so that if we start to play again,
  5528. // we won't have old data playing.
  5529. result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
  5530. if ( FAILED( result ) ) {
  5531. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";
  5532. errorText_ = errorStream_.str();
  5533. goto unlock;
  5534. }
  5535. // Zero the DS buffer
  5536. ZeroMemory( audioPtr, dataLen );
  5537. // Unlock the DS buffer
  5538. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5539. if ( FAILED( result ) ) {
  5540. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
  5541. errorText_ = errorStream_.str();
  5542. goto unlock;
  5543. }
  5544. // If we start playing again, we must begin at beginning of buffer.
  5545. handle->bufferPointer[0] = 0;
  5546. }
  5547. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5548. LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5549. audioPtr = NULL;
  5550. dataLen = 0;
  5551. stream_.state = STREAM_STOPPED;
  5552. if ( stream_.mode != DUPLEX )
  5553. MUTEX_LOCK( &stream_.mutex );
  5554. result = buffer->Stop();
  5555. if ( FAILED( result ) ) {
  5556. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";
  5557. errorText_ = errorStream_.str();
  5558. goto unlock;
  5559. }
  5560. // Lock the buffer and clear it so that if we start to play again,
  5561. // we won't have old data playing.
  5562. result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
  5563. if ( FAILED( result ) ) {
  5564. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";
  5565. errorText_ = errorStream_.str();
  5566. goto unlock;
  5567. }
  5568. // Zero the DS buffer
  5569. ZeroMemory( audioPtr, dataLen );
  5570. // Unlock the DS buffer
  5571. result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
  5572. if ( FAILED( result ) ) {
  5573. errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
  5574. errorText_ = errorStream_.str();
  5575. goto unlock;
  5576. }
  5577. // If we start recording again, we must begin at beginning of buffer.
  5578. handle->bufferPointer[1] = 0;
  5579. }
  5580. unlock:
  5581. timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
  5582. MUTEX_UNLOCK( &stream_.mutex );
  5583. if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );
  5584. }
  5585. void RtApiDs :: abortStream()
  5586. {
  5587. verifyStream();
  5588. if ( stream_.state == STREAM_STOPPED ) {
  5589. errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
  5590. error( RtAudioError::WARNING );
  5591. return;
  5592. }
  5593. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5594. handle->drainCounter = 2;
  5595. stopStream();
  5596. }
  5597. void RtApiDs :: callbackEvent()
  5598. {
  5599. if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {
  5600. Sleep( 50 ); // sleep 50 milliseconds
  5601. return;
  5602. }
  5603. if ( stream_.state == STREAM_CLOSED ) {
  5604. errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
  5605. error( RtAudioError::WARNING );
  5606. return;
  5607. }
  5608. CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
  5609. DsHandle *handle = (DsHandle *) stream_.apiHandle;
  5610. // Check if we were draining the stream and signal is finished.
  5611. if ( handle->drainCounter > stream_.nBuffers + 2 ) {
  5612. stream_.state = STREAM_STOPPING;
  5613. if ( handle->internalDrain == false )
  5614. SetEvent( handle->condition );
  5615. else
  5616. stopStream();
  5617. return;
  5618. }
  5619. // Invoke user callback to get fresh output data UNLESS we are
  5620. // draining stream.
  5621. if ( handle->drainCounter == 0 ) {
  5622. RtAudioCallback callback = (RtAudioCallback) info->callback;
  5623. double streamTime = getStreamTime();
  5624. RtAudioStreamStatus status = 0;
  5625. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  5626. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  5627. handle->xrun[0] = false;
  5628. }
  5629. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  5630. status |= RTAUDIO_INPUT_OVERFLOW;
  5631. handle->xrun[1] = false;
  5632. }
  5633. int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  5634. stream_.bufferSize, streamTime, status, info->userData );
  5635. if ( cbReturnValue == 2 ) {
  5636. stream_.state = STREAM_STOPPING;
  5637. handle->drainCounter = 2;
  5638. abortStream();
  5639. return;
  5640. }
  5641. else if ( cbReturnValue == 1 ) {
  5642. handle->drainCounter = 1;
  5643. handle->internalDrain = true;
  5644. }
  5645. }
  5646. HRESULT result;
  5647. DWORD currentWritePointer, safeWritePointer;
  5648. DWORD currentReadPointer, safeReadPointer;
  5649. UINT nextWritePointer;
  5650. LPVOID buffer1 = NULL;
  5651. LPVOID buffer2 = NULL;
  5652. DWORD bufferSize1 = 0;
  5653. DWORD bufferSize2 = 0;
  5654. char *buffer;
  5655. long bufferBytes;
  5656. MUTEX_LOCK( &stream_.mutex );
  5657. if ( stream_.state == STREAM_STOPPED ) {
  5658. MUTEX_UNLOCK( &stream_.mutex );
  5659. return;
  5660. }
  5661. if ( buffersRolling == false ) {
  5662. if ( stream_.mode == DUPLEX ) {
  5663. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5664. // It takes a while for the devices to get rolling. As a result,
  5665. // there's no guarantee that the capture and write device pointers
  5666. // will move in lockstep. Wait here for both devices to start
  5667. // rolling, and then set our buffer pointers accordingly.
  5668. // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
  5669. // bytes later than the write buffer.
  5670. // Stub: a serious risk of having a pre-emptive scheduling round
  5671. // take place between the two GetCurrentPosition calls... but I'm
  5672. // really not sure how to solve the problem. Temporarily boost to
  5673. // Realtime priority, maybe; but I'm not sure what priority the
  5674. // DirectSound service threads run at. We *should* be roughly
  5675. // within a ms or so of correct.
  5676. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5677. LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5678. DWORD startSafeWritePointer, startSafeReadPointer;
  5679. result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );
  5680. if ( FAILED( result ) ) {
  5681. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5682. errorText_ = errorStream_.str();
  5683. MUTEX_UNLOCK( &stream_.mutex );
  5684. error( RtAudioError::SYSTEM_ERROR );
  5685. return;
  5686. }
  5687. result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );
  5688. if ( FAILED( result ) ) {
  5689. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5690. errorText_ = errorStream_.str();
  5691. MUTEX_UNLOCK( &stream_.mutex );
  5692. error( RtAudioError::SYSTEM_ERROR );
  5693. return;
  5694. }
  5695. while ( true ) {
  5696. result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );
  5697. if ( FAILED( result ) ) {
  5698. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5699. errorText_ = errorStream_.str();
  5700. MUTEX_UNLOCK( &stream_.mutex );
  5701. error( RtAudioError::SYSTEM_ERROR );
  5702. return;
  5703. }
  5704. result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );
  5705. if ( FAILED( result ) ) {
  5706. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5707. errorText_ = errorStream_.str();
  5708. MUTEX_UNLOCK( &stream_.mutex );
  5709. error( RtAudioError::SYSTEM_ERROR );
  5710. return;
  5711. }
  5712. if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;
  5713. Sleep( 1 );
  5714. }
  5715. //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
  5716. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5717. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5718. handle->bufferPointer[1] = safeReadPointer;
  5719. }
  5720. else if ( stream_.mode == OUTPUT ) {
  5721. // Set the proper nextWritePosition after initial startup.
  5722. LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5723. result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5724. if ( FAILED( result ) ) {
  5725. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5726. errorText_ = errorStream_.str();
  5727. MUTEX_UNLOCK( &stream_.mutex );
  5728. error( RtAudioError::SYSTEM_ERROR );
  5729. return;
  5730. }
  5731. handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];
  5732. if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];
  5733. }
  5734. buffersRolling = true;
  5735. }
  5736. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  5737. LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
  5738. if ( handle->drainCounter > 1 ) { // write zeros to the output stream
  5739. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5740. bufferBytes *= formatBytes( stream_.userFormat );
  5741. memset( stream_.userBuffer[0], 0, bufferBytes );
  5742. }
  5743. // Setup parameters and do buffer conversion if necessary.
  5744. if ( stream_.doConvertBuffer[0] ) {
  5745. buffer = stream_.deviceBuffer;
  5746. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  5747. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
  5748. bufferBytes *= formatBytes( stream_.deviceFormat[0] );
  5749. }
  5750. else {
  5751. buffer = stream_.userBuffer[0];
  5752. bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
  5753. bufferBytes *= formatBytes( stream_.userFormat );
  5754. }
  5755. // No byte swapping necessary in DirectSound implementation.
  5756. // Ahhh ... windoze. 16-bit data is signed but 8-bit data is
  5757. // unsigned. So, we need to convert our signed 8-bit data here to
  5758. // unsigned.
  5759. if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
  5760. for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
  5761. DWORD dsBufferSize = handle->dsBufferSize[0];
  5762. nextWritePointer = handle->bufferPointer[0];
  5763. DWORD endWrite, leadPointer;
  5764. while ( true ) {
  5765. // Find out where the read and "safe write" pointers are.
  5766. result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );
  5767. if ( FAILED( result ) ) {
  5768. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
  5769. errorText_ = errorStream_.str();
  5770. MUTEX_UNLOCK( &stream_.mutex );
  5771. error( RtAudioError::SYSTEM_ERROR );
  5772. return;
  5773. }
  5774. // We will copy our output buffer into the region between
  5775. // safeWritePointer and leadPointer. If leadPointer is not
  5776. // beyond the next endWrite position, wait until it is.
  5777. leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];
  5778. //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;
  5779. if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;
  5780. if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset
  5781. endWrite = nextWritePointer + bufferBytes;
  5782. // Check whether the entire write region is behind the play pointer.
  5783. if ( leadPointer >= endWrite ) break;
  5784. // If we are here, then we must wait until the leadPointer advances
  5785. // beyond the end of our next write region. We use the
  5786. // Sleep() function to suspend operation until that happens.
  5787. double millis = ( endWrite - leadPointer ) * 1000.0;
  5788. millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
  5789. if ( millis < 1.0 ) millis = 1.0;
  5790. Sleep( (DWORD) millis );
  5791. }
  5792. if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )
  5793. || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {
  5794. // We've strayed into the forbidden zone ... resync the read pointer.
  5795. handle->xrun[0] = true;
  5796. nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;
  5797. if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;
  5798. handle->bufferPointer[0] = nextWritePointer;
  5799. endWrite = nextWritePointer + bufferBytes;
  5800. }
  5801. // Lock free space in the buffer
  5802. result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,
  5803. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5804. if ( FAILED( result ) ) {
  5805. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
  5806. errorText_ = errorStream_.str();
  5807. MUTEX_UNLOCK( &stream_.mutex );
  5808. error( RtAudioError::SYSTEM_ERROR );
  5809. return;
  5810. }
  5811. // Copy our buffer into the DS buffer
  5812. CopyMemory( buffer1, buffer, bufferSize1 );
  5813. if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
  5814. // Update our buffer offset and unlock sound buffer
  5815. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5816. if ( FAILED( result ) ) {
  5817. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
  5818. errorText_ = errorStream_.str();
  5819. MUTEX_UNLOCK( &stream_.mutex );
  5820. error( RtAudioError::SYSTEM_ERROR );
  5821. return;
  5822. }
  5823. nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5824. handle->bufferPointer[0] = nextWritePointer;
  5825. }
  5826. // Don't bother draining input
  5827. if ( handle->drainCounter ) {
  5828. handle->drainCounter++;
  5829. goto unlock;
  5830. }
  5831. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  5832. // Setup parameters.
  5833. if ( stream_.doConvertBuffer[1] ) {
  5834. buffer = stream_.deviceBuffer;
  5835. bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
  5836. bufferBytes *= formatBytes( stream_.deviceFormat[1] );
  5837. }
  5838. else {
  5839. buffer = stream_.userBuffer[1];
  5840. bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
  5841. bufferBytes *= formatBytes( stream_.userFormat );
  5842. }
  5843. LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
  5844. long nextReadPointer = handle->bufferPointer[1];
  5845. DWORD dsBufferSize = handle->dsBufferSize[1];
  5846. // Find out where the write and "safe read" pointers are.
  5847. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5848. if ( FAILED( result ) ) {
  5849. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5850. errorText_ = errorStream_.str();
  5851. MUTEX_UNLOCK( &stream_.mutex );
  5852. error( RtAudioError::SYSTEM_ERROR );
  5853. return;
  5854. }
  5855. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5856. DWORD endRead = nextReadPointer + bufferBytes;
  5857. // Handling depends on whether we are INPUT or DUPLEX.
  5858. // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
  5859. // then a wait here will drag the write pointers into the forbidden zone.
  5860. //
  5861. // In DUPLEX mode, rather than wait, we will back off the read pointer until
  5862. // it's in a safe position. This causes dropouts, but it seems to be the only
  5863. // practical way to sync up the read and write pointers reliably, given the
  5864. // the very complex relationship between phase and increment of the read and write
  5865. // pointers.
  5866. //
  5867. // In order to minimize audible dropouts in DUPLEX mode, we will
  5868. // provide a pre-roll period of 0.5 seconds in which we return
  5869. // zeros from the read buffer while the pointers sync up.
  5870. if ( stream_.mode == DUPLEX ) {
  5871. if ( safeReadPointer < endRead ) {
  5872. if ( duplexPrerollBytes <= 0 ) {
  5873. // Pre-roll time over. Be more agressive.
  5874. int adjustment = endRead-safeReadPointer;
  5875. handle->xrun[1] = true;
  5876. // Two cases:
  5877. // - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
  5878. // and perform fine adjustments later.
  5879. // - small adjustments: back off by twice as much.
  5880. if ( adjustment >= 2*bufferBytes )
  5881. nextReadPointer = safeReadPointer-2*bufferBytes;
  5882. else
  5883. nextReadPointer = safeReadPointer-bufferBytes-adjustment;
  5884. if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5885. }
  5886. else {
  5887. // In pre=roll time. Just do it.
  5888. nextReadPointer = safeReadPointer - bufferBytes;
  5889. while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;
  5890. }
  5891. endRead = nextReadPointer + bufferBytes;
  5892. }
  5893. }
  5894. else { // mode == INPUT
  5895. while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {
  5896. // See comments for playback.
  5897. double millis = (endRead - safeReadPointer) * 1000.0;
  5898. millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
  5899. if ( millis < 1.0 ) millis = 1.0;
  5900. Sleep( (DWORD) millis );
  5901. // Wake up and find out where we are now.
  5902. result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );
  5903. if ( FAILED( result ) ) {
  5904. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
  5905. errorText_ = errorStream_.str();
  5906. MUTEX_UNLOCK( &stream_.mutex );
  5907. error( RtAudioError::SYSTEM_ERROR );
  5908. return;
  5909. }
  5910. if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset
  5911. }
  5912. }
  5913. // Lock free space in the buffer
  5914. result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,
  5915. &bufferSize1, &buffer2, &bufferSize2, 0 );
  5916. if ( FAILED( result ) ) {
  5917. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
  5918. errorText_ = errorStream_.str();
  5919. MUTEX_UNLOCK( &stream_.mutex );
  5920. error( RtAudioError::SYSTEM_ERROR );
  5921. return;
  5922. }
  5923. if ( duplexPrerollBytes <= 0 ) {
  5924. // Copy our buffer into the DS buffer
  5925. CopyMemory( buffer, buffer1, bufferSize1 );
  5926. if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
  5927. }
  5928. else {
  5929. memset( buffer, 0, bufferSize1 );
  5930. if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
  5931. duplexPrerollBytes -= bufferSize1 + bufferSize2;
  5932. }
  5933. // Update our buffer offset and unlock sound buffer
  5934. nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;
  5935. dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
  5936. if ( FAILED( result ) ) {
  5937. errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
  5938. errorText_ = errorStream_.str();
  5939. MUTEX_UNLOCK( &stream_.mutex );
  5940. error( RtAudioError::SYSTEM_ERROR );
  5941. return;
  5942. }
  5943. handle->bufferPointer[1] = nextReadPointer;
  5944. // No byte swapping necessary in DirectSound implementation.
  5945. // If necessary, convert 8-bit data from unsigned to signed.
  5946. if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
  5947. for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
  5948. // Do buffer conversion if necessary.
  5949. if ( stream_.doConvertBuffer[1] )
  5950. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  5951. }
  5952. unlock:
  5953. MUTEX_UNLOCK( &stream_.mutex );
  5954. RtApi::tickStreamTime();
  5955. }
  5956. // Definitions for utility functions and callbacks
  5957. // specific to the DirectSound implementation.
  5958. static unsigned __stdcall callbackHandler( void *ptr )
  5959. {
  5960. CallbackInfo *info = (CallbackInfo *) ptr;
  5961. RtApiDs *object = (RtApiDs *) info->object;
  5962. bool* isRunning = &info->isRunning;
  5963. while ( *isRunning == true ) {
  5964. object->callbackEvent();
  5965. }
  5966. _endthreadex( 0 );
  5967. return 0;
  5968. }
  5969. static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
  5970. LPCTSTR description,
  5971. LPCTSTR /*module*/,
  5972. LPVOID lpContext )
  5973. {
  5974. struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;
  5975. std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;
  5976. HRESULT hr;
  5977. bool validDevice = false;
  5978. if ( probeInfo.isInput == true ) {
  5979. DSCCAPS caps;
  5980. LPDIRECTSOUNDCAPTURE object;
  5981. hr = DirectSoundCaptureCreate( lpguid, &object, NULL );
  5982. if ( hr != DS_OK ) return TRUE;
  5983. caps.dwSize = sizeof(caps);
  5984. hr = object->GetCaps( &caps );
  5985. if ( hr == DS_OK ) {
  5986. if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
  5987. validDevice = true;
  5988. }
  5989. object->Release();
  5990. }
  5991. else {
  5992. DSCAPS caps;
  5993. LPDIRECTSOUND object;
  5994. hr = DirectSoundCreate( lpguid, &object, NULL );
  5995. if ( hr != DS_OK ) return TRUE;
  5996. caps.dwSize = sizeof(caps);
  5997. hr = object->GetCaps( &caps );
  5998. if ( hr == DS_OK ) {
  5999. if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
  6000. validDevice = true;
  6001. }
  6002. object->Release();
  6003. }
  6004. // If good device, then save its name and guid.
  6005. std::string name = convertCharPointerToStdString( description );
  6006. //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )
  6007. if ( lpguid == NULL )
  6008. name = "Default Device";
  6009. if ( validDevice ) {
  6010. for ( unsigned int i=0; i<dsDevices.size(); i++ ) {
  6011. if ( dsDevices[i].name == name ) {
  6012. dsDevices[i].found = true;
  6013. if ( probeInfo.isInput ) {
  6014. dsDevices[i].id[1] = lpguid;
  6015. dsDevices[i].validId[1] = true;
  6016. }
  6017. else {
  6018. dsDevices[i].id[0] = lpguid;
  6019. dsDevices[i].validId[0] = true;
  6020. }
  6021. return TRUE;
  6022. }
  6023. }
  6024. DsDevice device;
  6025. device.name = name;
  6026. device.found = true;
  6027. if ( probeInfo.isInput ) {
  6028. device.id[1] = lpguid;
  6029. device.validId[1] = true;
  6030. }
  6031. else {
  6032. device.id[0] = lpguid;
  6033. device.validId[0] = true;
  6034. }
  6035. dsDevices.push_back( device );
  6036. }
  6037. return TRUE;
  6038. }
  6039. static const char* getErrorString( int code )
  6040. {
  6041. switch ( code ) {
  6042. case DSERR_ALLOCATED:
  6043. return "Already allocated";
  6044. case DSERR_CONTROLUNAVAIL:
  6045. return "Control unavailable";
  6046. case DSERR_INVALIDPARAM:
  6047. return "Invalid parameter";
  6048. case DSERR_INVALIDCALL:
  6049. return "Invalid call";
  6050. case DSERR_GENERIC:
  6051. return "Generic error";
  6052. case DSERR_PRIOLEVELNEEDED:
  6053. return "Priority level needed";
  6054. case DSERR_OUTOFMEMORY:
  6055. return "Out of memory";
  6056. case DSERR_BADFORMAT:
  6057. return "The sample rate or the channel format is not supported";
  6058. case DSERR_UNSUPPORTED:
  6059. return "Not supported";
  6060. case DSERR_NODRIVER:
  6061. return "No driver";
  6062. case DSERR_ALREADYINITIALIZED:
  6063. return "Already initialized";
  6064. case DSERR_NOAGGREGATION:
  6065. return "No aggregation";
  6066. case DSERR_BUFFERLOST:
  6067. return "Buffer lost";
  6068. case DSERR_OTHERAPPHASPRIO:
  6069. return "Another application already has priority";
  6070. case DSERR_UNINITIALIZED:
  6071. return "Uninitialized";
  6072. default:
  6073. return "DirectSound unknown error";
  6074. }
  6075. }
  6076. //******************** End of __WINDOWS_DS__ *********************//
  6077. #endif
  6078. #if defined(__LINUX_ALSA__)
  6079. #include <alsa/asoundlib.h>
  6080. #include <unistd.h>
  6081. // A structure to hold various information related to the ALSA API
  6082. // implementation.
  6083. struct AlsaHandle {
  6084. snd_pcm_t *handles[2];
  6085. bool synchronized;
  6086. bool xrun[2];
  6087. pthread_cond_t runnable_cv;
  6088. bool runnable;
  6089. AlsaHandle()
  6090. :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }
  6091. };
  6092. static void *alsaCallbackHandler( void * ptr );
  6093. RtApiAlsa :: RtApiAlsa()
  6094. {
  6095. // Nothing to do here.
  6096. }
  6097. RtApiAlsa :: ~RtApiAlsa()
  6098. {
  6099. if ( stream_.state != STREAM_CLOSED ) closeStream();
  6100. }
  6101. unsigned int RtApiAlsa :: getDeviceCount( void )
  6102. {
  6103. unsigned nDevices = 0;
  6104. int result, subdevice, card;
  6105. char name[64];
  6106. snd_ctl_t *handle = 0;
  6107. // Count cards and devices
  6108. card = -1;
  6109. snd_card_next( &card );
  6110. while ( card >= 0 ) {
  6111. sprintf( name, "hw:%d", card );
  6112. result = snd_ctl_open( &handle, name, 0 );
  6113. if ( result < 0 ) {
  6114. handle = 0;
  6115. errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6116. errorText_ = errorStream_.str();
  6117. error( RtAudioError::WARNING );
  6118. goto nextcard;
  6119. }
  6120. subdevice = -1;
  6121. while( 1 ) {
  6122. result = snd_ctl_pcm_next_device( handle, &subdevice );
  6123. if ( result < 0 ) {
  6124. errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  6125. errorText_ = errorStream_.str();
  6126. error( RtAudioError::WARNING );
  6127. break;
  6128. }
  6129. if ( subdevice < 0 )
  6130. break;
  6131. nDevices++;
  6132. }
  6133. nextcard:
  6134. if ( handle )
  6135. snd_ctl_close( handle );
  6136. snd_card_next( &card );
  6137. }
  6138. result = snd_ctl_open( &handle, "default", 0 );
  6139. if (result == 0) {
  6140. nDevices++;
  6141. snd_ctl_close( handle );
  6142. }
  6143. return nDevices;
  6144. }
  6145. RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
  6146. {
  6147. RtAudio::DeviceInfo info;
  6148. info.probed = false;
  6149. unsigned nDevices = 0;
  6150. int result, subdevice, card;
  6151. char name[64];
  6152. snd_ctl_t *chandle = 0;
  6153. // Count cards and devices
  6154. card = -1;
  6155. subdevice = -1;
  6156. snd_card_next( &card );
  6157. while ( card >= 0 ) {
  6158. sprintf( name, "hw:%d", card );
  6159. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  6160. if ( result < 0 ) {
  6161. chandle = 0;
  6162. errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6163. errorText_ = errorStream_.str();
  6164. error( RtAudioError::WARNING );
  6165. goto nextcard;
  6166. }
  6167. subdevice = -1;
  6168. while( 1 ) {
  6169. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  6170. if ( result < 0 ) {
  6171. errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
  6172. errorText_ = errorStream_.str();
  6173. error( RtAudioError::WARNING );
  6174. break;
  6175. }
  6176. if ( subdevice < 0 ) break;
  6177. if ( nDevices == device ) {
  6178. sprintf( name, "hw:%d,%d", card, subdevice );
  6179. goto foundDevice;
  6180. }
  6181. nDevices++;
  6182. }
  6183. nextcard:
  6184. if ( chandle )
  6185. snd_ctl_close( chandle );
  6186. snd_card_next( &card );
  6187. }
  6188. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6189. if ( result == 0 ) {
  6190. if ( nDevices == device ) {
  6191. strcpy( name, "default" );
  6192. goto foundDevice;
  6193. }
  6194. nDevices++;
  6195. }
  6196. if ( nDevices == 0 ) {
  6197. errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
  6198. error( RtAudioError::INVALID_USE );
  6199. return info;
  6200. }
  6201. if ( device >= nDevices ) {
  6202. errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
  6203. error( RtAudioError::INVALID_USE );
  6204. return info;
  6205. }
  6206. foundDevice:
  6207. // If a stream is already open, we cannot probe the stream devices.
  6208. // Thus, use the saved results.
  6209. if ( stream_.state != STREAM_CLOSED &&
  6210. ( stream_.device[0] == device || stream_.device[1] == device ) ) {
  6211. snd_ctl_close( chandle );
  6212. if ( device >= devices_.size() ) {
  6213. errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
  6214. error( RtAudioError::WARNING );
  6215. return info;
  6216. }
  6217. return devices_[ device ];
  6218. }
  6219. int openMode = SND_PCM_ASYNC;
  6220. snd_pcm_stream_t stream;
  6221. snd_pcm_info_t *pcminfo;
  6222. snd_pcm_info_alloca( &pcminfo );
  6223. snd_pcm_t *phandle;
  6224. snd_pcm_hw_params_t *params;
  6225. snd_pcm_hw_params_alloca( &params );
  6226. // First try for playback unless default device (which has subdev -1)
  6227. stream = SND_PCM_STREAM_PLAYBACK;
  6228. snd_pcm_info_set_stream( pcminfo, stream );
  6229. if ( subdevice != -1 ) {
  6230. snd_pcm_info_set_device( pcminfo, subdevice );
  6231. snd_pcm_info_set_subdevice( pcminfo, 0 );
  6232. result = snd_ctl_pcm_info( chandle, pcminfo );
  6233. if ( result < 0 ) {
  6234. // Device probably doesn't support playback.
  6235. goto captureProbe;
  6236. }
  6237. }
  6238. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
  6239. if ( result < 0 ) {
  6240. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6241. errorText_ = errorStream_.str();
  6242. error( RtAudioError::WARNING );
  6243. goto captureProbe;
  6244. }
  6245. // The device is open ... fill the parameter structure.
  6246. result = snd_pcm_hw_params_any( phandle, params );
  6247. if ( result < 0 ) {
  6248. snd_pcm_close( phandle );
  6249. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6250. errorText_ = errorStream_.str();
  6251. error( RtAudioError::WARNING );
  6252. goto captureProbe;
  6253. }
  6254. // Get output channel information.
  6255. unsigned int value;
  6256. result = snd_pcm_hw_params_get_channels_max( params, &value );
  6257. if ( result < 0 ) {
  6258. snd_pcm_close( phandle );
  6259. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
  6260. errorText_ = errorStream_.str();
  6261. error( RtAudioError::WARNING );
  6262. goto captureProbe;
  6263. }
  6264. info.outputChannels = value;
  6265. snd_pcm_close( phandle );
  6266. captureProbe:
  6267. stream = SND_PCM_STREAM_CAPTURE;
  6268. snd_pcm_info_set_stream( pcminfo, stream );
  6269. // Now try for capture unless default device (with subdev = -1)
  6270. if ( subdevice != -1 ) {
  6271. result = snd_ctl_pcm_info( chandle, pcminfo );
  6272. snd_ctl_close( chandle );
  6273. if ( result < 0 ) {
  6274. // Device probably doesn't support capture.
  6275. if ( info.outputChannels == 0 ) return info;
  6276. goto probeParameters;
  6277. }
  6278. }
  6279. else
  6280. snd_ctl_close( chandle );
  6281. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  6282. if ( result < 0 ) {
  6283. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6284. errorText_ = errorStream_.str();
  6285. error( RtAudioError::WARNING );
  6286. if ( info.outputChannels == 0 ) return info;
  6287. goto probeParameters;
  6288. }
  6289. // The device is open ... fill the parameter structure.
  6290. result = snd_pcm_hw_params_any( phandle, params );
  6291. if ( result < 0 ) {
  6292. snd_pcm_close( phandle );
  6293. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6294. errorText_ = errorStream_.str();
  6295. error( RtAudioError::WARNING );
  6296. if ( info.outputChannels == 0 ) return info;
  6297. goto probeParameters;
  6298. }
  6299. result = snd_pcm_hw_params_get_channels_max( params, &value );
  6300. if ( result < 0 ) {
  6301. snd_pcm_close( phandle );
  6302. errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
  6303. errorText_ = errorStream_.str();
  6304. error( RtAudioError::WARNING );
  6305. if ( info.outputChannels == 0 ) return info;
  6306. goto probeParameters;
  6307. }
  6308. info.inputChannels = value;
  6309. snd_pcm_close( phandle );
  6310. // If device opens for both playback and capture, we determine the channels.
  6311. if ( info.outputChannels > 0 && info.inputChannels > 0 )
  6312. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  6313. // ALSA doesn't provide default devices so we'll use the first available one.
  6314. if ( device == 0 && info.outputChannels > 0 )
  6315. info.isDefaultOutput = true;
  6316. if ( device == 0 && info.inputChannels > 0 )
  6317. info.isDefaultInput = true;
  6318. probeParameters:
  6319. // At this point, we just need to figure out the supported data
  6320. // formats and sample rates. We'll proceed by opening the device in
  6321. // the direction with the maximum number of channels, or playback if
  6322. // they are equal. This might limit our sample rate options, but so
  6323. // be it.
  6324. if ( info.outputChannels >= info.inputChannels )
  6325. stream = SND_PCM_STREAM_PLAYBACK;
  6326. else
  6327. stream = SND_PCM_STREAM_CAPTURE;
  6328. snd_pcm_info_set_stream( pcminfo, stream );
  6329. result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
  6330. if ( result < 0 ) {
  6331. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
  6332. errorText_ = errorStream_.str();
  6333. error( RtAudioError::WARNING );
  6334. return info;
  6335. }
  6336. // The device is open ... fill the parameter structure.
  6337. result = snd_pcm_hw_params_any( phandle, params );
  6338. if ( result < 0 ) {
  6339. snd_pcm_close( phandle );
  6340. errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
  6341. errorText_ = errorStream_.str();
  6342. error( RtAudioError::WARNING );
  6343. return info;
  6344. }
  6345. // Test our discrete set of sample rate values.
  6346. info.sampleRates.clear();
  6347. for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
  6348. if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {
  6349. info.sampleRates.push_back( SAMPLE_RATES[i] );
  6350. if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )
  6351. info.preferredSampleRate = SAMPLE_RATES[i];
  6352. }
  6353. }
  6354. if ( info.sampleRates.size() == 0 ) {
  6355. snd_pcm_close( phandle );
  6356. errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
  6357. errorText_ = errorStream_.str();
  6358. error( RtAudioError::WARNING );
  6359. return info;
  6360. }
  6361. // Probe the supported data formats ... we don't care about endian-ness just yet
  6362. snd_pcm_format_t format;
  6363. info.nativeFormats = 0;
  6364. format = SND_PCM_FORMAT_S8;
  6365. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6366. info.nativeFormats |= RTAUDIO_SINT8;
  6367. format = SND_PCM_FORMAT_S16;
  6368. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6369. info.nativeFormats |= RTAUDIO_SINT16;
  6370. format = SND_PCM_FORMAT_S24;
  6371. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6372. info.nativeFormats |= RTAUDIO_SINT24;
  6373. format = SND_PCM_FORMAT_S32;
  6374. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6375. info.nativeFormats |= RTAUDIO_SINT32;
  6376. format = SND_PCM_FORMAT_FLOAT;
  6377. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6378. info.nativeFormats |= RTAUDIO_FLOAT32;
  6379. format = SND_PCM_FORMAT_FLOAT64;
  6380. if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
  6381. info.nativeFormats |= RTAUDIO_FLOAT64;
  6382. // Check that we have at least one supported format
  6383. if ( info.nativeFormats == 0 ) {
  6384. snd_pcm_close( phandle );
  6385. errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
  6386. errorText_ = errorStream_.str();
  6387. error( RtAudioError::WARNING );
  6388. return info;
  6389. }
  6390. // Get the device name
  6391. char *cardname;
  6392. result = snd_card_get_name( card, &cardname );
  6393. if ( result >= 0 ) {
  6394. sprintf( name, "hw:%s,%d", cardname, subdevice );
  6395. free( cardname );
  6396. }
  6397. info.name = name;
  6398. // That's all ... close the device and return
  6399. snd_pcm_close( phandle );
  6400. info.probed = true;
  6401. return info;
  6402. }
  6403. void RtApiAlsa :: saveDeviceInfo( void )
  6404. {
  6405. devices_.clear();
  6406. unsigned int nDevices = getDeviceCount();
  6407. devices_.resize( nDevices );
  6408. for ( unsigned int i=0; i<nDevices; i++ )
  6409. devices_[i] = getDeviceInfo( i );
  6410. }
  6411. bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  6412. unsigned int firstChannel, unsigned int sampleRate,
  6413. RtAudioFormat format, unsigned int *bufferSize,
  6414. RtAudio::StreamOptions *options )
  6415. {
  6416. #if defined(__RTAUDIO_DEBUG__)
  6417. snd_output_t *out;
  6418. snd_output_stdio_attach(&out, stderr, 0);
  6419. #endif
  6420. // I'm not using the "plug" interface ... too much inconsistent behavior.
  6421. unsigned nDevices = 0;
  6422. int result, subdevice, card;
  6423. char name[64];
  6424. snd_ctl_t *chandle;
  6425. if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )
  6426. snprintf(name, sizeof(name), "%s", "default");
  6427. else {
  6428. // Count cards and devices
  6429. card = -1;
  6430. snd_card_next( &card );
  6431. while ( card >= 0 ) {
  6432. sprintf( name, "hw:%d", card );
  6433. result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
  6434. if ( result < 0 ) {
  6435. errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
  6436. errorText_ = errorStream_.str();
  6437. return FAILURE;
  6438. }
  6439. subdevice = -1;
  6440. while( 1 ) {
  6441. result = snd_ctl_pcm_next_device( chandle, &subdevice );
  6442. if ( result < 0 ) break;
  6443. if ( subdevice < 0 ) break;
  6444. if ( nDevices == device ) {
  6445. sprintf( name, "hw:%d,%d", card, subdevice );
  6446. snd_ctl_close( chandle );
  6447. goto foundDevice;
  6448. }
  6449. nDevices++;
  6450. }
  6451. snd_ctl_close( chandle );
  6452. snd_card_next( &card );
  6453. }
  6454. result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );
  6455. if ( result == 0 ) {
  6456. if ( nDevices == device ) {
  6457. strcpy( name, "default" );
  6458. snd_ctl_close( chandle );
  6459. goto foundDevice;
  6460. }
  6461. nDevices++;
  6462. }
  6463. snd_ctl_close( chandle );
  6464. if ( nDevices == 0 ) {
  6465. // This should not happen because a check is made before this function is called.
  6466. errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
  6467. return FAILURE;
  6468. }
  6469. if ( device >= nDevices ) {
  6470. // This should not happen because a check is made before this function is called.
  6471. errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
  6472. return FAILURE;
  6473. }
  6474. }
  6475. foundDevice:
  6476. // The getDeviceInfo() function will not work for a device that is
  6477. // already open. Thus, we'll probe the system before opening a
  6478. // stream and save the results for use by getDeviceInfo().
  6479. if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
  6480. this->saveDeviceInfo();
  6481. snd_pcm_stream_t stream;
  6482. if ( mode == OUTPUT )
  6483. stream = SND_PCM_STREAM_PLAYBACK;
  6484. else
  6485. stream = SND_PCM_STREAM_CAPTURE;
  6486. snd_pcm_t *phandle;
  6487. int openMode = SND_PCM_ASYNC;
  6488. result = snd_pcm_open( &phandle, name, stream, openMode );
  6489. if ( result < 0 ) {
  6490. if ( mode == OUTPUT )
  6491. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
  6492. else
  6493. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
  6494. errorText_ = errorStream_.str();
  6495. return FAILURE;
  6496. }
  6497. // Fill the parameter structure.
  6498. snd_pcm_hw_params_t *hw_params;
  6499. snd_pcm_hw_params_alloca( &hw_params );
  6500. result = snd_pcm_hw_params_any( phandle, hw_params );
  6501. if ( result < 0 ) {
  6502. snd_pcm_close( phandle );
  6503. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
  6504. errorText_ = errorStream_.str();
  6505. return FAILURE;
  6506. }
  6507. #if defined(__RTAUDIO_DEBUG__)
  6508. fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
  6509. snd_pcm_hw_params_dump( hw_params, out );
  6510. #endif
  6511. // Set access ... check user preference.
  6512. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
  6513. stream_.userInterleaved = false;
  6514. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6515. if ( result < 0 ) {
  6516. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6517. stream_.deviceInterleaved[mode] = true;
  6518. }
  6519. else
  6520. stream_.deviceInterleaved[mode] = false;
  6521. }
  6522. else {
  6523. stream_.userInterleaved = true;
  6524. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
  6525. if ( result < 0 ) {
  6526. result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
  6527. stream_.deviceInterleaved[mode] = false;
  6528. }
  6529. else
  6530. stream_.deviceInterleaved[mode] = true;
  6531. }
  6532. if ( result < 0 ) {
  6533. snd_pcm_close( phandle );
  6534. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
  6535. errorText_ = errorStream_.str();
  6536. return FAILURE;
  6537. }
  6538. // Determine how to set the device format.
  6539. stream_.userFormat = format;
  6540. snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
  6541. if ( format == RTAUDIO_SINT8 )
  6542. deviceFormat = SND_PCM_FORMAT_S8;
  6543. else if ( format == RTAUDIO_SINT16 )
  6544. deviceFormat = SND_PCM_FORMAT_S16;
  6545. else if ( format == RTAUDIO_SINT24 )
  6546. deviceFormat = SND_PCM_FORMAT_S24;
  6547. else if ( format == RTAUDIO_SINT32 )
  6548. deviceFormat = SND_PCM_FORMAT_S32;
  6549. else if ( format == RTAUDIO_FLOAT32 )
  6550. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6551. else if ( format == RTAUDIO_FLOAT64 )
  6552. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6553. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
  6554. stream_.deviceFormat[mode] = format;
  6555. goto setFormat;
  6556. }
  6557. // The user requested format is not natively supported by the device.
  6558. deviceFormat = SND_PCM_FORMAT_FLOAT64;
  6559. if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
  6560. stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
  6561. goto setFormat;
  6562. }
  6563. deviceFormat = SND_PCM_FORMAT_FLOAT;
  6564. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6565. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  6566. goto setFormat;
  6567. }
  6568. deviceFormat = SND_PCM_FORMAT_S32;
  6569. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6570. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  6571. goto setFormat;
  6572. }
  6573. deviceFormat = SND_PCM_FORMAT_S24;
  6574. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6575. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  6576. goto setFormat;
  6577. }
  6578. deviceFormat = SND_PCM_FORMAT_S16;
  6579. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6580. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  6581. goto setFormat;
  6582. }
  6583. deviceFormat = SND_PCM_FORMAT_S8;
  6584. if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
  6585. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  6586. goto setFormat;
  6587. }
  6588. // If we get here, no supported format was found.
  6589. snd_pcm_close( phandle );
  6590. errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
  6591. errorText_ = errorStream_.str();
  6592. return FAILURE;
  6593. setFormat:
  6594. result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
  6595. if ( result < 0 ) {
  6596. snd_pcm_close( phandle );
  6597. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
  6598. errorText_ = errorStream_.str();
  6599. return FAILURE;
  6600. }
  6601. // Determine whether byte-swaping is necessary.
  6602. stream_.doByteSwap[mode] = false;
  6603. if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
  6604. result = snd_pcm_format_cpu_endian( deviceFormat );
  6605. if ( result == 0 )
  6606. stream_.doByteSwap[mode] = true;
  6607. else if (result < 0) {
  6608. snd_pcm_close( phandle );
  6609. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
  6610. errorText_ = errorStream_.str();
  6611. return FAILURE;
  6612. }
  6613. }
  6614. // Set the sample rate.
  6615. result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
  6616. if ( result < 0 ) {
  6617. snd_pcm_close( phandle );
  6618. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
  6619. errorText_ = errorStream_.str();
  6620. return FAILURE;
  6621. }
  6622. // Determine the number of channels for this device. We support a possible
  6623. // minimum device channel number > than the value requested by the user.
  6624. stream_.nUserChannels[mode] = channels;
  6625. unsigned int value;
  6626. result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
  6627. unsigned int deviceChannels = value;
  6628. if ( result < 0 || deviceChannels < channels + firstChannel ) {
  6629. snd_pcm_close( phandle );
  6630. errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
  6631. errorText_ = errorStream_.str();
  6632. return FAILURE;
  6633. }
  6634. result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
  6635. if ( result < 0 ) {
  6636. snd_pcm_close( phandle );
  6637. errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6638. errorText_ = errorStream_.str();
  6639. return FAILURE;
  6640. }
  6641. deviceChannels = value;
  6642. if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
  6643. stream_.nDeviceChannels[mode] = deviceChannels;
  6644. // Set the device channels.
  6645. result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
  6646. if ( result < 0 ) {
  6647. snd_pcm_close( phandle );
  6648. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
  6649. errorText_ = errorStream_.str();
  6650. return FAILURE;
  6651. }
  6652. // Set the buffer (or period) size.
  6653. int dir = 0;
  6654. snd_pcm_uframes_t periodSize = *bufferSize;
  6655. result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
  6656. if ( result < 0 ) {
  6657. snd_pcm_close( phandle );
  6658. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
  6659. errorText_ = errorStream_.str();
  6660. return FAILURE;
  6661. }
  6662. *bufferSize = periodSize;
  6663. // Set the buffer number, which in ALSA is referred to as the "period".
  6664. unsigned int periods = 0;
  6665. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
  6666. if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;
  6667. if ( periods < 2 ) periods = 4; // a fairly safe default value
  6668. result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
  6669. if ( result < 0 ) {
  6670. snd_pcm_close( phandle );
  6671. errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
  6672. errorText_ = errorStream_.str();
  6673. return FAILURE;
  6674. }
  6675. // If attempting to setup a duplex stream, the bufferSize parameter
  6676. // MUST be the same in both directions!
  6677. if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
  6678. snd_pcm_close( phandle );
  6679. errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
  6680. errorText_ = errorStream_.str();
  6681. return FAILURE;
  6682. }
  6683. stream_.bufferSize = *bufferSize;
  6684. // Install the hardware configuration
  6685. result = snd_pcm_hw_params( phandle, hw_params );
  6686. if ( result < 0 ) {
  6687. snd_pcm_close( phandle );
  6688. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6689. errorText_ = errorStream_.str();
  6690. return FAILURE;
  6691. }
  6692. #if defined(__RTAUDIO_DEBUG__)
  6693. fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
  6694. snd_pcm_hw_params_dump( hw_params, out );
  6695. #endif
  6696. // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
  6697. snd_pcm_sw_params_t *sw_params = NULL;
  6698. snd_pcm_sw_params_alloca( &sw_params );
  6699. snd_pcm_sw_params_current( phandle, sw_params );
  6700. snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
  6701. snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
  6702. snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
  6703. // The following two settings were suggested by Theo Veenker
  6704. //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
  6705. //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
  6706. // here are two options for a fix
  6707. //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
  6708. snd_pcm_uframes_t val;
  6709. snd_pcm_sw_params_get_boundary( sw_params, &val );
  6710. snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
  6711. result = snd_pcm_sw_params( phandle, sw_params );
  6712. if ( result < 0 ) {
  6713. snd_pcm_close( phandle );
  6714. errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
  6715. errorText_ = errorStream_.str();
  6716. return FAILURE;
  6717. }
  6718. #if defined(__RTAUDIO_DEBUG__)
  6719. fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
  6720. snd_pcm_sw_params_dump( sw_params, out );
  6721. #endif
  6722. // Set flags for buffer conversion
  6723. stream_.doConvertBuffer[mode] = false;
  6724. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  6725. stream_.doConvertBuffer[mode] = true;
  6726. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  6727. stream_.doConvertBuffer[mode] = true;
  6728. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  6729. stream_.nUserChannels[mode] > 1 )
  6730. stream_.doConvertBuffer[mode] = true;
  6731. // Allocate the ApiHandle if necessary and then save.
  6732. AlsaHandle *apiInfo = 0;
  6733. if ( stream_.apiHandle == 0 ) {
  6734. try {
  6735. apiInfo = (AlsaHandle *) new AlsaHandle;
  6736. }
  6737. catch ( std::bad_alloc& ) {
  6738. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
  6739. goto error;
  6740. }
  6741. if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {
  6742. errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
  6743. goto error;
  6744. }
  6745. stream_.apiHandle = (void *) apiInfo;
  6746. apiInfo->handles[0] = 0;
  6747. apiInfo->handles[1] = 0;
  6748. }
  6749. else {
  6750. apiInfo = (AlsaHandle *) stream_.apiHandle;
  6751. }
  6752. apiInfo->handles[mode] = phandle;
  6753. phandle = 0;
  6754. // Allocate necessary internal buffers.
  6755. unsigned long bufferBytes;
  6756. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  6757. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  6758. if ( stream_.userBuffer[mode] == NULL ) {
  6759. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
  6760. goto error;
  6761. }
  6762. if ( stream_.doConvertBuffer[mode] ) {
  6763. bool makeBuffer = true;
  6764. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  6765. if ( mode == INPUT ) {
  6766. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  6767. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  6768. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  6769. }
  6770. }
  6771. if ( makeBuffer ) {
  6772. bufferBytes *= *bufferSize;
  6773. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  6774. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  6775. if ( stream_.deviceBuffer == NULL ) {
  6776. errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
  6777. goto error;
  6778. }
  6779. }
  6780. }
  6781. stream_.sampleRate = sampleRate;
  6782. stream_.nBuffers = periods;
  6783. stream_.device[mode] = device;
  6784. stream_.state = STREAM_STOPPED;
  6785. // Setup the buffer conversion information structure.
  6786. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  6787. // Setup thread if necessary.
  6788. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  6789. // We had already set up an output stream.
  6790. stream_.mode = DUPLEX;
  6791. // Link the streams if possible.
  6792. apiInfo->synchronized = false;
  6793. if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
  6794. apiInfo->synchronized = true;
  6795. else {
  6796. errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
  6797. error( RtAudioError::WARNING );
  6798. }
  6799. }
  6800. else {
  6801. stream_.mode = mode;
  6802. // Setup callback thread.
  6803. stream_.callbackInfo.object = (void *) this;
  6804. // Set the thread attributes for joinable and realtime scheduling
  6805. // priority (optional). The higher priority will only take affect
  6806. // if the program is run as root or suid. Note, under Linux
  6807. // processes with CAP_SYS_NICE privilege, a user can change
  6808. // scheduling policy and priority (thus need not be root). See
  6809. // POSIX "capabilities".
  6810. pthread_attr_t attr;
  6811. pthread_attr_init( &attr );
  6812. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  6813. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  6814. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  6815. stream_.callbackInfo.doRealtime = true;
  6816. struct sched_param param;
  6817. int priority = options->priority;
  6818. int min = sched_get_priority_min( SCHED_RR );
  6819. int max = sched_get_priority_max( SCHED_RR );
  6820. if ( priority < min ) priority = min;
  6821. else if ( priority > max ) priority = max;
  6822. param.sched_priority = priority;
  6823. // Set the policy BEFORE the priority. Otherwise it fails.
  6824. pthread_attr_setschedpolicy(&attr, SCHED_RR);
  6825. pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
  6826. // This is definitely required. Otherwise it fails.
  6827. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
  6828. pthread_attr_setschedparam(&attr, &param);
  6829. }
  6830. else
  6831. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  6832. #else
  6833. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  6834. #endif
  6835. stream_.callbackInfo.isRunning = true;
  6836. result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
  6837. pthread_attr_destroy( &attr );
  6838. if ( result ) {
  6839. // Failed. Try instead with default attributes.
  6840. result = pthread_create( &stream_.callbackInfo.thread, NULL, alsaCallbackHandler, &stream_.callbackInfo );
  6841. if ( result ) {
  6842. stream_.callbackInfo.isRunning = false;
  6843. errorText_ = "RtApiAlsa::error creating callback thread!";
  6844. goto error;
  6845. }
  6846. }
  6847. }
  6848. return SUCCESS;
  6849. error:
  6850. if ( apiInfo ) {
  6851. pthread_cond_destroy( &apiInfo->runnable_cv );
  6852. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6853. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6854. delete apiInfo;
  6855. stream_.apiHandle = 0;
  6856. }
  6857. if ( phandle) snd_pcm_close( phandle );
  6858. for ( int i=0; i<2; i++ ) {
  6859. if ( stream_.userBuffer[i] ) {
  6860. free( stream_.userBuffer[i] );
  6861. stream_.userBuffer[i] = 0;
  6862. }
  6863. }
  6864. if ( stream_.deviceBuffer ) {
  6865. free( stream_.deviceBuffer );
  6866. stream_.deviceBuffer = 0;
  6867. }
  6868. stream_.state = STREAM_CLOSED;
  6869. return FAILURE;
  6870. }
  6871. void RtApiAlsa :: closeStream()
  6872. {
  6873. if ( stream_.state == STREAM_CLOSED ) {
  6874. errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
  6875. error( RtAudioError::WARNING );
  6876. return;
  6877. }
  6878. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6879. stream_.callbackInfo.isRunning = false;
  6880. MUTEX_LOCK( &stream_.mutex );
  6881. if ( stream_.state == STREAM_STOPPED ) {
  6882. apiInfo->runnable = true;
  6883. pthread_cond_signal( &apiInfo->runnable_cv );
  6884. }
  6885. MUTEX_UNLOCK( &stream_.mutex );
  6886. pthread_join( stream_.callbackInfo.thread, NULL );
  6887. if ( stream_.state == STREAM_RUNNING ) {
  6888. stream_.state = STREAM_STOPPED;
  6889. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  6890. snd_pcm_drop( apiInfo->handles[0] );
  6891. if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
  6892. snd_pcm_drop( apiInfo->handles[1] );
  6893. }
  6894. if ( apiInfo ) {
  6895. pthread_cond_destroy( &apiInfo->runnable_cv );
  6896. if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
  6897. if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
  6898. delete apiInfo;
  6899. stream_.apiHandle = 0;
  6900. }
  6901. for ( int i=0; i<2; i++ ) {
  6902. if ( stream_.userBuffer[i] ) {
  6903. free( stream_.userBuffer[i] );
  6904. stream_.userBuffer[i] = 0;
  6905. }
  6906. }
  6907. if ( stream_.deviceBuffer ) {
  6908. free( stream_.deviceBuffer );
  6909. stream_.deviceBuffer = 0;
  6910. }
  6911. stream_.mode = UNINITIALIZED;
  6912. stream_.state = STREAM_CLOSED;
  6913. }
  6914. void RtApiAlsa :: startStream()
  6915. {
  6916. // This method calls snd_pcm_prepare if the device isn't already in that state.
  6917. verifyStream();
  6918. if ( stream_.state == STREAM_RUNNING ) {
  6919. errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
  6920. error( RtAudioError::WARNING );
  6921. return;
  6922. }
  6923. MUTEX_LOCK( &stream_.mutex );
  6924. #if defined( HAVE_GETTIMEOFDAY )
  6925. gettimeofday( &stream_.lastTickTimestamp, NULL );
  6926. #endif
  6927. int result = 0;
  6928. snd_pcm_state_t state;
  6929. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6930. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6931. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6932. state = snd_pcm_state( handle[0] );
  6933. if ( state != SND_PCM_STATE_PREPARED ) {
  6934. result = snd_pcm_prepare( handle[0] );
  6935. if ( result < 0 ) {
  6936. errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
  6937. errorText_ = errorStream_.str();
  6938. goto unlock;
  6939. }
  6940. }
  6941. }
  6942. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6943. result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open
  6944. state = snd_pcm_state( handle[1] );
  6945. if ( state != SND_PCM_STATE_PREPARED ) {
  6946. result = snd_pcm_prepare( handle[1] );
  6947. if ( result < 0 ) {
  6948. errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
  6949. errorText_ = errorStream_.str();
  6950. goto unlock;
  6951. }
  6952. }
  6953. }
  6954. stream_.state = STREAM_RUNNING;
  6955. unlock:
  6956. apiInfo->runnable = true;
  6957. pthread_cond_signal( &apiInfo->runnable_cv );
  6958. MUTEX_UNLOCK( &stream_.mutex );
  6959. if ( result >= 0 ) return;
  6960. error( RtAudioError::SYSTEM_ERROR );
  6961. }
  6962. void RtApiAlsa :: stopStream()
  6963. {
  6964. verifyStream();
  6965. if ( stream_.state == STREAM_STOPPED ) {
  6966. errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
  6967. error( RtAudioError::WARNING );
  6968. return;
  6969. }
  6970. stream_.state = STREAM_STOPPED;
  6971. MUTEX_LOCK( &stream_.mutex );
  6972. int result = 0;
  6973. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  6974. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  6975. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  6976. if ( apiInfo->synchronized )
  6977. result = snd_pcm_drop( handle[0] );
  6978. else
  6979. result = snd_pcm_drain( handle[0] );
  6980. if ( result < 0 ) {
  6981. errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
  6982. errorText_ = errorStream_.str();
  6983. goto unlock;
  6984. }
  6985. }
  6986. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  6987. result = snd_pcm_drop( handle[1] );
  6988. if ( result < 0 ) {
  6989. errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
  6990. errorText_ = errorStream_.str();
  6991. goto unlock;
  6992. }
  6993. }
  6994. unlock:
  6995. apiInfo->runnable = false; // fixes high CPU usage when stopped
  6996. MUTEX_UNLOCK( &stream_.mutex );
  6997. if ( result >= 0 ) return;
  6998. error( RtAudioError::SYSTEM_ERROR );
  6999. }
  7000. void RtApiAlsa :: abortStream()
  7001. {
  7002. verifyStream();
  7003. if ( stream_.state == STREAM_STOPPED ) {
  7004. errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
  7005. error( RtAudioError::WARNING );
  7006. return;
  7007. }
  7008. stream_.state = STREAM_STOPPED;
  7009. MUTEX_LOCK( &stream_.mutex );
  7010. int result = 0;
  7011. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  7012. snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
  7013. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7014. result = snd_pcm_drop( handle[0] );
  7015. if ( result < 0 ) {
  7016. errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
  7017. errorText_ = errorStream_.str();
  7018. goto unlock;
  7019. }
  7020. }
  7021. if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
  7022. result = snd_pcm_drop( handle[1] );
  7023. if ( result < 0 ) {
  7024. errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
  7025. errorText_ = errorStream_.str();
  7026. goto unlock;
  7027. }
  7028. }
  7029. unlock:
  7030. apiInfo->runnable = false; // fixes high CPU usage when stopped
  7031. MUTEX_UNLOCK( &stream_.mutex );
  7032. if ( result >= 0 ) return;
  7033. error( RtAudioError::SYSTEM_ERROR );
  7034. }
  7035. void RtApiAlsa :: callbackEvent()
  7036. {
  7037. AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
  7038. if ( stream_.state == STREAM_STOPPED ) {
  7039. MUTEX_LOCK( &stream_.mutex );
  7040. while ( !apiInfo->runnable )
  7041. pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );
  7042. if ( stream_.state != STREAM_RUNNING ) {
  7043. MUTEX_UNLOCK( &stream_.mutex );
  7044. return;
  7045. }
  7046. MUTEX_UNLOCK( &stream_.mutex );
  7047. }
  7048. if ( stream_.state == STREAM_CLOSED ) {
  7049. errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
  7050. error( RtAudioError::WARNING );
  7051. return;
  7052. }
  7053. int doStopStream = 0;
  7054. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  7055. double streamTime = getStreamTime();
  7056. RtAudioStreamStatus status = 0;
  7057. if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
  7058. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  7059. apiInfo->xrun[0] = false;
  7060. }
  7061. if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
  7062. status |= RTAUDIO_INPUT_OVERFLOW;
  7063. apiInfo->xrun[1] = false;
  7064. }
  7065. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  7066. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  7067. if ( doStopStream == 2 ) {
  7068. abortStream();
  7069. return;
  7070. }
  7071. MUTEX_LOCK( &stream_.mutex );
  7072. // The state might change while waiting on a mutex.
  7073. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  7074. int result;
  7075. char *buffer;
  7076. int channels;
  7077. snd_pcm_t **handle;
  7078. snd_pcm_sframes_t frames;
  7079. RtAudioFormat format;
  7080. handle = (snd_pcm_t **) apiInfo->handles;
  7081. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  7082. // Setup parameters.
  7083. if ( stream_.doConvertBuffer[1] ) {
  7084. buffer = stream_.deviceBuffer;
  7085. channels = stream_.nDeviceChannels[1];
  7086. format = stream_.deviceFormat[1];
  7087. }
  7088. else {
  7089. buffer = stream_.userBuffer[1];
  7090. channels = stream_.nUserChannels[1];
  7091. format = stream_.userFormat;
  7092. }
  7093. // Read samples from device in interleaved/non-interleaved format.
  7094. if ( stream_.deviceInterleaved[1] )
  7095. result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
  7096. else {
  7097. void *bufs[channels];
  7098. size_t offset = stream_.bufferSize * formatBytes( format );
  7099. for ( int i=0; i<channels; i++ )
  7100. bufs[i] = (void *) (buffer + (i * offset));
  7101. result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
  7102. }
  7103. if ( result < (int) stream_.bufferSize ) {
  7104. // Either an error or overrun occured.
  7105. if ( result == -EPIPE ) {
  7106. snd_pcm_state_t state = snd_pcm_state( handle[1] );
  7107. if ( state == SND_PCM_STATE_XRUN ) {
  7108. apiInfo->xrun[1] = true;
  7109. result = snd_pcm_prepare( handle[1] );
  7110. if ( result < 0 ) {
  7111. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
  7112. errorText_ = errorStream_.str();
  7113. }
  7114. }
  7115. else {
  7116. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  7117. errorText_ = errorStream_.str();
  7118. }
  7119. }
  7120. else {
  7121. errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
  7122. errorText_ = errorStream_.str();
  7123. }
  7124. error( RtAudioError::WARNING );
  7125. goto tryOutput;
  7126. }
  7127. // Do byte swapping if necessary.
  7128. if ( stream_.doByteSwap[1] )
  7129. byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
  7130. // Do buffer conversion if necessary.
  7131. if ( stream_.doConvertBuffer[1] )
  7132. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  7133. // Check stream latency
  7134. result = snd_pcm_delay( handle[1], &frames );
  7135. if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
  7136. }
  7137. tryOutput:
  7138. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7139. // Setup parameters and do buffer conversion if necessary.
  7140. if ( stream_.doConvertBuffer[0] ) {
  7141. buffer = stream_.deviceBuffer;
  7142. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  7143. channels = stream_.nDeviceChannels[0];
  7144. format = stream_.deviceFormat[0];
  7145. }
  7146. else {
  7147. buffer = stream_.userBuffer[0];
  7148. channels = stream_.nUserChannels[0];
  7149. format = stream_.userFormat;
  7150. }
  7151. // Do byte swapping if necessary.
  7152. if ( stream_.doByteSwap[0] )
  7153. byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
  7154. // Write samples to device in interleaved/non-interleaved format.
  7155. if ( stream_.deviceInterleaved[0] )
  7156. result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
  7157. else {
  7158. void *bufs[channels];
  7159. size_t offset = stream_.bufferSize * formatBytes( format );
  7160. for ( int i=0; i<channels; i++ )
  7161. bufs[i] = (void *) (buffer + (i * offset));
  7162. result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
  7163. }
  7164. if ( result < (int) stream_.bufferSize ) {
  7165. // Either an error or underrun occured.
  7166. if ( result == -EPIPE ) {
  7167. snd_pcm_state_t state = snd_pcm_state( handle[0] );
  7168. if ( state == SND_PCM_STATE_XRUN ) {
  7169. apiInfo->xrun[0] = true;
  7170. result = snd_pcm_prepare( handle[0] );
  7171. if ( result < 0 ) {
  7172. errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
  7173. errorText_ = errorStream_.str();
  7174. }
  7175. else
  7176. errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun.";
  7177. }
  7178. else {
  7179. errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
  7180. errorText_ = errorStream_.str();
  7181. }
  7182. }
  7183. else {
  7184. errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
  7185. errorText_ = errorStream_.str();
  7186. }
  7187. error( RtAudioError::WARNING );
  7188. goto unlock;
  7189. }
  7190. // Check stream latency
  7191. result = snd_pcm_delay( handle[0], &frames );
  7192. if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
  7193. }
  7194. unlock:
  7195. MUTEX_UNLOCK( &stream_.mutex );
  7196. RtApi::tickStreamTime();
  7197. if ( doStopStream == 1 ) this->stopStream();
  7198. }
  7199. static void *alsaCallbackHandler( void *ptr )
  7200. {
  7201. CallbackInfo *info = (CallbackInfo *) ptr;
  7202. RtApiAlsa *object = (RtApiAlsa *) info->object;
  7203. bool *isRunning = &info->isRunning;
  7204. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  7205. if ( info->doRealtime ) {
  7206. std::cerr << "RtAudio alsa: " <<
  7207. (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
  7208. "running realtime scheduling" << std::endl;
  7209. }
  7210. #endif
  7211. while ( *isRunning == true ) {
  7212. pthread_testcancel();
  7213. object->callbackEvent();
  7214. }
  7215. pthread_exit( NULL );
  7216. }
  7217. //******************** End of __LINUX_ALSA__ *********************//
  7218. #endif
  7219. #if defined(__LINUX_PULSE__)
  7220. // Code written by Peter Meerwald, pmeerw@pmeerw.net
  7221. // and Tristan Matthews.
  7222. #include <pulse/error.h>
  7223. #include <pulse/simple.h>
  7224. #include <cstdio>
  7225. static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,
  7226. 44100, 48000, 96000, 0};
  7227. struct rtaudio_pa_format_mapping_t {
  7228. RtAudioFormat rtaudio_format;
  7229. pa_sample_format_t pa_format;
  7230. };
  7231. static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {
  7232. {RTAUDIO_SINT16, PA_SAMPLE_S16LE},
  7233. {RTAUDIO_SINT32, PA_SAMPLE_S32LE},
  7234. {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},
  7235. {0, PA_SAMPLE_INVALID}};
  7236. struct PulseAudioHandle {
  7237. pa_simple *s_play;
  7238. pa_simple *s_rec;
  7239. pthread_t thread;
  7240. pthread_cond_t runnable_cv;
  7241. bool runnable;
  7242. PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }
  7243. };
  7244. RtApiPulse::~RtApiPulse()
  7245. {
  7246. if ( stream_.state != STREAM_CLOSED )
  7247. closeStream();
  7248. }
  7249. unsigned int RtApiPulse::getDeviceCount( void )
  7250. {
  7251. return 1;
  7252. }
  7253. RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )
  7254. {
  7255. RtAudio::DeviceInfo info;
  7256. info.probed = true;
  7257. info.name = "PulseAudio";
  7258. info.outputChannels = 2;
  7259. info.inputChannels = 2;
  7260. info.duplexChannels = 2;
  7261. info.isDefaultOutput = true;
  7262. info.isDefaultInput = true;
  7263. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )
  7264. info.sampleRates.push_back( *sr );
  7265. info.preferredSampleRate = 48000;
  7266. info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;
  7267. return info;
  7268. }
  7269. static void *pulseaudio_callback( void * user )
  7270. {
  7271. CallbackInfo *cbi = static_cast<CallbackInfo *>( user );
  7272. RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );
  7273. volatile bool *isRunning = &cbi->isRunning;
  7274. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  7275. if (cbi->doRealtime) {
  7276. std::cerr << "RtAudio pulse: " <<
  7277. (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
  7278. "running realtime scheduling" << std::endl;
  7279. }
  7280. #endif
  7281. while ( *isRunning ) {
  7282. pthread_testcancel();
  7283. context->callbackEvent();
  7284. }
  7285. pthread_exit( NULL );
  7286. }
  7287. void RtApiPulse::closeStream( void )
  7288. {
  7289. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7290. stream_.callbackInfo.isRunning = false;
  7291. if ( pah ) {
  7292. MUTEX_LOCK( &stream_.mutex );
  7293. if ( stream_.state == STREAM_STOPPED ) {
  7294. pah->runnable = true;
  7295. pthread_cond_signal( &pah->runnable_cv );
  7296. }
  7297. MUTEX_UNLOCK( &stream_.mutex );
  7298. pthread_join( pah->thread, 0 );
  7299. if ( pah->s_play ) {
  7300. pa_simple_flush( pah->s_play, NULL );
  7301. pa_simple_free( pah->s_play );
  7302. }
  7303. if ( pah->s_rec )
  7304. pa_simple_free( pah->s_rec );
  7305. pthread_cond_destroy( &pah->runnable_cv );
  7306. delete pah;
  7307. stream_.apiHandle = 0;
  7308. }
  7309. if ( stream_.userBuffer[0] ) {
  7310. free( stream_.userBuffer[0] );
  7311. stream_.userBuffer[0] = 0;
  7312. }
  7313. if ( stream_.userBuffer[1] ) {
  7314. free( stream_.userBuffer[1] );
  7315. stream_.userBuffer[1] = 0;
  7316. }
  7317. stream_.state = STREAM_CLOSED;
  7318. stream_.mode = UNINITIALIZED;
  7319. }
  7320. void RtApiPulse::callbackEvent( void )
  7321. {
  7322. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7323. if ( stream_.state == STREAM_STOPPED ) {
  7324. MUTEX_LOCK( &stream_.mutex );
  7325. while ( !pah->runnable )
  7326. pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );
  7327. if ( stream_.state != STREAM_RUNNING ) {
  7328. MUTEX_UNLOCK( &stream_.mutex );
  7329. return;
  7330. }
  7331. MUTEX_UNLOCK( &stream_.mutex );
  7332. }
  7333. if ( stream_.state == STREAM_CLOSED ) {
  7334. errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "
  7335. "this shouldn't happen!";
  7336. error( RtAudioError::WARNING );
  7337. return;
  7338. }
  7339. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  7340. double streamTime = getStreamTime();
  7341. RtAudioStreamStatus status = 0;
  7342. int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],
  7343. stream_.bufferSize, streamTime, status,
  7344. stream_.callbackInfo.userData );
  7345. if ( doStopStream == 2 ) {
  7346. abortStream();
  7347. return;
  7348. }
  7349. MUTEX_LOCK( &stream_.mutex );
  7350. void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];
  7351. void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];
  7352. if ( stream_.state != STREAM_RUNNING )
  7353. goto unlock;
  7354. int pa_error;
  7355. size_t bytes;
  7356. if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  7357. if ( stream_.doConvertBuffer[OUTPUT] ) {
  7358. convertBuffer( stream_.deviceBuffer,
  7359. stream_.userBuffer[OUTPUT],
  7360. stream_.convertInfo[OUTPUT] );
  7361. bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *
  7362. formatBytes( stream_.deviceFormat[OUTPUT] );
  7363. } else
  7364. bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *
  7365. formatBytes( stream_.userFormat );
  7366. if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {
  7367. errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<
  7368. pa_strerror( pa_error ) << ".";
  7369. errorText_ = errorStream_.str();
  7370. error( RtAudioError::WARNING );
  7371. }
  7372. }
  7373. if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {
  7374. if ( stream_.doConvertBuffer[INPUT] )
  7375. bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *
  7376. formatBytes( stream_.deviceFormat[INPUT] );
  7377. else
  7378. bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *
  7379. formatBytes( stream_.userFormat );
  7380. if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {
  7381. errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<
  7382. pa_strerror( pa_error ) << ".";
  7383. errorText_ = errorStream_.str();
  7384. error( RtAudioError::WARNING );
  7385. }
  7386. if ( stream_.doConvertBuffer[INPUT] ) {
  7387. convertBuffer( stream_.userBuffer[INPUT],
  7388. stream_.deviceBuffer,
  7389. stream_.convertInfo[INPUT] );
  7390. }
  7391. }
  7392. unlock:
  7393. MUTEX_UNLOCK( &stream_.mutex );
  7394. RtApi::tickStreamTime();
  7395. if ( doStopStream == 1 )
  7396. stopStream();
  7397. }
  7398. void RtApiPulse::startStream( void )
  7399. {
  7400. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7401. if ( stream_.state == STREAM_CLOSED ) {
  7402. errorText_ = "RtApiPulse::startStream(): the stream is not open!";
  7403. error( RtAudioError::INVALID_USE );
  7404. return;
  7405. }
  7406. if ( stream_.state == STREAM_RUNNING ) {
  7407. errorText_ = "RtApiPulse::startStream(): the stream is already running!";
  7408. error( RtAudioError::WARNING );
  7409. return;
  7410. }
  7411. MUTEX_LOCK( &stream_.mutex );
  7412. #if defined( HAVE_GETTIMEOFDAY )
  7413. gettimeofday( &stream_.lastTickTimestamp, NULL );
  7414. #endif
  7415. stream_.state = STREAM_RUNNING;
  7416. pah->runnable = true;
  7417. pthread_cond_signal( &pah->runnable_cv );
  7418. MUTEX_UNLOCK( &stream_.mutex );
  7419. }
  7420. void RtApiPulse::stopStream( void )
  7421. {
  7422. PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7423. if ( stream_.state == STREAM_CLOSED ) {
  7424. errorText_ = "RtApiPulse::stopStream(): the stream is not open!";
  7425. error( RtAudioError::INVALID_USE );
  7426. return;
  7427. }
  7428. if ( stream_.state == STREAM_STOPPED ) {
  7429. errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";
  7430. error( RtAudioError::WARNING );
  7431. return;
  7432. }
  7433. stream_.state = STREAM_STOPPED;
  7434. MUTEX_LOCK( &stream_.mutex );
  7435. if ( pah ) {
  7436. pah->runnable = false;
  7437. if ( pah->s_play ) {
  7438. int pa_error;
  7439. if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {
  7440. errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<
  7441. pa_strerror( pa_error ) << ".";
  7442. errorText_ = errorStream_.str();
  7443. MUTEX_UNLOCK( &stream_.mutex );
  7444. error( RtAudioError::SYSTEM_ERROR );
  7445. return;
  7446. }
  7447. }
  7448. }
  7449. stream_.state = STREAM_STOPPED;
  7450. MUTEX_UNLOCK( &stream_.mutex );
  7451. }
  7452. void RtApiPulse::abortStream( void )
  7453. {
  7454. PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );
  7455. if ( stream_.state == STREAM_CLOSED ) {
  7456. errorText_ = "RtApiPulse::abortStream(): the stream is not open!";
  7457. error( RtAudioError::INVALID_USE );
  7458. return;
  7459. }
  7460. if ( stream_.state == STREAM_STOPPED ) {
  7461. errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";
  7462. error( RtAudioError::WARNING );
  7463. return;
  7464. }
  7465. stream_.state = STREAM_STOPPED;
  7466. MUTEX_LOCK( &stream_.mutex );
  7467. if ( pah ) {
  7468. pah->runnable = false;
  7469. if ( pah->s_play ) {
  7470. int pa_error;
  7471. if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {
  7472. errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<
  7473. pa_strerror( pa_error ) << ".";
  7474. errorText_ = errorStream_.str();
  7475. MUTEX_UNLOCK( &stream_.mutex );
  7476. error( RtAudioError::SYSTEM_ERROR );
  7477. return;
  7478. }
  7479. }
  7480. }
  7481. stream_.state = STREAM_STOPPED;
  7482. MUTEX_UNLOCK( &stream_.mutex );
  7483. }
  7484. bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
  7485. unsigned int channels, unsigned int firstChannel,
  7486. unsigned int sampleRate, RtAudioFormat format,
  7487. unsigned int *bufferSize, RtAudio::StreamOptions *options )
  7488. {
  7489. PulseAudioHandle *pah = 0;
  7490. unsigned long bufferBytes = 0;
  7491. pa_sample_spec ss;
  7492. if ( device != 0 ) return false;
  7493. if ( mode != INPUT && mode != OUTPUT ) return false;
  7494. if ( channels != 1 && channels != 2 ) {
  7495. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";
  7496. return false;
  7497. }
  7498. ss.channels = channels;
  7499. if ( firstChannel != 0 ) return false;
  7500. bool sr_found = false;
  7501. for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {
  7502. if ( sampleRate == *sr ) {
  7503. sr_found = true;
  7504. stream_.sampleRate = sampleRate;
  7505. ss.rate = sampleRate;
  7506. break;
  7507. }
  7508. }
  7509. if ( !sr_found ) {
  7510. errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";
  7511. return false;
  7512. }
  7513. bool sf_found = 0;
  7514. for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;
  7515. sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {
  7516. if ( format == sf->rtaudio_format ) {
  7517. sf_found = true;
  7518. stream_.userFormat = sf->rtaudio_format;
  7519. stream_.deviceFormat[mode] = stream_.userFormat;
  7520. ss.format = sf->pa_format;
  7521. break;
  7522. }
  7523. }
  7524. if ( !sf_found ) { // Use internal data format conversion.
  7525. stream_.userFormat = format;
  7526. stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
  7527. ss.format = PA_SAMPLE_FLOAT32LE;
  7528. }
  7529. // Set other stream parameters.
  7530. if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
  7531. else stream_.userInterleaved = true;
  7532. stream_.deviceInterleaved[mode] = true;
  7533. stream_.nBuffers = 1;
  7534. stream_.doByteSwap[mode] = false;
  7535. stream_.nUserChannels[mode] = channels;
  7536. stream_.nDeviceChannels[mode] = channels + firstChannel;
  7537. stream_.channelOffset[mode] = 0;
  7538. std::string streamName = "RtAudio";
  7539. // Set flags for buffer conversion.
  7540. stream_.doConvertBuffer[mode] = false;
  7541. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  7542. stream_.doConvertBuffer[mode] = true;
  7543. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  7544. stream_.doConvertBuffer[mode] = true;
  7545. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] )
  7546. stream_.doConvertBuffer[mode] = true;
  7547. // Allocate necessary internal buffers.
  7548. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  7549. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  7550. if ( stream_.userBuffer[mode] == NULL ) {
  7551. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";
  7552. goto error;
  7553. }
  7554. stream_.bufferSize = *bufferSize;
  7555. if ( stream_.doConvertBuffer[mode] ) {
  7556. bool makeBuffer = true;
  7557. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  7558. if ( mode == INPUT ) {
  7559. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  7560. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  7561. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  7562. }
  7563. }
  7564. if ( makeBuffer ) {
  7565. bufferBytes *= *bufferSize;
  7566. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  7567. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  7568. if ( stream_.deviceBuffer == NULL ) {
  7569. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";
  7570. goto error;
  7571. }
  7572. }
  7573. }
  7574. stream_.device[mode] = device;
  7575. // Setup the buffer conversion information structure.
  7576. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  7577. if ( !stream_.apiHandle ) {
  7578. PulseAudioHandle *pah = new PulseAudioHandle;
  7579. if ( !pah ) {
  7580. errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";
  7581. goto error;
  7582. }
  7583. stream_.apiHandle = pah;
  7584. if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {
  7585. errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";
  7586. goto error;
  7587. }
  7588. }
  7589. pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );
  7590. int error;
  7591. if ( options && !options->streamName.empty() ) streamName = options->streamName;
  7592. switch ( mode ) {
  7593. case INPUT:
  7594. pa_buffer_attr buffer_attr;
  7595. buffer_attr.fragsize = bufferBytes;
  7596. buffer_attr.maxlength = -1;
  7597. pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );
  7598. if ( !pah->s_rec ) {
  7599. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";
  7600. goto error;
  7601. }
  7602. break;
  7603. case OUTPUT:
  7604. pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );
  7605. if ( !pah->s_play ) {
  7606. errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";
  7607. goto error;
  7608. }
  7609. break;
  7610. default:
  7611. goto error;
  7612. }
  7613. if ( stream_.mode == UNINITIALIZED )
  7614. stream_.mode = mode;
  7615. else if ( stream_.mode == mode )
  7616. goto error;
  7617. else
  7618. stream_.mode = DUPLEX;
  7619. if ( !stream_.callbackInfo.isRunning ) {
  7620. stream_.callbackInfo.object = this;
  7621. stream_.state = STREAM_STOPPED;
  7622. // Set the thread attributes for joinable and realtime scheduling
  7623. // priority (optional). The higher priority will only take affect
  7624. // if the program is run as root or suid. Note, under Linux
  7625. // processes with CAP_SYS_NICE privilege, a user can change
  7626. // scheduling policy and priority (thus need not be root). See
  7627. // POSIX "capabilities".
  7628. pthread_attr_t attr;
  7629. pthread_attr_init( &attr );
  7630. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  7631. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  7632. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  7633. stream_.callbackInfo.doRealtime = true;
  7634. struct sched_param param;
  7635. int priority = options->priority;
  7636. int min = sched_get_priority_min( SCHED_RR );
  7637. int max = sched_get_priority_max( SCHED_RR );
  7638. if ( priority < min ) priority = min;
  7639. else if ( priority > max ) priority = max;
  7640. param.sched_priority = priority;
  7641. // Set the policy BEFORE the priority. Otherwise it fails.
  7642. pthread_attr_setschedpolicy(&attr, SCHED_RR);
  7643. pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
  7644. // This is definitely required. Otherwise it fails.
  7645. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
  7646. pthread_attr_setschedparam(&attr, &param);
  7647. }
  7648. else
  7649. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7650. #else
  7651. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  7652. #endif
  7653. stream_.callbackInfo.isRunning = true;
  7654. int result = pthread_create( &pah->thread, &attr, pulseaudio_callback, (void *)&stream_.callbackInfo);
  7655. pthread_attr_destroy(&attr);
  7656. if(result != 0) {
  7657. // Failed. Try instead with default attributes.
  7658. result = pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo);
  7659. if(result != 0) {
  7660. stream_.callbackInfo.isRunning = false;
  7661. errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";
  7662. goto error;
  7663. }
  7664. }
  7665. }
  7666. return SUCCESS;
  7667. error:
  7668. if ( pah && stream_.callbackInfo.isRunning ) {
  7669. pthread_cond_destroy( &pah->runnable_cv );
  7670. delete pah;
  7671. stream_.apiHandle = 0;
  7672. }
  7673. for ( int i=0; i<2; i++ ) {
  7674. if ( stream_.userBuffer[i] ) {
  7675. free( stream_.userBuffer[i] );
  7676. stream_.userBuffer[i] = 0;
  7677. }
  7678. }
  7679. if ( stream_.deviceBuffer ) {
  7680. free( stream_.deviceBuffer );
  7681. stream_.deviceBuffer = 0;
  7682. }
  7683. stream_.state = STREAM_CLOSED;
  7684. return FAILURE;
  7685. }
  7686. //******************** End of __LINUX_PULSE__ *********************//
  7687. #endif
  7688. #if defined(__LINUX_OSS__)
  7689. #include <unistd.h>
  7690. #include <sys/ioctl.h>
  7691. #include <unistd.h>
  7692. #include <fcntl.h>
  7693. #include <sys/soundcard.h>
  7694. #include <errno.h>
  7695. #include <math.h>
  7696. static void *ossCallbackHandler(void * ptr);
  7697. // A structure to hold various information related to the OSS API
  7698. // implementation.
  7699. struct OssHandle {
  7700. int id[2]; // device ids
  7701. bool xrun[2];
  7702. bool triggered;
  7703. pthread_cond_t runnable;
  7704. OssHandle()
  7705. :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
  7706. };
  7707. RtApiOss :: RtApiOss()
  7708. {
  7709. // Nothing to do here.
  7710. }
  7711. RtApiOss :: ~RtApiOss()
  7712. {
  7713. if ( stream_.state != STREAM_CLOSED ) closeStream();
  7714. }
  7715. unsigned int RtApiOss :: getDeviceCount( void )
  7716. {
  7717. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7718. if ( mixerfd == -1 ) {
  7719. errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
  7720. error( RtAudioError::WARNING );
  7721. return 0;
  7722. }
  7723. oss_sysinfo sysinfo;
  7724. if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
  7725. close( mixerfd );
  7726. errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
  7727. error( RtAudioError::WARNING );
  7728. return 0;
  7729. }
  7730. close( mixerfd );
  7731. return sysinfo.numaudios;
  7732. }
  7733. RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
  7734. {
  7735. RtAudio::DeviceInfo info;
  7736. info.probed = false;
  7737. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7738. if ( mixerfd == -1 ) {
  7739. errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
  7740. error( RtAudioError::WARNING );
  7741. return info;
  7742. }
  7743. oss_sysinfo sysinfo;
  7744. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7745. if ( result == -1 ) {
  7746. close( mixerfd );
  7747. errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
  7748. error( RtAudioError::WARNING );
  7749. return info;
  7750. }
  7751. unsigned nDevices = sysinfo.numaudios;
  7752. if ( nDevices == 0 ) {
  7753. close( mixerfd );
  7754. errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
  7755. error( RtAudioError::INVALID_USE );
  7756. return info;
  7757. }
  7758. if ( device >= nDevices ) {
  7759. close( mixerfd );
  7760. errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
  7761. error( RtAudioError::INVALID_USE );
  7762. return info;
  7763. }
  7764. oss_audioinfo ainfo;
  7765. ainfo.dev = device;
  7766. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7767. close( mixerfd );
  7768. if ( result == -1 ) {
  7769. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7770. errorText_ = errorStream_.str();
  7771. error( RtAudioError::WARNING );
  7772. return info;
  7773. }
  7774. // Probe channels
  7775. if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
  7776. if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
  7777. if ( ainfo.caps & PCM_CAP_DUPLEX ) {
  7778. if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
  7779. info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
  7780. }
  7781. // Probe data formats ... do for input
  7782. unsigned long mask = ainfo.iformats;
  7783. if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
  7784. info.nativeFormats |= RTAUDIO_SINT16;
  7785. if ( mask & AFMT_S8 )
  7786. info.nativeFormats |= RTAUDIO_SINT8;
  7787. if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
  7788. info.nativeFormats |= RTAUDIO_SINT32;
  7789. #ifdef AFMT_FLOAT
  7790. if ( mask & AFMT_FLOAT )
  7791. info.nativeFormats |= RTAUDIO_FLOAT32;
  7792. #endif
  7793. if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
  7794. info.nativeFormats |= RTAUDIO_SINT24;
  7795. // Check that we have at least one supported format
  7796. if ( info.nativeFormats == 0 ) {
  7797. errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
  7798. errorText_ = errorStream_.str();
  7799. error( RtAudioError::WARNING );
  7800. return info;
  7801. }
  7802. // Probe the supported sample rates.
  7803. info.sampleRates.clear();
  7804. if ( ainfo.nrates ) {
  7805. for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
  7806. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7807. if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
  7808. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7809. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7810. info.preferredSampleRate = SAMPLE_RATES[k];
  7811. break;
  7812. }
  7813. }
  7814. }
  7815. }
  7816. else {
  7817. // Check min and max rate values;
  7818. for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
  7819. if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {
  7820. info.sampleRates.push_back( SAMPLE_RATES[k] );
  7821. if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
  7822. info.preferredSampleRate = SAMPLE_RATES[k];
  7823. }
  7824. }
  7825. }
  7826. if ( info.sampleRates.size() == 0 ) {
  7827. errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
  7828. errorText_ = errorStream_.str();
  7829. error( RtAudioError::WARNING );
  7830. }
  7831. else {
  7832. info.probed = true;
  7833. info.name = ainfo.name;
  7834. }
  7835. return info;
  7836. }
  7837. bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
  7838. unsigned int firstChannel, unsigned int sampleRate,
  7839. RtAudioFormat format, unsigned int *bufferSize,
  7840. RtAudio::StreamOptions *options )
  7841. {
  7842. int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
  7843. if ( mixerfd == -1 ) {
  7844. errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
  7845. return FAILURE;
  7846. }
  7847. oss_sysinfo sysinfo;
  7848. int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
  7849. if ( result == -1 ) {
  7850. close( mixerfd );
  7851. errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
  7852. return FAILURE;
  7853. }
  7854. unsigned nDevices = sysinfo.numaudios;
  7855. if ( nDevices == 0 ) {
  7856. // This should not happen because a check is made before this function is called.
  7857. close( mixerfd );
  7858. errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
  7859. return FAILURE;
  7860. }
  7861. if ( device >= nDevices ) {
  7862. // This should not happen because a check is made before this function is called.
  7863. close( mixerfd );
  7864. errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
  7865. return FAILURE;
  7866. }
  7867. oss_audioinfo ainfo;
  7868. ainfo.dev = device;
  7869. result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
  7870. close( mixerfd );
  7871. if ( result == -1 ) {
  7872. errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
  7873. errorText_ = errorStream_.str();
  7874. return FAILURE;
  7875. }
  7876. // Check if device supports input or output
  7877. if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
  7878. ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
  7879. if ( mode == OUTPUT )
  7880. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
  7881. else
  7882. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
  7883. errorText_ = errorStream_.str();
  7884. return FAILURE;
  7885. }
  7886. int flags = 0;
  7887. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  7888. if ( mode == OUTPUT )
  7889. flags |= O_WRONLY;
  7890. else { // mode == INPUT
  7891. if (stream_.mode == OUTPUT && stream_.device[0] == device) {
  7892. // We just set the same device for playback ... close and reopen for duplex (OSS only).
  7893. close( handle->id[0] );
  7894. handle->id[0] = 0;
  7895. if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
  7896. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
  7897. errorText_ = errorStream_.str();
  7898. return FAILURE;
  7899. }
  7900. // Check that the number previously set channels is the same.
  7901. if ( stream_.nUserChannels[0] != channels ) {
  7902. errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
  7903. errorText_ = errorStream_.str();
  7904. return FAILURE;
  7905. }
  7906. flags |= O_RDWR;
  7907. }
  7908. else
  7909. flags |= O_RDONLY;
  7910. }
  7911. // Set exclusive access if specified.
  7912. if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
  7913. // Try to open the device.
  7914. int fd;
  7915. fd = open( ainfo.devnode, flags, 0 );
  7916. if ( fd == -1 ) {
  7917. if ( errno == EBUSY )
  7918. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
  7919. else
  7920. errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
  7921. errorText_ = errorStream_.str();
  7922. return FAILURE;
  7923. }
  7924. // For duplex operation, specifically set this mode (this doesn't seem to work).
  7925. /*
  7926. if ( flags | O_RDWR ) {
  7927. result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
  7928. if ( result == -1) {
  7929. errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
  7930. errorText_ = errorStream_.str();
  7931. return FAILURE;
  7932. }
  7933. }
  7934. */
  7935. // Check the device channel support.
  7936. stream_.nUserChannels[mode] = channels;
  7937. if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
  7938. close( fd );
  7939. errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
  7940. errorText_ = errorStream_.str();
  7941. return FAILURE;
  7942. }
  7943. // Set the number of channels.
  7944. int deviceChannels = channels + firstChannel;
  7945. result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
  7946. if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
  7947. close( fd );
  7948. errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
  7949. errorText_ = errorStream_.str();
  7950. return FAILURE;
  7951. }
  7952. stream_.nDeviceChannels[mode] = deviceChannels;
  7953. // Get the data format mask
  7954. int mask;
  7955. result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
  7956. if ( result == -1 ) {
  7957. close( fd );
  7958. errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
  7959. errorText_ = errorStream_.str();
  7960. return FAILURE;
  7961. }
  7962. // Determine how to set the device format.
  7963. stream_.userFormat = format;
  7964. int deviceFormat = -1;
  7965. stream_.doByteSwap[mode] = false;
  7966. if ( format == RTAUDIO_SINT8 ) {
  7967. if ( mask & AFMT_S8 ) {
  7968. deviceFormat = AFMT_S8;
  7969. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  7970. }
  7971. }
  7972. else if ( format == RTAUDIO_SINT16 ) {
  7973. if ( mask & AFMT_S16_NE ) {
  7974. deviceFormat = AFMT_S16_NE;
  7975. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7976. }
  7977. else if ( mask & AFMT_S16_OE ) {
  7978. deviceFormat = AFMT_S16_OE;
  7979. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  7980. stream_.doByteSwap[mode] = true;
  7981. }
  7982. }
  7983. else if ( format == RTAUDIO_SINT24 ) {
  7984. if ( mask & AFMT_S24_NE ) {
  7985. deviceFormat = AFMT_S24_NE;
  7986. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7987. }
  7988. else if ( mask & AFMT_S24_OE ) {
  7989. deviceFormat = AFMT_S24_OE;
  7990. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  7991. stream_.doByteSwap[mode] = true;
  7992. }
  7993. }
  7994. else if ( format == RTAUDIO_SINT32 ) {
  7995. if ( mask & AFMT_S32_NE ) {
  7996. deviceFormat = AFMT_S32_NE;
  7997. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  7998. }
  7999. else if ( mask & AFMT_S32_OE ) {
  8000. deviceFormat = AFMT_S32_OE;
  8001. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  8002. stream_.doByteSwap[mode] = true;
  8003. }
  8004. }
  8005. if ( deviceFormat == -1 ) {
  8006. // The user requested format is not natively supported by the device.
  8007. if ( mask & AFMT_S16_NE ) {
  8008. deviceFormat = AFMT_S16_NE;
  8009. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  8010. }
  8011. else if ( mask & AFMT_S32_NE ) {
  8012. deviceFormat = AFMT_S32_NE;
  8013. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  8014. }
  8015. else if ( mask & AFMT_S24_NE ) {
  8016. deviceFormat = AFMT_S24_NE;
  8017. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  8018. }
  8019. else if ( mask & AFMT_S16_OE ) {
  8020. deviceFormat = AFMT_S16_OE;
  8021. stream_.deviceFormat[mode] = RTAUDIO_SINT16;
  8022. stream_.doByteSwap[mode] = true;
  8023. }
  8024. else if ( mask & AFMT_S32_OE ) {
  8025. deviceFormat = AFMT_S32_OE;
  8026. stream_.deviceFormat[mode] = RTAUDIO_SINT32;
  8027. stream_.doByteSwap[mode] = true;
  8028. }
  8029. else if ( mask & AFMT_S24_OE ) {
  8030. deviceFormat = AFMT_S24_OE;
  8031. stream_.deviceFormat[mode] = RTAUDIO_SINT24;
  8032. stream_.doByteSwap[mode] = true;
  8033. }
  8034. else if ( mask & AFMT_S8) {
  8035. deviceFormat = AFMT_S8;
  8036. stream_.deviceFormat[mode] = RTAUDIO_SINT8;
  8037. }
  8038. }
  8039. if ( stream_.deviceFormat[mode] == 0 ) {
  8040. // This really shouldn't happen ...
  8041. close( fd );
  8042. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
  8043. errorText_ = errorStream_.str();
  8044. return FAILURE;
  8045. }
  8046. // Set the data format.
  8047. int temp = deviceFormat;
  8048. result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
  8049. if ( result == -1 || deviceFormat != temp ) {
  8050. close( fd );
  8051. errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
  8052. errorText_ = errorStream_.str();
  8053. return FAILURE;
  8054. }
  8055. // Attempt to set the buffer size. According to OSS, the minimum
  8056. // number of buffers is two. The supposed minimum buffer size is 16
  8057. // bytes, so that will be our lower bound. The argument to this
  8058. // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
  8059. // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
  8060. // We'll check the actual value used near the end of the setup
  8061. // procedure.
  8062. int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
  8063. if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
  8064. int buffers = 0;
  8065. if ( options ) buffers = options->numberOfBuffers;
  8066. if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
  8067. if ( buffers < 2 ) buffers = 3;
  8068. temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
  8069. result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
  8070. if ( result == -1 ) {
  8071. close( fd );
  8072. errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
  8073. errorText_ = errorStream_.str();
  8074. return FAILURE;
  8075. }
  8076. stream_.nBuffers = buffers;
  8077. // Save buffer size (in sample frames).
  8078. *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
  8079. stream_.bufferSize = *bufferSize;
  8080. // Set the sample rate.
  8081. int srate = sampleRate;
  8082. result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
  8083. if ( result == -1 ) {
  8084. close( fd );
  8085. errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
  8086. errorText_ = errorStream_.str();
  8087. return FAILURE;
  8088. }
  8089. // Verify the sample rate setup worked.
  8090. if ( abs( srate - (int)sampleRate ) > 100 ) {
  8091. close( fd );
  8092. errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
  8093. errorText_ = errorStream_.str();
  8094. return FAILURE;
  8095. }
  8096. stream_.sampleRate = sampleRate;
  8097. if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
  8098. // We're doing duplex setup here.
  8099. stream_.deviceFormat[0] = stream_.deviceFormat[1];
  8100. stream_.nDeviceChannels[0] = deviceChannels;
  8101. }
  8102. // Set interleaving parameters.
  8103. stream_.userInterleaved = true;
  8104. stream_.deviceInterleaved[mode] = true;
  8105. if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
  8106. stream_.userInterleaved = false;
  8107. // Set flags for buffer conversion
  8108. stream_.doConvertBuffer[mode] = false;
  8109. if ( stream_.userFormat != stream_.deviceFormat[mode] )
  8110. stream_.doConvertBuffer[mode] = true;
  8111. if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
  8112. stream_.doConvertBuffer[mode] = true;
  8113. if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
  8114. stream_.nUserChannels[mode] > 1 )
  8115. stream_.doConvertBuffer[mode] = true;
  8116. // Allocate the stream handles if necessary and then save.
  8117. if ( stream_.apiHandle == 0 ) {
  8118. try {
  8119. handle = new OssHandle;
  8120. }
  8121. catch ( std::bad_alloc& ) {
  8122. errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
  8123. goto error;
  8124. }
  8125. if ( pthread_cond_init( &handle->runnable, NULL ) ) {
  8126. errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
  8127. goto error;
  8128. }
  8129. stream_.apiHandle = (void *) handle;
  8130. }
  8131. else {
  8132. handle = (OssHandle *) stream_.apiHandle;
  8133. }
  8134. handle->id[mode] = fd;
  8135. // Allocate necessary internal buffers.
  8136. unsigned long bufferBytes;
  8137. bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
  8138. stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
  8139. if ( stream_.userBuffer[mode] == NULL ) {
  8140. errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
  8141. goto error;
  8142. }
  8143. if ( stream_.doConvertBuffer[mode] ) {
  8144. bool makeBuffer = true;
  8145. bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
  8146. if ( mode == INPUT ) {
  8147. if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
  8148. unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
  8149. if ( bufferBytes <= bytesOut ) makeBuffer = false;
  8150. }
  8151. }
  8152. if ( makeBuffer ) {
  8153. bufferBytes *= *bufferSize;
  8154. if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
  8155. stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
  8156. if ( stream_.deviceBuffer == NULL ) {
  8157. errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
  8158. goto error;
  8159. }
  8160. }
  8161. }
  8162. stream_.device[mode] = device;
  8163. stream_.state = STREAM_STOPPED;
  8164. // Setup the buffer conversion information structure.
  8165. if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
  8166. // Setup thread if necessary.
  8167. if ( stream_.mode == OUTPUT && mode == INPUT ) {
  8168. // We had already set up an output stream.
  8169. stream_.mode = DUPLEX;
  8170. if ( stream_.device[0] == device ) handle->id[0] = fd;
  8171. }
  8172. else {
  8173. stream_.mode = mode;
  8174. // Setup callback thread.
  8175. stream_.callbackInfo.object = (void *) this;
  8176. // Set the thread attributes for joinable and realtime scheduling
  8177. // priority. The higher priority will only take affect if the
  8178. // program is run as root or suid.
  8179. pthread_attr_t attr;
  8180. pthread_attr_init( &attr );
  8181. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  8182. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  8183. if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
  8184. stream_.callbackInfo.doRealtime = true;
  8185. struct sched_param param;
  8186. int priority = options->priority;
  8187. int min = sched_get_priority_min( SCHED_RR );
  8188. int max = sched_get_priority_max( SCHED_RR );
  8189. if ( priority < min ) priority = min;
  8190. else if ( priority > max ) priority = max;
  8191. param.sched_priority = priority;
  8192. // Set the policy BEFORE the priority. Otherwise it fails.
  8193. pthread_attr_setschedpolicy(&attr, SCHED_RR);
  8194. pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
  8195. // This is definitely required. Otherwise it fails.
  8196. pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
  8197. pthread_attr_setschedparam(&attr, &param);
  8198. }
  8199. else
  8200. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  8201. #else
  8202. pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
  8203. #endif
  8204. stream_.callbackInfo.isRunning = true;
  8205. result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
  8206. pthread_attr_destroy( &attr );
  8207. if ( result ) {
  8208. // Failed. Try instead with default attributes.
  8209. result = pthread_create( &stream_.callbackInfo.thread, NULL, ossCallbackHandler, &stream_.callbackInfo );
  8210. if ( result ) {
  8211. stream_.callbackInfo.isRunning = false;
  8212. errorText_ = "RtApiOss::error creating callback thread!";
  8213. goto error;
  8214. }
  8215. }
  8216. }
  8217. return SUCCESS;
  8218. error:
  8219. if ( handle ) {
  8220. pthread_cond_destroy( &handle->runnable );
  8221. if ( handle->id[0] ) close( handle->id[0] );
  8222. if ( handle->id[1] ) close( handle->id[1] );
  8223. delete handle;
  8224. stream_.apiHandle = 0;
  8225. }
  8226. for ( int i=0; i<2; i++ ) {
  8227. if ( stream_.userBuffer[i] ) {
  8228. free( stream_.userBuffer[i] );
  8229. stream_.userBuffer[i] = 0;
  8230. }
  8231. }
  8232. if ( stream_.deviceBuffer ) {
  8233. free( stream_.deviceBuffer );
  8234. stream_.deviceBuffer = 0;
  8235. }
  8236. stream_.state = STREAM_CLOSED;
  8237. return FAILURE;
  8238. }
  8239. void RtApiOss :: closeStream()
  8240. {
  8241. if ( stream_.state == STREAM_CLOSED ) {
  8242. errorText_ = "RtApiOss::closeStream(): no open stream to close!";
  8243. error( RtAudioError::WARNING );
  8244. return;
  8245. }
  8246. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8247. stream_.callbackInfo.isRunning = false;
  8248. MUTEX_LOCK( &stream_.mutex );
  8249. if ( stream_.state == STREAM_STOPPED )
  8250. pthread_cond_signal( &handle->runnable );
  8251. MUTEX_UNLOCK( &stream_.mutex );
  8252. pthread_join( stream_.callbackInfo.thread, NULL );
  8253. if ( stream_.state == STREAM_RUNNING ) {
  8254. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
  8255. ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8256. else
  8257. ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8258. stream_.state = STREAM_STOPPED;
  8259. }
  8260. if ( handle ) {
  8261. pthread_cond_destroy( &handle->runnable );
  8262. if ( handle->id[0] ) close( handle->id[0] );
  8263. if ( handle->id[1] ) close( handle->id[1] );
  8264. delete handle;
  8265. stream_.apiHandle = 0;
  8266. }
  8267. for ( int i=0; i<2; i++ ) {
  8268. if ( stream_.userBuffer[i] ) {
  8269. free( stream_.userBuffer[i] );
  8270. stream_.userBuffer[i] = 0;
  8271. }
  8272. }
  8273. if ( stream_.deviceBuffer ) {
  8274. free( stream_.deviceBuffer );
  8275. stream_.deviceBuffer = 0;
  8276. }
  8277. stream_.mode = UNINITIALIZED;
  8278. stream_.state = STREAM_CLOSED;
  8279. }
  8280. void RtApiOss :: startStream()
  8281. {
  8282. verifyStream();
  8283. if ( stream_.state == STREAM_RUNNING ) {
  8284. errorText_ = "RtApiOss::startStream(): the stream is already running!";
  8285. error( RtAudioError::WARNING );
  8286. return;
  8287. }
  8288. MUTEX_LOCK( &stream_.mutex );
  8289. #if defined( HAVE_GETTIMEOFDAY )
  8290. gettimeofday( &stream_.lastTickTimestamp, NULL );
  8291. #endif
  8292. stream_.state = STREAM_RUNNING;
  8293. // No need to do anything else here ... OSS automatically starts
  8294. // when fed samples.
  8295. MUTEX_UNLOCK( &stream_.mutex );
  8296. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8297. pthread_cond_signal( &handle->runnable );
  8298. }
  8299. void RtApiOss :: stopStream()
  8300. {
  8301. verifyStream();
  8302. if ( stream_.state == STREAM_STOPPED ) {
  8303. errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
  8304. error( RtAudioError::WARNING );
  8305. return;
  8306. }
  8307. MUTEX_LOCK( &stream_.mutex );
  8308. // The state might change while waiting on a mutex.
  8309. if ( stream_.state == STREAM_STOPPED ) {
  8310. MUTEX_UNLOCK( &stream_.mutex );
  8311. return;
  8312. }
  8313. int result = 0;
  8314. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8315. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8316. // Flush the output with zeros a few times.
  8317. char *buffer;
  8318. int samples;
  8319. RtAudioFormat format;
  8320. if ( stream_.doConvertBuffer[0] ) {
  8321. buffer = stream_.deviceBuffer;
  8322. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  8323. format = stream_.deviceFormat[0];
  8324. }
  8325. else {
  8326. buffer = stream_.userBuffer[0];
  8327. samples = stream_.bufferSize * stream_.nUserChannels[0];
  8328. format = stream_.userFormat;
  8329. }
  8330. memset( buffer, 0, samples * formatBytes(format) );
  8331. for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
  8332. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8333. if ( result == -1 ) {
  8334. errorText_ = "RtApiOss::stopStream: audio write error.";
  8335. error( RtAudioError::WARNING );
  8336. }
  8337. }
  8338. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8339. if ( result == -1 ) {
  8340. errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  8341. errorText_ = errorStream_.str();
  8342. goto unlock;
  8343. }
  8344. handle->triggered = false;
  8345. }
  8346. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  8347. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8348. if ( result == -1 ) {
  8349. errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  8350. errorText_ = errorStream_.str();
  8351. goto unlock;
  8352. }
  8353. }
  8354. unlock:
  8355. stream_.state = STREAM_STOPPED;
  8356. MUTEX_UNLOCK( &stream_.mutex );
  8357. if ( result != -1 ) return;
  8358. error( RtAudioError::SYSTEM_ERROR );
  8359. }
  8360. void RtApiOss :: abortStream()
  8361. {
  8362. verifyStream();
  8363. if ( stream_.state == STREAM_STOPPED ) {
  8364. errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
  8365. error( RtAudioError::WARNING );
  8366. return;
  8367. }
  8368. MUTEX_LOCK( &stream_.mutex );
  8369. // The state might change while waiting on a mutex.
  8370. if ( stream_.state == STREAM_STOPPED ) {
  8371. MUTEX_UNLOCK( &stream_.mutex );
  8372. return;
  8373. }
  8374. int result = 0;
  8375. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8376. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8377. result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
  8378. if ( result == -1 ) {
  8379. errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
  8380. errorText_ = errorStream_.str();
  8381. goto unlock;
  8382. }
  8383. handle->triggered = false;
  8384. }
  8385. if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
  8386. result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
  8387. if ( result == -1 ) {
  8388. errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
  8389. errorText_ = errorStream_.str();
  8390. goto unlock;
  8391. }
  8392. }
  8393. unlock:
  8394. stream_.state = STREAM_STOPPED;
  8395. MUTEX_UNLOCK( &stream_.mutex );
  8396. if ( result != -1 ) return;
  8397. error( RtAudioError::SYSTEM_ERROR );
  8398. }
  8399. void RtApiOss :: callbackEvent()
  8400. {
  8401. OssHandle *handle = (OssHandle *) stream_.apiHandle;
  8402. if ( stream_.state == STREAM_STOPPED ) {
  8403. MUTEX_LOCK( &stream_.mutex );
  8404. pthread_cond_wait( &handle->runnable, &stream_.mutex );
  8405. if ( stream_.state != STREAM_RUNNING ) {
  8406. MUTEX_UNLOCK( &stream_.mutex );
  8407. return;
  8408. }
  8409. MUTEX_UNLOCK( &stream_.mutex );
  8410. }
  8411. if ( stream_.state == STREAM_CLOSED ) {
  8412. errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
  8413. error( RtAudioError::WARNING );
  8414. return;
  8415. }
  8416. // Invoke user callback to get fresh output data.
  8417. int doStopStream = 0;
  8418. RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
  8419. double streamTime = getStreamTime();
  8420. RtAudioStreamStatus status = 0;
  8421. if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
  8422. status |= RTAUDIO_OUTPUT_UNDERFLOW;
  8423. handle->xrun[0] = false;
  8424. }
  8425. if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
  8426. status |= RTAUDIO_INPUT_OVERFLOW;
  8427. handle->xrun[1] = false;
  8428. }
  8429. doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
  8430. stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
  8431. if ( doStopStream == 2 ) {
  8432. this->abortStream();
  8433. return;
  8434. }
  8435. MUTEX_LOCK( &stream_.mutex );
  8436. // The state might change while waiting on a mutex.
  8437. if ( stream_.state == STREAM_STOPPED ) goto unlock;
  8438. int result;
  8439. char *buffer;
  8440. int samples;
  8441. RtAudioFormat format;
  8442. if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
  8443. // Setup parameters and do buffer conversion if necessary.
  8444. if ( stream_.doConvertBuffer[0] ) {
  8445. buffer = stream_.deviceBuffer;
  8446. convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
  8447. samples = stream_.bufferSize * stream_.nDeviceChannels[0];
  8448. format = stream_.deviceFormat[0];
  8449. }
  8450. else {
  8451. buffer = stream_.userBuffer[0];
  8452. samples = stream_.bufferSize * stream_.nUserChannels[0];
  8453. format = stream_.userFormat;
  8454. }
  8455. // Do byte swapping if necessary.
  8456. if ( stream_.doByteSwap[0] )
  8457. byteSwapBuffer( buffer, samples, format );
  8458. if ( stream_.mode == DUPLEX && handle->triggered == false ) {
  8459. int trig = 0;
  8460. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8461. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8462. trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
  8463. ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
  8464. handle->triggered = true;
  8465. }
  8466. else
  8467. // Write samples to device.
  8468. result = write( handle->id[0], buffer, samples * formatBytes(format) );
  8469. if ( result == -1 ) {
  8470. // We'll assume this is an underrun, though there isn't a
  8471. // specific means for determining that.
  8472. handle->xrun[0] = true;
  8473. errorText_ = "RtApiOss::callbackEvent: audio write error.";
  8474. error( RtAudioError::WARNING );
  8475. // Continue on to input section.
  8476. }
  8477. }
  8478. if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
  8479. // Setup parameters.
  8480. if ( stream_.doConvertBuffer[1] ) {
  8481. buffer = stream_.deviceBuffer;
  8482. samples = stream_.bufferSize * stream_.nDeviceChannels[1];
  8483. format = stream_.deviceFormat[1];
  8484. }
  8485. else {
  8486. buffer = stream_.userBuffer[1];
  8487. samples = stream_.bufferSize * stream_.nUserChannels[1];
  8488. format = stream_.userFormat;
  8489. }
  8490. // Read samples from device.
  8491. result = read( handle->id[1], buffer, samples * formatBytes(format) );
  8492. if ( result == -1 ) {
  8493. // We'll assume this is an overrun, though there isn't a
  8494. // specific means for determining that.
  8495. handle->xrun[1] = true;
  8496. errorText_ = "RtApiOss::callbackEvent: audio read error.";
  8497. error( RtAudioError::WARNING );
  8498. goto unlock;
  8499. }
  8500. // Do byte swapping if necessary.
  8501. if ( stream_.doByteSwap[1] )
  8502. byteSwapBuffer( buffer, samples, format );
  8503. // Do buffer conversion if necessary.
  8504. if ( stream_.doConvertBuffer[1] )
  8505. convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
  8506. }
  8507. unlock:
  8508. MUTEX_UNLOCK( &stream_.mutex );
  8509. RtApi::tickStreamTime();
  8510. if ( doStopStream == 1 ) this->stopStream();
  8511. }
  8512. static void *ossCallbackHandler( void *ptr )
  8513. {
  8514. CallbackInfo *info = (CallbackInfo *) ptr;
  8515. RtApiOss *object = (RtApiOss *) info->object;
  8516. bool *isRunning = &info->isRunning;
  8517. #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread)
  8518. if (info->doRealtime) {
  8519. std::cerr << "RtAudio oss: " <<
  8520. (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") <<
  8521. "running realtime scheduling" << std::endl;
  8522. }
  8523. #endif
  8524. while ( *isRunning == true ) {
  8525. pthread_testcancel();
  8526. object->callbackEvent();
  8527. }
  8528. pthread_exit( NULL );
  8529. }
  8530. //******************** End of __LINUX_OSS__ *********************//
  8531. #endif
  8532. // *************************************************** //
  8533. //
  8534. // Protected common (OS-independent) RtAudio methods.
  8535. //
  8536. // *************************************************** //
  8537. // This method can be modified to control the behavior of error
  8538. // message printing.
  8539. void RtApi :: error( RtAudioError::Type type )
  8540. {
  8541. errorStream_.str(""); // clear the ostringstream
  8542. RtAudioErrorCallback errorCallback = (RtAudioErrorCallback) stream_.callbackInfo.errorCallback;
  8543. if ( errorCallback ) {
  8544. // abortStream() can generate new error messages. Ignore them. Just keep original one.
  8545. if ( firstErrorOccurred_ )
  8546. return;
  8547. firstErrorOccurred_ = true;
  8548. const std::string errorMessage = errorText_;
  8549. if ( type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED) {
  8550. stream_.callbackInfo.isRunning = false; // exit from the thread
  8551. abortStream();
  8552. }
  8553. errorCallback( type, errorMessage );
  8554. firstErrorOccurred_ = false;
  8555. return;
  8556. }
  8557. if ( type == RtAudioError::WARNING && showWarnings_ == true )
  8558. std::cerr << '\n' << errorText_ << "\n\n";
  8559. else if ( type != RtAudioError::WARNING )
  8560. throw( RtAudioError( errorText_, type ) );
  8561. }
  8562. void RtApi :: verifyStream()
  8563. {
  8564. if ( stream_.state == STREAM_CLOSED ) {
  8565. errorText_ = "RtApi:: a stream is not open!";
  8566. error( RtAudioError::INVALID_USE );
  8567. }
  8568. }
  8569. void RtApi :: clearStreamInfo()
  8570. {
  8571. stream_.mode = UNINITIALIZED;
  8572. stream_.state = STREAM_CLOSED;
  8573. stream_.sampleRate = 0;
  8574. stream_.bufferSize = 0;
  8575. stream_.nBuffers = 0;
  8576. stream_.userFormat = 0;
  8577. stream_.userInterleaved = true;
  8578. stream_.streamTime = 0.0;
  8579. stream_.apiHandle = 0;
  8580. stream_.deviceBuffer = 0;
  8581. stream_.callbackInfo.callback = 0;
  8582. stream_.callbackInfo.userData = 0;
  8583. stream_.callbackInfo.isRunning = false;
  8584. stream_.callbackInfo.errorCallback = 0;
  8585. for ( int i=0; i<2; i++ ) {
  8586. stream_.device[i] = 11111;
  8587. stream_.doConvertBuffer[i] = false;
  8588. stream_.deviceInterleaved[i] = true;
  8589. stream_.doByteSwap[i] = false;
  8590. stream_.nUserChannels[i] = 0;
  8591. stream_.nDeviceChannels[i] = 0;
  8592. stream_.channelOffset[i] = 0;
  8593. stream_.deviceFormat[i] = 0;
  8594. stream_.latency[i] = 0;
  8595. stream_.userBuffer[i] = 0;
  8596. stream_.convertInfo[i].channels = 0;
  8597. stream_.convertInfo[i].inJump = 0;
  8598. stream_.convertInfo[i].outJump = 0;
  8599. stream_.convertInfo[i].inFormat = 0;
  8600. stream_.convertInfo[i].outFormat = 0;
  8601. stream_.convertInfo[i].inOffset.clear();
  8602. stream_.convertInfo[i].outOffset.clear();
  8603. }
  8604. }
  8605. unsigned int RtApi :: formatBytes( RtAudioFormat format )
  8606. {
  8607. if ( format == RTAUDIO_SINT16 )
  8608. return 2;
  8609. else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )
  8610. return 4;
  8611. else if ( format == RTAUDIO_FLOAT64 )
  8612. return 8;
  8613. else if ( format == RTAUDIO_SINT24 )
  8614. return 3;
  8615. else if ( format == RTAUDIO_SINT8 )
  8616. return 1;
  8617. errorText_ = "RtApi::formatBytes: undefined format.";
  8618. error( RtAudioError::WARNING );
  8619. return 0;
  8620. }
  8621. void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
  8622. {
  8623. if ( mode == INPUT ) { // convert device to user buffer
  8624. stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
  8625. stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
  8626. stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
  8627. stream_.convertInfo[mode].outFormat = stream_.userFormat;
  8628. }
  8629. else { // convert user to device buffer
  8630. stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
  8631. stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
  8632. stream_.convertInfo[mode].inFormat = stream_.userFormat;
  8633. stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
  8634. }
  8635. if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
  8636. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
  8637. else
  8638. stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
  8639. // Set up the interleave/deinterleave offsets.
  8640. if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
  8641. if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
  8642. ( mode == INPUT && stream_.userInterleaved ) ) {
  8643. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8644. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8645. stream_.convertInfo[mode].outOffset.push_back( k );
  8646. stream_.convertInfo[mode].inJump = 1;
  8647. }
  8648. }
  8649. else {
  8650. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8651. stream_.convertInfo[mode].inOffset.push_back( k );
  8652. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8653. stream_.convertInfo[mode].outJump = 1;
  8654. }
  8655. }
  8656. }
  8657. else { // no (de)interleaving
  8658. if ( stream_.userInterleaved ) {
  8659. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8660. stream_.convertInfo[mode].inOffset.push_back( k );
  8661. stream_.convertInfo[mode].outOffset.push_back( k );
  8662. }
  8663. }
  8664. else {
  8665. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
  8666. stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
  8667. stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
  8668. stream_.convertInfo[mode].inJump = 1;
  8669. stream_.convertInfo[mode].outJump = 1;
  8670. }
  8671. }
  8672. }
  8673. // Add channel offset.
  8674. if ( firstChannel > 0 ) {
  8675. if ( stream_.deviceInterleaved[mode] ) {
  8676. if ( mode == OUTPUT ) {
  8677. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8678. stream_.convertInfo[mode].outOffset[k] += firstChannel;
  8679. }
  8680. else {
  8681. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8682. stream_.convertInfo[mode].inOffset[k] += firstChannel;
  8683. }
  8684. }
  8685. else {
  8686. if ( mode == OUTPUT ) {
  8687. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8688. stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
  8689. }
  8690. else {
  8691. for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
  8692. stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize );
  8693. }
  8694. }
  8695. }
  8696. }
  8697. void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
  8698. {
  8699. // This function does format conversion, input/output channel compensation, and
  8700. // data interleaving/deinterleaving. 24-bit integers are assumed to occupy
  8701. // the lower three bytes of a 32-bit integer.
  8702. // Clear our device buffer when in/out duplex device channels are different
  8703. if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
  8704. ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
  8705. memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
  8706. int j;
  8707. if (info.outFormat == RTAUDIO_FLOAT64) {
  8708. Float64 scale;
  8709. Float64 *out = (Float64 *)outBuffer;
  8710. if (info.inFormat == RTAUDIO_SINT8) {
  8711. signed char *in = (signed char *)inBuffer;
  8712. scale = 1.0 / 127.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]];
  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_SINT16) {
  8724. Int16 *in = (Int16 *)inBuffer;
  8725. scale = 1.0 / 32767.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_SINT24) {
  8737. Int24 *in = (Int24 *)inBuffer;
  8738. scale = 1.0 / 8388607.5;
  8739. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8740. for (j=0; j<info.channels; j++) {
  8741. out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());
  8742. out[info.outOffset[j]] += 0.5;
  8743. out[info.outOffset[j]] *= scale;
  8744. }
  8745. in += info.inJump;
  8746. out += info.outJump;
  8747. }
  8748. }
  8749. else if (info.inFormat == RTAUDIO_SINT32) {
  8750. Int32 *in = (Int32 *)inBuffer;
  8751. scale = 1.0 / 2147483647.5;
  8752. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8753. for (j=0; j<info.channels; j++) {
  8754. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8755. out[info.outOffset[j]] += 0.5;
  8756. out[info.outOffset[j]] *= scale;
  8757. }
  8758. in += info.inJump;
  8759. out += info.outJump;
  8760. }
  8761. }
  8762. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8763. Float32 *in = (Float32 *)inBuffer;
  8764. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8765. for (j=0; j<info.channels; j++) {
  8766. out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
  8767. }
  8768. in += info.inJump;
  8769. out += info.outJump;
  8770. }
  8771. }
  8772. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8773. // Channel compensation and/or (de)interleaving only.
  8774. Float64 *in = (Float64 *)inBuffer;
  8775. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8776. for (j=0; j<info.channels; j++) {
  8777. out[info.outOffset[j]] = in[info.inOffset[j]];
  8778. }
  8779. in += info.inJump;
  8780. out += info.outJump;
  8781. }
  8782. }
  8783. }
  8784. else if (info.outFormat == RTAUDIO_FLOAT32) {
  8785. Float32 scale;
  8786. Float32 *out = (Float32 *)outBuffer;
  8787. if (info.inFormat == RTAUDIO_SINT8) {
  8788. signed char *in = (signed char *)inBuffer;
  8789. scale = (Float32) ( 1.0 / 127.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]];
  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_SINT16) {
  8801. Int16 *in = (Int16 *)inBuffer;
  8802. scale = (Float32) ( 1.0 / 32767.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_SINT24) {
  8814. Int24 *in = (Int24 *)inBuffer;
  8815. scale = (Float32) ( 1.0 / 8388607.5 );
  8816. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8817. for (j=0; j<info.channels; j++) {
  8818. out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());
  8819. out[info.outOffset[j]] += 0.5;
  8820. out[info.outOffset[j]] *= scale;
  8821. }
  8822. in += info.inJump;
  8823. out += info.outJump;
  8824. }
  8825. }
  8826. else if (info.inFormat == RTAUDIO_SINT32) {
  8827. Int32 *in = (Int32 *)inBuffer;
  8828. scale = (Float32) ( 1.0 / 2147483647.5 );
  8829. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8830. for (j=0; j<info.channels; j++) {
  8831. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8832. out[info.outOffset[j]] += 0.5;
  8833. out[info.outOffset[j]] *= scale;
  8834. }
  8835. in += info.inJump;
  8836. out += info.outJump;
  8837. }
  8838. }
  8839. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8840. // Channel compensation and/or (de)interleaving only.
  8841. Float32 *in = (Float32 *)inBuffer;
  8842. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8843. for (j=0; j<info.channels; j++) {
  8844. out[info.outOffset[j]] = in[info.inOffset[j]];
  8845. }
  8846. in += info.inJump;
  8847. out += info.outJump;
  8848. }
  8849. }
  8850. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8851. Float64 *in = (Float64 *)inBuffer;
  8852. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8853. for (j=0; j<info.channels; j++) {
  8854. out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
  8855. }
  8856. in += info.inJump;
  8857. out += info.outJump;
  8858. }
  8859. }
  8860. }
  8861. else if (info.outFormat == RTAUDIO_SINT32) {
  8862. Int32 *out = (Int32 *)outBuffer;
  8863. if (info.inFormat == RTAUDIO_SINT8) {
  8864. signed char *in = (signed char *)inBuffer;
  8865. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8866. for (j=0; j<info.channels; j++) {
  8867. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8868. out[info.outOffset[j]] <<= 24;
  8869. }
  8870. in += info.inJump;
  8871. out += info.outJump;
  8872. }
  8873. }
  8874. else if (info.inFormat == RTAUDIO_SINT16) {
  8875. Int16 *in = (Int16 *)inBuffer;
  8876. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8877. for (j=0; j<info.channels; j++) {
  8878. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
  8879. out[info.outOffset[j]] <<= 16;
  8880. }
  8881. in += info.inJump;
  8882. out += info.outJump;
  8883. }
  8884. }
  8885. else if (info.inFormat == RTAUDIO_SINT24) {
  8886. Int24 *in = (Int24 *)inBuffer;
  8887. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8888. for (j=0; j<info.channels; j++) {
  8889. out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();
  8890. out[info.outOffset[j]] <<= 8;
  8891. }
  8892. in += info.inJump;
  8893. out += info.outJump;
  8894. }
  8895. }
  8896. else if (info.inFormat == RTAUDIO_SINT32) {
  8897. // Channel compensation and/or (de)interleaving only.
  8898. Int32 *in = (Int32 *)inBuffer;
  8899. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8900. for (j=0; j<info.channels; j++) {
  8901. out[info.outOffset[j]] = in[info.inOffset[j]];
  8902. }
  8903. in += info.inJump;
  8904. out += info.outJump;
  8905. }
  8906. }
  8907. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8908. Float32 *in = (Float32 *)inBuffer;
  8909. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8910. for (j=0; j<info.channels; j++) {
  8911. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8912. }
  8913. in += info.inJump;
  8914. out += info.outJump;
  8915. }
  8916. }
  8917. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8918. Float64 *in = (Float64 *)inBuffer;
  8919. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8920. for (j=0; j<info.channels; j++) {
  8921. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
  8922. }
  8923. in += info.inJump;
  8924. out += info.outJump;
  8925. }
  8926. }
  8927. }
  8928. else if (info.outFormat == RTAUDIO_SINT24) {
  8929. Int24 *out = (Int24 *)outBuffer;
  8930. if (info.inFormat == RTAUDIO_SINT8) {
  8931. signed char *in = (signed char *)inBuffer;
  8932. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8933. for (j=0; j<info.channels; j++) {
  8934. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);
  8935. //out[info.outOffset[j]] <<= 16;
  8936. }
  8937. in += info.inJump;
  8938. out += info.outJump;
  8939. }
  8940. }
  8941. else if (info.inFormat == RTAUDIO_SINT16) {
  8942. Int16 *in = (Int16 *)inBuffer;
  8943. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8944. for (j=0; j<info.channels; j++) {
  8945. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);
  8946. //out[info.outOffset[j]] <<= 8;
  8947. }
  8948. in += info.inJump;
  8949. out += info.outJump;
  8950. }
  8951. }
  8952. else if (info.inFormat == RTAUDIO_SINT24) {
  8953. // Channel compensation and/or (de)interleaving only.
  8954. Int24 *in = (Int24 *)inBuffer;
  8955. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8956. for (j=0; j<info.channels; j++) {
  8957. out[info.outOffset[j]] = in[info.inOffset[j]];
  8958. }
  8959. in += info.inJump;
  8960. out += info.outJump;
  8961. }
  8962. }
  8963. else if (info.inFormat == RTAUDIO_SINT32) {
  8964. Int32 *in = (Int32 *)inBuffer;
  8965. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8966. for (j=0; j<info.channels; j++) {
  8967. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);
  8968. //out[info.outOffset[j]] >>= 8;
  8969. }
  8970. in += info.inJump;
  8971. out += info.outJump;
  8972. }
  8973. }
  8974. else if (info.inFormat == RTAUDIO_FLOAT32) {
  8975. Float32 *in = (Float32 *)inBuffer;
  8976. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8977. for (j=0; j<info.channels; j++) {
  8978. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8979. }
  8980. in += info.inJump;
  8981. out += info.outJump;
  8982. }
  8983. }
  8984. else if (info.inFormat == RTAUDIO_FLOAT64) {
  8985. Float64 *in = (Float64 *)inBuffer;
  8986. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  8987. for (j=0; j<info.channels; j++) {
  8988. out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
  8989. }
  8990. in += info.inJump;
  8991. out += info.outJump;
  8992. }
  8993. }
  8994. }
  8995. else if (info.outFormat == RTAUDIO_SINT16) {
  8996. Int16 *out = (Int16 *)outBuffer;
  8997. if (info.inFormat == RTAUDIO_SINT8) {
  8998. signed char *in = (signed char *)inBuffer;
  8999. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9000. for (j=0; j<info.channels; j++) {
  9001. out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
  9002. out[info.outOffset[j]] <<= 8;
  9003. }
  9004. in += info.inJump;
  9005. out += info.outJump;
  9006. }
  9007. }
  9008. else if (info.inFormat == RTAUDIO_SINT16) {
  9009. // Channel compensation and/or (de)interleaving only.
  9010. Int16 *in = (Int16 *)inBuffer;
  9011. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9012. for (j=0; j<info.channels; j++) {
  9013. out[info.outOffset[j]] = in[info.inOffset[j]];
  9014. }
  9015. in += info.inJump;
  9016. out += info.outJump;
  9017. }
  9018. }
  9019. else if (info.inFormat == RTAUDIO_SINT24) {
  9020. Int24 *in = (Int24 *)inBuffer;
  9021. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9022. for (j=0; j<info.channels; j++) {
  9023. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);
  9024. }
  9025. in += info.inJump;
  9026. out += info.outJump;
  9027. }
  9028. }
  9029. else if (info.inFormat == RTAUDIO_SINT32) {
  9030. Int32 *in = (Int32 *)inBuffer;
  9031. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9032. for (j=0; j<info.channels; j++) {
  9033. out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
  9034. }
  9035. in += info.inJump;
  9036. out += info.outJump;
  9037. }
  9038. }
  9039. else if (info.inFormat == RTAUDIO_FLOAT32) {
  9040. Float32 *in = (Float32 *)inBuffer;
  9041. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9042. for (j=0; j<info.channels; j++) {
  9043. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  9044. }
  9045. in += info.inJump;
  9046. out += info.outJump;
  9047. }
  9048. }
  9049. else if (info.inFormat == RTAUDIO_FLOAT64) {
  9050. Float64 *in = (Float64 *)inBuffer;
  9051. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9052. for (j=0; j<info.channels; j++) {
  9053. out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
  9054. }
  9055. in += info.inJump;
  9056. out += info.outJump;
  9057. }
  9058. }
  9059. }
  9060. else if (info.outFormat == RTAUDIO_SINT8) {
  9061. signed char *out = (signed char *)outBuffer;
  9062. if (info.inFormat == RTAUDIO_SINT8) {
  9063. // Channel compensation and/or (de)interleaving only.
  9064. signed char *in = (signed char *)inBuffer;
  9065. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9066. for (j=0; j<info.channels; j++) {
  9067. out[info.outOffset[j]] = in[info.inOffset[j]];
  9068. }
  9069. in += info.inJump;
  9070. out += info.outJump;
  9071. }
  9072. }
  9073. if (info.inFormat == RTAUDIO_SINT16) {
  9074. Int16 *in = (Int16 *)inBuffer;
  9075. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9076. for (j=0; j<info.channels; j++) {
  9077. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
  9078. }
  9079. in += info.inJump;
  9080. out += info.outJump;
  9081. }
  9082. }
  9083. else if (info.inFormat == RTAUDIO_SINT24) {
  9084. Int24 *in = (Int24 *)inBuffer;
  9085. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9086. for (j=0; j<info.channels; j++) {
  9087. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);
  9088. }
  9089. in += info.inJump;
  9090. out += info.outJump;
  9091. }
  9092. }
  9093. else if (info.inFormat == RTAUDIO_SINT32) {
  9094. Int32 *in = (Int32 *)inBuffer;
  9095. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9096. for (j=0; j<info.channels; j++) {
  9097. out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
  9098. }
  9099. in += info.inJump;
  9100. out += info.outJump;
  9101. }
  9102. }
  9103. else if (info.inFormat == RTAUDIO_FLOAT32) {
  9104. Float32 *in = (Float32 *)inBuffer;
  9105. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9106. for (j=0; j<info.channels; j++) {
  9107. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  9108. }
  9109. in += info.inJump;
  9110. out += info.outJump;
  9111. }
  9112. }
  9113. else if (info.inFormat == RTAUDIO_FLOAT64) {
  9114. Float64 *in = (Float64 *)inBuffer;
  9115. for (unsigned int i=0; i<stream_.bufferSize; i++) {
  9116. for (j=0; j<info.channels; j++) {
  9117. out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
  9118. }
  9119. in += info.inJump;
  9120. out += info.outJump;
  9121. }
  9122. }
  9123. }
  9124. }
  9125. //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
  9126. //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
  9127. //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
  9128. void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
  9129. {
  9130. char val;
  9131. char *ptr;
  9132. ptr = buffer;
  9133. if ( format == RTAUDIO_SINT16 ) {
  9134. for ( unsigned int i=0; i<samples; i++ ) {
  9135. // Swap 1st and 2nd bytes.
  9136. val = *(ptr);
  9137. *(ptr) = *(ptr+1);
  9138. *(ptr+1) = val;
  9139. // Increment 2 bytes.
  9140. ptr += 2;
  9141. }
  9142. }
  9143. else if ( format == RTAUDIO_SINT32 ||
  9144. format == RTAUDIO_FLOAT32 ) {
  9145. for ( unsigned int i=0; i<samples; i++ ) {
  9146. // Swap 1st and 4th bytes.
  9147. val = *(ptr);
  9148. *(ptr) = *(ptr+3);
  9149. *(ptr+3) = val;
  9150. // Swap 2nd and 3rd bytes.
  9151. ptr += 1;
  9152. val = *(ptr);
  9153. *(ptr) = *(ptr+1);
  9154. *(ptr+1) = val;
  9155. // Increment 3 more bytes.
  9156. ptr += 3;
  9157. }
  9158. }
  9159. else if ( format == RTAUDIO_SINT24 ) {
  9160. for ( unsigned int i=0; i<samples; i++ ) {
  9161. // Swap 1st and 3rd bytes.
  9162. val = *(ptr);
  9163. *(ptr) = *(ptr+2);
  9164. *(ptr+2) = val;
  9165. // Increment 2 more bytes.
  9166. ptr += 2;
  9167. }
  9168. }
  9169. else if ( format == RTAUDIO_FLOAT64 ) {
  9170. for ( unsigned int i=0; i<samples; i++ ) {
  9171. // Swap 1st and 8th bytes
  9172. val = *(ptr);
  9173. *(ptr) = *(ptr+7);
  9174. *(ptr+7) = val;
  9175. // Swap 2nd and 7th bytes
  9176. ptr += 1;
  9177. val = *(ptr);
  9178. *(ptr) = *(ptr+5);
  9179. *(ptr+5) = val;
  9180. // Swap 3rd and 6th bytes
  9181. ptr += 1;
  9182. val = *(ptr);
  9183. *(ptr) = *(ptr+3);
  9184. *(ptr+3) = val;
  9185. // Swap 4th and 5th bytes
  9186. ptr += 1;
  9187. val = *(ptr);
  9188. *(ptr) = *(ptr+1);
  9189. *(ptr+1) = val;
  9190. // Increment 5 more bytes.
  9191. ptr += 5;
  9192. }
  9193. }
  9194. }
  9195. // Indentation settings for Vim and Emacs
  9196. //
  9197. // Local Variables:
  9198. // c-basic-offset: 2
  9199. // indent-tabs-mode: nil
  9200. // End:
  9201. //
  9202. // vim: et sts=2 sw=2