Audio plugin host https://kx.studio/carla
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.

10056 lines
344KB

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