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.

8536 lines
299KB

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