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.

10676 lines
366KB

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