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.

8364 lines
293KB

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