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.

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