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.

10681 lines
367KB

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