| 1 | /************************************************************************/ |
| 2 | /*! \class RtAudio |
| 3 | \brief Realtime audio i/o C++ classes. |
| 4 | |
| 5 | RtAudio provides a common API (Application Programming Interface) |
| 6 | for realtime audio input/output across Linux (native ALSA, Jack, |
| 7 | and OSS), Macintosh OS X (CoreAudio and Jack), and Windows |
| 8 | (DirectSound, ASIO and WASAPI) operating systems. |
| 9 | |
| 10 | RtAudio GitHub site: https://github.com/thestk/rtaudio |
| 11 | RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/ |
| 12 | |
| 13 | RtAudio: realtime audio i/o C++ classes |
| 14 | Copyright (c) 2001-2021 Gary P. Scavone |
| 15 | |
| 16 | Permission is hereby granted, free of charge, to any person |
| 17 | obtaining a copy of this software and associated documentation files |
| 18 | (the "Software"), to deal in the Software without restriction, |
| 19 | including without limitation the rights to use, copy, modify, merge, |
| 20 | publish, distribute, sublicense, and/or sell copies of the Software, |
| 21 | and to permit persons to whom the Software is furnished to do so, |
| 22 | subject to the following conditions: |
| 23 | |
| 24 | The above copyright notice and this permission notice shall be |
| 25 | included in all copies or substantial portions of the Software. |
| 26 | |
| 27 | Any person wishing to distribute modifications to the Software is |
| 28 | asked to send the modifications to the original developer so that |
| 29 | they can be incorporated into the canonical version. This is, |
| 30 | however, not a binding provision of this license. |
| 31 | |
| 32 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 33 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 34 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 35 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR |
| 36 | ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 37 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 38 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 39 | */ |
| 40 | /************************************************************************/ |
| 41 | |
| 42 | // RtAudio: Version 6.0.0beta1 |
| 43 | |
| 44 | #include "RtAudio.h" |
| 45 | #include <iostream> |
| 46 | #include <cstdlib> |
| 47 | #include <cstring> |
| 48 | #include <climits> |
| 49 | #include <cmath> |
| 50 | #include <algorithm> |
| 51 | |
| 52 | // Static variable definitions. |
| 53 | const unsigned int RtApi::MAX_SAMPLE_RATES = 14; |
| 54 | const unsigned int RtApi::SAMPLE_RATES[] = { |
| 55 | 4000, 5512, 8000, 9600, 11025, 16000, 22050, |
| 56 | 32000, 44100, 48000, 88200, 96000, 176400, 192000 |
| 57 | }; |
| 58 | |
| 59 | #if defined(_WIN32) || defined(__CYGWIN__) |
| 60 | #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A) |
| 61 | #define MUTEX_DESTROY(A) DeleteCriticalSection(A) |
| 62 | #define MUTEX_LOCK(A) EnterCriticalSection(A) |
| 63 | #define MUTEX_UNLOCK(A) LeaveCriticalSection(A) |
| 64 | |
| 65 | #include "tchar.h" |
| 66 | |
| 67 | template<typename T> inline |
| 68 | std::string convertCharPointerToStdString(const T *text); |
| 69 | |
| 70 | template<> inline |
| 71 | std::string convertCharPointerToStdString(const char *text) |
| 72 | { |
| 73 | return std::string(text); |
| 74 | } |
| 75 | |
| 76 | template<> inline |
| 77 | std::string convertCharPointerToStdString(const wchar_t *text) |
| 78 | { |
| 79 | int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL); |
| 80 | std::string s( length-1, '\0' ); |
| 81 | WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL); |
| 82 | return s; |
| 83 | } |
| 84 | |
| 85 | #elif defined(__unix__) || defined(__APPLE__) |
| 86 | // pthread API |
| 87 | #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL) |
| 88 | #define MUTEX_DESTROY(A) pthread_mutex_destroy(A) |
| 89 | #define MUTEX_LOCK(A) pthread_mutex_lock(A) |
| 90 | #define MUTEX_UNLOCK(A) pthread_mutex_unlock(A) |
| 91 | #endif |
| 92 | |
| 93 | // *************************************************** // |
| 94 | // |
| 95 | // RtAudio definitions. |
| 96 | // |
| 97 | // *************************************************** // |
| 98 | |
| 99 | std::string RtAudio :: getVersion( void ) |
| 100 | { |
| 101 | return RTAUDIO_VERSION; |
| 102 | } |
| 103 | |
| 104 | // Define API names and display names. |
| 105 | // Must be in same order as API enum. |
| 106 | extern "C" { |
| 107 | const char* rtaudio_api_names[][2] = { |
| 108 | { "unspecified" , "Unknown" }, |
| 109 | { "alsa" , "ALSA" }, |
| 110 | { "pulse" , "Pulse" }, |
| 111 | { "oss" , "OpenSoundSystem" }, |
| 112 | { "jack" , "Jack" }, |
| 113 | { "core" , "CoreAudio" }, |
| 114 | { "wasapi" , "WASAPI" }, |
| 115 | { "asio" , "ASIO" }, |
| 116 | { "ds" , "DirectSound" }, |
| 117 | { "dummy" , "Dummy" }, |
| 118 | }; |
| 119 | |
| 120 | const unsigned int rtaudio_num_api_names = |
| 121 | sizeof(rtaudio_api_names)/sizeof(rtaudio_api_names[0]); |
| 122 | |
| 123 | // The order here will control the order of RtAudio's API search in |
| 124 | // the constructor. |
| 125 | extern "C" const RtAudio::Api rtaudio_compiled_apis[] = { |
| 126 | #if defined(__UNIX_JACK__) |
| 127 | RtAudio::UNIX_JACK, |
| 128 | #endif |
| 129 | #if defined(__LINUX_PULSE__) |
| 130 | RtAudio::LINUX_PULSE, |
| 131 | #endif |
| 132 | #if defined(__LINUX_ALSA__) |
| 133 | RtAudio::LINUX_ALSA, |
| 134 | #endif |
| 135 | #if defined(__LINUX_OSS__) |
| 136 | RtAudio::LINUX_OSS, |
| 137 | #endif |
| 138 | #if defined(__WINDOWS_ASIO__) |
| 139 | RtAudio::WINDOWS_ASIO, |
| 140 | #endif |
| 141 | #if defined(__WINDOWS_WASAPI__) |
| 142 | RtAudio::WINDOWS_WASAPI, |
| 143 | #endif |
| 144 | #if defined(__WINDOWS_DS__) |
| 145 | RtAudio::WINDOWS_DS, |
| 146 | #endif |
| 147 | #if defined(__MACOSX_CORE__) |
| 148 | RtAudio::MACOSX_CORE, |
| 149 | #endif |
| 150 | #if defined(__RTAUDIO_DUMMY__) |
| 151 | RtAudio::RTAUDIO_DUMMY, |
| 152 | #endif |
| 153 | RtAudio::UNSPECIFIED, |
| 154 | }; |
| 155 | |
| 156 | extern "C" const unsigned int rtaudio_num_compiled_apis = |
| 157 | sizeof(rtaudio_compiled_apis)/sizeof(rtaudio_compiled_apis[0])-1; |
| 158 | } |
| 159 | |
| 160 | // This is a compile-time check that rtaudio_num_api_names == RtAudio::NUM_APIS. |
| 161 | // If the build breaks here, check that they match. |
| 162 | template<bool b> class StaticAssert { private: StaticAssert() {} }; |
| 163 | template<> class StaticAssert<true>{ public: StaticAssert() {} }; |
| 164 | class StaticAssertions { StaticAssertions() { |
| 165 | StaticAssert<rtaudio_num_api_names == RtAudio::NUM_APIS>(); |
| 166 | }}; |
| 167 | |
| 168 | void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis ) |
| 169 | { |
| 170 | apis = std::vector<RtAudio::Api>(rtaudio_compiled_apis, |
| 171 | rtaudio_compiled_apis + rtaudio_num_compiled_apis); |
| 172 | } |
| 173 | |
| 174 | std::string RtAudio :: getApiName( RtAudio::Api api ) |
| 175 | { |
| 176 | if (api < 0 || api >= RtAudio::NUM_APIS) |
| 177 | return ""; |
| 178 | return rtaudio_api_names[api][0]; |
| 179 | } |
| 180 | |
| 181 | std::string RtAudio :: getApiDisplayName( RtAudio::Api api ) |
| 182 | { |
| 183 | if (api < 0 || api >= RtAudio::NUM_APIS) |
| 184 | return "Unknown"; |
| 185 | return rtaudio_api_names[api][1]; |
| 186 | } |
| 187 | |
| 188 | RtAudio::Api RtAudio :: getCompiledApiByName( const std::string &name ) |
| 189 | { |
| 190 | unsigned int i=0; |
| 191 | for (i = 0; i < rtaudio_num_compiled_apis; ++i) |
| 192 | if (name == rtaudio_api_names[rtaudio_compiled_apis[i]][0]) |
| 193 | return rtaudio_compiled_apis[i]; |
| 194 | return RtAudio::UNSPECIFIED; |
| 195 | } |
| 196 | |
| 197 | void RtAudio :: openRtApi( RtAudio::Api api ) |
| 198 | { |
| 199 | if ( rtapi_ ) |
| 200 | delete rtapi_; |
| 201 | rtapi_ = 0; |
| 202 | |
| 203 | #if defined(__UNIX_JACK__) |
| 204 | if ( api == UNIX_JACK ) |
| 205 | rtapi_ = new RtApiJack(); |
| 206 | #endif |
| 207 | #if defined(__LINUX_ALSA__) |
| 208 | if ( api == LINUX_ALSA ) |
| 209 | rtapi_ = new RtApiAlsa(); |
| 210 | #endif |
| 211 | #if defined(__LINUX_PULSE__) |
| 212 | if ( api == LINUX_PULSE ) |
| 213 | rtapi_ = new RtApiPulse(); |
| 214 | #endif |
| 215 | #if defined(__LINUX_OSS__) |
| 216 | if ( api == LINUX_OSS ) |
| 217 | rtapi_ = new RtApiOss(); |
| 218 | #endif |
| 219 | #if defined(__WINDOWS_ASIO__) |
| 220 | if ( api == WINDOWS_ASIO ) |
| 221 | rtapi_ = new RtApiAsio(); |
| 222 | #endif |
| 223 | #if defined(__WINDOWS_WASAPI__) |
| 224 | if ( api == WINDOWS_WASAPI ) |
| 225 | rtapi_ = new RtApiWasapi(); |
| 226 | #endif |
| 227 | #if defined(__WINDOWS_DS__) |
| 228 | if ( api == WINDOWS_DS ) |
| 229 | rtapi_ = new RtApiDs(); |
| 230 | #endif |
| 231 | #if defined(__MACOSX_CORE__) |
| 232 | if ( api == MACOSX_CORE ) |
| 233 | rtapi_ = new RtApiCore(); |
| 234 | #endif |
| 235 | #if defined(__RTAUDIO_DUMMY__) |
| 236 | if ( api == RTAUDIO_DUMMY ) |
| 237 | rtapi_ = new RtApiDummy(); |
| 238 | #endif |
| 239 | } |
| 240 | |
| 241 | RtAudio :: RtAudio( RtAudio::Api api, RtAudioErrorCallback /* && */ errorCallback ) |
| 242 | { |
| 243 | rtapi_ = 0; |
| 244 | |
| 245 | std::string errorMessage; |
| 246 | if ( api != UNSPECIFIED ) { |
| 247 | // Attempt to open the specified API. |
| 248 | openRtApi( api ); |
| 249 | |
| 250 | if ( rtapi_ ) { |
| 251 | if ( errorCallback ) rtapi_->setErrorCallback( errorCallback ); |
| 252 | return; |
| 253 | } |
| 254 | |
| 255 | // No compiled support for specified API value. Issue a warning |
| 256 | // and continue as if no API was specified. |
| 257 | errorMessage = "RtAudio: no compiled support for specified API argument!"; |
| 258 | if ( errorCallback ) |
| 259 | errorCallback( RTAUDIO_INVALID_USE, errorMessage ); |
| 260 | else |
| 261 | std::cerr << '\n' << errorMessage << '\n' << std::endl; |
| 262 | } |
| 263 | |
| 264 | // Iterate through the compiled APIs and return as soon as we find |
| 265 | // one with at least one device or we reach the end of the list. |
| 266 | std::vector< RtAudio::Api > apis; |
| 267 | getCompiledApi( apis ); |
| 268 | for ( unsigned int i=0; i<apis.size(); i++ ) { |
| 269 | openRtApi( apis[i] ); |
| 270 | if ( rtapi_ && rtapi_->getDeviceCount() ) break; |
| 271 | } |
| 272 | |
| 273 | if ( rtapi_ ) { |
| 274 | if ( errorCallback ) rtapi_->setErrorCallback( errorCallback ); |
| 275 | return; |
| 276 | } |
| 277 | |
| 278 | // It should not be possible to get here because the preprocessor |
| 279 | // definition __RTAUDIO_DUMMY__ is automatically defined in RtAudio.h |
| 280 | // if no API-specific definitions are passed to the compiler. But just |
| 281 | // in case something weird happens, issue an error message and abort. |
| 282 | errorMessage = "RtAudio: no compiled API support found ... critical error!"; |
| 283 | if ( errorCallback ) |
| 284 | errorCallback( RTAUDIO_INVALID_USE, errorMessage ); |
| 285 | else |
| 286 | std::cerr << '\n' << errorMessage << '\n' << std::endl; |
| 287 | abort(); |
| 288 | } |
| 289 | |
| 290 | RtAudio :: ~RtAudio() |
| 291 | { |
| 292 | if ( rtapi_ ) |
| 293 | delete rtapi_; |
| 294 | } |
| 295 | |
| 296 | RtAudioErrorType RtAudio :: openStream( RtAudio::StreamParameters *outputParameters, |
| 297 | RtAudio::StreamParameters *inputParameters, |
| 298 | RtAudioFormat format, unsigned int sampleRate, |
| 299 | unsigned int *bufferFrames, |
| 300 | RtAudioCallback callback, void *userData, |
| 301 | RtAudio::StreamOptions *options ) |
| 302 | { |
| 303 | return rtapi_->openStream( outputParameters, inputParameters, format, |
| 304 | sampleRate, bufferFrames, callback, |
| 305 | userData, options ); |
| 306 | } |
| 307 | |
| 308 | // *************************************************** // |
| 309 | // |
| 310 | // Public RtApi definitions (see end of file for |
| 311 | // private or protected utility functions). |
| 312 | // |
| 313 | // *************************************************** // |
| 314 | |
| 315 | RtApi :: RtApi() |
| 316 | { |
| 317 | clearStreamInfo(); |
| 318 | MUTEX_INITIALIZE( &stream_.mutex ); |
| 319 | errorCallback_ = 0; |
| 320 | showWarnings_ = true; |
| 321 | } |
| 322 | |
| 323 | RtApi :: ~RtApi() |
| 324 | { |
| 325 | MUTEX_DESTROY( &stream_.mutex ); |
| 326 | } |
| 327 | |
| 328 | RtAudioErrorType RtApi :: openStream( RtAudio::StreamParameters *oParams, |
| 329 | RtAudio::StreamParameters *iParams, |
| 330 | RtAudioFormat format, unsigned int sampleRate, |
| 331 | unsigned int *bufferFrames, |
| 332 | RtAudioCallback callback, void *userData, |
| 333 | RtAudio::StreamOptions *options ) |
| 334 | { |
| 335 | if ( stream_.state != STREAM_CLOSED ) { |
| 336 | errorText_ = "RtApi::openStream: a stream is already open!"; |
| 337 | return error( RTAUDIO_INVALID_USE ); |
| 338 | } |
| 339 | |
| 340 | // Clear stream information potentially left from a previously open stream. |
| 341 | clearStreamInfo(); |
| 342 | |
| 343 | if ( oParams && oParams->nChannels < 1 ) { |
| 344 | errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one."; |
| 345 | return error( RTAUDIO_INVALID_USE ); |
| 346 | } |
| 347 | |
| 348 | if ( iParams && iParams->nChannels < 1 ) { |
| 349 | errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one."; |
| 350 | return error( RTAUDIO_INVALID_USE ); |
| 351 | } |
| 352 | |
| 353 | if ( oParams == NULL && iParams == NULL ) { |
| 354 | errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!"; |
| 355 | return error( RTAUDIO_INVALID_USE ); |
| 356 | } |
| 357 | |
| 358 | if ( formatBytes(format) == 0 ) { |
| 359 | errorText_ = "RtApi::openStream: 'format' parameter value is undefined."; |
| 360 | return error( RTAUDIO_INVALID_USE ); |
| 361 | } |
| 362 | |
| 363 | unsigned int nDevices = getDeviceCount(); |
| 364 | unsigned int oChannels = 0; |
| 365 | if ( oParams ) { |
| 366 | oChannels = oParams->nChannels; |
| 367 | if ( oParams->deviceId >= nDevices ) { |
| 368 | errorText_ = "RtApi::openStream: output device parameter value is invalid."; |
| 369 | return error( RTAUDIO_INVALID_USE ); |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | unsigned int iChannels = 0; |
| 374 | if ( iParams ) { |
| 375 | iChannels = iParams->nChannels; |
| 376 | if ( iParams->deviceId >= nDevices ) { |
| 377 | errorText_ = "RtApi::openStream: input device parameter value is invalid."; |
| 378 | return error( RTAUDIO_INVALID_USE ); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | bool result; |
| 383 | |
| 384 | if ( oChannels > 0 ) { |
| 385 | |
| 386 | result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel, |
| 387 | sampleRate, format, bufferFrames, options ); |
| 388 | if ( result == false ) { |
| 389 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | if ( iChannels > 0 ) { |
| 394 | |
| 395 | result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel, |
| 396 | sampleRate, format, bufferFrames, options ); |
| 397 | if ( result == false ) { |
| 398 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | stream_.callbackInfo.callback = (void *) callback; |
| 403 | stream_.callbackInfo.userData = userData; |
| 404 | |
| 405 | if ( options ) options->numberOfBuffers = stream_.nBuffers; |
| 406 | stream_.state = STREAM_STOPPED; |
| 407 | return RTAUDIO_NO_ERROR; |
| 408 | } |
| 409 | |
| 410 | unsigned int RtApi :: getDefaultInputDevice( void ) |
| 411 | { |
| 412 | // Should be reimplemented in subclasses if necessary. |
| 413 | unsigned int nDevices = getDeviceCount(); |
| 414 | for ( unsigned int i = 0; i < nDevices; i++ ) { |
| 415 | if ( getDeviceInfo( i ).isDefaultInput ) { |
| 416 | return i; |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | return 0; |
| 421 | } |
| 422 | |
| 423 | unsigned int RtApi :: getDefaultOutputDevice( void ) |
| 424 | { |
| 425 | // Should be reimplemented in subclasses if necessary. |
| 426 | unsigned int nDevices = getDeviceCount(); |
| 427 | for ( unsigned int i = 0; i < nDevices; i++ ) { |
| 428 | if ( getDeviceInfo( i ).isDefaultOutput ) { |
| 429 | return i; |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | return 0; |
| 434 | } |
| 435 | |
| 436 | void RtApi :: closeStream( void ) |
| 437 | { |
| 438 | // MUST be implemented in subclasses! |
| 439 | return; |
| 440 | } |
| 441 | |
| 442 | bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/, |
| 443 | unsigned int /*firstChannel*/, unsigned int /*sampleRate*/, |
| 444 | RtAudioFormat /*format*/, unsigned int * /*bufferSize*/, |
| 445 | RtAudio::StreamOptions * /*options*/ ) |
| 446 | { |
| 447 | // MUST be implemented in subclasses! |
| 448 | return FAILURE; |
| 449 | } |
| 450 | |
| 451 | void RtApi :: tickStreamTime( void ) |
| 452 | { |
| 453 | // Subclasses that do not provide their own implementation of |
| 454 | // getStreamTime should call this function once per buffer I/O to |
| 455 | // provide basic stream time support. |
| 456 | |
| 457 | stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate ); |
| 458 | |
| 459 | /* |
| 460 | #if defined( HAVE_GETTIMEOFDAY ) |
| 461 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 462 | #endif |
| 463 | */ |
| 464 | } |
| 465 | |
| 466 | long RtApi :: getStreamLatency( void ) |
| 467 | { |
| 468 | long totalLatency = 0; |
| 469 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) |
| 470 | totalLatency = stream_.latency[0]; |
| 471 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) |
| 472 | totalLatency += stream_.latency[1]; |
| 473 | |
| 474 | return totalLatency; |
| 475 | } |
| 476 | |
| 477 | /* |
| 478 | double RtApi :: getStreamTime( void ) |
| 479 | { |
| 480 | #if defined( HAVE_GETTIMEOFDAY ) |
| 481 | // Return a very accurate estimate of the stream time by |
| 482 | // adding in the elapsed time since the last tick. |
| 483 | struct timeval then; |
| 484 | struct timeval now; |
| 485 | |
| 486 | if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 ) |
| 487 | return stream_.streamTime; |
| 488 | |
| 489 | gettimeofday( &now, NULL ); |
| 490 | then = stream_.lastTickTimestamp; |
| 491 | return stream_.streamTime + |
| 492 | ((now.tv_sec + 0.000001 * now.tv_usec) - |
| 493 | (then.tv_sec + 0.000001 * then.tv_usec)); |
| 494 | #else |
| 495 | return stream_.streamTime; |
| 496 | #endif |
| 497 | } |
| 498 | */ |
| 499 | |
| 500 | void RtApi :: setStreamTime( double time ) |
| 501 | { |
| 502 | if ( time >= 0.0 ) |
| 503 | stream_.streamTime = time; |
| 504 | /* |
| 505 | #if defined( HAVE_GETTIMEOFDAY ) |
| 506 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 507 | #endif |
| 508 | */ |
| 509 | } |
| 510 | |
| 511 | unsigned int RtApi :: getStreamSampleRate( void ) |
| 512 | { |
| 513 | if ( isStreamOpen() ) return stream_.sampleRate; |
| 514 | else return 0; |
| 515 | } |
| 516 | |
| 517 | |
| 518 | // *************************************************** // |
| 519 | // |
| 520 | // OS/API-specific methods. |
| 521 | // |
| 522 | // *************************************************** // |
| 523 | |
| 524 | #if defined(__MACOSX_CORE__) |
| 525 | |
| 526 | #include <unistd.h> |
| 527 | |
| 528 | // The OS X CoreAudio API is designed to use a separate callback |
| 529 | // procedure for each of its audio devices. A single RtAudio duplex |
| 530 | // stream using two different devices is supported here, though it |
| 531 | // cannot be guaranteed to always behave correctly because we cannot |
| 532 | // synchronize these two callbacks. |
| 533 | // |
| 534 | // A property listener is installed for over/underrun information. |
| 535 | // However, no functionality is currently provided to allow property |
| 536 | // listeners to trigger user handlers because it is unclear what could |
| 537 | // be done if a critical stream parameter (buffer size, sample rate, |
| 538 | // device disconnect) notification arrived. The listeners entail |
| 539 | // quite a bit of extra code and most likely, a user program wouldn't |
| 540 | // be prepared for the result anyway. However, we do provide a flag |
| 541 | // to the client callback function to inform of an over/underrun. |
| 542 | |
| 543 | // A structure to hold various information related to the CoreAudio API |
| 544 | // implementation. |
| 545 | struct CoreHandle { |
| 546 | AudioDeviceID id[2]; // device ids |
| 547 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 548 | AudioDeviceIOProcID procId[2]; |
| 549 | #endif |
| 550 | UInt32 iStream[2]; // device stream index (or first if using multiple) |
| 551 | UInt32 nStreams[2]; // number of streams to use |
| 552 | bool xrun[2]; |
| 553 | char *deviceBuffer; |
| 554 | pthread_cond_t condition; |
| 555 | int drainCounter; // Tracks callback counts when draining |
| 556 | bool internalDrain; // Indicates if stop is initiated from callback or not. |
| 557 | bool xrunListenerAdded[2]; |
| 558 | bool disconnectListenerAdded[2]; |
| 559 | |
| 560 | CoreHandle() |
| 561 | :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; procId[0] = 0; procId[1] = 0; xrun[0] = false; xrun[1] = false; xrunListenerAdded[0] = false; xrunListenerAdded[1] = false; disconnectListenerAdded[0] = false; disconnectListenerAdded[1] = false; } |
| 562 | }; |
| 563 | |
| 564 | // kAudioObjectPropertyElementMaster (deprecated as of macOS 12) |
| 565 | // renamed to kAudioObjectPropertyElementMain | chuck-1.5.1.1 |
| 566 | #if __MAC_OS_X_VERSION_MIN_REQUIRED < 120000 // before macOS 12 |
| 567 | #define kAudioObjectPropertyElementMain kAudioObjectPropertyElementMaster |
| 568 | #endif |
| 569 | |
| 570 | RtApiCore:: RtApiCore() |
| 571 | { |
| 572 | #if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER ) |
| 573 | // This is a largely undocumented but absolutely necessary |
| 574 | // requirement starting with OS-X 10.6. If not called, queries and |
| 575 | // updates to various audio device properties are not handled |
| 576 | // correctly. |
| 577 | CFRunLoopRef theRunLoop = NULL; |
| 578 | AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop, |
| 579 | kAudioObjectPropertyScopeGlobal, |
| 580 | kAudioObjectPropertyElementMain }; |
| 581 | OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop); |
| 582 | if ( result != noErr ) { |
| 583 | errorText_ = "RtApiCore::RtApiCore: error setting run loop property!"; |
| 584 | error( RTAUDIO_SYSTEM_ERROR ); |
| 585 | } |
| 586 | #endif |
| 587 | } |
| 588 | |
| 589 | RtApiCore :: ~RtApiCore() |
| 590 | { |
| 591 | // The subclass destructor gets called before the base class |
| 592 | // destructor, so close an existing stream before deallocating |
| 593 | // apiDeviceId memory. |
| 594 | if ( stream_.state != STREAM_CLOSED ) closeStream(); |
| 595 | } |
| 596 | |
| 597 | unsigned int RtApiCore :: getDeviceCount( void ) |
| 598 | { |
| 599 | // Find out how many audio devices there are, if any. |
| 600 | UInt32 dataSize; |
| 601 | AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; |
| 602 | OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize ); |
| 603 | if ( result != noErr ) { |
| 604 | errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!"; |
| 605 | error( RTAUDIO_SYSTEM_ERROR ); |
| 606 | return 0; |
| 607 | } |
| 608 | |
| 609 | return dataSize / sizeof( AudioDeviceID ); |
| 610 | } |
| 611 | |
| 612 | unsigned int RtApiCore :: getDefaultInputDevice( void ) |
| 613 | { |
| 614 | unsigned int nDevices = getDeviceCount(); |
| 615 | if ( nDevices <= 1 ) return 0; |
| 616 | |
| 617 | AudioDeviceID id; |
| 618 | UInt32 dataSize = sizeof( AudioDeviceID ); |
| 619 | AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; |
| 620 | OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id ); |
| 621 | if ( result != noErr ) { |
| 622 | errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device."; |
| 623 | error( RTAUDIO_SYSTEM_ERROR ); |
| 624 | return 0; |
| 625 | } |
| 626 | |
| 627 | dataSize *= nDevices; |
| 628 | AudioDeviceID deviceList[ nDevices ]; |
| 629 | property.mSelector = kAudioHardwarePropertyDevices; |
| 630 | result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList ); |
| 631 | if ( result != noErr ) { |
| 632 | errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs."; |
| 633 | error( RTAUDIO_SYSTEM_ERROR ); |
| 634 | return 0; |
| 635 | } |
| 636 | |
| 637 | for ( unsigned int i=0; i<nDevices; i++ ) |
| 638 | if ( id == deviceList[i] ) return i; |
| 639 | |
| 640 | errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!"; |
| 641 | error( RTAUDIO_WARNING ); |
| 642 | return 0; |
| 643 | } |
| 644 | |
| 645 | unsigned int RtApiCore :: getDefaultOutputDevice( void ) |
| 646 | { |
| 647 | unsigned int nDevices = getDeviceCount(); |
| 648 | if ( nDevices <= 1 ) return 0; |
| 649 | |
| 650 | AudioDeviceID id; |
| 651 | UInt32 dataSize = sizeof( AudioDeviceID ); |
| 652 | AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; |
| 653 | OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id ); |
| 654 | if ( result != noErr ) { |
| 655 | errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device."; |
| 656 | error( RTAUDIO_SYSTEM_ERROR ); |
| 657 | return 0; |
| 658 | } |
| 659 | |
| 660 | dataSize = sizeof( AudioDeviceID ) * nDevices; |
| 661 | AudioDeviceID deviceList[ nDevices ]; |
| 662 | property.mSelector = kAudioHardwarePropertyDevices; |
| 663 | result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList ); |
| 664 | if ( result != noErr ) { |
| 665 | errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs."; |
| 666 | error( RTAUDIO_SYSTEM_ERROR ); |
| 667 | return 0; |
| 668 | } |
| 669 | |
| 670 | for ( unsigned int i=0; i<nDevices; i++ ) |
| 671 | if ( id == deviceList[i] ) return i; |
| 672 | |
| 673 | errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!"; |
| 674 | error( RTAUDIO_WARNING ); |
| 675 | return 0; |
| 676 | } |
| 677 | |
| 678 | RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device ) |
| 679 | { |
| 680 | RtAudio::DeviceInfo info; |
| 681 | info.probed = false; |
| 682 | |
| 683 | // Get device ID |
| 684 | unsigned int nDevices = getDeviceCount(); |
| 685 | if ( nDevices == 0 ) { |
| 686 | errorText_ = "RtApiCore::getDeviceInfo: no devices found!"; |
| 687 | error( RTAUDIO_INVALID_USE ); |
| 688 | return info; |
| 689 | } |
| 690 | |
| 691 | if ( device >= nDevices ) { |
| 692 | errorText_ = "RtApiCore::getDeviceInfo: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 693 | error( RTAUDIO_INVALID_USE ); |
| 694 | return info; |
| 695 | } |
| 696 | |
| 697 | AudioDeviceID deviceList[ nDevices ]; |
| 698 | UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices; |
| 699 | AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices, |
| 700 | kAudioObjectPropertyScopeGlobal, |
| 701 | kAudioObjectPropertyElementMain }; |
| 702 | OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, |
| 703 | 0, NULL, &dataSize, (void *) &deviceList ); |
| 704 | if ( result != noErr ) { |
| 705 | errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs."; |
| 706 | error( RTAUDIO_WARNING ); |
| 707 | return info; |
| 708 | } |
| 709 | |
| 710 | AudioDeviceID id = deviceList[ device ]; |
| 711 | |
| 712 | // Get the device name. |
| 713 | info.name.erase(); |
| 714 | CFStringRef cfname; |
| 715 | dataSize = sizeof( CFStringRef ); |
| 716 | property.mSelector = kAudioObjectPropertyManufacturer; |
| 717 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname ); |
| 718 | if ( result != noErr ) { |
| 719 | errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer."; |
| 720 | errorText_ = errorStream_.str(); |
| 721 | error( RTAUDIO_WARNING ); |
| 722 | return info; |
| 723 | } |
| 724 | |
| 725 | //const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() ); |
| 726 | long length = CFStringGetLength(cfname); |
| 727 | char *mname = (char *)malloc(length * 3 + 1); |
| 728 | #if defined( UNICODE ) || defined( _UNICODE ) |
| 729 | CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8); |
| 730 | #else |
| 731 | CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding()); |
| 732 | #endif |
| 733 | info.name.append( (const char *)mname, strlen(mname) ); |
| 734 | info.name.append( ": " ); |
| 735 | CFRelease( cfname ); |
| 736 | free(mname); |
| 737 | |
| 738 | property.mSelector = kAudioObjectPropertyName; |
| 739 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname ); |
| 740 | if ( result != noErr ) { |
| 741 | errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name."; |
| 742 | errorText_ = errorStream_.str(); |
| 743 | error( RTAUDIO_WARNING ); |
| 744 | return info; |
| 745 | } |
| 746 | |
| 747 | //const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() ); |
| 748 | length = CFStringGetLength(cfname); |
| 749 | char *name = (char *)malloc(length * 3 + 1); |
| 750 | #if defined( UNICODE ) || defined( _UNICODE ) |
| 751 | CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8); |
| 752 | #else |
| 753 | CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding()); |
| 754 | #endif |
| 755 | info.name.append( (const char *)name, strlen(name) ); |
| 756 | CFRelease( cfname ); |
| 757 | free(name); |
| 758 | |
| 759 | // Get the output stream "configuration". |
| 760 | AudioBufferList *bufferList = nil; |
| 761 | property.mSelector = kAudioDevicePropertyStreamConfiguration; |
| 762 | property.mScope = kAudioDevicePropertyScopeOutput; |
| 763 | // property.mElement = kAudioObjectPropertyElementWildcard; |
| 764 | dataSize = 0; |
| 765 | result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize ); |
| 766 | if ( result != noErr || dataSize == 0 ) { |
| 767 | errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ")."; |
| 768 | errorText_ = errorStream_.str(); |
| 769 | error( RTAUDIO_WARNING ); |
| 770 | return info; |
| 771 | } |
| 772 | |
| 773 | // Allocate the AudioBufferList. |
| 774 | bufferList = (AudioBufferList *) malloc( dataSize ); |
| 775 | if ( bufferList == NULL ) { |
| 776 | errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList."; |
| 777 | error( RTAUDIO_WARNING ); |
| 778 | return info; |
| 779 | } |
| 780 | |
| 781 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList ); |
| 782 | if ( result != noErr || dataSize == 0 ) { |
| 783 | free( bufferList ); |
| 784 | errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ")."; |
| 785 | errorText_ = errorStream_.str(); |
| 786 | error( RTAUDIO_WARNING ); |
| 787 | return info; |
| 788 | } |
| 789 | |
| 790 | // Get output channel information. |
| 791 | unsigned int i, nStreams = bufferList->mNumberBuffers; |
| 792 | for ( i=0; i<nStreams; i++ ) |
| 793 | info.outputChannels += bufferList->mBuffers[i].mNumberChannels; |
| 794 | free( bufferList ); |
| 795 | |
| 796 | // Get the input stream "configuration". |
| 797 | property.mScope = kAudioDevicePropertyScopeInput; |
| 798 | result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize ); |
| 799 | if ( result != noErr || dataSize == 0 ) { |
| 800 | errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ")."; |
| 801 | errorText_ = errorStream_.str(); |
| 802 | error( RTAUDIO_WARNING ); |
| 803 | return info; |
| 804 | } |
| 805 | |
| 806 | // Allocate the AudioBufferList. |
| 807 | bufferList = (AudioBufferList *) malloc( dataSize ); |
| 808 | if ( bufferList == NULL ) { |
| 809 | errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList."; |
| 810 | error( RTAUDIO_WARNING ); |
| 811 | return info; |
| 812 | } |
| 813 | |
| 814 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList ); |
| 815 | if (result != noErr || dataSize == 0) { |
| 816 | free( bufferList ); |
| 817 | errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ")."; |
| 818 | errorText_ = errorStream_.str(); |
| 819 | error( RTAUDIO_WARNING ); |
| 820 | return info; |
| 821 | } |
| 822 | |
| 823 | // Get input channel information. |
| 824 | nStreams = bufferList->mNumberBuffers; |
| 825 | for ( i=0; i<nStreams; i++ ) |
| 826 | info.inputChannels += bufferList->mBuffers[i].mNumberChannels; |
| 827 | free( bufferList ); |
| 828 | |
| 829 | // If device opens for both playback and capture, we determine the channels. |
| 830 | if ( info.outputChannels > 0 && info.inputChannels > 0 ) |
| 831 | info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels; |
| 832 | |
| 833 | // Probe the device sample rates. |
| 834 | bool isInput = false; |
| 835 | if ( info.outputChannels == 0 ) isInput = true; |
| 836 | |
| 837 | // Determine the supported sample rates. |
| 838 | property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates; |
| 839 | if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput; |
| 840 | result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize ); |
| 841 | if ( result != kAudioHardwareNoError || dataSize == 0 ) { |
| 842 | errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info."; |
| 843 | errorText_ = errorStream_.str(); |
| 844 | error( RTAUDIO_WARNING ); |
| 845 | return info; |
| 846 | } |
| 847 | |
| 848 | UInt32 nRanges = dataSize / sizeof( AudioValueRange ); |
| 849 | AudioValueRange rangeList[ nRanges ]; |
| 850 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList ); |
| 851 | if ( result != kAudioHardwareNoError ) { |
| 852 | errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates."; |
| 853 | errorText_ = errorStream_.str(); |
| 854 | error( RTAUDIO_WARNING ); |
| 855 | return info; |
| 856 | } |
| 857 | |
| 858 | // The sample rate reporting mechanism is a bit of a mystery. It |
| 859 | // seems that it can either return individual rates or a range of |
| 860 | // rates. I assume that if the min / max range values are the same, |
| 861 | // then that represents a single supported rate and if the min / max |
| 862 | // range values are different, the device supports an arbitrary |
| 863 | // range of values (though there might be multiple ranges, so we'll |
| 864 | // use the most conservative range). |
| 865 | Float64 minimumRate = 1.0, maximumRate = 10000000000.0; |
| 866 | bool haveValueRange = false; |
| 867 | info.sampleRates.clear(); |
| 868 | for ( UInt32 i=0; i<nRanges; i++ ) { |
| 869 | if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) { |
| 870 | unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum; |
| 871 | info.sampleRates.push_back( tmpSr ); |
| 872 | |
| 873 | if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) ) |
| 874 | info.preferredSampleRate = tmpSr; |
| 875 | |
| 876 | } else { |
| 877 | haveValueRange = true; |
| 878 | if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum; |
| 879 | if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum; |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | if ( haveValueRange ) { |
| 884 | for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) { |
| 885 | if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) { |
| 886 | info.sampleRates.push_back( SAMPLE_RATES[k] ); |
| 887 | |
| 888 | if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) ) |
| 889 | info.preferredSampleRate = SAMPLE_RATES[k]; |
| 890 | } |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | // Sort and remove any redundant values |
| 895 | std::sort( info.sampleRates.begin(), info.sampleRates.end() ); |
| 896 | info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() ); |
| 897 | |
| 898 | if ( info.sampleRates.size() == 0 ) { |
| 899 | errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ")."; |
| 900 | errorText_ = errorStream_.str(); |
| 901 | error( RTAUDIO_WARNING ); |
| 902 | return info; |
| 903 | } |
| 904 | |
| 905 | // Probe the currently configured sample rate |
| 906 | Float64 nominalRate; |
| 907 | dataSize = sizeof( Float64 ); |
| 908 | property.mSelector = kAudioDevicePropertyNominalSampleRate; |
| 909 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate ); |
| 910 | if ( result == noErr ) info.currentSampleRate = (unsigned int) nominalRate; |
| 911 | |
| 912 | // CoreAudio always uses 32-bit floating point data for PCM streams. |
| 913 | // Thus, any other "physical" formats supported by the device are of |
| 914 | // no interest to the client. |
| 915 | info.nativeFormats = RTAUDIO_FLOAT32; |
| 916 | |
| 917 | if ( info.outputChannels > 0 ) |
| 918 | if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true; |
| 919 | if ( info.inputChannels > 0 ) |
| 920 | if ( getDefaultInputDevice() == device ) info.isDefaultInput = true; |
| 921 | |
| 922 | info.probed = true; |
| 923 | return info; |
| 924 | } |
| 925 | |
| 926 | static OSStatus callbackHandler( AudioDeviceID inDevice, |
| 927 | const AudioTimeStamp* /*inNow*/, |
| 928 | const AudioBufferList* inInputData, |
| 929 | const AudioTimeStamp* /*inInputTime*/, |
| 930 | AudioBufferList* outOutputData, |
| 931 | const AudioTimeStamp* /*inOutputTime*/, |
| 932 | void* infoPointer ) |
| 933 | { |
| 934 | CallbackInfo *info = (CallbackInfo *) infoPointer; |
| 935 | |
| 936 | RtApiCore *object = (RtApiCore *) info->object; |
| 937 | if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false ) |
| 938 | return kAudioHardwareUnspecifiedError; |
| 939 | else |
| 940 | return kAudioHardwareNoError; |
| 941 | } |
| 942 | |
| 943 | static OSStatus disconnectListener( AudioObjectID /*inDevice*/, |
| 944 | UInt32 nAddresses, |
| 945 | const AudioObjectPropertyAddress properties[], |
| 946 | void* infoPointer ) |
| 947 | { |
| 948 | for ( UInt32 i=0; i<nAddresses; i++ ) { |
| 949 | if ( properties[i].mSelector == kAudioDevicePropertyDeviceIsAlive ) { |
| 950 | CallbackInfo *info = (CallbackInfo *) infoPointer; |
| 951 | RtApiCore *object = (RtApiCore *) info->object; |
| 952 | info->deviceDisconnected = true; |
| 953 | object->closeStream(); |
| 954 | return kAudioHardwareUnspecifiedError; |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | return kAudioHardwareNoError; |
| 959 | } |
| 960 | |
| 961 | static OSStatus xrunListener( AudioObjectID /*inDevice*/, |
| 962 | UInt32 nAddresses, |
| 963 | const AudioObjectPropertyAddress properties[], |
| 964 | void* handlePointer ) |
| 965 | { |
| 966 | CoreHandle *handle = (CoreHandle *) handlePointer; |
| 967 | for ( UInt32 i=0; i<nAddresses; i++ ) { |
| 968 | if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) { |
| 969 | if ( properties[i].mScope == kAudioDevicePropertyScopeInput ) |
| 970 | handle->xrun[1] = true; |
| 971 | else |
| 972 | handle->xrun[0] = true; |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | return kAudioHardwareNoError; |
| 977 | } |
| 978 | |
| 979 | bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, |
| 980 | unsigned int firstChannel, unsigned int sampleRate, |
| 981 | RtAudioFormat format, unsigned int *bufferSize, |
| 982 | RtAudio::StreamOptions *options ) |
| 983 | { |
| 984 | // Get device ID |
| 985 | unsigned int nDevices = getDeviceCount(); |
| 986 | if ( nDevices == 0 ) { |
| 987 | // This should not happen because a check is made before this function is called. |
| 988 | errorText_ = "RtApiCore::probeDeviceOpen: no devices found!"; |
| 989 | return FAILURE; |
| 990 | } |
| 991 | |
| 992 | if ( device >= nDevices ) { |
| 993 | // This should not happen because a check is made before this function is called. |
| 994 | errorText_ = "RtApiCore::probeDeviceOpen: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 995 | return FAILURE; |
| 996 | } |
| 997 | |
| 998 | AudioDeviceID deviceList[ nDevices ]; |
| 999 | UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices; |
| 1000 | AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices, |
| 1001 | kAudioObjectPropertyScopeGlobal, |
| 1002 | kAudioObjectPropertyElementMain }; |
| 1003 | OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, |
| 1004 | 0, NULL, &dataSize, (void *) &deviceList ); |
| 1005 | if ( result != noErr ) { |
| 1006 | errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs."; |
| 1007 | return FAILURE; |
| 1008 | } |
| 1009 | |
| 1010 | AudioDeviceID id = deviceList[ device ]; |
| 1011 | |
| 1012 | // Setup for stream mode. |
| 1013 | bool isInput = false; |
| 1014 | if ( mode == INPUT ) { |
| 1015 | isInput = true; |
| 1016 | property.mScope = kAudioDevicePropertyScopeInput; |
| 1017 | } |
| 1018 | else |
| 1019 | property.mScope = kAudioDevicePropertyScopeOutput; |
| 1020 | |
| 1021 | // Get the stream "configuration". |
| 1022 | AudioBufferList *bufferList = nil; |
| 1023 | dataSize = 0; |
| 1024 | property.mSelector = kAudioDevicePropertyStreamConfiguration; |
| 1025 | result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize ); |
| 1026 | if ( result != noErr || dataSize == 0 ) { |
| 1027 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ")."; |
| 1028 | errorText_ = errorStream_.str(); |
| 1029 | return FAILURE; |
| 1030 | } |
| 1031 | |
| 1032 | // Allocate the AudioBufferList. |
| 1033 | bufferList = (AudioBufferList *) malloc( dataSize ); |
| 1034 | if ( bufferList == NULL ) { |
| 1035 | errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList."; |
| 1036 | return FAILURE; |
| 1037 | } |
| 1038 | |
| 1039 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList ); |
| 1040 | if (result != noErr || dataSize == 0) { |
| 1041 | free( bufferList ); |
| 1042 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ")."; |
| 1043 | errorText_ = errorStream_.str(); |
| 1044 | return FAILURE; |
| 1045 | } |
| 1046 | |
| 1047 | // Search for one or more streams that contain the desired number of |
| 1048 | // channels. CoreAudio devices can have an arbitrary number of |
| 1049 | // streams and each stream can have an arbitrary number of channels. |
| 1050 | // For each stream, a single buffer of interleaved samples is |
| 1051 | // provided. RtAudio prefers the use of one stream of interleaved |
| 1052 | // data or multiple consecutive single-channel streams. However, we |
| 1053 | // now support multiple consecutive multi-channel streams of |
| 1054 | // interleaved data as well. |
| 1055 | UInt32 iStream, offsetCounter = firstChannel; |
| 1056 | UInt32 nStreams = bufferList->mNumberBuffers; |
| 1057 | bool monoMode = false; |
| 1058 | bool foundStream = false; |
| 1059 | |
| 1060 | // First check that the device supports the requested number of |
| 1061 | // channels. |
| 1062 | UInt32 deviceChannels = 0; |
| 1063 | for ( iStream=0; iStream<nStreams; iStream++ ) |
| 1064 | deviceChannels += bufferList->mBuffers[iStream].mNumberChannels; |
| 1065 | |
| 1066 | if ( deviceChannels < ( channels + firstChannel ) ) { |
| 1067 | free( bufferList ); |
| 1068 | errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count."; |
| 1069 | errorText_ = errorStream_.str(); |
| 1070 | return FAILURE; |
| 1071 | } |
| 1072 | |
| 1073 | // Look for a single stream meeting our needs. |
| 1074 | UInt32 firstStream = 0, streamCount = 1, streamChannels = 0, channelOffset = 0; |
| 1075 | for ( iStream=0; iStream<nStreams; iStream++ ) { |
| 1076 | streamChannels = bufferList->mBuffers[iStream].mNumberChannels; |
| 1077 | if ( streamChannels >= channels + offsetCounter ) { |
| 1078 | firstStream = iStream; |
| 1079 | channelOffset = offsetCounter; |
| 1080 | foundStream = true; |
| 1081 | break; |
| 1082 | } |
| 1083 | if ( streamChannels > offsetCounter ) break; |
| 1084 | offsetCounter -= streamChannels; |
| 1085 | } |
| 1086 | |
| 1087 | // If we didn't find a single stream above, then we should be able |
| 1088 | // to meet the channel specification with multiple streams. |
| 1089 | if ( foundStream == false ) { |
| 1090 | monoMode = true; |
| 1091 | offsetCounter = firstChannel; |
| 1092 | for ( iStream=0; iStream<nStreams; iStream++ ) { |
| 1093 | streamChannels = bufferList->mBuffers[iStream].mNumberChannels; |
| 1094 | if ( streamChannels > offsetCounter ) break; |
| 1095 | offsetCounter -= streamChannels; |
| 1096 | } |
| 1097 | |
| 1098 | firstStream = iStream; |
| 1099 | channelOffset = offsetCounter; |
| 1100 | Int32 channelCounter = channels + offsetCounter - streamChannels; |
| 1101 | |
| 1102 | if ( streamChannels > 1 ) monoMode = false; |
| 1103 | while ( channelCounter > 0 ) { |
| 1104 | streamChannels = bufferList->mBuffers[++iStream].mNumberChannels; |
| 1105 | if ( streamChannels > 1 ) monoMode = false; |
| 1106 | channelCounter -= streamChannels; |
| 1107 | streamCount++; |
| 1108 | } |
| 1109 | } |
| 1110 | |
| 1111 | free( bufferList ); |
| 1112 | |
| 1113 | // Determine the buffer size. |
| 1114 | AudioValueRange bufferRange; |
| 1115 | dataSize = sizeof( AudioValueRange ); |
| 1116 | property.mSelector = kAudioDevicePropertyBufferFrameSizeRange; |
| 1117 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange ); |
| 1118 | |
| 1119 | if ( result != noErr ) { |
| 1120 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ")."; |
| 1121 | errorText_ = errorStream_.str(); |
| 1122 | return FAILURE; |
| 1123 | } |
| 1124 | |
| 1125 | if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned int) bufferRange.mMinimum; |
| 1126 | else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned int) bufferRange.mMaximum; |
| 1127 | if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned int) bufferRange.mMinimum; |
| 1128 | |
| 1129 | // Set the buffer size. For multiple streams, I'm assuming we only |
| 1130 | // need to make this setting for the master channel. |
| 1131 | UInt32 theSize = (UInt32) *bufferSize; |
| 1132 | dataSize = sizeof( UInt32 ); |
| 1133 | property.mSelector = kAudioDevicePropertyBufferFrameSize; |
| 1134 | result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize ); |
| 1135 | |
| 1136 | if ( result != noErr ) { |
| 1137 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ")."; |
| 1138 | errorText_ = errorStream_.str(); |
| 1139 | return FAILURE; |
| 1140 | } |
| 1141 | |
| 1142 | // If attempting to setup a duplex stream, the bufferSize parameter |
| 1143 | // MUST be the same in both directions! |
| 1144 | *bufferSize = theSize; |
| 1145 | if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) { |
| 1146 | errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ")."; |
| 1147 | errorText_ = errorStream_.str(); |
| 1148 | return FAILURE; |
| 1149 | } |
| 1150 | |
| 1151 | stream_.bufferSize = *bufferSize; |
| 1152 | stream_.nBuffers = 1; |
| 1153 | |
| 1154 | // Try to set "hog" mode ... it's not clear to me this is working. |
| 1155 | if ( options && options->flags & RTAUDIO_HOG_DEVICE ) { |
| 1156 | pid_t hog_pid; |
| 1157 | dataSize = sizeof( hog_pid ); |
| 1158 | property.mSelector = kAudioDevicePropertyHogMode; |
| 1159 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid ); |
| 1160 | if ( result != noErr ) { |
| 1161 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!"; |
| 1162 | errorText_ = errorStream_.str(); |
| 1163 | return FAILURE; |
| 1164 | } |
| 1165 | |
| 1166 | if ( hog_pid != getpid() ) { |
| 1167 | hog_pid = getpid(); |
| 1168 | result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid ); |
| 1169 | if ( result != noErr ) { |
| 1170 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!"; |
| 1171 | errorText_ = errorStream_.str(); |
| 1172 | return FAILURE; |
| 1173 | } |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | // Check and if necessary, change the sample rate for the device. |
| 1178 | Float64 nominalRate; |
| 1179 | dataSize = sizeof( Float64 ); |
| 1180 | property.mSelector = kAudioDevicePropertyNominalSampleRate; |
| 1181 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate ); |
| 1182 | if ( result != noErr ) { |
| 1183 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate."; |
| 1184 | errorText_ = errorStream_.str(); |
| 1185 | return FAILURE; |
| 1186 | } |
| 1187 | |
| 1188 | // Only try to change the sample rate if off by more than 1 Hz. |
| 1189 | if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) { |
| 1190 | |
| 1191 | nominalRate = (Float64) sampleRate; |
| 1192 | result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate ); |
| 1193 | if ( result != noErr ) { |
| 1194 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ")."; |
| 1195 | errorText_ = errorStream_.str(); |
| 1196 | return FAILURE; |
| 1197 | } |
| 1198 | |
| 1199 | // Now wait until the reported nominal rate is what we just set. |
| 1200 | UInt32 microCounter = 0; |
| 1201 | Float64 reportedRate = 0.0; |
| 1202 | while ( reportedRate != nominalRate ) { |
| 1203 | microCounter += 5000; |
| 1204 | if ( microCounter > 2000000 ) break; |
| 1205 | usleep( 5000 ); |
| 1206 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &reportedRate ); |
| 1207 | } |
| 1208 | |
| 1209 | if ( microCounter > 2000000 ) { |
| 1210 | errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ")."; |
| 1211 | errorText_ = errorStream_.str(); |
| 1212 | return FAILURE; |
| 1213 | } |
| 1214 | } |
| 1215 | |
| 1216 | // Now set the stream format for all streams. Also, check the |
| 1217 | // physical format of the device and change that if necessary. |
| 1218 | AudioStreamBasicDescription description; |
| 1219 | dataSize = sizeof( AudioStreamBasicDescription ); |
| 1220 | property.mSelector = kAudioStreamPropertyVirtualFormat; |
| 1221 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description ); |
| 1222 | if ( result != noErr ) { |
| 1223 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ")."; |
| 1224 | errorText_ = errorStream_.str(); |
| 1225 | return FAILURE; |
| 1226 | } |
| 1227 | |
| 1228 | // Set the sample rate and data format id. However, only make the |
| 1229 | // change if the sample rate is not within 1.0 of the desired |
| 1230 | // rate and the format is not linear pcm. |
| 1231 | bool updateFormat = false; |
| 1232 | if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) { |
| 1233 | description.mSampleRate = (Float64) sampleRate; |
| 1234 | updateFormat = true; |
| 1235 | } |
| 1236 | |
| 1237 | if ( description.mFormatID != kAudioFormatLinearPCM ) { |
| 1238 | description.mFormatID = kAudioFormatLinearPCM; |
| 1239 | updateFormat = true; |
| 1240 | } |
| 1241 | |
| 1242 | if ( updateFormat ) { |
| 1243 | result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description ); |
| 1244 | if ( result != noErr ) { |
| 1245 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ")."; |
| 1246 | errorText_ = errorStream_.str(); |
| 1247 | return FAILURE; |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | // Now check the physical format. |
| 1252 | property.mSelector = kAudioStreamPropertyPhysicalFormat; |
| 1253 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description ); |
| 1254 | if ( result != noErr ) { |
| 1255 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ")."; |
| 1256 | errorText_ = errorStream_.str(); |
| 1257 | return FAILURE; |
| 1258 | } |
| 1259 | |
| 1260 | //std::cout << "Current physical stream format:" << std::endl; |
| 1261 | //std::cout << " mBitsPerChan = " << description.mBitsPerChannel << std::endl; |
| 1262 | //std::cout << " aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl; |
| 1263 | //std::cout << " bytesPerFrame = " << description.mBytesPerFrame << std::endl; |
| 1264 | //std::cout << " sample rate = " << description.mSampleRate << std::endl; |
| 1265 | |
| 1266 | if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) { |
| 1267 | description.mFormatID = kAudioFormatLinearPCM; |
| 1268 | //description.mSampleRate = (Float64) sampleRate; |
| 1269 | AudioStreamBasicDescription testDescription = description; |
| 1270 | UInt32 formatFlags; |
| 1271 | |
| 1272 | // We'll try higher bit rates first and then work our way down. |
| 1273 | std::vector< std::pair<UInt32, UInt32> > physicalFormats; |
| 1274 | formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger; |
| 1275 | physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) ); |
| 1276 | formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat; |
| 1277 | physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) ); |
| 1278 | physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) ); // 24-bit packed |
| 1279 | formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh ); |
| 1280 | physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low |
| 1281 | formatFlags |= kAudioFormatFlagIsAlignedHigh; |
| 1282 | physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high |
| 1283 | formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat; |
| 1284 | physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) ); |
| 1285 | physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) ); |
| 1286 | |
| 1287 | bool setPhysicalFormat = false; |
| 1288 | for( unsigned int i=0; i<physicalFormats.size(); i++ ) { |
| 1289 | testDescription = description; |
| 1290 | testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first; |
| 1291 | testDescription.mFormatFlags = physicalFormats[i].second; |
| 1292 | if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) ) |
| 1293 | testDescription.mBytesPerFrame = 4 * testDescription.mChannelsPerFrame; |
| 1294 | else |
| 1295 | testDescription.mBytesPerFrame = testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame; |
| 1296 | testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket; |
| 1297 | result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription ); |
| 1298 | if ( result == noErr ) { |
| 1299 | setPhysicalFormat = true; |
| 1300 | //std::cout << "Updated physical stream format:" << std::endl; |
| 1301 | //std::cout << " mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl; |
| 1302 | //std::cout << " aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl; |
| 1303 | //std::cout << " bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl; |
| 1304 | //std::cout << " sample rate = " << testDescription.mSampleRate << std::endl; |
| 1305 | break; |
| 1306 | } |
| 1307 | } |
| 1308 | |
| 1309 | if ( !setPhysicalFormat ) { |
| 1310 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ")."; |
| 1311 | errorText_ = errorStream_.str(); |
| 1312 | return FAILURE; |
| 1313 | } |
| 1314 | } // done setting virtual/physical formats. |
| 1315 | |
| 1316 | // Get the stream / device latency. |
| 1317 | UInt32 latency; |
| 1318 | dataSize = sizeof( UInt32 ); |
| 1319 | property.mSelector = kAudioDevicePropertyLatency; |
| 1320 | if ( AudioObjectHasProperty( id, &property ) == true ) { |
| 1321 | result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency ); |
| 1322 | if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency; |
| 1323 | else { |
| 1324 | errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ")."; |
| 1325 | errorText_ = errorStream_.str(); |
| 1326 | error( RTAUDIO_WARNING ); |
| 1327 | } |
| 1328 | } |
| 1329 | |
| 1330 | // Byte-swapping: According to AudioHardware.h, the stream data will |
| 1331 | // always be presented in native-endian format, so we should never |
| 1332 | // need to byte swap. |
| 1333 | stream_.doByteSwap[mode] = false; |
| 1334 | |
| 1335 | // From the CoreAudio documentation, PCM data must be supplied as |
| 1336 | // 32-bit floats. |
| 1337 | stream_.userFormat = format; |
| 1338 | stream_.deviceFormat[mode] = RTAUDIO_FLOAT32; |
| 1339 | |
| 1340 | if ( streamCount == 1 ) |
| 1341 | stream_.nDeviceChannels[mode] = description.mChannelsPerFrame; |
| 1342 | else // multiple streams |
| 1343 | stream_.nDeviceChannels[mode] = channels; |
| 1344 | stream_.nUserChannels[mode] = channels; |
| 1345 | stream_.channelOffset[mode] = channelOffset; // offset within a CoreAudio stream |
| 1346 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false; |
| 1347 | else stream_.userInterleaved = true; |
| 1348 | stream_.deviceInterleaved[mode] = true; |
| 1349 | if ( monoMode == true ) stream_.deviceInterleaved[mode] = false; |
| 1350 | |
| 1351 | // Set flags for buffer conversion. |
| 1352 | stream_.doConvertBuffer[mode] = false; |
| 1353 | if ( stream_.userFormat != stream_.deviceFormat[mode] ) |
| 1354 | stream_.doConvertBuffer[mode] = true; |
| 1355 | if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] ) |
| 1356 | stream_.doConvertBuffer[mode] = true; |
| 1357 | if ( streamCount == 1 ) { |
| 1358 | if ( stream_.nUserChannels[mode] > 1 && |
| 1359 | stream_.userInterleaved != stream_.deviceInterleaved[mode] ) |
| 1360 | stream_.doConvertBuffer[mode] = true; |
| 1361 | } |
| 1362 | else if ( monoMode && stream_.userInterleaved ) |
| 1363 | stream_.doConvertBuffer[mode] = true; |
| 1364 | |
| 1365 | // Allocate our CoreHandle structure for the stream. |
| 1366 | CoreHandle *handle = 0; |
| 1367 | if ( stream_.apiHandle == 0 ) { |
| 1368 | try { |
| 1369 | handle = new CoreHandle; |
| 1370 | } |
| 1371 | catch ( std::bad_alloc& ) { |
| 1372 | errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory."; |
| 1373 | goto error; |
| 1374 | } |
| 1375 | |
| 1376 | if ( pthread_cond_init( &handle->condition, NULL ) ) { |
| 1377 | errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable."; |
| 1378 | goto error; |
| 1379 | } |
| 1380 | stream_.apiHandle = (void *) handle; |
| 1381 | } |
| 1382 | else |
| 1383 | handle = (CoreHandle *) stream_.apiHandle; |
| 1384 | handle->iStream[mode] = firstStream; |
| 1385 | handle->nStreams[mode] = streamCount; |
| 1386 | handle->id[mode] = id; |
| 1387 | |
| 1388 | // Allocate necessary internal buffers. |
| 1389 | unsigned long bufferBytes; |
| 1390 | bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat ); |
| 1391 | stream_.userBuffer[mode] = (char *) malloc( bufferBytes * sizeof(char) ); |
| 1392 | if ( stream_.userBuffer[mode] == NULL ) { |
| 1393 | errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory."; |
| 1394 | goto error; |
| 1395 | } |
| 1396 | |
| 1397 | // If possible, we will make use of the CoreAudio stream buffers as |
| 1398 | // "device buffers". However, we can't do this if using multiple |
| 1399 | // streams. |
| 1400 | if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) { |
| 1401 | |
| 1402 | bool makeBuffer = true; |
| 1403 | bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] ); |
| 1404 | if ( mode == INPUT ) { |
| 1405 | if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) { |
| 1406 | unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] ); |
| 1407 | if ( bufferBytes <= bytesOut ) makeBuffer = false; |
| 1408 | } |
| 1409 | } |
| 1410 | |
| 1411 | if ( makeBuffer ) { |
| 1412 | bufferBytes *= *bufferSize; |
| 1413 | if ( stream_.deviceBuffer ) free( stream_.deviceBuffer ); |
| 1414 | stream_.deviceBuffer = (char *) calloc( bufferBytes, sizeof(char) ); |
| 1415 | if ( stream_.deviceBuffer == NULL ) { |
| 1416 | errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory."; |
| 1417 | goto error; |
| 1418 | } |
| 1419 | } |
| 1420 | } |
| 1421 | |
| 1422 | stream_.sampleRate = sampleRate; |
| 1423 | stream_.device[mode] = device; |
| 1424 | stream_.state = STREAM_STOPPED; |
| 1425 | stream_.callbackInfo.object = (void *) this; |
| 1426 | |
| 1427 | // Setup the buffer conversion information structure. |
| 1428 | if ( stream_.doConvertBuffer[mode] ) { |
| 1429 | if ( streamCount > 1 ) setConvertInfo( mode, 0 ); |
| 1430 | else setConvertInfo( mode, channelOffset ); |
| 1431 | } |
| 1432 | |
| 1433 | if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device ) |
| 1434 | // Only one callback procedure and property listener per device. |
| 1435 | stream_.mode = DUPLEX; |
| 1436 | else { |
| 1437 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 1438 | result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] ); |
| 1439 | #else |
| 1440 | // deprecated in favor of AudioDeviceCreateIOProcID() |
| 1441 | result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo ); |
| 1442 | #endif |
| 1443 | if ( result != noErr ) { |
| 1444 | errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ")."; |
| 1445 | errorText_ = errorStream_.str(); |
| 1446 | goto error; |
| 1447 | } |
| 1448 | if ( stream_.mode == OUTPUT && mode == INPUT ) |
| 1449 | stream_.mode = DUPLEX; |
| 1450 | else |
| 1451 | stream_.mode = mode; |
| 1452 | |
| 1453 | // Setup the device property listener for over/underload. |
| 1454 | property.mSelector = kAudioDeviceProcessorOverload; |
| 1455 | property.mScope = kAudioObjectPropertyScopeGlobal; |
| 1456 | result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle ); |
| 1457 | if ( result != noErr ) { |
| 1458 | errorStream_ << "RtApiCore::probeDeviceOpen: system error setting xrun listener for device (" << device << ")."; |
| 1459 | errorText_ = errorStream_.str(); |
| 1460 | goto error; |
| 1461 | } |
| 1462 | handle->xrunListenerAdded[mode] = true; |
| 1463 | |
| 1464 | // Setup a listener to detect a possible device disconnect. |
| 1465 | property.mSelector = kAudioDevicePropertyDeviceIsAlive; |
| 1466 | result = AudioObjectAddPropertyListener( id , &property, disconnectListener, (void *) &stream_.callbackInfo ); |
| 1467 | if ( result != noErr ) { |
| 1468 | AudioObjectRemovePropertyListener( id, &property, xrunListener, (void *) handle ); |
| 1469 | errorStream_ << "RtApiCore::probeDeviceOpen: system error setting disconnect listener for device (" << device << ")."; |
| 1470 | errorText_ = errorStream_.str(); |
| 1471 | goto error; |
| 1472 | } |
| 1473 | handle->disconnectListenerAdded[mode] = true; |
| 1474 | } |
| 1475 | |
| 1476 | return SUCCESS; |
| 1477 | |
| 1478 | error: |
| 1479 | closeStream(); // this should safely clear out procedures, listeners and memory, even for duplex stream |
| 1480 | return FAILURE; |
| 1481 | } |
| 1482 | |
| 1483 | void RtApiCore :: closeStream( void ) |
| 1484 | { |
| 1485 | if ( stream_.state == STREAM_CLOSED ) { |
| 1486 | errorText_ = "RtApiCore::closeStream(): no open stream to close!"; |
| 1487 | error( RTAUDIO_WARNING ); |
| 1488 | return; |
| 1489 | } |
| 1490 | |
| 1491 | CoreHandle *handle = (CoreHandle *) stream_.apiHandle; |
| 1492 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 1493 | if ( handle ) { |
| 1494 | AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices, |
| 1495 | kAudioObjectPropertyScopeGlobal, |
| 1496 | kAudioObjectPropertyElementMain }; |
| 1497 | |
| 1498 | if ( handle->xrunListenerAdded[0] ) { |
| 1499 | property.mSelector = kAudioDeviceProcessorOverload; |
| 1500 | if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) { |
| 1501 | errorText_ = "RtApiCore::closeStream(): error removing xrun property listener!"; |
| 1502 | error( RTAUDIO_WARNING ); |
| 1503 | } |
| 1504 | } |
| 1505 | if ( handle->disconnectListenerAdded[0] ) { |
| 1506 | property.mSelector = kAudioDevicePropertyDeviceIsAlive; |
| 1507 | if (AudioObjectRemovePropertyListener( handle->id[0], &property, disconnectListener, (void *) &stream_.callbackInfo ) != noErr) { |
| 1508 | errorText_ = "RtApiCore::closeStream(): error removing disconnect property listener!"; |
| 1509 | error( RTAUDIO_WARNING ); |
| 1510 | } |
| 1511 | } |
| 1512 | |
| 1513 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 1514 | if ( handle->procId[0] ) { |
| 1515 | if ( stream_.state == STREAM_RUNNING ) |
| 1516 | AudioDeviceStop( handle->id[0], handle->procId[0] ); |
| 1517 | AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] ); |
| 1518 | } |
| 1519 | #else // deprecated behaviour |
| 1520 | if ( stream_.state == STREAM_RUNNING ) |
| 1521 | AudioDeviceStop( handle->id[0], callbackHandler ); |
| 1522 | AudioDeviceRemoveIOProc( handle->id[0], callbackHandler ); |
| 1523 | #endif |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) { |
| 1528 | if ( handle ) { |
| 1529 | AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices, |
| 1530 | kAudioObjectPropertyScopeGlobal, |
| 1531 | kAudioObjectPropertyElementMain }; |
| 1532 | |
| 1533 | if ( handle->xrunListenerAdded[1] ) { |
| 1534 | property.mSelector = kAudioDeviceProcessorOverload; |
| 1535 | if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) { |
| 1536 | errorText_ = "RtApiCore::closeStream(): error removing xrun property listener!"; |
| 1537 | error( RTAUDIO_WARNING ); |
| 1538 | } |
| 1539 | } |
| 1540 | |
| 1541 | if ( handle->disconnectListenerAdded[0] ) { |
| 1542 | property.mSelector = kAudioDevicePropertyDeviceIsAlive; |
| 1543 | if (AudioObjectRemovePropertyListener( handle->id[1], &property, disconnectListener, (void *) &stream_.callbackInfo ) != noErr) { |
| 1544 | errorText_ = "RtApiCore::closeStream(): error removing disconnect property listener!"; |
| 1545 | error( RTAUDIO_WARNING ); |
| 1546 | } |
| 1547 | } |
| 1548 | |
| 1549 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 1550 | if ( handle->procId[1] ) { |
| 1551 | if ( stream_.state == STREAM_RUNNING ) |
| 1552 | AudioDeviceStop( handle->id[1], handle->procId[1] ); |
| 1553 | AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] ); |
| 1554 | } |
| 1555 | #else // deprecated behaviour |
| 1556 | if ( stream_.state == STREAM_RUNNING ) |
| 1557 | AudioDeviceStop( handle->id[1], callbackHandler ); |
| 1558 | AudioDeviceRemoveIOProc( handle->id[1], callbackHandler ); |
| 1559 | #endif |
| 1560 | } |
| 1561 | } |
| 1562 | |
| 1563 | for ( int i=0; i<2; i++ ) { |
| 1564 | if ( stream_.userBuffer[i] ) { |
| 1565 | free( stream_.userBuffer[i] ); |
| 1566 | stream_.userBuffer[i] = 0; |
| 1567 | } |
| 1568 | } |
| 1569 | |
| 1570 | if ( stream_.deviceBuffer ) { |
| 1571 | free( stream_.deviceBuffer ); |
| 1572 | stream_.deviceBuffer = 0; |
| 1573 | } |
| 1574 | |
| 1575 | // Destroy pthread condition variable. |
| 1576 | pthread_cond_signal( &handle->condition ); // signal condition variable in case stopStream is blocked |
| 1577 | pthread_cond_destroy( &handle->condition ); |
| 1578 | delete handle; |
| 1579 | stream_.apiHandle = 0; |
| 1580 | |
| 1581 | CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo; |
| 1582 | if ( info->deviceDisconnected ) { |
| 1583 | errorText_ = "RtApiCore: the stream device was disconnected (and closed)!"; |
| 1584 | error( RTAUDIO_DEVICE_DISCONNECT ); |
| 1585 | } |
| 1586 | |
| 1587 | clearStreamInfo(); |
| 1588 | //stream_.mode = UNINITIALIZED; |
| 1589 | //stream_.state = STREAM_CLOSED; |
| 1590 | } |
| 1591 | |
| 1592 | RtAudioErrorType RtApiCore :: startStream( void ) |
| 1593 | { |
| 1594 | if ( stream_.state != STREAM_STOPPED ) { |
| 1595 | if ( stream_.state == STREAM_RUNNING ) |
| 1596 | errorText_ = "RtApiCore::startStream(): the stream is already running!"; |
| 1597 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 1598 | errorText_ = "RtApiCore::startStream(): the stream is stopping or closed!"; |
| 1599 | return error( RTAUDIO_WARNING ); |
| 1600 | } |
| 1601 | |
| 1602 | /* |
| 1603 | #if defined( HAVE_GETTIMEOFDAY ) |
| 1604 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 1605 | #endif |
| 1606 | */ |
| 1607 | |
| 1608 | OSStatus result = noErr; |
| 1609 | CoreHandle *handle = (CoreHandle *) stream_.apiHandle; |
| 1610 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 1611 | |
| 1612 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 1613 | result = AudioDeviceStart( handle->id[0], handle->procId[0] ); |
| 1614 | #else // deprecated behaviour |
| 1615 | result = AudioDeviceStart( handle->id[0], callbackHandler ); |
| 1616 | #endif |
| 1617 | if ( result != noErr ) { |
| 1618 | errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ")."; |
| 1619 | errorText_ = errorStream_.str(); |
| 1620 | goto unlock; |
| 1621 | } |
| 1622 | } |
| 1623 | |
| 1624 | if ( stream_.mode == INPUT || |
| 1625 | ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) { |
| 1626 | |
| 1627 | // Clear user input buffer |
| 1628 | unsigned long bufferBytes; |
| 1629 | bufferBytes = stream_.nUserChannels[1] * stream_.bufferSize * formatBytes( stream_.userFormat ); |
| 1630 | memset( stream_.userBuffer[1], 0, bufferBytes * sizeof(char) ); |
| 1631 | |
| 1632 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 1633 | result = AudioDeviceStart( handle->id[1], handle->procId[1] ); |
| 1634 | #else // deprecated behaviour |
| 1635 | result = AudioDeviceStart( handle->id[1], callbackHandler ); |
| 1636 | #endif |
| 1637 | if ( result != noErr ) { |
| 1638 | errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ")."; |
| 1639 | errorText_ = errorStream_.str(); |
| 1640 | goto unlock; |
| 1641 | } |
| 1642 | } |
| 1643 | |
| 1644 | handle->drainCounter = 0; |
| 1645 | handle->internalDrain = false; |
| 1646 | stream_.state = STREAM_RUNNING; |
| 1647 | |
| 1648 | unlock: |
| 1649 | if ( result == noErr ) return RTAUDIO_NO_ERROR; |
| 1650 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 1651 | } |
| 1652 | |
| 1653 | RtAudioErrorType RtApiCore :: stopStream( void ) |
| 1654 | { |
| 1655 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 1656 | if ( stream_.state == STREAM_STOPPED ) |
| 1657 | errorText_ = "RtApiCore::stopStream(): the stream is already stopped!"; |
| 1658 | else if ( stream_.state == STREAM_CLOSED ) |
| 1659 | errorText_ = "RtApiCore::stopStream(): the stream is closed!"; |
| 1660 | return error( RTAUDIO_WARNING ); |
| 1661 | } |
| 1662 | |
| 1663 | OSStatus result = noErr; |
| 1664 | CoreHandle *handle = (CoreHandle *) stream_.apiHandle; |
| 1665 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 1666 | |
| 1667 | if ( handle->drainCounter == 0 ) { |
| 1668 | handle->drainCounter = 2; |
| 1669 | pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled |
| 1670 | } |
| 1671 | |
| 1672 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 1673 | result = AudioDeviceStop( handle->id[0], handle->procId[0] ); |
| 1674 | #else // deprecated behaviour |
| 1675 | result = AudioDeviceStop( handle->id[0], callbackHandler ); |
| 1676 | #endif |
| 1677 | if ( result != noErr ) { |
| 1678 | errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ")."; |
| 1679 | errorText_ = errorStream_.str(); |
| 1680 | goto unlock; |
| 1681 | } |
| 1682 | } |
| 1683 | |
| 1684 | if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) { |
| 1685 | #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 ) |
| 1686 | result = AudioDeviceStop( handle->id[1], handle->procId[1] ); |
| 1687 | #else // deprecated behaviour |
| 1688 | result = AudioDeviceStop( handle->id[1], callbackHandler ); |
| 1689 | #endif |
| 1690 | if ( result != noErr ) { |
| 1691 | errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ")."; |
| 1692 | errorText_ = errorStream_.str(); |
| 1693 | goto unlock; |
| 1694 | } |
| 1695 | } |
| 1696 | |
| 1697 | stream_.state = STREAM_STOPPED; |
| 1698 | |
| 1699 | unlock: |
| 1700 | if ( result == noErr ) return RTAUDIO_NO_ERROR; |
| 1701 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 1702 | } |
| 1703 | |
| 1704 | RtAudioErrorType RtApiCore :: abortStream( void ) |
| 1705 | { |
| 1706 | if ( stream_.state != STREAM_RUNNING ) { |
| 1707 | if ( stream_.state == STREAM_STOPPED ) |
| 1708 | errorText_ = "RtApiCore::abortStream(): the stream is already stopped!"; |
| 1709 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 1710 | errorText_ = "RtApiCore::abortStream(): the stream is stopping or closed!"; |
| 1711 | return error( RTAUDIO_WARNING ); |
| 1712 | } |
| 1713 | |
| 1714 | CoreHandle *handle = (CoreHandle *) stream_.apiHandle; |
| 1715 | handle->drainCounter = 2; |
| 1716 | |
| 1717 | stream_.state = STREAM_STOPPING; |
| 1718 | return stopStream(); |
| 1719 | } |
| 1720 | |
| 1721 | // This function will be called by a spawned thread when the user |
| 1722 | // callback function signals that the stream should be stopped or |
| 1723 | // aborted. It is better to handle it this way because the |
| 1724 | // callbackEvent() function probably should return before the AudioDeviceStop() |
| 1725 | // function is called. |
| 1726 | static void *coreStopStream( void *ptr ) |
| 1727 | { |
| 1728 | CallbackInfo *info = (CallbackInfo *) ptr; |
| 1729 | RtApiCore *object = (RtApiCore *) info->object; |
| 1730 | |
| 1731 | object->stopStream(); |
| 1732 | pthread_exit( NULL ); |
| 1733 | } |
| 1734 | |
| 1735 | bool RtApiCore :: callbackEvent( AudioDeviceID deviceId, |
| 1736 | const AudioBufferList *inBufferList, |
| 1737 | const AudioBufferList *outBufferList ) |
| 1738 | { |
| 1739 | if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS; |
| 1740 | if ( stream_.state == STREAM_CLOSED ) { |
| 1741 | errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!"; |
| 1742 | error( RTAUDIO_WARNING ); |
| 1743 | return FAILURE; |
| 1744 | } |
| 1745 | |
| 1746 | CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo; |
| 1747 | CoreHandle *handle = (CoreHandle *) stream_.apiHandle; |
| 1748 | |
| 1749 | // Check if we were draining the stream and signal is finished. |
| 1750 | if ( handle->drainCounter > 3 ) { |
| 1751 | ThreadHandle threadId; |
| 1752 | |
| 1753 | stream_.state = STREAM_STOPPING; |
| 1754 | if ( handle->internalDrain == true ) |
| 1755 | pthread_create( &threadId, NULL, coreStopStream, info ); |
| 1756 | else // external call to stopStream() |
| 1757 | pthread_cond_signal( &handle->condition ); |
| 1758 | return SUCCESS; |
| 1759 | } |
| 1760 | |
| 1761 | AudioDeviceID outputDevice = handle->id[0]; |
| 1762 | |
| 1763 | // Invoke user callback to get fresh output data UNLESS we are |
| 1764 | // draining stream or duplex mode AND the input/output devices are |
| 1765 | // different AND this function is called for the input device. |
| 1766 | if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) { |
| 1767 | RtAudioCallback callback = (RtAudioCallback) info->callback; |
| 1768 | double streamTime = getStreamTime(); |
| 1769 | RtAudioStreamStatus status = 0; |
| 1770 | if ( stream_.mode != INPUT && handle->xrun[0] == true ) { |
| 1771 | status |= RTAUDIO_OUTPUT_UNDERFLOW; |
| 1772 | handle->xrun[0] = false; |
| 1773 | } |
| 1774 | if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) { |
| 1775 | status |= RTAUDIO_INPUT_OVERFLOW; |
| 1776 | handle->xrun[1] = false; |
| 1777 | } |
| 1778 | |
| 1779 | int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1], |
| 1780 | stream_.bufferSize, streamTime, status, info->userData ); |
| 1781 | if ( cbReturnValue == 2 ) { |
| 1782 | abortStream(); |
| 1783 | return SUCCESS; |
| 1784 | } |
| 1785 | else if ( cbReturnValue == 1 ) { |
| 1786 | handle->drainCounter = 1; |
| 1787 | handle->internalDrain = true; |
| 1788 | } |
| 1789 | } |
| 1790 | |
| 1791 | if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) { |
| 1792 | |
| 1793 | if ( handle->drainCounter > 1 ) { // write zeros to the output stream |
| 1794 | |
| 1795 | if ( handle->nStreams[0] == 1 ) { |
| 1796 | memset( outBufferList->mBuffers[handle->iStream[0]].mData, |
| 1797 | 0, |
| 1798 | outBufferList->mBuffers[handle->iStream[0]].mDataByteSize ); |
| 1799 | } |
| 1800 | else { // fill multiple streams with zeros |
| 1801 | for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) { |
| 1802 | memset( outBufferList->mBuffers[handle->iStream[0]+i].mData, |
| 1803 | 0, |
| 1804 | outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize ); |
| 1805 | } |
| 1806 | } |
| 1807 | } |
| 1808 | else if ( handle->nStreams[0] == 1 ) { |
| 1809 | if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer |
| 1810 | convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData, |
| 1811 | stream_.userBuffer[0], stream_.convertInfo[0] ); |
| 1812 | } |
| 1813 | else { // copy from user buffer |
| 1814 | memcpy( outBufferList->mBuffers[handle->iStream[0]].mData, |
| 1815 | stream_.userBuffer[0], |
| 1816 | outBufferList->mBuffers[handle->iStream[0]].mDataByteSize ); |
| 1817 | } |
| 1818 | } |
| 1819 | else { // fill multiple streams |
| 1820 | Float32 *inBuffer = (Float32 *) stream_.userBuffer[0]; |
| 1821 | if ( stream_.doConvertBuffer[0] ) { |
| 1822 | convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] ); |
| 1823 | inBuffer = (Float32 *) stream_.deviceBuffer; |
| 1824 | } |
| 1825 | |
| 1826 | if ( stream_.deviceInterleaved[0] == false ) { // mono mode |
| 1827 | UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize; |
| 1828 | for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) { |
| 1829 | memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData, |
| 1830 | (void *)&inBuffer[i*stream_.bufferSize], bufferBytes ); |
| 1831 | } |
| 1832 | } |
| 1833 | else { // fill multiple multi-channel streams with interleaved data |
| 1834 | UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset; |
| 1835 | Float32 *out, *in; |
| 1836 | |
| 1837 | bool inInterleaved = ( stream_.userInterleaved ) ? true : false; |
| 1838 | UInt32 inChannels = stream_.nUserChannels[0]; |
| 1839 | if ( stream_.doConvertBuffer[0] ) { |
| 1840 | inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode |
| 1841 | inChannels = stream_.nDeviceChannels[0]; |
| 1842 | } |
| 1843 | |
| 1844 | if ( inInterleaved ) inOffset = 1; |
| 1845 | else inOffset = stream_.bufferSize; |
| 1846 | |
| 1847 | channelsLeft = inChannels; |
| 1848 | for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) { |
| 1849 | in = inBuffer; |
| 1850 | out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData; |
| 1851 | streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels; |
| 1852 | |
| 1853 | outJump = 0; |
| 1854 | // Account for possible channel offset in first stream |
| 1855 | if ( i == 0 && stream_.channelOffset[0] > 0 ) { |
| 1856 | streamChannels -= stream_.channelOffset[0]; |
| 1857 | outJump = stream_.channelOffset[0]; |
| 1858 | out += outJump; |
| 1859 | } |
| 1860 | |
| 1861 | // Account for possible unfilled channels at end of the last stream |
| 1862 | if ( streamChannels > channelsLeft ) { |
| 1863 | outJump = streamChannels - channelsLeft; |
| 1864 | streamChannels = channelsLeft; |
| 1865 | } |
| 1866 | |
| 1867 | // Determine input buffer offsets and skips |
| 1868 | if ( inInterleaved ) { |
| 1869 | inJump = inChannels; |
| 1870 | in += inChannels - channelsLeft; |
| 1871 | } |
| 1872 | else { |
| 1873 | inJump = 1; |
| 1874 | in += (inChannels - channelsLeft) * inOffset; |
| 1875 | } |
| 1876 | |
| 1877 | for ( unsigned int i=0; i<stream_.bufferSize; i++ ) { |
| 1878 | for ( unsigned int j=0; j<streamChannels; j++ ) { |
| 1879 | *out++ = in[j*inOffset]; |
| 1880 | } |
| 1881 | out += outJump; |
| 1882 | in += inJump; |
| 1883 | } |
| 1884 | channelsLeft -= streamChannels; |
| 1885 | } |
| 1886 | } |
| 1887 | } |
| 1888 | } |
| 1889 | |
| 1890 | // Don't bother draining input |
| 1891 | if ( handle->drainCounter ) { |
| 1892 | handle->drainCounter++; |
| 1893 | goto unlock; |
| 1894 | } |
| 1895 | |
| 1896 | AudioDeviceID inputDevice; |
| 1897 | inputDevice = handle->id[1]; |
| 1898 | if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) { |
| 1899 | |
| 1900 | if ( handle->nStreams[1] == 1 ) { |
| 1901 | if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer |
| 1902 | convertBuffer( stream_.userBuffer[1], |
| 1903 | (char *) inBufferList->mBuffers[handle->iStream[1]].mData, |
| 1904 | stream_.convertInfo[1] ); |
| 1905 | } |
| 1906 | else { // copy to user buffer |
| 1907 | memcpy( stream_.userBuffer[1], |
| 1908 | inBufferList->mBuffers[handle->iStream[1]].mData, |
| 1909 | inBufferList->mBuffers[handle->iStream[1]].mDataByteSize ); |
| 1910 | } |
| 1911 | } |
| 1912 | else { // read from multiple streams |
| 1913 | Float32 *outBuffer = (Float32 *) stream_.userBuffer[1]; |
| 1914 | if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer; |
| 1915 | |
| 1916 | if ( stream_.deviceInterleaved[1] == false ) { // mono mode |
| 1917 | UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize; |
| 1918 | for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) { |
| 1919 | memcpy( (void *)&outBuffer[i*stream_.bufferSize], |
| 1920 | inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes ); |
| 1921 | } |
| 1922 | } |
| 1923 | else { // read from multiple multi-channel streams |
| 1924 | UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset; |
| 1925 | Float32 *out, *in; |
| 1926 | |
| 1927 | bool outInterleaved = ( stream_.userInterleaved ) ? true : false; |
| 1928 | UInt32 outChannels = stream_.nUserChannels[1]; |
| 1929 | if ( stream_.doConvertBuffer[1] ) { |
| 1930 | outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode |
| 1931 | outChannels = stream_.nDeviceChannels[1]; |
| 1932 | } |
| 1933 | |
| 1934 | if ( outInterleaved ) outOffset = 1; |
| 1935 | else outOffset = stream_.bufferSize; |
| 1936 | |
| 1937 | channelsLeft = outChannels; |
| 1938 | for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) { |
| 1939 | out = outBuffer; |
| 1940 | in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData; |
| 1941 | streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels; |
| 1942 | |
| 1943 | inJump = 0; |
| 1944 | // Account for possible channel offset in first stream |
| 1945 | if ( i == 0 && stream_.channelOffset[1] > 0 ) { |
| 1946 | streamChannels -= stream_.channelOffset[1]; |
| 1947 | inJump = stream_.channelOffset[1]; |
| 1948 | in += inJump; |
| 1949 | } |
| 1950 | |
| 1951 | // Account for possible unread channels at end of the last stream |
| 1952 | if ( streamChannels > channelsLeft ) { |
| 1953 | inJump = streamChannels - channelsLeft; |
| 1954 | streamChannels = channelsLeft; |
| 1955 | } |
| 1956 | |
| 1957 | // Determine output buffer offsets and skips |
| 1958 | if ( outInterleaved ) { |
| 1959 | outJump = outChannels; |
| 1960 | out += outChannels - channelsLeft; |
| 1961 | } |
| 1962 | else { |
| 1963 | outJump = 1; |
| 1964 | out += (outChannels - channelsLeft) * outOffset; |
| 1965 | } |
| 1966 | |
| 1967 | for ( unsigned int i=0; i<stream_.bufferSize; i++ ) { |
| 1968 | for ( unsigned int j=0; j<streamChannels; j++ ) { |
| 1969 | out[j*outOffset] = *in++; |
| 1970 | } |
| 1971 | out += outJump; |
| 1972 | in += inJump; |
| 1973 | } |
| 1974 | channelsLeft -= streamChannels; |
| 1975 | } |
| 1976 | } |
| 1977 | |
| 1978 | if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer |
| 1979 | convertBuffer( stream_.userBuffer[1], |
| 1980 | stream_.deviceBuffer, |
| 1981 | stream_.convertInfo[1] ); |
| 1982 | } |
| 1983 | } |
| 1984 | } |
| 1985 | |
| 1986 | unlock: |
| 1987 | |
| 1988 | // Make sure to only tick duplex stream time once if using two devices |
| 1989 | if ( stream_.mode == DUPLEX ) { |
| 1990 | if ( handle->id[0] == handle->id[1] ) // same device, only one callback |
| 1991 | RtApi::tickStreamTime(); |
| 1992 | else if ( deviceId == handle->id[0] ) |
| 1993 | RtApi::tickStreamTime(); // two devices, only tick on the output callback |
| 1994 | } else |
| 1995 | RtApi::tickStreamTime(); // input or output stream only |
| 1996 | |
| 1997 | return SUCCESS; |
| 1998 | } |
| 1999 | |
| 2000 | const char* RtApiCore :: getErrorCode( OSStatus code ) |
| 2001 | { |
| 2002 | switch( code ) { |
| 2003 | |
| 2004 | case kAudioHardwareNotRunningError: |
| 2005 | return "kAudioHardwareNotRunningError"; |
| 2006 | |
| 2007 | case kAudioHardwareUnspecifiedError: |
| 2008 | return "kAudioHardwareUnspecifiedError"; |
| 2009 | |
| 2010 | case kAudioHardwareUnknownPropertyError: |
| 2011 | return "kAudioHardwareUnknownPropertyError"; |
| 2012 | |
| 2013 | case kAudioHardwareBadPropertySizeError: |
| 2014 | return "kAudioHardwareBadPropertySizeError"; |
| 2015 | |
| 2016 | case kAudioHardwareIllegalOperationError: |
| 2017 | return "kAudioHardwareIllegalOperationError"; |
| 2018 | |
| 2019 | case kAudioHardwareBadObjectError: |
| 2020 | return "kAudioHardwareBadObjectError"; |
| 2021 | |
| 2022 | case kAudioHardwareBadDeviceError: |
| 2023 | return "kAudioHardwareBadDeviceError"; |
| 2024 | |
| 2025 | case kAudioHardwareBadStreamError: |
| 2026 | return "kAudioHardwareBadStreamError"; |
| 2027 | |
| 2028 | case kAudioHardwareUnsupportedOperationError: |
| 2029 | return "kAudioHardwareUnsupportedOperationError"; |
| 2030 | |
| 2031 | case kAudioDeviceUnsupportedFormatError: |
| 2032 | return "kAudioDeviceUnsupportedFormatError"; |
| 2033 | |
| 2034 | case kAudioDevicePermissionsError: |
| 2035 | return "kAudioDevicePermissionsError"; |
| 2036 | |
| 2037 | default: |
| 2038 | return "CoreAudio unknown error"; |
| 2039 | } |
| 2040 | } |
| 2041 | |
| 2042 | //******************** End of __MACOSX_CORE__ *********************// |
| 2043 | #endif |
| 2044 | |
| 2045 | #if defined(__UNIX_JACK__) |
| 2046 | |
| 2047 | // JACK is a low-latency audio server, originally written for the |
| 2048 | // GNU/Linux operating system and now also ported to OS-X and |
| 2049 | // Windows. It can connect a number of different applications to an |
| 2050 | // audio device, as well as allowing them to share audio between |
| 2051 | // themselves. |
| 2052 | // |
| 2053 | // When using JACK with RtAudio, "devices" refer to JACK clients that |
| 2054 | // have ports connected to the server. The JACK server is typically |
| 2055 | // started in a terminal as follows: |
| 2056 | // |
| 2057 | // .jackd -d alsa -d hw:0 |
| 2058 | // |
| 2059 | // or through an interface program such as qjackctl. Many of the |
| 2060 | // parameters normally set for a stream are fixed by the JACK server |
| 2061 | // and can be specified when the JACK server is started. In |
| 2062 | // particular, |
| 2063 | // |
| 2064 | // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4 |
| 2065 | // |
| 2066 | // specifies a sample rate of 44100 Hz, a buffer size of 512 sample |
| 2067 | // frames, and number of buffers = 4. Once the server is running, it |
| 2068 | // is not possible to override these values. If the values are not |
| 2069 | // specified in the command-line, the JACK server uses default values. |
| 2070 | // |
| 2071 | // The JACK server does not have to be running when an instance of |
| 2072 | // RtApiJack is created, though the function getDeviceCount() will |
| 2073 | // report 0 devices found until JACK has been started. When no |
| 2074 | // devices are available (i.e., the JACK server is not running), a |
| 2075 | // stream cannot be opened. |
| 2076 | |
| 2077 | #include <jack/jack.h> |
| 2078 | #include <unistd.h> |
| 2079 | #include <cstdio> |
| 2080 | |
| 2081 | // A structure to hold various information related to the Jack API |
| 2082 | // implementation. |
| 2083 | struct JackHandle { |
| 2084 | jack_client_t *client; |
| 2085 | jack_port_t **ports[2]; |
| 2086 | std::string deviceName[2]; |
| 2087 | bool xrun[2]; |
| 2088 | pthread_cond_t condition; |
| 2089 | int drainCounter; // Tracks callback counts when draining |
| 2090 | bool internalDrain; // Indicates if stop is initiated from callback or not. |
| 2091 | |
| 2092 | JackHandle() |
| 2093 | :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; } |
| 2094 | }; |
| 2095 | |
| 2096 | // added 1.5.0.2 (thanks @garyscavone and @gyroplast) |
| 2097 | std::string escapeJackPortRegex(std::string &str) |
| 2098 | { |
| 2099 | const std::string need_escaping = "()[]{}*+?$^.|\\"; |
| 2100 | std::string escaped_string; |
| 2101 | for (auto c : str) |
| 2102 | { |
| 2103 | if (need_escaping.find(c) != std::string::npos) |
| 2104 | escaped_string.push_back('\\'); |
| 2105 | |
| 2106 | escaped_string.push_back(c); |
| 2107 | } |
| 2108 | return escaped_string; |
| 2109 | } |
| 2110 | |
| 2111 | #if !defined(__RTAUDIO_DEBUG__) |
| 2112 | static void jackSilentError( const char * ) {}; |
| 2113 | #endif |
| 2114 | |
| 2115 | RtApiJack :: RtApiJack() |
| 2116 | :shouldAutoconnect_(true) { |
| 2117 | // Nothing to do here. |
| 2118 | #if !defined(__RTAUDIO_DEBUG__) |
| 2119 | // Turn off Jack's internal error reporting. |
| 2120 | jack_set_error_function( &jackSilentError ); |
| 2121 | #endif |
| 2122 | } |
| 2123 | |
| 2124 | RtApiJack :: ~RtApiJack() |
| 2125 | { |
| 2126 | if ( stream_.state != STREAM_CLOSED ) closeStream(); |
| 2127 | } |
| 2128 | |
| 2129 | unsigned int RtApiJack :: getDeviceCount( void ) |
| 2130 | { |
| 2131 | // See if we can become a jack client. |
| 2132 | jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption; |
| 2133 | jack_status_t *status = NULL; |
| 2134 | jack_client_t *client = jack_client_open( "RtApiJackCount", options, status ); |
| 2135 | if ( client == 0 ) return 0; |
| 2136 | |
| 2137 | const char **ports; |
| 2138 | std::string port, previousPort; |
| 2139 | unsigned int nChannels = 0, nDevices = 0; |
| 2140 | ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 ); |
| 2141 | if ( ports ) { |
| 2142 | // Parse the port names up to the first colon (:). |
| 2143 | size_t iColon = 0; |
| 2144 | do { |
| 2145 | port = (char *) ports[ nChannels ]; |
| 2146 | iColon = port.find(":"); |
| 2147 | if ( iColon != std::string::npos ) { |
| 2148 | port = port.substr( 0, iColon + 1 ); |
| 2149 | if ( port != previousPort ) { |
| 2150 | nDevices++; |
| 2151 | previousPort = port; |
| 2152 | } |
| 2153 | } |
| 2154 | } while ( ports[++nChannels] ); |
| 2155 | free( ports ); |
| 2156 | } |
| 2157 | |
| 2158 | jack_client_close( client ); |
| 2159 | return nDevices; |
| 2160 | } |
| 2161 | |
| 2162 | RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device ) |
| 2163 | { |
| 2164 | RtAudio::DeviceInfo info; |
| 2165 | info.probed = false; |
| 2166 | |
| 2167 | jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption |
| 2168 | jack_status_t *status = NULL; |
| 2169 | jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status ); |
| 2170 | if ( client == 0 ) { |
| 2171 | errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!"; |
| 2172 | error( RTAUDIO_WARNING ); |
| 2173 | return info; |
| 2174 | } |
| 2175 | |
| 2176 | const char **ports; |
| 2177 | std::string port, previousPort; |
| 2178 | unsigned int nPorts = 0, nDevices = 0; |
| 2179 | ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 ); |
| 2180 | if ( ports ) { |
| 2181 | // Parse the port names up to the first colon (:). |
| 2182 | size_t iColon = 0; |
| 2183 | do { |
| 2184 | port = (char *) ports[ nPorts ]; |
| 2185 | iColon = port.find(":"); |
| 2186 | if ( iColon != std::string::npos ) { |
| 2187 | port = port.substr( 0, iColon ); |
| 2188 | if ( port != previousPort ) { |
| 2189 | if ( nDevices == device ) info.name = port; |
| 2190 | nDevices++; |
| 2191 | previousPort = port; |
| 2192 | } |
| 2193 | } |
| 2194 | } while ( ports[++nPorts] ); |
| 2195 | free( ports ); |
| 2196 | } |
| 2197 | |
| 2198 | if ( device >= nDevices ) { |
| 2199 | jack_client_close( client ); |
| 2200 | errorText_ = "RtApiJack::getDeviceInfo: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 2201 | error( RTAUDIO_INVALID_USE ); |
| 2202 | return info; |
| 2203 | } |
| 2204 | |
| 2205 | // Get the current jack server sample rate. |
| 2206 | info.sampleRates.clear(); |
| 2207 | |
| 2208 | info.preferredSampleRate = jack_get_sample_rate( client ); |
| 2209 | info.sampleRates.push_back( info.preferredSampleRate ); |
| 2210 | |
| 2211 | // Count the available ports containing the client name as device |
| 2212 | // channels. Jack "input ports" equal RtAudio output channels. |
| 2213 | unsigned int nChannels = 0; |
| 2214 | ports = jack_get_ports( client, escapeJackPortRegex(info.name).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput ); |
| 2215 | if ( ports ) { |
| 2216 | while ( ports[ nChannels ] ) nChannels++; |
| 2217 | free( ports ); |
| 2218 | info.outputChannels = nChannels; |
| 2219 | } |
| 2220 | |
| 2221 | // Jack "output ports" equal RtAudio input channels. |
| 2222 | nChannels = 0; |
| 2223 | ports = jack_get_ports( client, escapeJackPortRegex(info.name).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput ); |
| 2224 | if ( ports ) { |
| 2225 | while ( ports[ nChannels ] ) nChannels++; |
| 2226 | free( ports ); |
| 2227 | info.inputChannels = nChannels; |
| 2228 | } |
| 2229 | |
| 2230 | if ( info.outputChannels == 0 && info.inputChannels == 0 ) { |
| 2231 | jack_client_close(client); |
| 2232 | errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!"; |
| 2233 | error( RTAUDIO_WARNING ); |
| 2234 | return info; |
| 2235 | } |
| 2236 | |
| 2237 | // If device opens for both playback and capture, we determine the channels. |
| 2238 | if ( info.outputChannels > 0 && info.inputChannels > 0 ) |
| 2239 | info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels; |
| 2240 | |
| 2241 | // Jack always uses 32-bit floats. |
| 2242 | info.nativeFormats = RTAUDIO_FLOAT32; |
| 2243 | |
| 2244 | // Jack doesn't provide default devices so we'll use the first available one. |
| 2245 | if ( device == 0 && info.outputChannels > 0 ) |
| 2246 | info.isDefaultOutput = true; |
| 2247 | if ( device == 0 && info.inputChannels > 0 ) |
| 2248 | info.isDefaultInput = true; |
| 2249 | |
| 2250 | jack_client_close(client); |
| 2251 | info.probed = true; |
| 2252 | return info; |
| 2253 | } |
| 2254 | |
| 2255 | static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer ) |
| 2256 | { |
| 2257 | CallbackInfo *info = (CallbackInfo *) infoPointer; |
| 2258 | |
| 2259 | RtApiJack *object = (RtApiJack *) info->object; |
| 2260 | if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1; |
| 2261 | |
| 2262 | return 0; |
| 2263 | } |
| 2264 | |
| 2265 | // This function will be called by a spawned thread when the Jack |
| 2266 | // server signals that it is shutting down. It is necessary to handle |
| 2267 | // it this way because the jackShutdown() function must return before |
| 2268 | // the jack_deactivate() function (in closeStream()) will return. |
| 2269 | static void *jackCloseStream( void *ptr ) |
| 2270 | { |
| 2271 | CallbackInfo *info = (CallbackInfo *) ptr; |
| 2272 | RtApiJack *object = (RtApiJack *) info->object; |
| 2273 | |
| 2274 | info->deviceDisconnected = true; |
| 2275 | object->closeStream(); |
| 2276 | pthread_exit( NULL ); |
| 2277 | } |
| 2278 | |
| 2279 | static void jackShutdown( void *infoPointer ) |
| 2280 | { |
| 2281 | CallbackInfo *info = (CallbackInfo *) infoPointer; |
| 2282 | RtApiJack *object = (RtApiJack *) info->object; |
| 2283 | |
| 2284 | // Check current stream state. If stopped, then we'll assume this |
| 2285 | // was called as a result of a call to RtApiJack::stopStream (the |
| 2286 | // deactivation of a client handle causes this function to be called). |
| 2287 | // If not, we'll assume the Jack server is shutting down or some |
| 2288 | // other problem occurred and we should close the stream. |
| 2289 | if ( object->isStreamRunning() == false ) return; |
| 2290 | |
| 2291 | ThreadHandle threadId; |
| 2292 | pthread_create( &threadId, NULL, jackCloseStream, info ); |
| 2293 | } |
| 2294 | |
| 2295 | static int jackXrun( void *infoPointer ) |
| 2296 | { |
| 2297 | JackHandle *handle = *((JackHandle **) infoPointer); |
| 2298 | |
| 2299 | if ( handle->ports[0] ) handle->xrun[0] = true; |
| 2300 | if ( handle->ports[1] ) handle->xrun[1] = true; |
| 2301 | |
| 2302 | return 0; |
| 2303 | } |
| 2304 | |
| 2305 | bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, |
| 2306 | unsigned int firstChannel, unsigned int sampleRate, |
| 2307 | RtAudioFormat format, unsigned int *bufferSize, |
| 2308 | RtAudio::StreamOptions *options ) |
| 2309 | { |
| 2310 | JackHandle *handle = (JackHandle *) stream_.apiHandle; |
| 2311 | |
| 2312 | // Look for jack server and try to become a client (only do once per stream). |
| 2313 | jack_client_t *client = 0; |
| 2314 | if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) { |
| 2315 | jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption; |
| 2316 | jack_status_t *status = NULL; |
| 2317 | if ( options && !options->streamName.empty() ) |
| 2318 | client = jack_client_open( options->streamName.c_str(), jackoptions, status ); |
| 2319 | else |
| 2320 | client = jack_client_open( "RtApiJack", jackoptions, status ); |
| 2321 | if ( client == 0 ) { |
| 2322 | errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!"; |
| 2323 | error( RTAUDIO_WARNING ); |
| 2324 | return FAILURE; |
| 2325 | } |
| 2326 | } |
| 2327 | else { |
| 2328 | // The handle must have been created on an earlier pass. |
| 2329 | client = handle->client; |
| 2330 | } |
| 2331 | |
| 2332 | const char **ports; |
| 2333 | std::string port, previousPort, deviceName; |
| 2334 | unsigned int nPorts = 0, nDevices = 0; |
| 2335 | ports = jack_get_ports( client, NULL, JACK_DEFAULT_AUDIO_TYPE, 0 ); |
| 2336 | if ( ports ) { |
| 2337 | // Parse the port names up to the first colon (:). |
| 2338 | size_t iColon = 0; |
| 2339 | do { |
| 2340 | port = (char *) ports[ nPorts ]; |
| 2341 | iColon = port.find(":"); |
| 2342 | if ( iColon != std::string::npos ) { |
| 2343 | port = port.substr( 0, iColon ); |
| 2344 | if ( port != previousPort ) { |
| 2345 | if ( nDevices == device ) deviceName = port; |
| 2346 | nDevices++; |
| 2347 | previousPort = port; |
| 2348 | } |
| 2349 | } |
| 2350 | } while ( ports[++nPorts] ); |
| 2351 | free( ports ); |
| 2352 | } |
| 2353 | |
| 2354 | if ( device >= nDevices ) { |
| 2355 | errorText_ = "RtApiJack::probeDeviceOpen: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 2356 | return FAILURE; |
| 2357 | } |
| 2358 | |
| 2359 | unsigned long flag = JackPortIsInput; |
| 2360 | if ( mode == INPUT ) flag = JackPortIsOutput; |
| 2361 | |
| 2362 | if ( ! (options && (options->flags & RTAUDIO_JACK_DONT_CONNECT)) ) { |
| 2363 | // Count the available ports containing the client name as device |
| 2364 | // channels. Jack "input ports" equal RtAudio output channels. |
| 2365 | unsigned int nChannels = 0; |
| 2366 | ports = jack_get_ports( client, escapeJackPortRegex(deviceName).c_str(), JACK_DEFAULT_AUDIO_TYPE, flag ); |
| 2367 | if ( ports ) { |
| 2368 | while ( ports[ nChannels ] ) nChannels++; |
| 2369 | free( ports ); |
| 2370 | } |
| 2371 | // Compare the jack ports for specified client to the requested number of channels. |
| 2372 | if ( nChannels < (channels + firstChannel) ) { |
| 2373 | errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ")."; |
| 2374 | errorText_ = errorStream_.str(); |
| 2375 | return FAILURE; |
| 2376 | } |
| 2377 | } |
| 2378 | |
| 2379 | // Check the jack server sample rate. |
| 2380 | unsigned int jackRate = jack_get_sample_rate( client ); |
| 2381 | if ( sampleRate != jackRate ) { |
| 2382 | jack_client_close( client ); |
| 2383 | errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ")."; |
| 2384 | errorText_ = errorStream_.str(); |
| 2385 | return FAILURE; |
| 2386 | } |
| 2387 | stream_.sampleRate = jackRate; |
| 2388 | |
| 2389 | // Get the latency of the JACK port. |
| 2390 | ports = jack_get_ports( client, escapeJackPortRegex(deviceName).c_str(), JACK_DEFAULT_AUDIO_TYPE, flag ); |
| 2391 | if ( ports[ firstChannel ] ) { |
| 2392 | // Added by Ge Wang |
| 2393 | jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency); |
| 2394 | // the range (usually the min and max are equal) |
| 2395 | jack_latency_range_t latrange; latrange.min = latrange.max = 0; |
| 2396 | // get the latency range |
| 2397 | jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange ); |
| 2398 | // be optimistic, use the min! |
| 2399 | stream_.latency[mode] = latrange.min; |
| 2400 | //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) ); |
| 2401 | } |
| 2402 | free( ports ); |
| 2403 | |
| 2404 | // The jack server always uses 32-bit floating-point data. |
| 2405 | stream_.deviceFormat[mode] = RTAUDIO_FLOAT32; |
| 2406 | stream_.userFormat = format; |
| 2407 | |
| 2408 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false; |
| 2409 | else stream_.userInterleaved = true; |
| 2410 | |
| 2411 | // Jack always uses non-interleaved buffers. |
| 2412 | stream_.deviceInterleaved[mode] = false; |
| 2413 | |
| 2414 | // Jack always provides host byte-ordered data. |
| 2415 | stream_.doByteSwap[mode] = false; |
| 2416 | |
| 2417 | // Get the buffer size. The buffer size and number of buffers |
| 2418 | // (periods) is set when the jack server is started. |
| 2419 | stream_.bufferSize = (int) jack_get_buffer_size( client ); |
| 2420 | *bufferSize = stream_.bufferSize; |
| 2421 | |
| 2422 | stream_.nDeviceChannels[mode] = channels; |
| 2423 | stream_.nUserChannels[mode] = channels; |
| 2424 | |
| 2425 | // Set flags for buffer conversion. |
| 2426 | stream_.doConvertBuffer[mode] = false; |
| 2427 | if ( stream_.userFormat != stream_.deviceFormat[mode] ) |
| 2428 | stream_.doConvertBuffer[mode] = true; |
| 2429 | if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] && |
| 2430 | stream_.nUserChannels[mode] > 1 ) |
| 2431 | stream_.doConvertBuffer[mode] = true; |
| 2432 | |
| 2433 | // Allocate our JackHandle structure for the stream. |
| 2434 | if ( handle == 0 ) { |
| 2435 | try { |
| 2436 | handle = new JackHandle; |
| 2437 | } |
| 2438 | catch ( std::bad_alloc& ) { |
| 2439 | errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory."; |
| 2440 | goto error; |
| 2441 | } |
| 2442 | |
| 2443 | if ( pthread_cond_init(&handle->condition, NULL) ) { |
| 2444 | errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable."; |
| 2445 | goto error; |
| 2446 | } |
| 2447 | stream_.apiHandle = (void *) handle; |
| 2448 | handle->client = client; |
| 2449 | } |
| 2450 | handle->deviceName[mode] = deviceName; |
| 2451 | |
| 2452 | // Allocate necessary internal buffers. |
| 2453 | unsigned long bufferBytes; |
| 2454 | bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat ); |
| 2455 | stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 ); |
| 2456 | if ( stream_.userBuffer[mode] == NULL ) { |
| 2457 | errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory."; |
| 2458 | goto error; |
| 2459 | } |
| 2460 | |
| 2461 | if ( stream_.doConvertBuffer[mode] ) { |
| 2462 | |
| 2463 | bool makeBuffer = true; |
| 2464 | if ( mode == OUTPUT ) |
| 2465 | bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] ); |
| 2466 | else { // mode == INPUT |
| 2467 | bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] ); |
| 2468 | if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) { |
| 2469 | unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]); |
| 2470 | if ( bufferBytes < bytesOut ) makeBuffer = false; |
| 2471 | } |
| 2472 | } |
| 2473 | |
| 2474 | if ( makeBuffer ) { |
| 2475 | bufferBytes *= *bufferSize; |
| 2476 | if ( stream_.deviceBuffer ) free( stream_.deviceBuffer ); |
| 2477 | stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 ); |
| 2478 | if ( stream_.deviceBuffer == NULL ) { |
| 2479 | errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory."; |
| 2480 | goto error; |
| 2481 | } |
| 2482 | } |
| 2483 | } |
| 2484 | |
| 2485 | // Allocate memory for the Jack ports (channels) identifiers. |
| 2486 | handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels ); |
| 2487 | if ( handle->ports[mode] == NULL ) { |
| 2488 | errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory."; |
| 2489 | goto error; |
| 2490 | } |
| 2491 | |
| 2492 | stream_.device[mode] = device; |
| 2493 | stream_.channelOffset[mode] = firstChannel; |
| 2494 | stream_.state = STREAM_STOPPED; |
| 2495 | stream_.callbackInfo.object = (void *) this; |
| 2496 | |
| 2497 | if ( stream_.mode == OUTPUT && mode == INPUT ) |
| 2498 | // We had already set up the stream for output. |
| 2499 | stream_.mode = DUPLEX; |
| 2500 | else { |
| 2501 | stream_.mode = mode; |
| 2502 | jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo ); |
| 2503 | jack_set_xrun_callback( handle->client, jackXrun, (void *) &stream_.apiHandle ); |
| 2504 | jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo ); |
| 2505 | } |
| 2506 | |
| 2507 | // Register our ports. |
| 2508 | char label[64]; |
| 2509 | if ( mode == OUTPUT ) { |
| 2510 | for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) { |
| 2511 | snprintf( label, 64, "outport %d", i ); |
| 2512 | handle->ports[0][i] = jack_port_register( handle->client, (const char *)label, |
| 2513 | JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 ); |
| 2514 | } |
| 2515 | } |
| 2516 | else { |
| 2517 | for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) { |
| 2518 | snprintf( label, 64, "inport %d", i ); |
| 2519 | handle->ports[1][i] = jack_port_register( handle->client, (const char *)label, |
| 2520 | JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 ); |
| 2521 | } |
| 2522 | } |
| 2523 | |
| 2524 | // Setup the buffer conversion information structure. We don't use |
| 2525 | // buffers to do channel offsets, so we override that parameter |
| 2526 | // here. |
| 2527 | if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 ); |
| 2528 | |
| 2529 | if ( options && options->flags & RTAUDIO_JACK_DONT_CONNECT ) shouldAutoconnect_ = false; |
| 2530 | |
| 2531 | return SUCCESS; |
| 2532 | |
| 2533 | error: |
| 2534 | if ( handle ) { |
| 2535 | pthread_cond_destroy( &handle->condition ); |
| 2536 | jack_client_close( handle->client ); |
| 2537 | |
| 2538 | if ( handle->ports[0] ) free( handle->ports[0] ); |
| 2539 | if ( handle->ports[1] ) free( handle->ports[1] ); |
| 2540 | |
| 2541 | delete handle; |
| 2542 | stream_.apiHandle = 0; |
| 2543 | } |
| 2544 | |
| 2545 | for ( int i=0; i<2; i++ ) { |
| 2546 | if ( stream_.userBuffer[i] ) { |
| 2547 | free( stream_.userBuffer[i] ); |
| 2548 | stream_.userBuffer[i] = 0; |
| 2549 | } |
| 2550 | } |
| 2551 | |
| 2552 | if ( stream_.deviceBuffer ) { |
| 2553 | free( stream_.deviceBuffer ); |
| 2554 | stream_.deviceBuffer = 0; |
| 2555 | } |
| 2556 | |
| 2557 | return FAILURE; |
| 2558 | } |
| 2559 | |
| 2560 | void RtApiJack :: closeStream( void ) |
| 2561 | { |
| 2562 | if ( stream_.state == STREAM_CLOSED ) { |
| 2563 | errorText_ = "RtApiJack::closeStream(): no open stream to close!"; |
| 2564 | error( RTAUDIO_WARNING ); |
| 2565 | return; |
| 2566 | } |
| 2567 | |
| 2568 | JackHandle *handle = (JackHandle *) stream_.apiHandle; |
| 2569 | if ( handle ) { |
| 2570 | if ( stream_.state == STREAM_RUNNING ) |
| 2571 | jack_deactivate( handle->client ); |
| 2572 | |
| 2573 | jack_client_close( handle->client ); |
| 2574 | } |
| 2575 | |
| 2576 | if ( handle ) { |
| 2577 | if ( handle->ports[0] ) free( handle->ports[0] ); |
| 2578 | if ( handle->ports[1] ) free( handle->ports[1] ); |
| 2579 | pthread_cond_destroy( &handle->condition ); |
| 2580 | delete handle; |
| 2581 | stream_.apiHandle = 0; |
| 2582 | } |
| 2583 | |
| 2584 | CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo; |
| 2585 | if ( info->deviceDisconnected ) { |
| 2586 | errorText_ = "RtApiJack: the Jack server is shutting down this client ... stream stopped and closed!"; |
| 2587 | error( RTAUDIO_DEVICE_DISCONNECT ); |
| 2588 | } |
| 2589 | |
| 2590 | for ( int i=0; i<2; i++ ) { |
| 2591 | if ( stream_.userBuffer[i] ) { |
| 2592 | free( stream_.userBuffer[i] ); |
| 2593 | stream_.userBuffer[i] = 0; |
| 2594 | } |
| 2595 | } |
| 2596 | |
| 2597 | if ( stream_.deviceBuffer ) { |
| 2598 | free( stream_.deviceBuffer ); |
| 2599 | stream_.deviceBuffer = 0; |
| 2600 | } |
| 2601 | |
| 2602 | clearStreamInfo(); |
| 2603 | //stream_.mode = UNINITIALIZED; |
| 2604 | //stream_.state = STREAM_CLOSED; |
| 2605 | } |
| 2606 | |
| 2607 | RtAudioErrorType RtApiJack :: startStream( void ) |
| 2608 | { |
| 2609 | if ( stream_.state != STREAM_STOPPED ) { |
| 2610 | if ( stream_.state == STREAM_RUNNING ) |
| 2611 | errorText_ = "RtApiJack::startStream(): the stream is already running!"; |
| 2612 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 2613 | errorText_ = "RtApiJack::startStream(): the stream is stopping or closed!"; |
| 2614 | return error( RTAUDIO_WARNING ); |
| 2615 | } |
| 2616 | |
| 2617 | /* |
| 2618 | #if defined( HAVE_GETTIMEOFDAY ) |
| 2619 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 2620 | #endif |
| 2621 | */ |
| 2622 | |
| 2623 | JackHandle *handle = (JackHandle *) stream_.apiHandle; |
| 2624 | int result = jack_activate( handle->client ); |
| 2625 | if ( result ) { |
| 2626 | errorText_ = "RtApiJack::startStream(): unable to activate JACK client!"; |
| 2627 | goto unlock; |
| 2628 | } |
| 2629 | |
| 2630 | const char **ports; |
| 2631 | |
| 2632 | // Get the list of available ports. |
| 2633 | if ( shouldAutoconnect_ && (stream_.mode == OUTPUT || stream_.mode == DUPLEX) ) { |
| 2634 | result = 1; |
| 2635 | ports = jack_get_ports( handle->client, escapeJackPortRegex(handle->deviceName[0]).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput); |
| 2636 | if ( ports == NULL) { |
| 2637 | errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!"; |
| 2638 | goto unlock; |
| 2639 | } |
| 2640 | |
| 2641 | // Now make the port connections. Since RtAudio wasn't designed to |
| 2642 | // allow the user to select particular channels of a device, we'll |
| 2643 | // just open the first "nChannels" ports with offset. |
| 2644 | for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) { |
| 2645 | result = 1; |
| 2646 | if ( ports[ stream_.channelOffset[0] + i ] ) |
| 2647 | result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] ); |
| 2648 | if ( result ) { |
| 2649 | free( ports ); |
| 2650 | errorText_ = "RtApiJack::startStream(): error connecting output ports!"; |
| 2651 | goto unlock; |
| 2652 | } |
| 2653 | } |
| 2654 | free(ports); |
| 2655 | } |
| 2656 | |
| 2657 | if ( shouldAutoconnect_ && (stream_.mode == INPUT || stream_.mode == DUPLEX) ) { |
| 2658 | result = 1; |
| 2659 | ports = jack_get_ports( handle->client, escapeJackPortRegex(handle->deviceName[1]).c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput ); |
| 2660 | if ( ports == NULL) { |
| 2661 | errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!"; |
| 2662 | goto unlock; |
| 2663 | } |
| 2664 | |
| 2665 | // Now make the port connections. See note above. |
| 2666 | for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) { |
| 2667 | result = 1; |
| 2668 | if ( ports[ stream_.channelOffset[1] + i ] ) |
| 2669 | result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) ); |
| 2670 | if ( result ) { |
| 2671 | free( ports ); |
| 2672 | errorText_ = "RtApiJack::startStream(): error connecting input ports!"; |
| 2673 | goto unlock; |
| 2674 | } |
| 2675 | } |
| 2676 | free(ports); |
| 2677 | } |
| 2678 | |
| 2679 | handle->drainCounter = 0; |
| 2680 | handle->internalDrain = false; |
| 2681 | stream_.state = STREAM_RUNNING; |
| 2682 | |
| 2683 | unlock: |
| 2684 | if ( result == 0 ) return RTAUDIO_NO_ERROR; |
| 2685 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 2686 | } |
| 2687 | |
| 2688 | RtAudioErrorType RtApiJack :: stopStream( void ) |
| 2689 | { |
| 2690 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 2691 | if ( stream_.state == STREAM_STOPPED ) |
| 2692 | errorText_ = "RtApiJack::stopStream(): the stream is already stopped!"; |
| 2693 | else if ( stream_.state == STREAM_CLOSED ) |
| 2694 | errorText_ = "RtApiJack::stopStream(): the stream is closed!"; |
| 2695 | return error( RTAUDIO_WARNING ); |
| 2696 | } |
| 2697 | |
| 2698 | JackHandle *handle = (JackHandle *) stream_.apiHandle; |
| 2699 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 2700 | |
| 2701 | if ( handle->drainCounter == 0 ) { |
| 2702 | handle->drainCounter = 2; |
| 2703 | pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled |
| 2704 | } |
| 2705 | } |
| 2706 | |
| 2707 | jack_deactivate( handle->client ); |
| 2708 | stream_.state = STREAM_STOPPED; |
| 2709 | return RTAUDIO_NO_ERROR; |
| 2710 | } |
| 2711 | |
| 2712 | RtAudioErrorType RtApiJack :: abortStream( void ) |
| 2713 | { |
| 2714 | if ( stream_.state != STREAM_RUNNING ) { |
| 2715 | if ( stream_.state == STREAM_STOPPED ) |
| 2716 | errorText_ = "RtApiJack::abortStream(): the stream is already stopped!"; |
| 2717 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 2718 | errorText_ = "RtApiJack::abortStream(): the stream is stopping or closed!"; |
| 2719 | return error( RTAUDIO_WARNING ); |
| 2720 | } |
| 2721 | |
| 2722 | JackHandle *handle = (JackHandle *) stream_.apiHandle; |
| 2723 | handle->drainCounter = 2; |
| 2724 | |
| 2725 | return stopStream(); |
| 2726 | } |
| 2727 | |
| 2728 | // This function will be called by a spawned thread when the user |
| 2729 | // callback function signals that the stream should be stopped or |
| 2730 | // aborted. It is necessary to handle it this way because the |
| 2731 | // callbackEvent() function must return before the jack_deactivate() |
| 2732 | // function will return. |
| 2733 | static void *jackStopStream( void *ptr ) |
| 2734 | { |
| 2735 | CallbackInfo *info = (CallbackInfo *) ptr; |
| 2736 | RtApiJack *object = (RtApiJack *) info->object; |
| 2737 | |
| 2738 | object->stopStream(); |
| 2739 | pthread_exit( NULL ); |
| 2740 | } |
| 2741 | |
| 2742 | bool RtApiJack :: callbackEvent( unsigned long nframes ) |
| 2743 | { |
| 2744 | if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS; |
| 2745 | if ( stream_.state == STREAM_CLOSED ) { |
| 2746 | errorText_ = "RtApiJack::callbackEvent(): the stream is closed ... this shouldn't happen!"; |
| 2747 | error( RTAUDIO_WARNING ); |
| 2748 | return FAILURE; |
| 2749 | } |
| 2750 | if ( stream_.bufferSize != nframes ) { |
| 2751 | errorText_ = "RtApiJack::callbackEvent(): the JACK buffer size has changed ... cannot process!"; |
| 2752 | error( RTAUDIO_WARNING ); |
| 2753 | return FAILURE; |
| 2754 | } |
| 2755 | |
| 2756 | CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo; |
| 2757 | JackHandle *handle = (JackHandle *) stream_.apiHandle; |
| 2758 | |
| 2759 | // Check if we were draining the stream and signal is finished. |
| 2760 | if ( handle->drainCounter > 3 ) { |
| 2761 | ThreadHandle threadId; |
| 2762 | |
| 2763 | stream_.state = STREAM_STOPPING; |
| 2764 | if ( handle->internalDrain == true ) |
| 2765 | pthread_create( &threadId, NULL, jackStopStream, info ); |
| 2766 | else // external call to stopStream() |
| 2767 | pthread_cond_signal( &handle->condition ); |
| 2768 | return SUCCESS; |
| 2769 | } |
| 2770 | |
| 2771 | // Invoke user callback first, to get fresh output data. |
| 2772 | if ( handle->drainCounter == 0 ) { |
| 2773 | RtAudioCallback callback = (RtAudioCallback) info->callback; |
| 2774 | double streamTime = getStreamTime(); |
| 2775 | RtAudioStreamStatus status = 0; |
| 2776 | if ( stream_.mode != INPUT && handle->xrun[0] == true ) { |
| 2777 | status |= RTAUDIO_OUTPUT_UNDERFLOW; |
| 2778 | handle->xrun[0] = false; |
| 2779 | } |
| 2780 | if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) { |
| 2781 | status |= RTAUDIO_INPUT_OVERFLOW; |
| 2782 | handle->xrun[1] = false; |
| 2783 | } |
| 2784 | int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1], |
| 2785 | stream_.bufferSize, streamTime, status, info->userData ); |
| 2786 | if ( cbReturnValue == 2 ) { |
| 2787 | stream_.state = STREAM_STOPPING; |
| 2788 | handle->drainCounter = 2; |
| 2789 | ThreadHandle id; |
| 2790 | pthread_create( &id, NULL, jackStopStream, info ); |
| 2791 | return SUCCESS; |
| 2792 | } |
| 2793 | else if ( cbReturnValue == 1 ) { |
| 2794 | handle->drainCounter = 1; |
| 2795 | handle->internalDrain = true; |
| 2796 | } |
| 2797 | } |
| 2798 | |
| 2799 | jack_default_audio_sample_t *jackbuffer; |
| 2800 | unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t ); |
| 2801 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 2802 | |
| 2803 | if ( handle->drainCounter > 1 ) { // write zeros to the output stream |
| 2804 | |
| 2805 | for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) { |
| 2806 | jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes ); |
| 2807 | memset( jackbuffer, 0, bufferBytes ); |
| 2808 | } |
| 2809 | |
| 2810 | } |
| 2811 | else if ( stream_.doConvertBuffer[0] ) { |
| 2812 | |
| 2813 | convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] ); |
| 2814 | |
| 2815 | for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) { |
| 2816 | jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes ); |
| 2817 | memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes ); |
| 2818 | } |
| 2819 | } |
| 2820 | else { // no buffer conversion |
| 2821 | for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) { |
| 2822 | jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes ); |
| 2823 | memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes ); |
| 2824 | } |
| 2825 | } |
| 2826 | } |
| 2827 | |
| 2828 | // Don't bother draining input |
| 2829 | if ( handle->drainCounter ) { |
| 2830 | handle->drainCounter++; |
| 2831 | goto unlock; |
| 2832 | } |
| 2833 | |
| 2834 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) { |
| 2835 | |
| 2836 | if ( stream_.doConvertBuffer[1] ) { |
| 2837 | for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) { |
| 2838 | jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes ); |
| 2839 | memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes ); |
| 2840 | } |
| 2841 | convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] ); |
| 2842 | } |
| 2843 | else { // no buffer conversion |
| 2844 | for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) { |
| 2845 | jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes ); |
| 2846 | memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes ); |
| 2847 | } |
| 2848 | } |
| 2849 | } |
| 2850 | |
| 2851 | unlock: |
| 2852 | RtApi::tickStreamTime(); |
| 2853 | return SUCCESS; |
| 2854 | } |
| 2855 | //******************** End of __UNIX_JACK__ *********************// |
| 2856 | #endif |
| 2857 | |
| 2858 | #if defined(__WINDOWS_ASIO__) // ASIO API on Windows |
| 2859 | |
| 2860 | // The ASIO API is designed around a callback scheme, so this |
| 2861 | // implementation is similar to that used for OS-X CoreAudio and Linux |
| 2862 | // Jack. The primary constraint with ASIO is that it only allows |
| 2863 | // access to a single driver at a time. Thus, it is not possible to |
| 2864 | // have more than one simultaneous RtAudio stream. |
| 2865 | // |
| 2866 | // This implementation also requires a number of external ASIO files |
| 2867 | // and a few global variables. The ASIO callback scheme does not |
| 2868 | // allow for the passing of user data, so we must create a global |
| 2869 | // pointer to our callbackInfo structure. |
| 2870 | // |
| 2871 | // On unix systems, we make use of a pthread condition variable. |
| 2872 | // Since there is no equivalent in Windows, I hacked something based |
| 2873 | // on information found in |
| 2874 | // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html. |
| 2875 | |
| 2876 | #include "asiosys.h" |
| 2877 | #include "asio.h" |
| 2878 | #include "iasiothiscallresolver.h" |
| 2879 | #include "asiodrivers.h" |
| 2880 | #include <cmath> |
| 2881 | |
| 2882 | static AsioDrivers drivers; |
| 2883 | static ASIOCallbacks asioCallbacks; |
| 2884 | static ASIODriverInfo driverInfo; |
| 2885 | static CallbackInfo *asioCallbackInfo; |
| 2886 | static bool asioXRun; |
| 2887 | |
| 2888 | struct AsioHandle { |
| 2889 | int drainCounter; // Tracks callback counts when draining |
| 2890 | bool internalDrain; // Indicates if stop is initiated from callback or not. |
| 2891 | ASIOBufferInfo *bufferInfos; |
| 2892 | HANDLE condition; |
| 2893 | |
| 2894 | AsioHandle() |
| 2895 | :drainCounter(0), internalDrain(false), bufferInfos(0) {} |
| 2896 | }; |
| 2897 | |
| 2898 | // Function declarations (definitions at end of section) |
| 2899 | static const char* getAsioErrorString( ASIOError result ); |
| 2900 | static void sampleRateChanged( ASIOSampleRate sRate ); |
| 2901 | static long asioMessages( long selector, long value, void* message, double* opt ); |
| 2902 | |
| 2903 | RtApiAsio :: RtApiAsio() |
| 2904 | { |
| 2905 | // ASIO cannot run on a multi-threaded apartment. You can call |
| 2906 | // CoInitialize beforehand, but it must be for apartment threading |
| 2907 | // (in which case, CoInitilialize will return S_FALSE here). |
| 2908 | coInitialized_ = false; |
| 2909 | HRESULT hr = CoInitialize( NULL ); |
| 2910 | if ( FAILED(hr) ) { |
| 2911 | errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)"; |
| 2912 | error( RTAUDIO_WARNING ); |
| 2913 | } |
| 2914 | coInitialized_ = true; |
| 2915 | |
| 2916 | drivers.removeCurrentDriver(); |
| 2917 | driverInfo.asioVersion = 2; |
| 2918 | |
| 2919 | // See note in DirectSound implementation about GetDesktopWindow(). |
| 2920 | driverInfo.sysRef = GetForegroundWindow(); |
| 2921 | } |
| 2922 | |
| 2923 | RtApiAsio :: ~RtApiAsio() |
| 2924 | { |
| 2925 | if ( stream_.state != STREAM_CLOSED ) closeStream(); |
| 2926 | if ( coInitialized_ ) CoUninitialize(); |
| 2927 | } |
| 2928 | |
| 2929 | unsigned int RtApiAsio :: getDeviceCount( void ) |
| 2930 | { |
| 2931 | return (unsigned int) drivers.asioGetNumDev(); |
| 2932 | } |
| 2933 | |
| 2934 | // We can only load one ASIO driver, so the default output is always the first device. |
| 2935 | unsigned int RtApiAsio :: getDefaultOutputDevice( void ) |
| 2936 | { |
| 2937 | return 0; |
| 2938 | } |
| 2939 | |
| 2940 | // We can only load one ASIO driver, so the default input is always the first device. |
| 2941 | unsigned int RtApiAsio :: getDefaultInputDevice( void ) |
| 2942 | { |
| 2943 | return 0; |
| 2944 | } |
| 2945 | |
| 2946 | RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device ) |
| 2947 | { |
| 2948 | RtAudio::DeviceInfo info; |
| 2949 | info.probed = false; |
| 2950 | |
| 2951 | // Get device ID |
| 2952 | unsigned int nDevices = getDeviceCount(); |
| 2953 | if ( nDevices == 0 ) { |
| 2954 | errorText_ = "RtApiAsio::getDeviceInfo: no devices found!"; |
| 2955 | error( RTAUDIO_INVALID_USE ); |
| 2956 | return info; |
| 2957 | } |
| 2958 | |
| 2959 | if ( device >= nDevices ) { |
| 2960 | errorText_ = "RtApiAsio::getDeviceInfo: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 2961 | error( RTAUDIO_INVALID_USE ); |
| 2962 | return info; |
| 2963 | } |
| 2964 | |
| 2965 | // If a stream is already open, we cannot probe other devices. Thus, use the saved results. |
| 2966 | if ( stream_.state != STREAM_CLOSED ) { |
| 2967 | if ( device >= devices_.size() ) { |
| 2968 | errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened."; |
| 2969 | error( RTAUDIO_WARNING ); |
| 2970 | return info; |
| 2971 | } |
| 2972 | return devices_[ device ]; |
| 2973 | } |
| 2974 | |
| 2975 | char driverName[32]; |
| 2976 | ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 ); |
| 2977 | if ( result != ASE_OK ) { |
| 2978 | errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ")."; |
| 2979 | errorText_ = errorStream_.str(); |
| 2980 | error( RTAUDIO_WARNING ); |
| 2981 | return info; |
| 2982 | } |
| 2983 | |
| 2984 | info.name = driverName; |
| 2985 | |
| 2986 | if ( !drivers.loadDriver( driverName ) ) { |
| 2987 | errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ")."; |
| 2988 | errorText_ = errorStream_.str(); |
| 2989 | error( RTAUDIO_WARNING ); |
| 2990 | return info; |
| 2991 | } |
| 2992 | |
| 2993 | result = ASIOInit( &driverInfo ); |
| 2994 | if ( result != ASE_OK ) { |
| 2995 | errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ")."; |
| 2996 | errorText_ = errorStream_.str(); |
| 2997 | error( RTAUDIO_WARNING ); |
| 2998 | return info; |
| 2999 | } |
| 3000 | |
| 3001 | // Determine the device channel information. |
| 3002 | long inputChannels, outputChannels; |
| 3003 | result = ASIOGetChannels( &inputChannels, &outputChannels ); |
| 3004 | if ( result != ASE_OK ) { |
| 3005 | drivers.removeCurrentDriver(); |
| 3006 | errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ")."; |
| 3007 | errorText_ = errorStream_.str(); |
| 3008 | error( RTAUDIO_WARNING ); |
| 3009 | return info; |
| 3010 | } |
| 3011 | |
| 3012 | info.outputChannels = outputChannels; |
| 3013 | info.inputChannels = inputChannels; |
| 3014 | if ( info.outputChannels > 0 && info.inputChannels > 0 ) |
| 3015 | info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels; |
| 3016 | |
| 3017 | // Determine the supported sample rates. |
| 3018 | info.sampleRates.clear(); |
| 3019 | for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) { |
| 3020 | result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] ); |
| 3021 | if ( result == ASE_OK ) { |
| 3022 | info.sampleRates.push_back( SAMPLE_RATES[i] ); |
| 3023 | |
| 3024 | if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) ) |
| 3025 | info.preferredSampleRate = SAMPLE_RATES[i]; |
| 3026 | } |
| 3027 | } |
| 3028 | |
| 3029 | // Determine supported data types ... just check first channel and assume rest are the same. |
| 3030 | ASIOChannelInfo channelInfo; |
| 3031 | channelInfo.channel = 0; |
| 3032 | channelInfo.isInput = true; |
| 3033 | if ( info.inputChannels <= 0 ) channelInfo.isInput = false; |
| 3034 | result = ASIOGetChannelInfo( &channelInfo ); |
| 3035 | if ( result != ASE_OK ) { |
| 3036 | drivers.removeCurrentDriver(); |
| 3037 | errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ")."; |
| 3038 | errorText_ = errorStream_.str(); |
| 3039 | error( RTAUDIO_WARNING ); |
| 3040 | return info; |
| 3041 | } |
| 3042 | |
| 3043 | info.nativeFormats = 0; |
| 3044 | if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) |
| 3045 | info.nativeFormats |= RTAUDIO_SINT16; |
| 3046 | else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) |
| 3047 | info.nativeFormats |= RTAUDIO_SINT32; |
| 3048 | else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) |
| 3049 | info.nativeFormats |= RTAUDIO_FLOAT32; |
| 3050 | else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) |
| 3051 | info.nativeFormats |= RTAUDIO_FLOAT64; |
| 3052 | else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) |
| 3053 | info.nativeFormats |= RTAUDIO_SINT24; |
| 3054 | |
| 3055 | if ( info.outputChannels > 0 ) |
| 3056 | if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true; |
| 3057 | if ( info.inputChannels > 0 ) |
| 3058 | if ( getDefaultInputDevice() == device ) info.isDefaultInput = true; |
| 3059 | |
| 3060 | info.probed = true; |
| 3061 | drivers.removeCurrentDriver(); |
| 3062 | return info; |
| 3063 | } |
| 3064 | |
| 3065 | static void bufferSwitch( long index, ASIOBool /*processNow*/ ) |
| 3066 | { |
| 3067 | RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object; |
| 3068 | object->callbackEvent( index ); |
| 3069 | } |
| 3070 | |
| 3071 | void RtApiAsio :: saveDeviceInfo( void ) |
| 3072 | { |
| 3073 | devices_.clear(); |
| 3074 | |
| 3075 | unsigned int nDevices = getDeviceCount(); |
| 3076 | devices_.resize( nDevices ); |
| 3077 | for ( unsigned int i=0; i<nDevices; i++ ) |
| 3078 | devices_[i] = getDeviceInfo( i ); |
| 3079 | } |
| 3080 | |
| 3081 | bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, |
| 3082 | unsigned int firstChannel, unsigned int sampleRate, |
| 3083 | RtAudioFormat format, unsigned int *bufferSize, |
| 3084 | RtAudio::StreamOptions *options ) |
| 3085 | {//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 3086 | |
| 3087 | bool isDuplexInput = mode == INPUT && stream_.mode == OUTPUT; |
| 3088 | |
| 3089 | // For ASIO, a duplex stream MUST use the same driver. |
| 3090 | if ( isDuplexInput && stream_.device[0] != device ) { |
| 3091 | errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!"; |
| 3092 | return FAILURE; |
| 3093 | } |
| 3094 | |
| 3095 | char driverName[32]; |
| 3096 | ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 ); |
| 3097 | if ( result != ASE_OK ) { |
| 3098 | errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ")."; |
| 3099 | errorText_ = errorStream_.str(); |
| 3100 | return FAILURE; |
| 3101 | } |
| 3102 | |
| 3103 | // Only load the driver once for duplex stream. |
| 3104 | if ( !isDuplexInput ) { |
| 3105 | // The getDeviceInfo() function will not work when a stream is open |
| 3106 | // because ASIO does not allow multiple devices to run at the same |
| 3107 | // time. Thus, we'll probe the system before opening a stream and |
| 3108 | // save the results for use by getDeviceInfo(). |
| 3109 | this->saveDeviceInfo(); |
| 3110 | |
| 3111 | if ( !drivers.loadDriver( driverName ) ) { |
| 3112 | errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ")."; |
| 3113 | errorText_ = errorStream_.str(); |
| 3114 | return FAILURE; |
| 3115 | } |
| 3116 | |
| 3117 | result = ASIOInit( &driverInfo ); |
| 3118 | if ( result != ASE_OK ) { |
| 3119 | errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ")."; |
| 3120 | errorText_ = errorStream_.str(); |
| 3121 | return FAILURE; |
| 3122 | } |
| 3123 | } |
| 3124 | |
| 3125 | // keep them before any "goto error", they are used for error cleanup + goto device boundary checks |
| 3126 | bool buffersAllocated = false; |
| 3127 | AsioHandle *handle = (AsioHandle *) stream_.apiHandle; |
| 3128 | unsigned int nChannels; |
| 3129 | |
| 3130 | |
| 3131 | // Check the device channel count. |
| 3132 | long inputChannels, outputChannels; |
| 3133 | result = ASIOGetChannels( &inputChannels, &outputChannels ); |
| 3134 | if ( result != ASE_OK ) { |
| 3135 | errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ")."; |
| 3136 | errorText_ = errorStream_.str(); |
| 3137 | goto error; |
| 3138 | } |
| 3139 | |
| 3140 | if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) || |
| 3141 | ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) { |
| 3142 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ")."; |
| 3143 | errorText_ = errorStream_.str(); |
| 3144 | goto error; |
| 3145 | } |
| 3146 | stream_.nDeviceChannels[mode] = channels; |
| 3147 | stream_.nUserChannels[mode] = channels; |
| 3148 | stream_.channelOffset[mode] = firstChannel; |
| 3149 | |
| 3150 | // Verify the sample rate is supported. |
| 3151 | result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate ); |
| 3152 | if ( result != ASE_OK ) { |
| 3153 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ")."; |
| 3154 | errorText_ = errorStream_.str(); |
| 3155 | goto error; |
| 3156 | } |
| 3157 | |
| 3158 | // Get the current sample rate |
| 3159 | ASIOSampleRate currentRate; |
| 3160 | result = ASIOGetSampleRate( ¤tRate ); |
| 3161 | if ( result != ASE_OK ) { |
| 3162 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate."; |
| 3163 | errorText_ = errorStream_.str(); |
| 3164 | goto error; |
| 3165 | } |
| 3166 | |
| 3167 | // Set the sample rate only if necessary |
| 3168 | if ( currentRate != sampleRate ) { |
| 3169 | result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate ); |
| 3170 | if ( result != ASE_OK ) { |
| 3171 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ")."; |
| 3172 | errorText_ = errorStream_.str(); |
| 3173 | goto error; |
| 3174 | } |
| 3175 | } |
| 3176 | |
| 3177 | // Determine the driver data type. |
| 3178 | ASIOChannelInfo channelInfo; |
| 3179 | channelInfo.channel = 0; |
| 3180 | if ( mode == OUTPUT ) channelInfo.isInput = false; |
| 3181 | else channelInfo.isInput = true; |
| 3182 | result = ASIOGetChannelInfo( &channelInfo ); |
| 3183 | if ( result != ASE_OK ) { |
| 3184 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format."; |
| 3185 | errorText_ = errorStream_.str(); |
| 3186 | goto error; |
| 3187 | } |
| 3188 | |
| 3189 | // Assuming WINDOWS host is always little-endian. |
| 3190 | stream_.doByteSwap[mode] = false; |
| 3191 | stream_.userFormat = format; |
| 3192 | stream_.deviceFormat[mode] = 0; |
| 3193 | if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) { |
| 3194 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 3195 | if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true; |
| 3196 | } |
| 3197 | else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) { |
| 3198 | stream_.deviceFormat[mode] = RTAUDIO_SINT32; |
| 3199 | if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true; |
| 3200 | } |
| 3201 | else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) { |
| 3202 | stream_.deviceFormat[mode] = RTAUDIO_FLOAT32; |
| 3203 | if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true; |
| 3204 | } |
| 3205 | else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) { |
| 3206 | stream_.deviceFormat[mode] = RTAUDIO_FLOAT64; |
| 3207 | if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true; |
| 3208 | } |
| 3209 | else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) { |
| 3210 | stream_.deviceFormat[mode] = RTAUDIO_SINT24; |
| 3211 | if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true; |
| 3212 | } |
| 3213 | |
| 3214 | if ( stream_.deviceFormat[mode] == 0 ) { |
| 3215 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio."; |
| 3216 | errorText_ = errorStream_.str(); |
| 3217 | goto error; |
| 3218 | } |
| 3219 | |
| 3220 | // Set the buffer size. For a duplex stream, this will end up |
| 3221 | // setting the buffer size based on the input constraints, which |
| 3222 | // should be ok. |
| 3223 | long minSize, maxSize, preferSize, granularity; |
| 3224 | result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity ); |
| 3225 | if ( result != ASE_OK ) { |
| 3226 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size."; |
| 3227 | errorText_ = errorStream_.str(); |
| 3228 | goto error; |
| 3229 | } |
| 3230 | |
| 3231 | if ( isDuplexInput ) { |
| 3232 | // When this is the duplex input (output was opened before), then we have to use the same |
| 3233 | // buffersize as the output, because it might use the preferred buffer size, which most |
| 3234 | // likely wasn't passed as input to this. The buffer sizes have to be identically anyway, |
| 3235 | // So instead of throwing an error, make them equal. The caller uses the reference |
| 3236 | // to the "bufferSize" param as usual to set up processing buffers. |
| 3237 | |
| 3238 | *bufferSize = stream_.bufferSize; |
| 3239 | |
| 3240 | } else { |
| 3241 | if ( *bufferSize == 0 ) *bufferSize = preferSize; |
| 3242 | else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize; |
| 3243 | else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize; |
| 3244 | else if ( granularity == -1 ) { |
| 3245 | // Make sure bufferSize is a power of two. |
| 3246 | int log2_of_min_size = 0; |
| 3247 | int log2_of_max_size = 0; |
| 3248 | |
| 3249 | for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) { |
| 3250 | if ( minSize & ((long)1 << i) ) log2_of_min_size = i; |
| 3251 | if ( maxSize & ((long)1 << i) ) log2_of_max_size = i; |
| 3252 | } |
| 3253 | |
| 3254 | long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) ); |
| 3255 | int min_delta_num = log2_of_min_size; |
| 3256 | |
| 3257 | for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) { |
| 3258 | long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) ); |
| 3259 | if (current_delta < min_delta) { |
| 3260 | min_delta = current_delta; |
| 3261 | min_delta_num = i; |
| 3262 | } |
| 3263 | } |
| 3264 | |
| 3265 | *bufferSize = ( (unsigned int)1 << min_delta_num ); |
| 3266 | if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize; |
| 3267 | else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize; |
| 3268 | } |
| 3269 | else if ( granularity != 0 ) { |
| 3270 | // Set to an even multiple of granularity, rounding up. |
| 3271 | *bufferSize = (*bufferSize + granularity-1) / granularity * granularity; |
| 3272 | } |
| 3273 | } |
| 3274 | |
| 3275 | /* |
| 3276 | // we don't use it anymore, see above! |
| 3277 | // Just left it here for the case... |
| 3278 | if ( isDuplexInput && stream_.bufferSize != *bufferSize ) { |
| 3279 | errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!"; |
| 3280 | goto error; |
| 3281 | } |
| 3282 | */ |
| 3283 | |
| 3284 | stream_.bufferSize = *bufferSize; |
| 3285 | stream_.nBuffers = 2; |
| 3286 | |
| 3287 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false; |
| 3288 | else stream_.userInterleaved = true; |
| 3289 | |
| 3290 | // ASIO always uses non-interleaved buffers. |
| 3291 | stream_.deviceInterleaved[mode] = false; |
| 3292 | |
| 3293 | // Allocate, if necessary, our AsioHandle structure for the stream. |
| 3294 | if ( handle == 0 ) { |
| 3295 | try { |
| 3296 | handle = new AsioHandle; |
| 3297 | } |
| 3298 | catch ( std::bad_alloc& ) { |
| 3299 | errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory."; |
| 3300 | goto error; |
| 3301 | } |
| 3302 | handle->bufferInfos = 0; |
| 3303 | |
| 3304 | // Create a manual-reset event. |
| 3305 | handle->condition = CreateEvent( NULL, // no security |
| 3306 | TRUE, // manual-reset |
| 3307 | FALSE, // non-signaled initially |
| 3308 | NULL ); // unnamed |
| 3309 | stream_.apiHandle = (void *) handle; |
| 3310 | } |
| 3311 | |
| 3312 | // Create the ASIO internal buffers. Since RtAudio sets up input |
| 3313 | // and output separately, we'll have to dispose of previously |
| 3314 | // created output buffers for a duplex stream. |
| 3315 | if ( mode == INPUT && stream_.mode == OUTPUT ) { |
| 3316 | ASIODisposeBuffers(); |
| 3317 | if ( handle->bufferInfos ) free( handle->bufferInfos ); |
| 3318 | } |
| 3319 | |
| 3320 | // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure. |
| 3321 | unsigned int i; |
| 3322 | nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1]; |
| 3323 | handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) ); |
| 3324 | if ( handle->bufferInfos == NULL ) { |
| 3325 | errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ")."; |
| 3326 | errorText_ = errorStream_.str(); |
| 3327 | goto error; |
| 3328 | } |
| 3329 | |
| 3330 | ASIOBufferInfo *infos; |
| 3331 | infos = handle->bufferInfos; |
| 3332 | for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) { |
| 3333 | infos->isInput = ASIOFalse; |
| 3334 | infos->channelNum = i + stream_.channelOffset[0]; |
| 3335 | infos->buffers[0] = infos->buffers[1] = 0; |
| 3336 | } |
| 3337 | for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) { |
| 3338 | infos->isInput = ASIOTrue; |
| 3339 | infos->channelNum = i + stream_.channelOffset[1]; |
| 3340 | infos->buffers[0] = infos->buffers[1] = 0; |
| 3341 | } |
| 3342 | |
| 3343 | // prepare for callbacks |
| 3344 | stream_.sampleRate = sampleRate; |
| 3345 | stream_.device[mode] = device; |
| 3346 | stream_.mode = isDuplexInput ? DUPLEX : mode; |
| 3347 | |
| 3348 | // store this class instance before registering callbacks, that are going to use it |
| 3349 | asioCallbackInfo = &stream_.callbackInfo; |
| 3350 | stream_.callbackInfo.object = (void *) this; |
| 3351 | |
| 3352 | // Set up the ASIO callback structure and create the ASIO data buffers. |
| 3353 | asioCallbacks.bufferSwitch = &bufferSwitch; |
| 3354 | asioCallbacks.sampleRateDidChange = &sampleRateChanged; |
| 3355 | asioCallbacks.asioMessage = &asioMessages; |
| 3356 | asioCallbacks.bufferSwitchTimeInfo = NULL; |
| 3357 | result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks ); |
| 3358 | if ( result != ASE_OK ) { |
| 3359 | // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges |
| 3360 | // but only accept the preferred buffer size as parameter for ASIOCreateBuffers (e.g. Creative's ASIO driver). |
| 3361 | // In that case, let's be naïve and try that instead. |
| 3362 | *bufferSize = preferSize; |
| 3363 | stream_.bufferSize = *bufferSize; |
| 3364 | result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks ); |
| 3365 | } |
| 3366 | |
| 3367 | if ( result != ASE_OK ) { |
| 3368 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers."; |
| 3369 | errorText_ = errorStream_.str(); |
| 3370 | goto error; |
| 3371 | } |
| 3372 | buffersAllocated = true; |
| 3373 | stream_.state = STREAM_STOPPED; |
| 3374 | |
| 3375 | // Set flags for buffer conversion. |
| 3376 | stream_.doConvertBuffer[mode] = false; |
| 3377 | if ( stream_.userFormat != stream_.deviceFormat[mode] ) |
| 3378 | stream_.doConvertBuffer[mode] = true; |
| 3379 | if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] && |
| 3380 | stream_.nUserChannels[mode] > 1 ) |
| 3381 | stream_.doConvertBuffer[mode] = true; |
| 3382 | |
| 3383 | // Allocate necessary internal buffers |
| 3384 | unsigned long bufferBytes; |
| 3385 | bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat ); |
| 3386 | stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 ); |
| 3387 | if ( stream_.userBuffer[mode] == NULL ) { |
| 3388 | errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory."; |
| 3389 | goto error; |
| 3390 | } |
| 3391 | |
| 3392 | if ( stream_.doConvertBuffer[mode] ) { |
| 3393 | |
| 3394 | bool makeBuffer = true; |
| 3395 | bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] ); |
| 3396 | if ( isDuplexInput && stream_.deviceBuffer ) { |
| 3397 | unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] ); |
| 3398 | if ( bufferBytes <= bytesOut ) makeBuffer = false; |
| 3399 | } |
| 3400 | |
| 3401 | if ( makeBuffer ) { |
| 3402 | bufferBytes *= *bufferSize; |
| 3403 | if ( stream_.deviceBuffer ) free( stream_.deviceBuffer ); |
| 3404 | stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 ); |
| 3405 | if ( stream_.deviceBuffer == NULL ) { |
| 3406 | errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory."; |
| 3407 | goto error; |
| 3408 | } |
| 3409 | } |
| 3410 | } |
| 3411 | |
| 3412 | // Determine device latencies |
| 3413 | long inputLatency, outputLatency; |
| 3414 | result = ASIOGetLatencies( &inputLatency, &outputLatency ); |
| 3415 | if ( result != ASE_OK ) { |
| 3416 | errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency."; |
| 3417 | errorText_ = errorStream_.str(); |
| 3418 | error( RTAUDIO_WARNING); // warn but don't fail |
| 3419 | } |
| 3420 | else { |
| 3421 | stream_.latency[0] = outputLatency; |
| 3422 | stream_.latency[1] = inputLatency; |
| 3423 | } |
| 3424 | |
| 3425 | // Setup the buffer conversion information structure. We don't use |
| 3426 | // buffers to do channel offsets, so we override that parameter |
| 3427 | // here. |
| 3428 | if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 ); |
| 3429 | |
| 3430 | return SUCCESS; |
| 3431 | |
| 3432 | error: |
| 3433 | if ( !isDuplexInput ) { |
| 3434 | // the cleanup for error in the duplex input, is done by RtApi::openStream |
| 3435 | // So we clean up for single channel only |
| 3436 | |
| 3437 | if ( buffersAllocated ) |
| 3438 | ASIODisposeBuffers(); |
| 3439 | |
| 3440 | drivers.removeCurrentDriver(); |
| 3441 | |
| 3442 | if ( handle ) { |
| 3443 | CloseHandle( handle->condition ); |
| 3444 | if ( handle->bufferInfos ) |
| 3445 | free( handle->bufferInfos ); |
| 3446 | |
| 3447 | delete handle; |
| 3448 | stream_.apiHandle = 0; |
| 3449 | } |
| 3450 | |
| 3451 | |
| 3452 | if ( stream_.userBuffer[mode] ) { |
| 3453 | free( stream_.userBuffer[mode] ); |
| 3454 | stream_.userBuffer[mode] = 0; |
| 3455 | } |
| 3456 | |
| 3457 | if ( stream_.deviceBuffer ) { |
| 3458 | free( stream_.deviceBuffer ); |
| 3459 | stream_.deviceBuffer = 0; |
| 3460 | } |
| 3461 | } |
| 3462 | |
| 3463 | return FAILURE; |
| 3464 | }//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 3465 | |
| 3466 | void RtApiAsio :: closeStream() |
| 3467 | { |
| 3468 | if ( stream_.state == STREAM_CLOSED ) { |
| 3469 | errorText_ = "RtApiAsio::closeStream(): no open stream to close!"; |
| 3470 | error( RTAUDIO_WARNING ); |
| 3471 | return; |
| 3472 | } |
| 3473 | |
| 3474 | if ( stream_.state == STREAM_RUNNING ) { |
| 3475 | stream_.state = STREAM_STOPPED; |
| 3476 | ASIOStop(); |
| 3477 | } |
| 3478 | ASIODisposeBuffers(); |
| 3479 | drivers.removeCurrentDriver(); |
| 3480 | |
| 3481 | AsioHandle *handle = (AsioHandle *) stream_.apiHandle; |
| 3482 | if ( handle ) { |
| 3483 | CloseHandle( handle->condition ); |
| 3484 | if ( handle->bufferInfos ) |
| 3485 | free( handle->bufferInfos ); |
| 3486 | delete handle; |
| 3487 | stream_.apiHandle = 0; |
| 3488 | } |
| 3489 | |
| 3490 | for ( int i=0; i<2; i++ ) { |
| 3491 | if ( stream_.userBuffer[i] ) { |
| 3492 | free( stream_.userBuffer[i] ); |
| 3493 | stream_.userBuffer[i] = 0; |
| 3494 | } |
| 3495 | } |
| 3496 | |
| 3497 | if ( stream_.deviceBuffer ) { |
| 3498 | free( stream_.deviceBuffer ); |
| 3499 | stream_.deviceBuffer = 0; |
| 3500 | } |
| 3501 | |
| 3502 | clearStreamInfo(); |
| 3503 | //stream_.mode = UNINITIALIZED; |
| 3504 | //stream_.state = STREAM_CLOSED; |
| 3505 | } |
| 3506 | |
| 3507 | bool stopThreadCalled = false; |
| 3508 | |
| 3509 | RtAudioErrorType RtApiAsio :: startStream() |
| 3510 | { |
| 3511 | if ( stream_.state != STREAM_STOPPED ) { |
| 3512 | if ( stream_.state == STREAM_RUNNING ) |
| 3513 | errorText_ = "RtApiAsio::startStream(): the stream is already running!"; |
| 3514 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 3515 | errorText_ = "RtApiAsio::startStream(): the stream is stopping or closed!"; |
| 3516 | return error( RTAUDIO_WARNING ); |
| 3517 | } |
| 3518 | |
| 3519 | /* |
| 3520 | #if defined( HAVE_GETTIMEOFDAY ) |
| 3521 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 3522 | #endif |
| 3523 | */ |
| 3524 | |
| 3525 | AsioHandle *handle = (AsioHandle *) stream_.apiHandle; |
| 3526 | ASIOError result = ASIOStart(); |
| 3527 | if ( result != ASE_OK ) { |
| 3528 | errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device."; |
| 3529 | errorText_ = errorStream_.str(); |
| 3530 | goto unlock; |
| 3531 | } |
| 3532 | |
| 3533 | handle->drainCounter = 0; |
| 3534 | handle->internalDrain = false; |
| 3535 | ResetEvent( handle->condition ); |
| 3536 | stream_.state = STREAM_RUNNING; |
| 3537 | asioXRun = false; |
| 3538 | |
| 3539 | unlock: |
| 3540 | stopThreadCalled = false; |
| 3541 | |
| 3542 | if ( result == ASE_OK ) return RTAUDIO_NO_ERROR; |
| 3543 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 3544 | } |
| 3545 | |
| 3546 | RtAudioErrorType RtApiAsio :: stopStream() |
| 3547 | { |
| 3548 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 3549 | if ( stream_.state == STREAM_STOPPED ) |
| 3550 | errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!"; |
| 3551 | else if ( stream_.state == STREAM_CLOSED ) |
| 3552 | errorText_ = "RtApiAsio::stopStream(): the stream is closed!"; |
| 3553 | return error( RTAUDIO_WARNING ); |
| 3554 | } |
| 3555 | |
| 3556 | AsioHandle *handle = (AsioHandle *) stream_.apiHandle; |
| 3557 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 3558 | if ( handle->drainCounter == 0 ) { |
| 3559 | handle->drainCounter = 2; |
| 3560 | WaitForSingleObject( handle->condition, INFINITE ); // block until signaled |
| 3561 | } |
| 3562 | } |
| 3563 | |
| 3564 | stream_.state = STREAM_STOPPED; |
| 3565 | |
| 3566 | ASIOError result = ASIOStop(); |
| 3567 | if ( result != ASE_OK ) { |
| 3568 | errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device."; |
| 3569 | errorText_ = errorStream_.str(); |
| 3570 | } |
| 3571 | |
| 3572 | if ( result == ASE_OK ) return RTAUDIO_NO_ERROR; |
| 3573 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 3574 | } |
| 3575 | |
| 3576 | RtAudioErrorType RtApiAsio :: abortStream() |
| 3577 | { |
| 3578 | if ( stream_.state != STREAM_RUNNING ) { |
| 3579 | if ( stream_.state == STREAM_STOPPED ) |
| 3580 | errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!"; |
| 3581 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 3582 | errorText_ = "RtApiAsio::abortStream(): the stream is stopping or closed!"; |
| 3583 | return error( RTAUDIO_WARNING ); |
| 3584 | } |
| 3585 | |
| 3586 | // The following lines were commented-out because some behavior was |
| 3587 | // noted where the device buffers need to be zeroed to avoid |
| 3588 | // continuing sound, even when the device buffers are completely |
| 3589 | // disposed. So now, calling abort is the same as calling stop. |
| 3590 | // AsioHandle *handle = (AsioHandle *) stream_.apiHandle; |
| 3591 | // handle->drainCounter = 2; |
| 3592 | stopStream(); |
| 3593 | return RTAUDIO_NO_ERROR; |
| 3594 | } |
| 3595 | |
| 3596 | // This function will be called by a spawned thread when the user |
| 3597 | // callback function signals that the stream should be stopped or |
| 3598 | // aborted. It is necessary to handle it this way because the |
| 3599 | // callbackEvent() function must return before the ASIOStop() |
| 3600 | // function will return. |
| 3601 | static unsigned __stdcall asioStopStream( void *ptr ) |
| 3602 | { |
| 3603 | CallbackInfo *info = (CallbackInfo *) ptr; |
| 3604 | RtApiAsio *object = (RtApiAsio *) info->object; |
| 3605 | |
| 3606 | object->stopStream(); |
| 3607 | _endthreadex( 0 ); |
| 3608 | return 0; |
| 3609 | } |
| 3610 | |
| 3611 | bool RtApiAsio :: callbackEvent( long bufferIndex ) |
| 3612 | { |
| 3613 | if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS; |
| 3614 | if ( stream_.state == STREAM_CLOSED ) { |
| 3615 | errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!"; |
| 3616 | error( RTAUDIO_WARNING ); |
| 3617 | return FAILURE; |
| 3618 | } |
| 3619 | |
| 3620 | CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo; |
| 3621 | AsioHandle *handle = (AsioHandle *) stream_.apiHandle; |
| 3622 | |
| 3623 | // Check if we were draining the stream and signal if finished. |
| 3624 | if ( handle->drainCounter > 3 ) { |
| 3625 | |
| 3626 | stream_.state = STREAM_STOPPING; |
| 3627 | if ( handle->internalDrain == false ) |
| 3628 | SetEvent( handle->condition ); |
| 3629 | else { // spawn a thread to stop the stream |
| 3630 | unsigned threadId; |
| 3631 | stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream, |
| 3632 | &stream_.callbackInfo, 0, &threadId ); |
| 3633 | } |
| 3634 | return SUCCESS; |
| 3635 | } |
| 3636 | |
| 3637 | // Invoke user callback to get fresh output data UNLESS we are |
| 3638 | // draining stream. |
| 3639 | if ( handle->drainCounter == 0 ) { |
| 3640 | RtAudioCallback callback = (RtAudioCallback) info->callback; |
| 3641 | double streamTime = getStreamTime(); |
| 3642 | RtAudioStreamStatus status = 0; |
| 3643 | if ( stream_.mode != INPUT && asioXRun == true ) { |
| 3644 | status |= RTAUDIO_OUTPUT_UNDERFLOW; |
| 3645 | asioXRun = false; |
| 3646 | } |
| 3647 | if ( stream_.mode != OUTPUT && asioXRun == true ) { |
| 3648 | status |= RTAUDIO_INPUT_OVERFLOW; |
| 3649 | asioXRun = false; |
| 3650 | } |
| 3651 | int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1], |
| 3652 | stream_.bufferSize, streamTime, status, info->userData ); |
| 3653 | if ( cbReturnValue == 2 ) { |
| 3654 | stream_.state = STREAM_STOPPING; |
| 3655 | handle->drainCounter = 2; |
| 3656 | unsigned threadId; |
| 3657 | stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream, |
| 3658 | &stream_.callbackInfo, 0, &threadId ); |
| 3659 | return SUCCESS; |
| 3660 | } |
| 3661 | else if ( cbReturnValue == 1 ) { |
| 3662 | handle->drainCounter = 1; |
| 3663 | handle->internalDrain = true; |
| 3664 | } |
| 3665 | } |
| 3666 | |
| 3667 | unsigned int nChannels, bufferBytes, i, j; |
| 3668 | nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1]; |
| 3669 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 3670 | |
| 3671 | bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] ); |
| 3672 | |
| 3673 | if ( handle->drainCounter > 1 ) { // write zeros to the output stream |
| 3674 | |
| 3675 | for ( i=0, j=0; i<nChannels; i++ ) { |
| 3676 | if ( handle->bufferInfos[i].isInput != ASIOTrue ) |
| 3677 | memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes ); |
| 3678 | } |
| 3679 | |
| 3680 | } |
| 3681 | else if ( stream_.doConvertBuffer[0] ) { |
| 3682 | |
| 3683 | convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] ); |
| 3684 | if ( stream_.doByteSwap[0] ) |
| 3685 | byteSwapBuffer( stream_.deviceBuffer, |
| 3686 | stream_.bufferSize * stream_.nDeviceChannels[0], |
| 3687 | stream_.deviceFormat[0] ); |
| 3688 | |
| 3689 | for ( i=0, j=0; i<nChannels; i++ ) { |
| 3690 | if ( handle->bufferInfos[i].isInput != ASIOTrue ) |
| 3691 | memcpy( handle->bufferInfos[i].buffers[bufferIndex], |
| 3692 | &stream_.deviceBuffer[j++*bufferBytes], bufferBytes ); |
| 3693 | } |
| 3694 | |
| 3695 | } |
| 3696 | else { |
| 3697 | |
| 3698 | if ( stream_.doByteSwap[0] ) |
| 3699 | byteSwapBuffer( stream_.userBuffer[0], |
| 3700 | stream_.bufferSize * stream_.nUserChannels[0], |
| 3701 | stream_.userFormat ); |
| 3702 | |
| 3703 | for ( i=0, j=0; i<nChannels; i++ ) { |
| 3704 | if ( handle->bufferInfos[i].isInput != ASIOTrue ) |
| 3705 | memcpy( handle->bufferInfos[i].buffers[bufferIndex], |
| 3706 | &stream_.userBuffer[0][bufferBytes*j++], bufferBytes ); |
| 3707 | } |
| 3708 | |
| 3709 | } |
| 3710 | } |
| 3711 | |
| 3712 | // Don't bother draining input |
| 3713 | if ( handle->drainCounter ) { |
| 3714 | handle->drainCounter++; |
| 3715 | goto unlock; |
| 3716 | } |
| 3717 | |
| 3718 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) { |
| 3719 | |
| 3720 | bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]); |
| 3721 | |
| 3722 | if (stream_.doConvertBuffer[1]) { |
| 3723 | |
| 3724 | // Always interleave ASIO input data. |
| 3725 | for ( i=0, j=0; i<nChannels; i++ ) { |
| 3726 | if ( handle->bufferInfos[i].isInput == ASIOTrue ) |
| 3727 | memcpy( &stream_.deviceBuffer[j++*bufferBytes], |
| 3728 | handle->bufferInfos[i].buffers[bufferIndex], |
| 3729 | bufferBytes ); |
| 3730 | } |
| 3731 | |
| 3732 | if ( stream_.doByteSwap[1] ) |
| 3733 | byteSwapBuffer( stream_.deviceBuffer, |
| 3734 | stream_.bufferSize * stream_.nDeviceChannels[1], |
| 3735 | stream_.deviceFormat[1] ); |
| 3736 | convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] ); |
| 3737 | |
| 3738 | } |
| 3739 | else { |
| 3740 | for ( i=0, j=0; i<nChannels; i++ ) { |
| 3741 | if ( handle->bufferInfos[i].isInput == ASIOTrue ) { |
| 3742 | memcpy( &stream_.userBuffer[1][bufferBytes*j++], |
| 3743 | handle->bufferInfos[i].buffers[bufferIndex], |
| 3744 | bufferBytes ); |
| 3745 | } |
| 3746 | } |
| 3747 | |
| 3748 | if ( stream_.doByteSwap[1] ) |
| 3749 | byteSwapBuffer( stream_.userBuffer[1], |
| 3750 | stream_.bufferSize * stream_.nUserChannels[1], |
| 3751 | stream_.userFormat ); |
| 3752 | } |
| 3753 | } |
| 3754 | |
| 3755 | unlock: |
| 3756 | // The following call was suggested by Malte Clasen. While the API |
| 3757 | // documentation indicates it should not be required, some device |
| 3758 | // drivers apparently do not function correctly without it. |
| 3759 | ASIOOutputReady(); |
| 3760 | |
| 3761 | RtApi::tickStreamTime(); |
| 3762 | return SUCCESS; |
| 3763 | } |
| 3764 | |
| 3765 | static void sampleRateChanged( ASIOSampleRate sRate ) |
| 3766 | { |
| 3767 | // The ASIO documentation says that this usually only happens during |
| 3768 | // external sync. Audio processing is not stopped by the driver, |
| 3769 | // actual sample rate might not have even changed, maybe only the |
| 3770 | // sample rate status of an AES/EBU or S/PDIF digital input at the |
| 3771 | // audio device. |
| 3772 | |
| 3773 | RtApi *object = (RtApi *) asioCallbackInfo->object; |
| 3774 | if ( object->stopStream() ) { |
| 3775 | std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << /*TODO object->errorText_ <<*/ ")!\n" << std::endl; |
| 3776 | return; |
| 3777 | } |
| 3778 | |
| 3779 | std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl; |
| 3780 | } |
| 3781 | |
| 3782 | static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ ) |
| 3783 | { |
| 3784 | long ret = 0; |
| 3785 | |
| 3786 | switch( selector ) { |
| 3787 | case kAsioSelectorSupported: |
| 3788 | if ( value == kAsioResetRequest |
| 3789 | || value == kAsioEngineVersion |
| 3790 | || value == kAsioResyncRequest |
| 3791 | || value == kAsioLatenciesChanged |
| 3792 | // The following three were added for ASIO 2.0, you don't |
| 3793 | // necessarily have to support them. |
| 3794 | || value == kAsioSupportsTimeInfo |
| 3795 | || value == kAsioSupportsTimeCode |
| 3796 | || value == kAsioSupportsInputMonitor) |
| 3797 | ret = 1L; |
| 3798 | break; |
| 3799 | case kAsioResetRequest: |
| 3800 | // Defer the task and perform the reset of the driver during the |
| 3801 | // next "safe" situation. You cannot reset the driver right now, |
| 3802 | // as this code is called from the driver. Reset the driver is |
| 3803 | // done by completely destruct is. I.e. ASIOStop(), |
| 3804 | // ASIODisposeBuffers(), Destruction Afterwards you initialize the |
| 3805 | // driver again. |
| 3806 | std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl; |
| 3807 | ret = 1L; |
| 3808 | break; |
| 3809 | case kAsioResyncRequest: |
| 3810 | // This informs the application that the driver encountered some |
| 3811 | // non-fatal data loss. It is used for synchronization purposes |
| 3812 | // of different media. Added mainly to work around the Win16Mutex |
| 3813 | // problems in Windows 95/98 with the Windows Multimedia system, |
| 3814 | // which could lose data because the Mutex was held too long by |
| 3815 | // another thread. However a driver can issue it in other |
| 3816 | // situations, too. |
| 3817 | // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl; |
| 3818 | asioXRun = true; |
| 3819 | ret = 1L; |
| 3820 | break; |
| 3821 | case kAsioLatenciesChanged: |
| 3822 | // This will inform the host application that the drivers were |
| 3823 | // latencies changed. Beware, it this does not mean that the |
| 3824 | // buffer sizes have changed! You might need to update internal |
| 3825 | // delay data. |
| 3826 | std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl; |
| 3827 | ret = 1L; |
| 3828 | break; |
| 3829 | case kAsioEngineVersion: |
| 3830 | // Return the supported ASIO version of the host application. If |
| 3831 | // a host application does not implement this selector, ASIO 1.0 |
| 3832 | // is assumed by the driver. |
| 3833 | ret = 2L; |
| 3834 | break; |
| 3835 | case kAsioSupportsTimeInfo: |
| 3836 | // Informs the driver whether the |
| 3837 | // asioCallbacks.bufferSwitchTimeInfo() callback is supported. |
| 3838 | // For compatibility with ASIO 1.0 drivers the host application |
| 3839 | // should always support the "old" bufferSwitch method, too. |
| 3840 | ret = 0; |
| 3841 | break; |
| 3842 | case kAsioSupportsTimeCode: |
| 3843 | // Informs the driver whether application is interested in time |
| 3844 | // code info. If an application does not need to know about time |
| 3845 | // code, the driver has less work to do. |
| 3846 | ret = 0; |
| 3847 | break; |
| 3848 | } |
| 3849 | return ret; |
| 3850 | } |
| 3851 | |
| 3852 | static const char* getAsioErrorString( ASIOError result ) |
| 3853 | { |
| 3854 | struct Messages |
| 3855 | { |
| 3856 | ASIOError value; |
| 3857 | const char*message; |
| 3858 | }; |
| 3859 | |
| 3860 | static const Messages m[] = |
| 3861 | { |
| 3862 | { ASE_NotPresent, "Hardware input or output is not present or available." }, |
| 3863 | { ASE_HWMalfunction, "Hardware is malfunctioning." }, |
| 3864 | { ASE_InvalidParameter, "Invalid input parameter." }, |
| 3865 | { ASE_InvalidMode, "Invalid mode." }, |
| 3866 | { ASE_SPNotAdvancing, "Sample position not advancing." }, |
| 3867 | { ASE_NoClock, "Sample clock or rate cannot be determined or is not present." }, |
| 3868 | { ASE_NoMemory, "Not enough memory to complete the request." } |
| 3869 | }; |
| 3870 | |
| 3871 | for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i ) |
| 3872 | if ( m[i].value == result ) return m[i].message; |
| 3873 | |
| 3874 | return "Unknown error."; |
| 3875 | } |
| 3876 | |
| 3877 | //******************** End of __WINDOWS_ASIO__ *********************// |
| 3878 | #endif |
| 3879 | |
| 3880 | |
| 3881 | #if defined(__WINDOWS_WASAPI__) // Windows WASAPI API |
| 3882 | |
| 3883 | // Authored by Marcus Tomlinson <[email protected]>, April 2014 |
| 3884 | // - Introduces support for the Windows WASAPI API |
| 3885 | // - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required |
| 3886 | // - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface |
| 3887 | // - Includes automatic internal conversion of sample rate and buffer size between hardware and the user |
| 3888 | |
| 3889 | #ifndef INITGUID |
| 3890 | #define INITGUID |
| 3891 | #endif |
| 3892 | |
| 3893 | #include <mfapi.h> |
| 3894 | #include <mferror.h> |
| 3895 | #include <mfplay.h> |
| 3896 | #include <mftransform.h> |
| 3897 | #include <wmcodecdsp.h> |
| 3898 | |
| 3899 | #include <audioclient.h> |
| 3900 | #include <avrt.h> |
| 3901 | #include <mmdeviceapi.h> |
| 3902 | #include <functiondiscoverykeys_devpkey.h> |
| 3903 | |
| 3904 | #ifndef MF_E_TRANSFORM_NEED_MORE_INPUT |
| 3905 | #define MF_E_TRANSFORM_NEED_MORE_INPUT _HRESULT_TYPEDEF_(0xc00d6d72) |
| 3906 | #endif |
| 3907 | |
| 3908 | #ifndef MFSTARTUP_NOSOCKET |
| 3909 | #define MFSTARTUP_NOSOCKET 0x1 |
| 3910 | #endif |
| 3911 | |
| 3912 | #ifdef _MSC_VER |
| 3913 | #pragma comment( lib, "ksuser" ) |
| 3914 | #pragma comment( lib, "mfplat.lib" ) |
| 3915 | #pragma comment( lib, "mfuuid.lib" ) |
| 3916 | #pragma comment( lib, "wmcodecdspuuid" ) |
| 3917 | #endif |
| 3918 | |
| 3919 | //============================================================================= |
| 3920 | |
| 3921 | #define CK_SAFE_RELEASE( objectPtr )\ |
| 3922 | if ( objectPtr )\ |
| 3923 | {\ |
| 3924 | objectPtr->Release();\ |
| 3925 | objectPtr = NULL;\ |
| 3926 | } |
| 3927 | |
| 3928 | typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex ); |
| 3929 | |
| 3930 | #ifndef __IAudioClient3_INTERFACE_DEFINED__ |
| 3931 | MIDL_INTERFACE( "00000000-0000-0000-0000-000000000000" ) IAudioClient3 |
| 3932 | { |
| 3933 | virtual HRESULT GetSharedModeEnginePeriod( WAVEFORMATEX*, UINT32*, UINT32*, UINT32*, UINT32* ) = 0; |
| 3934 | virtual HRESULT InitializeSharedAudioStream( DWORD, UINT32, WAVEFORMATEX*, LPCGUID ) = 0; |
| 3935 | }; |
| 3936 | #ifdef __CRT_UUID_DECL |
| 3937 | __CRT_UUID_DECL( IAudioClient3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) |
| 3938 | #endif |
| 3939 | #endif |
| 3940 | |
| 3941 | //----------------------------------------------------------------------------- |
| 3942 | |
| 3943 | // WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size. |
| 3944 | // Therefore we must perform all necessary conversions to user buffers in order to satisfy these |
| 3945 | // requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to |
| 3946 | // provide intermediate storage for read / write synchronization. |
| 3947 | class WasapiBuffer |
| 3948 | { |
| 3949 | public: |
| 3950 | WasapiBuffer() |
| 3951 | : buffer_( NULL ), |
| 3952 | bufferSize_( 0 ), |
| 3953 | inIndex_( 0 ), |
| 3954 | outIndex_( 0 ) {} |
| 3955 | |
| 3956 | ~WasapiBuffer() { |
| 3957 | free( buffer_ ); |
| 3958 | } |
| 3959 | |
| 3960 | // sets the length of the internal ring buffer |
| 3961 | void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) { |
| 3962 | free( buffer_ ); |
| 3963 | |
| 3964 | buffer_ = ( char* ) calloc( bufferSize, formatBytes ); |
| 3965 | |
| 3966 | bufferSize_ = bufferSize; |
| 3967 | inIndex_ = 0; |
| 3968 | outIndex_ = 0; |
| 3969 | } |
| 3970 | |
| 3971 | // attempt to push a buffer into the ring buffer at the current "in" index |
| 3972 | bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format ) |
| 3973 | { |
| 3974 | if ( !buffer || // incoming buffer is NULL |
| 3975 | bufferSize == 0 || // incoming buffer has no data |
| 3976 | bufferSize > bufferSize_ ) // incoming buffer too large |
| 3977 | { |
| 3978 | return false; |
| 3979 | } |
| 3980 | |
| 3981 | unsigned int relOutIndex = outIndex_; |
| 3982 | unsigned int inIndexEnd = inIndex_ + bufferSize; |
| 3983 | if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) { |
| 3984 | relOutIndex += bufferSize_; |
| 3985 | } |
| 3986 | |
| 3987 | // the "IN" index CAN BEGIN at the "OUT" index |
| 3988 | // the "IN" index CANNOT END at the "OUT" index |
| 3989 | if ( inIndex_ < relOutIndex && inIndexEnd >= relOutIndex ) { |
| 3990 | return false; // not enough space between "in" index and "out" index |
| 3991 | } |
| 3992 | |
| 3993 | // copy buffer from external to internal |
| 3994 | int fromZeroSize = inIndex_ + bufferSize - bufferSize_; |
| 3995 | fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize; |
| 3996 | int fromInSize = bufferSize - fromZeroSize; |
| 3997 | |
| 3998 | switch( format ) |
| 3999 | { |
| 4000 | case RTAUDIO_SINT8: |
| 4001 | memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) ); |
| 4002 | memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) ); |
| 4003 | break; |
| 4004 | case RTAUDIO_SINT16: |
| 4005 | memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) ); |
| 4006 | memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) ); |
| 4007 | break; |
| 4008 | case RTAUDIO_SINT24: |
| 4009 | memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) ); |
| 4010 | memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) ); |
| 4011 | break; |
| 4012 | case RTAUDIO_SINT32: |
| 4013 | memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) ); |
| 4014 | memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) ); |
| 4015 | break; |
| 4016 | case RTAUDIO_FLOAT32: |
| 4017 | memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) ); |
| 4018 | memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) ); |
| 4019 | break; |
| 4020 | case RTAUDIO_FLOAT64: |
| 4021 | memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) ); |
| 4022 | memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) ); |
| 4023 | break; |
| 4024 | } |
| 4025 | |
| 4026 | // update "in" index |
| 4027 | inIndex_ += bufferSize; |
| 4028 | inIndex_ %= bufferSize_; |
| 4029 | |
| 4030 | return true; |
| 4031 | } |
| 4032 | |
| 4033 | // attempt to pull a buffer from the ring buffer from the current "out" index |
| 4034 | bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format ) |
| 4035 | { |
| 4036 | if ( !buffer || // incoming buffer is NULL |
| 4037 | bufferSize == 0 || // incoming buffer has no data |
| 4038 | bufferSize > bufferSize_ ) // incoming buffer too large |
| 4039 | { |
| 4040 | return false; |
| 4041 | } |
| 4042 | |
| 4043 | unsigned int relInIndex = inIndex_; |
| 4044 | unsigned int outIndexEnd = outIndex_ + bufferSize; |
| 4045 | if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) { |
| 4046 | relInIndex += bufferSize_; |
| 4047 | } |
| 4048 | |
| 4049 | // the "OUT" index CANNOT BEGIN at the "IN" index |
| 4050 | // the "OUT" index CAN END at the "IN" index |
| 4051 | if ( outIndex_ <= relInIndex && outIndexEnd > relInIndex ) { |
| 4052 | return false; // not enough space between "out" index and "in" index |
| 4053 | } |
| 4054 | |
| 4055 | // copy buffer from internal to external |
| 4056 | int fromZeroSize = outIndex_ + bufferSize - bufferSize_; |
| 4057 | fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize; |
| 4058 | int fromOutSize = bufferSize - fromZeroSize; |
| 4059 | |
| 4060 | switch( format ) |
| 4061 | { |
| 4062 | case RTAUDIO_SINT8: |
| 4063 | memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) ); |
| 4064 | memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) ); |
| 4065 | break; |
| 4066 | case RTAUDIO_SINT16: |
| 4067 | memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) ); |
| 4068 | memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) ); |
| 4069 | break; |
| 4070 | case RTAUDIO_SINT24: |
| 4071 | memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) ); |
| 4072 | memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) ); |
| 4073 | break; |
| 4074 | case RTAUDIO_SINT32: |
| 4075 | memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) ); |
| 4076 | memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) ); |
| 4077 | break; |
| 4078 | case RTAUDIO_FLOAT32: |
| 4079 | memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) ); |
| 4080 | memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) ); |
| 4081 | break; |
| 4082 | case RTAUDIO_FLOAT64: |
| 4083 | memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) ); |
| 4084 | memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) ); |
| 4085 | break; |
| 4086 | } |
| 4087 | |
| 4088 | // update "out" index |
| 4089 | outIndex_ += bufferSize; |
| 4090 | outIndex_ %= bufferSize_; |
| 4091 | |
| 4092 | return true; |
| 4093 | } |
| 4094 | |
| 4095 | private: |
| 4096 | char* buffer_; |
| 4097 | unsigned int bufferSize_; |
| 4098 | unsigned int inIndex_; |
| 4099 | unsigned int outIndex_; |
| 4100 | }; |
| 4101 | |
| 4102 | //----------------------------------------------------------------------------- |
| 4103 | |
| 4104 | // In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate |
| 4105 | // between HW and the user. The WasapiResampler class is used to perform this conversion between |
| 4106 | // HwIn->UserIn and UserOut->HwOut during the stream callback loop. |
| 4107 | class WasapiResampler |
| 4108 | { |
| 4109 | public: |
| 4110 | WasapiResampler( bool isFloat, unsigned int bitsPerSample, unsigned int channelCount, |
| 4111 | unsigned int inSampleRate, unsigned int outSampleRate ) |
| 4112 | : _bytesPerSample( bitsPerSample / 8 ) |
| 4113 | , _channelCount( channelCount ) |
| 4114 | , _sampleRatio( ( float ) outSampleRate / inSampleRate ) |
| 4115 | , _transformUnk( NULL ) |
| 4116 | , _transform( NULL ) |
| 4117 | , _mediaType( NULL ) |
| 4118 | , _inputMediaType( NULL ) |
| 4119 | , _outputMediaType( NULL ) |
| 4120 | |
| 4121 | #ifdef __IWMResamplerProps_FWD_DEFINED__ |
| 4122 | , _resamplerProps( NULL ) |
| 4123 | #endif |
| 4124 | { |
| 4125 | // 1. Initialization |
| 4126 | |
| 4127 | MFStartup( MF_VERSION, MFSTARTUP_NOSOCKET ); |
| 4128 | |
| 4129 | // 2. Create Resampler Transform Object |
| 4130 | |
| 4131 | CoCreateInstance( CLSID_CResamplerMediaObject, NULL, CLSCTX_INPROC_SERVER, |
| 4132 | IID_IUnknown, ( void** ) &_transformUnk ); |
| 4133 | |
| 4134 | _transformUnk->QueryInterface( IID_PPV_ARGS( &_transform ) ); |
| 4135 | |
| 4136 | #ifdef __IWMResamplerProps_FWD_DEFINED__ |
| 4137 | _transformUnk->QueryInterface( IID_PPV_ARGS( &_resamplerProps ) ); |
| 4138 | _resamplerProps->SetHalfFilterLength( 60 ); // best conversion quality |
| 4139 | #endif |
| 4140 | |
| 4141 | // 3. Specify input / output format |
| 4142 | |
| 4143 | MFCreateMediaType( &_mediaType ); |
| 4144 | _mediaType->SetGUID( MF_MT_MAJOR_TYPE, MFMediaType_Audio ); |
| 4145 | _mediaType->SetGUID( MF_MT_SUBTYPE, isFloat ? MFAudioFormat_Float : MFAudioFormat_PCM ); |
| 4146 | _mediaType->SetUINT32( MF_MT_AUDIO_NUM_CHANNELS, channelCount ); |
| 4147 | _mediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, inSampleRate ); |
| 4148 | _mediaType->SetUINT32( MF_MT_AUDIO_BLOCK_ALIGNMENT, _bytesPerSample * channelCount ); |
| 4149 | _mediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * inSampleRate ); |
| 4150 | _mediaType->SetUINT32( MF_MT_AUDIO_BITS_PER_SAMPLE, bitsPerSample ); |
| 4151 | _mediaType->SetUINT32( MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE ); |
| 4152 | |
| 4153 | MFCreateMediaType( &_inputMediaType ); |
| 4154 | _mediaType->CopyAllItems( _inputMediaType ); |
| 4155 | |
| 4156 | _transform->SetInputType( 0, _inputMediaType, 0 ); |
| 4157 | |
| 4158 | MFCreateMediaType( &_outputMediaType ); |
| 4159 | _mediaType->CopyAllItems( _outputMediaType ); |
| 4160 | |
| 4161 | _outputMediaType->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, outSampleRate ); |
| 4162 | _outputMediaType->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, _bytesPerSample * channelCount * outSampleRate ); |
| 4163 | |
| 4164 | _transform->SetOutputType( 0, _outputMediaType, 0 ); |
| 4165 | |
| 4166 | // 4. Send stream start messages to Resampler |
| 4167 | |
| 4168 | _transform->ProcessMessage( MFT_MESSAGE_COMMAND_FLUSH, 0 ); |
| 4169 | _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0 ); |
| 4170 | _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0 ); |
| 4171 | } |
| 4172 | |
| 4173 | ~WasapiResampler() |
| 4174 | { |
| 4175 | // 8. Send stream stop messages to Resampler |
| 4176 | |
| 4177 | _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0 ); |
| 4178 | _transform->ProcessMessage( MFT_MESSAGE_NOTIFY_END_STREAMING, 0 ); |
| 4179 | |
| 4180 | // 9. Cleanup |
| 4181 | |
| 4182 | MFShutdown(); |
| 4183 | |
| 4184 | CK_SAFE_RELEASE( _transformUnk ); |
| 4185 | CK_SAFE_RELEASE( _transform ); |
| 4186 | CK_SAFE_RELEASE( _mediaType ); |
| 4187 | CK_SAFE_RELEASE( _inputMediaType ); |
| 4188 | CK_SAFE_RELEASE( _outputMediaType ); |
| 4189 | |
| 4190 | #ifdef __IWMResamplerProps_FWD_DEFINED__ |
| 4191 | CK_SAFE_RELEASE( _resamplerProps ); |
| 4192 | #endif |
| 4193 | } |
| 4194 | |
| 4195 | void Convert( char* outBuffer, const char* inBuffer, unsigned int inSampleCount, unsigned int& outSampleCount, int maxOutSampleCount = -1 ) |
| 4196 | { |
| 4197 | unsigned int inputBufferSize = _bytesPerSample * _channelCount * inSampleCount; |
| 4198 | if ( _sampleRatio == 1 ) |
| 4199 | { |
| 4200 | // no sample rate conversion required |
| 4201 | memcpy( outBuffer, inBuffer, inputBufferSize ); |
| 4202 | outSampleCount = inSampleCount; |
| 4203 | return; |
| 4204 | } |
| 4205 | |
| 4206 | unsigned int outputBufferSize = 0; |
| 4207 | if ( maxOutSampleCount != -1 ) |
| 4208 | { |
| 4209 | outputBufferSize = _bytesPerSample * _channelCount * maxOutSampleCount; |
| 4210 | } |
| 4211 | else |
| 4212 | { |
| 4213 | outputBufferSize = ( unsigned int ) ceilf( inputBufferSize * _sampleRatio ) + ( _bytesPerSample * _channelCount ); |
| 4214 | } |
| 4215 | |
| 4216 | IMFMediaBuffer* rInBuffer; |
| 4217 | IMFSample* rInSample; |
| 4218 | BYTE* rInByteBuffer = NULL; |
| 4219 | |
| 4220 | // 5. Create Sample object from input data |
| 4221 | |
| 4222 | MFCreateMemoryBuffer( inputBufferSize, &rInBuffer ); |
| 4223 | |
| 4224 | rInBuffer->Lock( &rInByteBuffer, NULL, NULL ); |
| 4225 | memcpy( rInByteBuffer, inBuffer, inputBufferSize ); |
| 4226 | rInBuffer->Unlock(); |
| 4227 | rInByteBuffer = NULL; |
| 4228 | |
| 4229 | rInBuffer->SetCurrentLength( inputBufferSize ); |
| 4230 | |
| 4231 | MFCreateSample( &rInSample ); |
| 4232 | rInSample->AddBuffer( rInBuffer ); |
| 4233 | |
| 4234 | // 6. Pass input data to Resampler |
| 4235 | |
| 4236 | _transform->ProcessInput( 0, rInSample, 0 ); |
| 4237 | |
| 4238 | CK_SAFE_RELEASE( rInBuffer ); |
| 4239 | CK_SAFE_RELEASE( rInSample ); |
| 4240 | |
| 4241 | // 7. Perform sample rate conversion |
| 4242 | |
| 4243 | IMFMediaBuffer* rOutBuffer = NULL; |
| 4244 | BYTE* rOutByteBuffer = NULL; |
| 4245 | |
| 4246 | MFT_OUTPUT_DATA_BUFFER rOutDataBuffer; |
| 4247 | DWORD rStatus; |
| 4248 | DWORD rBytes = outputBufferSize; // maximum bytes accepted per ProcessOutput |
| 4249 | |
| 4250 | // 7.1 Create Sample object for output data |
| 4251 | |
| 4252 | memset( &rOutDataBuffer, 0, sizeof rOutDataBuffer ); |
| 4253 | MFCreateSample( &( rOutDataBuffer.pSample ) ); |
| 4254 | MFCreateMemoryBuffer( rBytes, &rOutBuffer ); |
| 4255 | rOutDataBuffer.pSample->AddBuffer( rOutBuffer ); |
| 4256 | rOutDataBuffer.dwStreamID = 0; |
| 4257 | rOutDataBuffer.dwStatus = 0; |
| 4258 | rOutDataBuffer.pEvents = NULL; |
| 4259 | |
| 4260 | // 7.2 Get output data from Resampler |
| 4261 | |
| 4262 | if ( _transform->ProcessOutput( 0, 1, &rOutDataBuffer, &rStatus ) == MF_E_TRANSFORM_NEED_MORE_INPUT ) |
| 4263 | { |
| 4264 | outSampleCount = 0; |
| 4265 | CK_SAFE_RELEASE( rOutBuffer ); |
| 4266 | CK_SAFE_RELEASE( rOutDataBuffer.pSample ); |
| 4267 | return; |
| 4268 | } |
| 4269 | |
| 4270 | // 7.3 Write output data to outBuffer |
| 4271 | |
| 4272 | CK_SAFE_RELEASE( rOutBuffer ); |
| 4273 | rOutDataBuffer.pSample->ConvertToContiguousBuffer( &rOutBuffer ); |
| 4274 | rOutBuffer->GetCurrentLength( &rBytes ); |
| 4275 | |
| 4276 | rOutBuffer->Lock( &rOutByteBuffer, NULL, NULL ); |
| 4277 | memcpy( outBuffer, rOutByteBuffer, rBytes ); |
| 4278 | rOutBuffer->Unlock(); |
| 4279 | rOutByteBuffer = NULL; |
| 4280 | |
| 4281 | outSampleCount = rBytes / _bytesPerSample / _channelCount; |
| 4282 | CK_SAFE_RELEASE( rOutBuffer ); |
| 4283 | CK_SAFE_RELEASE( rOutDataBuffer.pSample ); |
| 4284 | } |
| 4285 | |
| 4286 | private: |
| 4287 | unsigned int _bytesPerSample; |
| 4288 | unsigned int _channelCount; |
| 4289 | float _sampleRatio; |
| 4290 | |
| 4291 | IUnknown* _transformUnk; |
| 4292 | IMFTransform* _transform; |
| 4293 | IMFMediaType* _mediaType; |
| 4294 | IMFMediaType* _inputMediaType; |
| 4295 | IMFMediaType* _outputMediaType; |
| 4296 | |
| 4297 | #ifdef __IWMResamplerProps_FWD_DEFINED__ |
| 4298 | IWMResamplerProps* _resamplerProps; |
| 4299 | #endif |
| 4300 | }; |
| 4301 | |
| 4302 | //----------------------------------------------------------------------------- |
| 4303 | |
| 4304 | // A structure to hold various information related to the WASAPI implementation. |
| 4305 | struct WasapiHandle |
| 4306 | { |
| 4307 | IAudioClient* captureAudioClient; |
| 4308 | IAudioClient* renderAudioClient; |
| 4309 | IAudioCaptureClient* captureClient; |
| 4310 | IAudioRenderClient* renderClient; |
| 4311 | HANDLE captureEvent; |
| 4312 | HANDLE renderEvent; |
| 4313 | |
| 4314 | WasapiHandle() |
| 4315 | : captureAudioClient( NULL ), |
| 4316 | renderAudioClient( NULL ), |
| 4317 | captureClient( NULL ), |
| 4318 | renderClient( NULL ), |
| 4319 | captureEvent( NULL ), |
| 4320 | renderEvent( NULL ) {} |
| 4321 | }; |
| 4322 | |
| 4323 | //============================================================================= |
| 4324 | |
| 4325 | RtApiWasapi::RtApiWasapi() |
| 4326 | : coInitialized_( false ), deviceEnumerator_( NULL ) |
| 4327 | { |
| 4328 | // WASAPI can run either apartment or multi-threaded |
| 4329 | HRESULT hr = CoInitialize( NULL ); |
| 4330 | if ( !FAILED( hr ) ) |
| 4331 | coInitialized_ = true; |
| 4332 | |
| 4333 | // Instantiate device enumerator |
| 4334 | hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL, |
| 4335 | CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ), |
| 4336 | ( void** ) &deviceEnumerator_ ); |
| 4337 | |
| 4338 | // If this runs on an old Windows, it will fail. Ignore and proceed. |
| 4339 | if ( FAILED( hr ) ) |
| 4340 | deviceEnumerator_ = NULL; |
| 4341 | } |
| 4342 | |
| 4343 | //----------------------------------------------------------------------------- |
| 4344 | |
| 4345 | RtApiWasapi::~RtApiWasapi() |
| 4346 | { |
| 4347 | if ( stream_.state != STREAM_CLOSED ) |
| 4348 | closeStream(); |
| 4349 | |
| 4350 | CK_SAFE_RELEASE( deviceEnumerator_ ); |
| 4351 | |
| 4352 | // If this object previously called CoInitialize() |
| 4353 | if ( coInitialized_ ) |
| 4354 | CoUninitialize(); |
| 4355 | } |
| 4356 | |
| 4357 | //============================================================================= |
| 4358 | |
| 4359 | unsigned int RtApiWasapi::getDeviceCount( void ) |
| 4360 | { |
| 4361 | unsigned int captureDeviceCount = 0; |
| 4362 | unsigned int renderDeviceCount = 0; |
| 4363 | |
| 4364 | IMMDeviceCollection* captureDevices = NULL; |
| 4365 | IMMDeviceCollection* renderDevices = NULL; |
| 4366 | |
| 4367 | if ( !deviceEnumerator_ ) |
| 4368 | return 0; |
| 4369 | |
| 4370 | // Count capture devices |
| 4371 | errorText_.clear(); |
| 4372 | HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices ); |
| 4373 | if ( FAILED( hr ) ) { |
| 4374 | errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection."; |
| 4375 | goto Exit; |
| 4376 | } |
| 4377 | |
| 4378 | hr = captureDevices->GetCount( &captureDeviceCount ); |
| 4379 | if ( FAILED( hr ) ) { |
| 4380 | errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count."; |
| 4381 | goto Exit; |
| 4382 | } |
| 4383 | |
| 4384 | // Count render devices |
| 4385 | hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices ); |
| 4386 | if ( FAILED( hr ) ) { |
| 4387 | errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection."; |
| 4388 | goto Exit; |
| 4389 | } |
| 4390 | |
| 4391 | hr = renderDevices->GetCount( &renderDeviceCount ); |
| 4392 | if ( FAILED( hr ) ) { |
| 4393 | errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count."; |
| 4394 | goto Exit; |
| 4395 | } |
| 4396 | |
| 4397 | Exit: |
| 4398 | // release all references |
| 4399 | CK_SAFE_RELEASE( captureDevices ); |
| 4400 | CK_SAFE_RELEASE( renderDevices ); |
| 4401 | |
| 4402 | if ( errorText_.empty() ) |
| 4403 | return captureDeviceCount + renderDeviceCount; |
| 4404 | |
| 4405 | error( RTAUDIO_DRIVER_ERROR ); |
| 4406 | return 0; |
| 4407 | } |
| 4408 | |
| 4409 | //----------------------------------------------------------------------------- |
| 4410 | |
| 4411 | RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device ) |
| 4412 | { |
| 4413 | RtAudio::DeviceInfo info; |
| 4414 | unsigned int captureDeviceCount = 0; |
| 4415 | unsigned int renderDeviceCount = 0; |
| 4416 | std::string defaultDeviceName; |
| 4417 | bool isCaptureDevice = false; |
| 4418 | |
| 4419 | PROPVARIANT deviceNameProp; |
| 4420 | PROPVARIANT defaultDeviceNameProp; |
| 4421 | |
| 4422 | IMMDeviceCollection* captureDevices = NULL; |
| 4423 | IMMDeviceCollection* renderDevices = NULL; |
| 4424 | IMMDevice* devicePtr = NULL; |
| 4425 | IMMDevice* defaultDevicePtr = NULL; |
| 4426 | IAudioClient* audioClient = NULL; |
| 4427 | IPropertyStore* devicePropStore = NULL; |
| 4428 | IPropertyStore* defaultDevicePropStore = NULL; |
| 4429 | |
| 4430 | WAVEFORMATEX* deviceFormat = NULL; |
| 4431 | WAVEFORMATEX* closestMatchFormat = NULL; |
| 4432 | |
| 4433 | // probed |
| 4434 | info.probed = false; |
| 4435 | |
| 4436 | // Count capture devices |
| 4437 | errorText_.clear(); |
| 4438 | RtAudioErrorType errorType = RTAUDIO_DRIVER_ERROR; |
| 4439 | HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices ); |
| 4440 | if ( FAILED( hr ) ) { |
| 4441 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection."; |
| 4442 | goto Exit; |
| 4443 | } |
| 4444 | |
| 4445 | hr = captureDevices->GetCount( &captureDeviceCount ); |
| 4446 | if ( FAILED( hr ) ) { |
| 4447 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count."; |
| 4448 | goto Exit; |
| 4449 | } |
| 4450 | |
| 4451 | // Count render devices |
| 4452 | hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices ); |
| 4453 | if ( FAILED( hr ) ) { |
| 4454 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection."; |
| 4455 | goto Exit; |
| 4456 | } |
| 4457 | |
| 4458 | hr = renderDevices->GetCount( &renderDeviceCount ); |
| 4459 | if ( FAILED( hr ) ) { |
| 4460 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count."; |
| 4461 | goto Exit; |
| 4462 | } |
| 4463 | |
| 4464 | // validate device index |
| 4465 | if ( device >= captureDeviceCount + renderDeviceCount ) { |
| 4466 | errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index."; |
| 4467 | errorType = RTAUDIO_INVALID_USE; |
| 4468 | goto Exit; |
| 4469 | } |
| 4470 | |
| 4471 | // determine whether index falls within capture or render devices |
| 4472 | if ( device >= renderDeviceCount ) { |
| 4473 | hr = captureDevices->Item( device - renderDeviceCount, &devicePtr ); |
| 4474 | if ( FAILED( hr ) ) { |
| 4475 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle."; |
| 4476 | goto Exit; |
| 4477 | } |
| 4478 | isCaptureDevice = true; |
| 4479 | } |
| 4480 | else { |
| 4481 | hr = renderDevices->Item( device, &devicePtr ); |
| 4482 | if ( FAILED( hr ) ) { |
| 4483 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle."; |
| 4484 | goto Exit; |
| 4485 | } |
| 4486 | isCaptureDevice = false; |
| 4487 | } |
| 4488 | |
| 4489 | // get default device name |
| 4490 | if ( isCaptureDevice ) { |
| 4491 | hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr ); |
| 4492 | if ( FAILED( hr ) ) { |
| 4493 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle."; |
| 4494 | goto Exit; |
| 4495 | } |
| 4496 | } |
| 4497 | else { |
| 4498 | hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr ); |
| 4499 | if ( FAILED( hr ) ) { |
| 4500 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle."; |
| 4501 | goto Exit; |
| 4502 | } |
| 4503 | } |
| 4504 | |
| 4505 | hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore ); |
| 4506 | if ( FAILED( hr ) ) { |
| 4507 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store."; |
| 4508 | goto Exit; |
| 4509 | } |
| 4510 | PropVariantInit( &defaultDeviceNameProp ); |
| 4511 | |
| 4512 | hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp ); |
| 4513 | if ( FAILED( hr ) ) { |
| 4514 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName."; |
| 4515 | goto Exit; |
| 4516 | } |
| 4517 | |
| 4518 | defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal); |
| 4519 | |
| 4520 | // name |
| 4521 | hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore ); |
| 4522 | if ( FAILED( hr ) ) { |
| 4523 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store."; |
| 4524 | goto Exit; |
| 4525 | } |
| 4526 | |
| 4527 | PropVariantInit( &deviceNameProp ); |
| 4528 | |
| 4529 | hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp ); |
| 4530 | if ( FAILED( hr ) ) { |
| 4531 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName."; |
| 4532 | goto Exit; |
| 4533 | } |
| 4534 | |
| 4535 | info.name =convertCharPointerToStdString(deviceNameProp.pwszVal); |
| 4536 | |
| 4537 | // is default |
| 4538 | if ( isCaptureDevice ) { |
| 4539 | info.isDefaultInput = info.name == defaultDeviceName; |
| 4540 | info.isDefaultOutput = false; |
| 4541 | } |
| 4542 | else { |
| 4543 | info.isDefaultInput = false; |
| 4544 | info.isDefaultOutput = info.name == defaultDeviceName; |
| 4545 | } |
| 4546 | |
| 4547 | // channel count |
| 4548 | hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient ); |
| 4549 | if ( FAILED( hr ) ) { |
| 4550 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client."; |
| 4551 | goto Exit; |
| 4552 | } |
| 4553 | |
| 4554 | hr = audioClient->GetMixFormat( &deviceFormat ); |
| 4555 | if ( FAILED( hr ) ) { |
| 4556 | errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format."; |
| 4557 | goto Exit; |
| 4558 | } |
| 4559 | |
| 4560 | if ( isCaptureDevice ) { |
| 4561 | info.inputChannels = deviceFormat->nChannels; |
| 4562 | info.outputChannels = 0; |
| 4563 | info.duplexChannels = 0; |
| 4564 | } |
| 4565 | else { |
| 4566 | info.inputChannels = 0; |
| 4567 | info.outputChannels = deviceFormat->nChannels; |
| 4568 | info.duplexChannels = 0; |
| 4569 | } |
| 4570 | |
| 4571 | // sample rates |
| 4572 | info.sampleRates.clear(); |
| 4573 | |
| 4574 | // allow support for all sample rates as we have a built-in sample rate converter |
| 4575 | for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) { |
| 4576 | info.sampleRates.push_back( SAMPLE_RATES[i] ); |
| 4577 | } |
| 4578 | info.preferredSampleRate = deviceFormat->nSamplesPerSec; |
| 4579 | |
| 4580 | // native format |
| 4581 | info.nativeFormats = 0; |
| 4582 | |
| 4583 | if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT || |
| 4584 | ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE && |
| 4585 | ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) ) |
| 4586 | { |
| 4587 | if ( deviceFormat->wBitsPerSample == 32 ) { |
| 4588 | info.nativeFormats |= RTAUDIO_FLOAT32; |
| 4589 | } |
| 4590 | else if ( deviceFormat->wBitsPerSample == 64 ) { |
| 4591 | info.nativeFormats |= RTAUDIO_FLOAT64; |
| 4592 | } |
| 4593 | } |
| 4594 | else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM || |
| 4595 | ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE && |
| 4596 | ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) ) |
| 4597 | { |
| 4598 | if ( deviceFormat->wBitsPerSample == 8 ) { |
| 4599 | info.nativeFormats |= RTAUDIO_SINT8; |
| 4600 | } |
| 4601 | else if ( deviceFormat->wBitsPerSample == 16 ) { |
| 4602 | info.nativeFormats |= RTAUDIO_SINT16; |
| 4603 | } |
| 4604 | else if ( deviceFormat->wBitsPerSample == 24 ) { |
| 4605 | info.nativeFormats |= RTAUDIO_SINT24; |
| 4606 | } |
| 4607 | else if ( deviceFormat->wBitsPerSample == 32 ) { |
| 4608 | info.nativeFormats |= RTAUDIO_SINT32; |
| 4609 | } |
| 4610 | } |
| 4611 | |
| 4612 | // probed |
| 4613 | info.probed = true; |
| 4614 | |
| 4615 | Exit: |
| 4616 | // release all references |
| 4617 | PropVariantClear( &deviceNameProp ); |
| 4618 | PropVariantClear( &defaultDeviceNameProp ); |
| 4619 | |
| 4620 | CK_SAFE_RELEASE( captureDevices ); |
| 4621 | CK_SAFE_RELEASE( renderDevices ); |
| 4622 | CK_SAFE_RELEASE( devicePtr ); |
| 4623 | CK_SAFE_RELEASE( defaultDevicePtr ); |
| 4624 | CK_SAFE_RELEASE( audioClient ); |
| 4625 | CK_SAFE_RELEASE( devicePropStore ); |
| 4626 | CK_SAFE_RELEASE( defaultDevicePropStore ); |
| 4627 | |
| 4628 | CoTaskMemFree( deviceFormat ); |
| 4629 | CoTaskMemFree( closestMatchFormat ); |
| 4630 | |
| 4631 | if ( !errorText_.empty() ) |
| 4632 | error( errorType ); |
| 4633 | return info; |
| 4634 | } |
| 4635 | |
| 4636 | void RtApiWasapi::closeStream( void ) |
| 4637 | { |
| 4638 | if ( stream_.state == STREAM_CLOSED ) { |
| 4639 | errorText_ = "RtApiWasapi::closeStream: No open stream to close."; |
| 4640 | error( RTAUDIO_WARNING ); |
| 4641 | return; |
| 4642 | } |
| 4643 | |
| 4644 | if ( stream_.state != STREAM_STOPPED ) |
| 4645 | stopStream(); |
| 4646 | |
| 4647 | // clean up stream memory |
| 4648 | CK_SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) |
| 4649 | CK_SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) |
| 4650 | |
| 4651 | CK_SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient ) |
| 4652 | CK_SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient ) |
| 4653 | |
| 4654 | if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent ) |
| 4655 | CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent ); |
| 4656 | |
| 4657 | if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent ) |
| 4658 | CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent ); |
| 4659 | |
| 4660 | delete ( WasapiHandle* ) stream_.apiHandle; |
| 4661 | stream_.apiHandle = NULL; |
| 4662 | |
| 4663 | for ( int i = 0; i < 2; i++ ) { |
| 4664 | if ( stream_.userBuffer[i] ) { |
| 4665 | free( stream_.userBuffer[i] ); |
| 4666 | stream_.userBuffer[i] = 0; |
| 4667 | } |
| 4668 | } |
| 4669 | |
| 4670 | if ( stream_.deviceBuffer ) { |
| 4671 | free( stream_.deviceBuffer ); |
| 4672 | stream_.deviceBuffer = 0; |
| 4673 | } |
| 4674 | |
| 4675 | clearStreamInfo(); |
| 4676 | //stream_.state = STREAM_CLOSED; |
| 4677 | } |
| 4678 | |
| 4679 | //----------------------------------------------------------------------------- |
| 4680 | |
| 4681 | RtAudioErrorType RtApiWasapi::startStream( void ) |
| 4682 | { |
| 4683 | if ( stream_.state != STREAM_STOPPED ) { |
| 4684 | if ( stream_.state == STREAM_RUNNING ) |
| 4685 | errorText_ = "RtApiWasapi::startStream(): the stream is already running!"; |
| 4686 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 4687 | errorText_ = "RtApiWasapi::startStream(): the stream is stopping or closed!"; |
| 4688 | return error( RTAUDIO_WARNING ); |
| 4689 | } |
| 4690 | |
| 4691 | /* |
| 4692 | #if defined( HAVE_GETTIMEOFDAY ) |
| 4693 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 4694 | #endif |
| 4695 | */ |
| 4696 | |
| 4697 | // update stream state |
| 4698 | stream_.state = STREAM_RUNNING; |
| 4699 | |
| 4700 | // create WASAPI stream thread |
| 4701 | stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL ); |
| 4702 | |
| 4703 | if ( !stream_.callbackInfo.thread ) { |
| 4704 | errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread."; |
| 4705 | return error( RTAUDIO_THREAD_ERROR ); |
| 4706 | } |
| 4707 | else { |
| 4708 | SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority ); |
| 4709 | ResumeThread( ( void* ) stream_.callbackInfo.thread ); |
| 4710 | } |
| 4711 | return RTAUDIO_NO_ERROR; |
| 4712 | } |
| 4713 | |
| 4714 | //----------------------------------------------------------------------------- |
| 4715 | |
| 4716 | RtAudioErrorType RtApiWasapi::stopStream( void ) |
| 4717 | { |
| 4718 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 4719 | if ( stream_.state == STREAM_STOPPED ) |
| 4720 | errorText_ = "RtApiWasapi::stopStream(): the stream is already stopped!"; |
| 4721 | else if ( stream_.state == STREAM_CLOSED ) |
| 4722 | errorText_ = "RtApiWasapi::stopStream(): the stream is closed!"; |
| 4723 | return error( RTAUDIO_WARNING ); |
| 4724 | } |
| 4725 | |
| 4726 | // inform stream thread by setting stream state to STREAM_STOPPING |
| 4727 | stream_.state = STREAM_STOPPING; |
| 4728 | |
| 4729 | WaitForSingleObject( ( void* ) stream_.callbackInfo.thread, INFINITE ); |
| 4730 | |
| 4731 | // close thread handle |
| 4732 | if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) { |
| 4733 | errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread."; |
| 4734 | return error( RTAUDIO_THREAD_ERROR ); |
| 4735 | } |
| 4736 | |
| 4737 | stream_.callbackInfo.thread = (ThreadHandle) NULL; |
| 4738 | return RTAUDIO_NO_ERROR; |
| 4739 | } |
| 4740 | |
| 4741 | //----------------------------------------------------------------------------- |
| 4742 | |
| 4743 | RtAudioErrorType RtApiWasapi::abortStream( void ) |
| 4744 | { |
| 4745 | if ( stream_.state != STREAM_RUNNING ) { |
| 4746 | if ( stream_.state == STREAM_STOPPED ) |
| 4747 | errorText_ = "RtApiWasapi::abortStream(): the stream is already stopped!"; |
| 4748 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 4749 | errorText_ = "RtApiWasapi::abortStream(): the stream is stopping or closed!"; |
| 4750 | return error( RTAUDIO_WARNING ); |
| 4751 | } |
| 4752 | |
| 4753 | // inform stream thread by setting stream state to STREAM_STOPPING |
| 4754 | stream_.state = STREAM_STOPPING; |
| 4755 | |
| 4756 | WaitForSingleObject( ( void* ) stream_.callbackInfo.thread, INFINITE ); |
| 4757 | |
| 4758 | // close thread handle |
| 4759 | if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) { |
| 4760 | errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread."; |
| 4761 | return error( RTAUDIO_THREAD_ERROR ); |
| 4762 | } |
| 4763 | |
| 4764 | stream_.callbackInfo.thread = (ThreadHandle) NULL; |
| 4765 | return RTAUDIO_NO_ERROR; |
| 4766 | } |
| 4767 | |
| 4768 | //----------------------------------------------------------------------------- |
| 4769 | |
| 4770 | bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, |
| 4771 | unsigned int firstChannel, unsigned int sampleRate, |
| 4772 | RtAudioFormat format, unsigned int* bufferSize, |
| 4773 | RtAudio::StreamOptions* options ) |
| 4774 | { |
| 4775 | bool methodResult = FAILURE; |
| 4776 | unsigned int captureDeviceCount = 0; |
| 4777 | unsigned int renderDeviceCount = 0; |
| 4778 | |
| 4779 | IMMDeviceCollection* captureDevices = NULL; |
| 4780 | IMMDeviceCollection* renderDevices = NULL; |
| 4781 | IMMDevice* devicePtr = NULL; |
| 4782 | WAVEFORMATEX* deviceFormat = NULL; |
| 4783 | unsigned int bufferBytes; |
| 4784 | stream_.state = STREAM_STOPPED; |
| 4785 | |
| 4786 | // create API Handle if not already created |
| 4787 | if ( !stream_.apiHandle ) |
| 4788 | stream_.apiHandle = ( void* ) new WasapiHandle(); |
| 4789 | |
| 4790 | // Count capture devices |
| 4791 | errorText_.clear(); |
| 4792 | RtAudioErrorType errorType = RTAUDIO_DRIVER_ERROR; |
| 4793 | HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices ); |
| 4794 | if ( FAILED( hr ) ) { |
| 4795 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection."; |
| 4796 | goto Exit; |
| 4797 | } |
| 4798 | |
| 4799 | hr = captureDevices->GetCount( &captureDeviceCount ); |
| 4800 | if ( FAILED( hr ) ) { |
| 4801 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count."; |
| 4802 | goto Exit; |
| 4803 | } |
| 4804 | |
| 4805 | // Count render devices |
| 4806 | hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices ); |
| 4807 | if ( FAILED( hr ) ) { |
| 4808 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection."; |
| 4809 | goto Exit; |
| 4810 | } |
| 4811 | |
| 4812 | hr = renderDevices->GetCount( &renderDeviceCount ); |
| 4813 | if ( FAILED( hr ) ) { |
| 4814 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count."; |
| 4815 | goto Exit; |
| 4816 | } |
| 4817 | |
| 4818 | // validate device index |
| 4819 | if ( device >= captureDeviceCount + renderDeviceCount ) { |
| 4820 | errorType = RTAUDIO_INVALID_USE; |
| 4821 | errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index."; |
| 4822 | goto Exit; |
| 4823 | } |
| 4824 | |
| 4825 | // if device index falls within capture devices |
| 4826 | if ( device >= renderDeviceCount ) { |
| 4827 | if ( mode != INPUT ) { |
| 4828 | errorType = RTAUDIO_INVALID_USE; |
| 4829 | errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device."; |
| 4830 | goto Exit; |
| 4831 | } |
| 4832 | |
| 4833 | // retrieve captureAudioClient from devicePtr |
| 4834 | IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient; |
| 4835 | |
| 4836 | hr = captureDevices->Item( device - renderDeviceCount, &devicePtr ); |
| 4837 | if ( FAILED( hr ) ) { |
| 4838 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle."; |
| 4839 | goto Exit; |
| 4840 | } |
| 4841 | |
| 4842 | hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, |
| 4843 | NULL, ( void** ) &captureAudioClient ); |
| 4844 | if ( FAILED( hr ) ) { |
| 4845 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device audio client."; |
| 4846 | goto Exit; |
| 4847 | } |
| 4848 | |
| 4849 | hr = captureAudioClient->GetMixFormat( &deviceFormat ); |
| 4850 | if ( FAILED( hr ) ) { |
| 4851 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device mix format."; |
| 4852 | goto Exit; |
| 4853 | } |
| 4854 | |
| 4855 | stream_.nDeviceChannels[mode] = deviceFormat->nChannels; |
| 4856 | captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] ); |
| 4857 | } |
| 4858 | |
| 4859 | // if device index falls within render devices and is configured for loopback |
| 4860 | if ( device < renderDeviceCount && mode == INPUT ) |
| 4861 | { |
| 4862 | // if renderAudioClient is not initialised, initialise it now |
| 4863 | IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient; |
| 4864 | if ( !renderAudioClient ) |
| 4865 | { |
| 4866 | probeDeviceOpen( device, OUTPUT, channels, firstChannel, sampleRate, format, bufferSize, options ); |
| 4867 | } |
| 4868 | |
| 4869 | // retrieve captureAudioClient from devicePtr |
| 4870 | IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient; |
| 4871 | |
| 4872 | hr = renderDevices->Item( device, &devicePtr ); |
| 4873 | if ( FAILED( hr ) ) { |
| 4874 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle."; |
| 4875 | goto Exit; |
| 4876 | } |
| 4877 | |
| 4878 | hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, |
| 4879 | NULL, ( void** ) &captureAudioClient ); |
| 4880 | if ( FAILED( hr ) ) { |
| 4881 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client."; |
| 4882 | goto Exit; |
| 4883 | } |
| 4884 | |
| 4885 | hr = captureAudioClient->GetMixFormat( &deviceFormat ); |
| 4886 | if ( FAILED( hr ) ) { |
| 4887 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format."; |
| 4888 | goto Exit; |
| 4889 | } |
| 4890 | |
| 4891 | stream_.nDeviceChannels[mode] = deviceFormat->nChannels; |
| 4892 | captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] ); |
| 4893 | } |
| 4894 | |
| 4895 | // if device index falls within render devices and is configured for output |
| 4896 | if ( device < renderDeviceCount && mode == OUTPUT ) |
| 4897 | { |
| 4898 | // if renderAudioClient is already initialised, don't initialise it again |
| 4899 | IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient; |
| 4900 | if ( renderAudioClient ) |
| 4901 | { |
| 4902 | methodResult = SUCCESS; |
| 4903 | goto Exit; |
| 4904 | } |
| 4905 | |
| 4906 | hr = renderDevices->Item( device, &devicePtr ); |
| 4907 | if ( FAILED( hr ) ) { |
| 4908 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle."; |
| 4909 | goto Exit; |
| 4910 | } |
| 4911 | |
| 4912 | hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, |
| 4913 | NULL, ( void** ) &renderAudioClient ); |
| 4914 | if ( FAILED( hr ) ) { |
| 4915 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device audio client."; |
| 4916 | goto Exit; |
| 4917 | } |
| 4918 | |
| 4919 | hr = renderAudioClient->GetMixFormat( &deviceFormat ); |
| 4920 | if ( FAILED( hr ) ) { |
| 4921 | errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device mix format."; |
| 4922 | goto Exit; |
| 4923 | } |
| 4924 | |
| 4925 | stream_.nDeviceChannels[mode] = deviceFormat->nChannels; |
| 4926 | renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] ); |
| 4927 | } |
| 4928 | |
| 4929 | // fill stream data |
| 4930 | if ( ( stream_.mode == OUTPUT && mode == INPUT ) || |
| 4931 | ( stream_.mode == INPUT && mode == OUTPUT ) ) { |
| 4932 | stream_.mode = DUPLEX; |
| 4933 | } |
| 4934 | else { |
| 4935 | stream_.mode = mode; |
| 4936 | } |
| 4937 | |
| 4938 | stream_.device[mode] = device; |
| 4939 | stream_.doByteSwap[mode] = false; |
| 4940 | stream_.sampleRate = sampleRate; |
| 4941 | stream_.bufferSize = *bufferSize; |
| 4942 | stream_.nBuffers = 1; |
| 4943 | stream_.nUserChannels[mode] = channels; |
| 4944 | stream_.channelOffset[mode] = firstChannel; |
| 4945 | stream_.userFormat = format; |
| 4946 | stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats; |
| 4947 | |
| 4948 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) |
| 4949 | stream_.userInterleaved = false; |
| 4950 | else |
| 4951 | stream_.userInterleaved = true; |
| 4952 | stream_.deviceInterleaved[mode] = true; |
| 4953 | |
| 4954 | // Set flags for buffer conversion. |
| 4955 | stream_.doConvertBuffer[mode] = false; |
| 4956 | if ( stream_.userFormat != stream_.deviceFormat[mode] || |
| 4957 | stream_.nUserChannels[0] != stream_.nDeviceChannels[0] || |
| 4958 | stream_.nUserChannels[1] != stream_.nDeviceChannels[1] ) |
| 4959 | stream_.doConvertBuffer[mode] = true; |
| 4960 | else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] && |
| 4961 | stream_.nUserChannels[mode] > 1 ) |
| 4962 | stream_.doConvertBuffer[mode] = true; |
| 4963 | |
| 4964 | if ( stream_.doConvertBuffer[mode] ) |
| 4965 | setConvertInfo( mode, firstChannel ); |
| 4966 | |
| 4967 | // Allocate necessary internal buffers |
| 4968 | bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat ); |
| 4969 | |
| 4970 | stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 ); |
| 4971 | if ( !stream_.userBuffer[mode] ) { |
| 4972 | errorType = RTAUDIO_MEMORY_ERROR; |
| 4973 | errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory."; |
| 4974 | goto Exit; |
| 4975 | } |
| 4976 | |
| 4977 | if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) |
| 4978 | stream_.callbackInfo.priority = 15; |
| 4979 | else |
| 4980 | stream_.callbackInfo.priority = 0; |
| 4981 | |
| 4982 | ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback |
| 4983 | ///! TODO: RTAUDIO_HOG_DEVICE // Exclusive mode |
| 4984 | |
| 4985 | methodResult = SUCCESS; |
| 4986 | |
| 4987 | Exit: |
| 4988 | //clean up |
| 4989 | CK_SAFE_RELEASE( captureDevices ); |
| 4990 | CK_SAFE_RELEASE( renderDevices ); |
| 4991 | CK_SAFE_RELEASE( devicePtr ); |
| 4992 | CoTaskMemFree( deviceFormat ); |
| 4993 | |
| 4994 | // if method failed, close the stream |
| 4995 | if ( methodResult == FAILURE ) |
| 4996 | closeStream(); |
| 4997 | |
| 4998 | if ( !errorText_.empty() ) |
| 4999 | error( errorType ); |
| 5000 | return methodResult; |
| 5001 | } |
| 5002 | |
| 5003 | //============================================================================= |
| 5004 | |
| 5005 | DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr ) |
| 5006 | { |
| 5007 | if ( wasapiPtr ) |
| 5008 | ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread(); |
| 5009 | |
| 5010 | return 0; |
| 5011 | } |
| 5012 | |
| 5013 | DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr ) |
| 5014 | { |
| 5015 | if ( wasapiPtr ) |
| 5016 | ( ( RtApiWasapi* ) wasapiPtr )->stopStream(); |
| 5017 | |
| 5018 | return 0; |
| 5019 | } |
| 5020 | |
| 5021 | DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr ) |
| 5022 | { |
| 5023 | if ( wasapiPtr ) |
| 5024 | ( ( RtApiWasapi* ) wasapiPtr )->abortStream(); |
| 5025 | |
| 5026 | return 0; |
| 5027 | } |
| 5028 | |
| 5029 | //----------------------------------------------------------------------------- |
| 5030 | |
| 5031 | void RtApiWasapi::wasapiThread() |
| 5032 | { |
| 5033 | // as this is a new thread, we must CoInitialize it |
| 5034 | CoInitialize( NULL ); |
| 5035 | |
| 5036 | HRESULT hr; |
| 5037 | |
| 5038 | IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient; |
| 5039 | IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient; |
| 5040 | IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient; |
| 5041 | IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient; |
| 5042 | HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent; |
| 5043 | HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent; |
| 5044 | |
| 5045 | WAVEFORMATEX* captureFormat = NULL; |
| 5046 | WAVEFORMATEX* renderFormat = NULL; |
| 5047 | float captureSrRatio = 0.0f; |
| 5048 | float renderSrRatio = 0.0f; |
| 5049 | WasapiBuffer captureBuffer; |
| 5050 | WasapiBuffer renderBuffer; |
| 5051 | WasapiResampler* captureResampler = NULL; |
| 5052 | WasapiResampler* renderResampler = NULL; |
| 5053 | |
| 5054 | // declare local stream variables |
| 5055 | RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback; |
| 5056 | BYTE* streamBuffer = NULL; |
| 5057 | DWORD captureFlags = 0; |
| 5058 | unsigned int bufferFrameCount = 0; |
| 5059 | unsigned int numFramesPadding = 0; |
| 5060 | unsigned int convBufferSize = 0; |
| 5061 | bool loopbackEnabled = stream_.device[INPUT] == stream_.device[OUTPUT]; |
| 5062 | bool callbackPushed = true; |
| 5063 | bool callbackPulled = false; |
| 5064 | bool callbackStopped = false; |
| 5065 | int callbackResult = 0; |
| 5066 | |
| 5067 | // convBuffer is used to store converted buffers between WASAPI and the user |
| 5068 | char* convBuffer = NULL; |
| 5069 | unsigned int convBuffSize = 0; |
| 5070 | unsigned int deviceBuffSize = 0; |
| 5071 | |
| 5072 | std::string errorText; |
| 5073 | RtAudioErrorType errorType = RTAUDIO_DRIVER_ERROR; |
| 5074 | |
| 5075 | // Attempt to assign "Pro Audio" characteristic to thread |
| 5076 | HMODULE AvrtDll = LoadLibraryW( L"AVRT.dll" ); |
| 5077 | if ( AvrtDll ) { |
| 5078 | DWORD taskIndex = 0; |
| 5079 | TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = |
| 5080 | ( TAvSetMmThreadCharacteristicsPtr ) (void(*)()) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" ); |
| 5081 | AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex ); |
| 5082 | FreeLibrary( AvrtDll ); |
| 5083 | } |
| 5084 | |
| 5085 | // start capture stream if applicable |
| 5086 | if ( captureAudioClient ) { |
| 5087 | hr = captureAudioClient->GetMixFormat( &captureFormat ); |
| 5088 | if ( FAILED( hr ) ) { |
| 5089 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format."; |
| 5090 | goto Exit; |
| 5091 | } |
| 5092 | |
| 5093 | // init captureResampler |
| 5094 | captureResampler = new WasapiResampler( stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[INPUT] == RTAUDIO_FLOAT64, |
| 5095 | formatBytes( stream_.deviceFormat[INPUT] ) * 8, stream_.nDeviceChannels[INPUT], |
| 5096 | captureFormat->nSamplesPerSec, stream_.sampleRate ); |
| 5097 | |
| 5098 | captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate ); |
| 5099 | |
| 5100 | if ( !captureClient ) { |
| 5101 | IAudioClient3* captureAudioClient3 = nullptr; |
| 5102 | captureAudioClient->QueryInterface( __uuidof( IAudioClient3 ), ( void** ) &captureAudioClient3 ); |
| 5103 | if ( captureAudioClient3 && !loopbackEnabled ) |
| 5104 | { |
| 5105 | UINT32 Ignore; |
| 5106 | UINT32 MinPeriodInFrames; |
| 5107 | hr = captureAudioClient3->GetSharedModeEnginePeriod( captureFormat, |
| 5108 | &Ignore, |
| 5109 | &Ignore, |
| 5110 | &MinPeriodInFrames, |
| 5111 | &Ignore ); |
| 5112 | if ( FAILED( hr ) ) { |
| 5113 | errorText = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client."; |
| 5114 | goto Exit; |
| 5115 | } |
| 5116 | |
| 5117 | hr = captureAudioClient3->InitializeSharedAudioStream( AUDCLNT_STREAMFLAGS_EVENTCALLBACK, |
| 5118 | MinPeriodInFrames, |
| 5119 | captureFormat, |
| 5120 | NULL ); |
| 5121 | } |
| 5122 | else |
| 5123 | { |
| 5124 | hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED, |
| 5125 | loopbackEnabled ? AUDCLNT_STREAMFLAGS_LOOPBACK : AUDCLNT_STREAMFLAGS_EVENTCALLBACK, |
| 5126 | 0, |
| 5127 | 0, |
| 5128 | captureFormat, |
| 5129 | NULL ); |
| 5130 | } |
| 5131 | |
| 5132 | if ( FAILED( hr ) ) { |
| 5133 | errorText = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client."; |
| 5134 | goto Exit; |
| 5135 | } |
| 5136 | |
| 5137 | hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ), |
| 5138 | ( void** ) &captureClient ); |
| 5139 | if ( FAILED( hr ) ) { |
| 5140 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle."; |
| 5141 | goto Exit; |
| 5142 | } |
| 5143 | |
| 5144 | // don't configure captureEvent if in loopback mode |
| 5145 | if ( !loopbackEnabled ) |
| 5146 | { |
| 5147 | // configure captureEvent to trigger on every available capture buffer |
| 5148 | captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); |
| 5149 | if ( !captureEvent ) { |
| 5150 | errorType = RTAUDIO_SYSTEM_ERROR; |
| 5151 | errorText = "RtApiWasapi::wasapiThread: Unable to create capture event."; |
| 5152 | goto Exit; |
| 5153 | } |
| 5154 | |
| 5155 | hr = captureAudioClient->SetEventHandle( captureEvent ); |
| 5156 | if ( FAILED( hr ) ) { |
| 5157 | errorText = "RtApiWasapi::wasapiThread: Unable to set capture event handle."; |
| 5158 | goto Exit; |
| 5159 | } |
| 5160 | |
| 5161 | ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent; |
| 5162 | } |
| 5163 | |
| 5164 | ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient; |
| 5165 | |
| 5166 | // reset the capture stream |
| 5167 | hr = captureAudioClient->Reset(); |
| 5168 | if ( FAILED( hr ) ) { |
| 5169 | errorText = "RtApiWasapi::wasapiThread: Unable to reset capture stream."; |
| 5170 | goto Exit; |
| 5171 | } |
| 5172 | |
| 5173 | // start the capture stream |
| 5174 | hr = captureAudioClient->Start(); |
| 5175 | if ( FAILED( hr ) ) { |
| 5176 | errorText = "RtApiWasapi::wasapiThread: Unable to start capture stream."; |
| 5177 | goto Exit; |
| 5178 | } |
| 5179 | } |
| 5180 | |
| 5181 | unsigned int inBufferSize = 0; |
| 5182 | hr = captureAudioClient->GetBufferSize( &inBufferSize ); |
| 5183 | if ( FAILED( hr ) ) { |
| 5184 | errorText = "RtApiWasapi::wasapiThread: Unable to get capture buffer size."; |
| 5185 | goto Exit; |
| 5186 | } |
| 5187 | |
| 5188 | // scale outBufferSize according to stream->user sample rate ratio |
| 5189 | unsigned int outBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT]; |
| 5190 | inBufferSize *= stream_.nDeviceChannels[INPUT]; |
| 5191 | |
| 5192 | // set captureBuffer size |
| 5193 | captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) ); |
| 5194 | } |
| 5195 | |
| 5196 | // start render stream if applicable |
| 5197 | if ( renderAudioClient ) { |
| 5198 | hr = renderAudioClient->GetMixFormat( &renderFormat ); |
| 5199 | if ( FAILED( hr ) ) { |
| 5200 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format."; |
| 5201 | goto Exit; |
| 5202 | } |
| 5203 | |
| 5204 | // init renderResampler |
| 5205 | renderResampler = new WasapiResampler( stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT32 || stream_.deviceFormat[OUTPUT] == RTAUDIO_FLOAT64, |
| 5206 | formatBytes( stream_.deviceFormat[OUTPUT] ) * 8, stream_.nDeviceChannels[OUTPUT], |
| 5207 | stream_.sampleRate, renderFormat->nSamplesPerSec ); |
| 5208 | |
| 5209 | renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate ); |
| 5210 | |
| 5211 | if ( !renderClient ) { |
| 5212 | IAudioClient3* renderAudioClient3 = nullptr; |
| 5213 | renderAudioClient->QueryInterface( __uuidof( IAudioClient3 ), ( void** ) &renderAudioClient3 ); |
| 5214 | if ( renderAudioClient3 ) |
| 5215 | { |
| 5216 | UINT32 Ignore; |
| 5217 | UINT32 MinPeriodInFrames; |
| 5218 | hr = renderAudioClient3->GetSharedModeEnginePeriod( renderFormat, |
| 5219 | &Ignore, |
| 5220 | &Ignore, |
| 5221 | &MinPeriodInFrames, |
| 5222 | &Ignore ); |
| 5223 | if ( FAILED( hr ) ) { |
| 5224 | errorText = "RtApiWasapi::wasapiThread: Unable to initialize render audio client."; |
| 5225 | goto Exit; |
| 5226 | } |
| 5227 | |
| 5228 | hr = renderAudioClient3->InitializeSharedAudioStream( AUDCLNT_STREAMFLAGS_EVENTCALLBACK, |
| 5229 | MinPeriodInFrames, |
| 5230 | renderFormat, |
| 5231 | NULL ); |
| 5232 | } |
| 5233 | else |
| 5234 | { |
| 5235 | hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED, |
| 5236 | AUDCLNT_STREAMFLAGS_EVENTCALLBACK, |
| 5237 | 0, |
| 5238 | 0, |
| 5239 | renderFormat, |
| 5240 | NULL ); |
| 5241 | } |
| 5242 | |
| 5243 | if ( FAILED( hr ) ) { |
| 5244 | errorText = "RtApiWasapi::wasapiThread: Unable to initialize render audio client."; |
| 5245 | goto Exit; |
| 5246 | } |
| 5247 | |
| 5248 | hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ), |
| 5249 | ( void** ) &renderClient ); |
| 5250 | if ( FAILED( hr ) ) { |
| 5251 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle."; |
| 5252 | goto Exit; |
| 5253 | } |
| 5254 | |
| 5255 | // configure renderEvent to trigger on every available render buffer |
| 5256 | renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); |
| 5257 | if ( !renderEvent ) { |
| 5258 | errorType = RTAUDIO_SYSTEM_ERROR; |
| 5259 | errorText = "RtApiWasapi::wasapiThread: Unable to create render event."; |
| 5260 | goto Exit; |
| 5261 | } |
| 5262 | |
| 5263 | hr = renderAudioClient->SetEventHandle( renderEvent ); |
| 5264 | if ( FAILED( hr ) ) { |
| 5265 | errorText = "RtApiWasapi::wasapiThread: Unable to set render event handle."; |
| 5266 | goto Exit; |
| 5267 | } |
| 5268 | |
| 5269 | ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient; |
| 5270 | ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent; |
| 5271 | |
| 5272 | // reset the render stream |
| 5273 | hr = renderAudioClient->Reset(); |
| 5274 | if ( FAILED( hr ) ) { |
| 5275 | errorText = "RtApiWasapi::wasapiThread: Unable to reset render stream."; |
| 5276 | goto Exit; |
| 5277 | } |
| 5278 | |
| 5279 | // start the render stream |
| 5280 | hr = renderAudioClient->Start(); |
| 5281 | if ( FAILED( hr ) ) { |
| 5282 | errorText = "RtApiWasapi::wasapiThread: Unable to start render stream."; |
| 5283 | goto Exit; |
| 5284 | } |
| 5285 | } |
| 5286 | |
| 5287 | unsigned int outBufferSize = 0; |
| 5288 | hr = renderAudioClient->GetBufferSize( &outBufferSize ); |
| 5289 | if ( FAILED( hr ) ) { |
| 5290 | errorText = "RtApiWasapi::wasapiThread: Unable to get render buffer size."; |
| 5291 | goto Exit; |
| 5292 | } |
| 5293 | |
| 5294 | // scale inBufferSize according to user->stream sample rate ratio |
| 5295 | unsigned int inBufferSize = ( unsigned int ) ceilf( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT]; |
| 5296 | outBufferSize *= stream_.nDeviceChannels[OUTPUT]; |
| 5297 | |
| 5298 | // set renderBuffer size |
| 5299 | renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) ); |
| 5300 | } |
| 5301 | |
| 5302 | // malloc buffer memory |
| 5303 | if ( stream_.mode == INPUT ) |
| 5304 | { |
| 5305 | using namespace std; // for ceilf |
| 5306 | convBuffSize = ( unsigned int ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ); |
| 5307 | deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ); |
| 5308 | } |
| 5309 | else if ( stream_.mode == OUTPUT ) |
| 5310 | { |
| 5311 | convBuffSize = ( unsigned int ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ); |
| 5312 | deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ); |
| 5313 | } |
| 5314 | else if ( stream_.mode == DUPLEX ) |
| 5315 | { |
| 5316 | convBuffSize = std::max( ( unsigned int ) ( ceilf( stream_.bufferSize * captureSrRatio ) ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ), |
| 5317 | ( unsigned int ) ( ceilf( stream_.bufferSize * renderSrRatio ) ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) ); |
| 5318 | deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ), |
| 5319 | stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) ); |
| 5320 | } |
| 5321 | |
| 5322 | convBuffSize *= 2; // allow overflow for *SrRatio remainders |
| 5323 | convBuffer = ( char* ) calloc( convBuffSize, 1 ); |
| 5324 | stream_.deviceBuffer = ( char* ) calloc( deviceBuffSize, 1 ); |
| 5325 | if ( !convBuffer || !stream_.deviceBuffer ) { |
| 5326 | errorType = RTAUDIO_MEMORY_ERROR; |
| 5327 | errorText = "RtApiWasapi::wasapiThread: Error allocating device buffer memory."; |
| 5328 | goto Exit; |
| 5329 | } |
| 5330 | |
| 5331 | // stream process loop |
| 5332 | while ( stream_.state != STREAM_STOPPING ) { |
| 5333 | if ( !callbackPulled ) { |
| 5334 | // Callback Input |
| 5335 | // ============== |
| 5336 | // 1. Pull callback buffer from inputBuffer |
| 5337 | // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count |
| 5338 | // Convert callback buffer to user format |
| 5339 | |
| 5340 | if ( captureAudioClient ) |
| 5341 | { |
| 5342 | int samplesToPull = ( unsigned int ) floorf( stream_.bufferSize * captureSrRatio ); |
| 5343 | |
| 5344 | convBufferSize = 0; |
| 5345 | while ( convBufferSize < stream_.bufferSize ) |
| 5346 | { |
| 5347 | // Pull callback buffer from inputBuffer |
| 5348 | callbackPulled = captureBuffer.pullBuffer( convBuffer, |
| 5349 | samplesToPull * stream_.nDeviceChannels[INPUT], |
| 5350 | stream_.deviceFormat[INPUT] ); |
| 5351 | |
| 5352 | if ( !callbackPulled ) |
| 5353 | { |
| 5354 | break; |
| 5355 | } |
| 5356 | |
| 5357 | // Convert callback buffer to user sample rate |
| 5358 | unsigned int deviceBufferOffset = convBufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ); |
| 5359 | unsigned int convSamples = 0; |
| 5360 | |
| 5361 | captureResampler->Convert( stream_.deviceBuffer + deviceBufferOffset, |
| 5362 | convBuffer, |
| 5363 | samplesToPull, |
| 5364 | convSamples, |
| 5365 | convBufferSize == 0 ? -1 : stream_.bufferSize - convBufferSize ); |
| 5366 | |
| 5367 | convBufferSize += convSamples; |
| 5368 | samplesToPull = 1; // now pull one sample at a time until we have stream_.bufferSize samples |
| 5369 | } |
| 5370 | |
| 5371 | if ( callbackPulled ) |
| 5372 | { |
| 5373 | if ( stream_.doConvertBuffer[INPUT] ) { |
| 5374 | // Convert callback buffer to user format |
| 5375 | convertBuffer( stream_.userBuffer[INPUT], |
| 5376 | stream_.deviceBuffer, |
| 5377 | stream_.convertInfo[INPUT] ); |
| 5378 | } |
| 5379 | else { |
| 5380 | // no further conversion, simple copy deviceBuffer to userBuffer |
| 5381 | memcpy( stream_.userBuffer[INPUT], |
| 5382 | stream_.deviceBuffer, |
| 5383 | stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) ); |
| 5384 | } |
| 5385 | } |
| 5386 | } |
| 5387 | else { |
| 5388 | // if there is no capture stream, set callbackPulled flag |
| 5389 | callbackPulled = true; |
| 5390 | } |
| 5391 | |
| 5392 | // Execute Callback |
| 5393 | // ================ |
| 5394 | // 1. Execute user callback method |
| 5395 | // 2. Handle return value from callback |
| 5396 | |
| 5397 | // if callback has not requested the stream to stop |
| 5398 | if ( callbackPulled && !callbackStopped ) { |
| 5399 | // Execute user callback method |
| 5400 | callbackResult = callback( stream_.userBuffer[OUTPUT], |
| 5401 | stream_.userBuffer[INPUT], |
| 5402 | stream_.bufferSize, |
| 5403 | getStreamTime(), |
| 5404 | captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0, |
| 5405 | stream_.callbackInfo.userData ); |
| 5406 | |
| 5407 | // tick stream time |
| 5408 | RtApi::tickStreamTime(); |
| 5409 | |
| 5410 | // Handle return value from callback |
| 5411 | if ( callbackResult == 1 ) { |
| 5412 | // instantiate a thread to stop this thread |
| 5413 | HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL ); |
| 5414 | if ( !threadHandle ) { |
| 5415 | errorType = RTAUDIO_THREAD_ERROR; |
| 5416 | errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread."; |
| 5417 | goto Exit; |
| 5418 | } |
| 5419 | else if ( !CloseHandle( threadHandle ) ) { |
| 5420 | errorType = RTAUDIO_THREAD_ERROR; |
| 5421 | errorText = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle."; |
| 5422 | goto Exit; |
| 5423 | } |
| 5424 | |
| 5425 | callbackStopped = true; |
| 5426 | } |
| 5427 | else if ( callbackResult == 2 ) { |
| 5428 | // instantiate a thread to stop this thread |
| 5429 | HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL ); |
| 5430 | if ( !threadHandle ) { |
| 5431 | errorType = RTAUDIO_THREAD_ERROR; |
| 5432 | errorText = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread."; |
| 5433 | goto Exit; |
| 5434 | } |
| 5435 | else if ( !CloseHandle( threadHandle ) ) { |
| 5436 | errorType = RTAUDIO_THREAD_ERROR; |
| 5437 | errorText = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle."; |
| 5438 | goto Exit; |
| 5439 | } |
| 5440 | |
| 5441 | callbackStopped = true; |
| 5442 | } |
| 5443 | } |
| 5444 | } |
| 5445 | |
| 5446 | // Callback Output |
| 5447 | // =============== |
| 5448 | // 1. Convert callback buffer to stream format |
| 5449 | // 2. Convert callback buffer to stream sample rate and channel count |
| 5450 | // 3. Push callback buffer into outputBuffer |
| 5451 | |
| 5452 | if ( renderAudioClient && callbackPulled ) |
| 5453 | { |
| 5454 | // if the last call to renderBuffer.PushBuffer() was successful |
| 5455 | if ( callbackPushed || convBufferSize == 0 ) |
| 5456 | { |
| 5457 | if ( stream_.doConvertBuffer[OUTPUT] ) |
| 5458 | { |
| 5459 | // Convert callback buffer to stream format |
| 5460 | convertBuffer( stream_.deviceBuffer, |
| 5461 | stream_.userBuffer[OUTPUT], |
| 5462 | stream_.convertInfo[OUTPUT] ); |
| 5463 | |
| 5464 | } |
| 5465 | else { |
| 5466 | // no further conversion, simple copy userBuffer to deviceBuffer |
| 5467 | memcpy( stream_.deviceBuffer, |
| 5468 | stream_.userBuffer[OUTPUT], |
| 5469 | stream_.bufferSize * stream_.nUserChannels[OUTPUT] * formatBytes( stream_.userFormat ) ); |
| 5470 | } |
| 5471 | |
| 5472 | // Convert callback buffer to stream sample rate |
| 5473 | renderResampler->Convert( convBuffer, |
| 5474 | stream_.deviceBuffer, |
| 5475 | stream_.bufferSize, |
| 5476 | convBufferSize ); |
| 5477 | } |
| 5478 | |
| 5479 | // Push callback buffer into outputBuffer |
| 5480 | callbackPushed = renderBuffer.pushBuffer( convBuffer, |
| 5481 | convBufferSize * stream_.nDeviceChannels[OUTPUT], |
| 5482 | stream_.deviceFormat[OUTPUT] ); |
| 5483 | } |
| 5484 | else { |
| 5485 | // if there is no render stream, set callbackPushed flag |
| 5486 | callbackPushed = true; |
| 5487 | } |
| 5488 | |
| 5489 | // Stream Capture |
| 5490 | // ============== |
| 5491 | // 1. Get capture buffer from stream |
| 5492 | // 2. Push capture buffer into inputBuffer |
| 5493 | // 3. If 2. was successful: Release capture buffer |
| 5494 | |
| 5495 | if ( captureAudioClient ) { |
| 5496 | // if the callback input buffer was not pulled from captureBuffer, wait for next capture event |
| 5497 | if ( !callbackPulled ) { |
| 5498 | WaitForSingleObject( loopbackEnabled ? renderEvent : captureEvent, INFINITE ); |
| 5499 | } |
| 5500 | |
| 5501 | // Get capture buffer from stream |
| 5502 | hr = captureClient->GetBuffer( &streamBuffer, |
| 5503 | &bufferFrameCount, |
| 5504 | &captureFlags, NULL, NULL ); |
| 5505 | if ( FAILED( hr ) ) { |
| 5506 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer."; |
| 5507 | goto Exit; |
| 5508 | } |
| 5509 | |
| 5510 | if ( bufferFrameCount != 0 ) { |
| 5511 | // Push capture buffer into inputBuffer |
| 5512 | if ( captureBuffer.pushBuffer( ( char* ) streamBuffer, |
| 5513 | bufferFrameCount * stream_.nDeviceChannels[INPUT], |
| 5514 | stream_.deviceFormat[INPUT] ) ) |
| 5515 | { |
| 5516 | // Release capture buffer |
| 5517 | hr = captureClient->ReleaseBuffer( bufferFrameCount ); |
| 5518 | if ( FAILED( hr ) ) { |
| 5519 | errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer."; |
| 5520 | goto Exit; |
| 5521 | } |
| 5522 | } |
| 5523 | else |
| 5524 | { |
| 5525 | // Inform WASAPI that capture was unsuccessful |
| 5526 | hr = captureClient->ReleaseBuffer( 0 ); |
| 5527 | if ( FAILED( hr ) ) { |
| 5528 | errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer."; |
| 5529 | goto Exit; |
| 5530 | } |
| 5531 | } |
| 5532 | } |
| 5533 | else |
| 5534 | { |
| 5535 | // Inform WASAPI that capture was unsuccessful |
| 5536 | hr = captureClient->ReleaseBuffer( 0 ); |
| 5537 | if ( FAILED( hr ) ) { |
| 5538 | errorText = "RtApiWasapi::wasapiThread: Unable to release capture buffer."; |
| 5539 | goto Exit; |
| 5540 | } |
| 5541 | } |
| 5542 | } |
| 5543 | |
| 5544 | // Stream Render |
| 5545 | // ============= |
| 5546 | // 1. Get render buffer from stream |
| 5547 | // 2. Pull next buffer from outputBuffer |
| 5548 | // 3. If 2. was successful: Fill render buffer with next buffer |
| 5549 | // Release render buffer |
| 5550 | |
| 5551 | if ( renderAudioClient ) { |
| 5552 | // if the callback output buffer was not pushed to renderBuffer, wait for next render event |
| 5553 | if ( callbackPulled && !callbackPushed ) { |
| 5554 | WaitForSingleObject( renderEvent, INFINITE ); |
| 5555 | } |
| 5556 | |
| 5557 | // Get render buffer from stream |
| 5558 | hr = renderAudioClient->GetBufferSize( &bufferFrameCount ); |
| 5559 | if ( FAILED( hr ) ) { |
| 5560 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size."; |
| 5561 | goto Exit; |
| 5562 | } |
| 5563 | |
| 5564 | hr = renderAudioClient->GetCurrentPadding( &numFramesPadding ); |
| 5565 | if ( FAILED( hr ) ) { |
| 5566 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding."; |
| 5567 | goto Exit; |
| 5568 | } |
| 5569 | |
| 5570 | bufferFrameCount -= numFramesPadding; |
| 5571 | |
| 5572 | if ( bufferFrameCount != 0 ) { |
| 5573 | hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer ); |
| 5574 | if ( FAILED( hr ) ) { |
| 5575 | errorText = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer."; |
| 5576 | goto Exit; |
| 5577 | } |
| 5578 | |
| 5579 | // Pull next buffer from outputBuffer |
| 5580 | // Fill render buffer with next buffer |
| 5581 | if ( renderBuffer.pullBuffer( ( char* ) streamBuffer, |
| 5582 | bufferFrameCount * stream_.nDeviceChannels[OUTPUT], |
| 5583 | stream_.deviceFormat[OUTPUT] ) ) |
| 5584 | { |
| 5585 | // Release render buffer |
| 5586 | hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 ); |
| 5587 | if ( FAILED( hr ) ) { |
| 5588 | errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer."; |
| 5589 | goto Exit; |
| 5590 | } |
| 5591 | } |
| 5592 | else |
| 5593 | { |
| 5594 | // Inform WASAPI that render was unsuccessful |
| 5595 | hr = renderClient->ReleaseBuffer( 0, 0 ); |
| 5596 | if ( FAILED( hr ) ) { |
| 5597 | errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer."; |
| 5598 | goto Exit; |
| 5599 | } |
| 5600 | } |
| 5601 | } |
| 5602 | else |
| 5603 | { |
| 5604 | // Inform WASAPI that render was unsuccessful |
| 5605 | hr = renderClient->ReleaseBuffer( 0, 0 ); |
| 5606 | if ( FAILED( hr ) ) { |
| 5607 | errorText = "RtApiWasapi::wasapiThread: Unable to release render buffer."; |
| 5608 | goto Exit; |
| 5609 | } |
| 5610 | } |
| 5611 | } |
| 5612 | |
| 5613 | // if the callback buffer was pushed renderBuffer reset callbackPulled flag |
| 5614 | if ( callbackPushed ) { |
| 5615 | // unsetting the callbackPulled flag lets the stream know that |
| 5616 | // the audio device is ready for another callback output buffer. |
| 5617 | callbackPulled = false; |
| 5618 | } |
| 5619 | |
| 5620 | } |
| 5621 | |
| 5622 | Exit: |
| 5623 | // clean up |
| 5624 | CoTaskMemFree( captureFormat ); |
| 5625 | CoTaskMemFree( renderFormat ); |
| 5626 | |
| 5627 | free ( convBuffer ); |
| 5628 | delete renderResampler; |
| 5629 | delete captureResampler; |
| 5630 | |
| 5631 | CoUninitialize(); |
| 5632 | |
| 5633 | if ( !errorText.empty() ) |
| 5634 | { |
| 5635 | errorText_ = errorText; |
| 5636 | error( errorType ); |
| 5637 | } |
| 5638 | |
| 5639 | // update stream state |
| 5640 | stream_.state = STREAM_STOPPED; |
| 5641 | } |
| 5642 | |
| 5643 | //******************** End of __WINDOWS_WASAPI__ *********************// |
| 5644 | #endif |
| 5645 | |
| 5646 | |
| 5647 | #if defined(__WINDOWS_DS__) // Windows DirectSound API |
| 5648 | |
| 5649 | // Modified by Robin Davies, October 2005 |
| 5650 | // - Improvements to DirectX pointer chasing. |
| 5651 | // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30. |
| 5652 | // - Auto-call CoInitialize for DSOUND and ASIO platforms. |
| 5653 | // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007 |
| 5654 | // Changed device query structure for RtAudio 4.0.7, January 2010 |
| 5655 | |
| 5656 | #include <windows.h> |
| 5657 | #include <process.h> |
| 5658 | #include <mmsystem.h> |
| 5659 | #include <mmreg.h> |
| 5660 | #include <dsound.h> |
| 5661 | #include <assert.h> |
| 5662 | #include <algorithm> |
| 5663 | |
| 5664 | #if defined(__MINGW32__) |
| 5665 | // missing from latest mingw winapi |
| 5666 | #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */ |
| 5667 | #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */ |
| 5668 | #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */ |
| 5669 | #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */ |
| 5670 | #endif |
| 5671 | |
| 5672 | #define MINIMUM_DEVICE_BUFFER_SIZE 32768 |
| 5673 | |
| 5674 | #ifdef _MSC_VER // if Microsoft Visual C++ |
| 5675 | #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually. |
| 5676 | #endif |
| 5677 | |
| 5678 | static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize ) |
| 5679 | { |
| 5680 | if ( pointer > bufferSize ) pointer -= bufferSize; |
| 5681 | if ( laterPointer < earlierPointer ) laterPointer += bufferSize; |
| 5682 | if ( pointer < earlierPointer ) pointer += bufferSize; |
| 5683 | return pointer >= earlierPointer && pointer < laterPointer; |
| 5684 | } |
| 5685 | |
| 5686 | // A structure to hold various information related to the DirectSound |
| 5687 | // API implementation. |
| 5688 | struct DsHandle { |
| 5689 | unsigned int drainCounter; // Tracks callback counts when draining |
| 5690 | bool internalDrain; // Indicates if stop is initiated from callback or not. |
| 5691 | void *id[2]; |
| 5692 | void *buffer[2]; |
| 5693 | bool xrun[2]; |
| 5694 | UINT bufferPointer[2]; |
| 5695 | DWORD dsBufferSize[2]; |
| 5696 | DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by. |
| 5697 | HANDLE condition; |
| 5698 | |
| 5699 | DsHandle() |
| 5700 | :drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; } |
| 5701 | }; |
| 5702 | |
| 5703 | // Declarations for utility functions, callbacks, and structures |
| 5704 | // specific to the DirectSound implementation. |
| 5705 | static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid, |
| 5706 | LPCTSTR description, |
| 5707 | LPCTSTR module, |
| 5708 | LPVOID lpContext ); |
| 5709 | |
| 5710 | static const char* getErrorString( int code ); |
| 5711 | |
| 5712 | static unsigned __stdcall callbackHandler( void *ptr ); |
| 5713 | |
| 5714 | struct DsDevice { |
| 5715 | LPGUID id[2]; |
| 5716 | bool validId[2]; |
| 5717 | bool found; |
| 5718 | std::string name; |
| 5719 | |
| 5720 | DsDevice() |
| 5721 | : found(false) { validId[0] = false; validId[1] = false; } |
| 5722 | }; |
| 5723 | |
| 5724 | struct DsProbeData { |
| 5725 | bool isInput; |
| 5726 | std::vector<struct DsDevice>* dsDevices; |
| 5727 | }; |
| 5728 | |
| 5729 | RtApiDs :: RtApiDs() |
| 5730 | { |
| 5731 | // Dsound will run both-threaded. If CoInitialize fails, then just |
| 5732 | // accept whatever the mainline chose for a threading model. |
| 5733 | coInitialized_ = false; |
| 5734 | HRESULT hr = CoInitialize( NULL ); |
| 5735 | if ( !FAILED( hr ) ) coInitialized_ = true; |
| 5736 | } |
| 5737 | |
| 5738 | RtApiDs :: ~RtApiDs() |
| 5739 | { |
| 5740 | if ( stream_.state != STREAM_CLOSED ) closeStream(); |
| 5741 | if ( coInitialized_ ) CoUninitialize(); // balanced call. |
| 5742 | } |
| 5743 | |
| 5744 | // The DirectSound default output is always the first device. |
| 5745 | unsigned int RtApiDs :: getDefaultOutputDevice( void ) |
| 5746 | { |
| 5747 | return 0; |
| 5748 | } |
| 5749 | |
| 5750 | // The DirectSound default input is always the first input device, |
| 5751 | // which is the first capture device enumerated. |
| 5752 | unsigned int RtApiDs :: getDefaultInputDevice( void ) |
| 5753 | { |
| 5754 | return 0; |
| 5755 | } |
| 5756 | |
| 5757 | unsigned int RtApiDs :: getDeviceCount( void ) |
| 5758 | { |
| 5759 | // Set query flag for previously found devices to false, so that we |
| 5760 | // can check for any devices that have disappeared. |
| 5761 | for ( unsigned int i=0; i<dsDevices.size(); i++ ) |
| 5762 | dsDevices[i].found = false; |
| 5763 | |
| 5764 | // Query DirectSound devices. |
| 5765 | struct DsProbeData probeInfo; |
| 5766 | probeInfo.isInput = false; |
| 5767 | probeInfo.dsDevices = &dsDevices; |
| 5768 | HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo ); |
| 5769 | if ( FAILED( result ) ) { |
| 5770 | errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!"; |
| 5771 | errorText_ = errorStream_.str(); |
| 5772 | error( RTAUDIO_WARNING ); |
| 5773 | } |
| 5774 | |
| 5775 | // Query DirectSoundCapture devices. |
| 5776 | probeInfo.isInput = true; |
| 5777 | result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo ); |
| 5778 | if ( FAILED( result ) ) { |
| 5779 | errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!"; |
| 5780 | errorText_ = errorStream_.str(); |
| 5781 | error( RTAUDIO_WARNING ); |
| 5782 | } |
| 5783 | |
| 5784 | // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut). |
| 5785 | for ( unsigned int i=0; i<dsDevices.size(); ) { |
| 5786 | if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i ); |
| 5787 | else i++; |
| 5788 | } |
| 5789 | |
| 5790 | return static_cast<unsigned int>(dsDevices.size()); |
| 5791 | } |
| 5792 | |
| 5793 | RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device ) |
| 5794 | { |
| 5795 | RtAudio::DeviceInfo info; |
| 5796 | info.probed = false; |
| 5797 | |
| 5798 | if ( dsDevices.size() == 0 ) { |
| 5799 | // Force a query of all devices |
| 5800 | getDeviceCount(); |
| 5801 | if ( dsDevices.size() == 0 ) { |
| 5802 | errorText_ = "RtApiDs::getDeviceInfo: no devices found!"; |
| 5803 | error( RTAUDIO_INVALID_USE ); |
| 5804 | return info; |
| 5805 | } |
| 5806 | } |
| 5807 | |
| 5808 | if ( device >= dsDevices.size() ) { |
| 5809 | errorText_ = "RtApiDs::getDeviceInfo: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 5810 | error( RTAUDIO_INVALID_USE ); |
| 5811 | return info; |
| 5812 | } |
| 5813 | |
| 5814 | HRESULT result; |
| 5815 | if ( dsDevices[ device ].validId[0] == false ) goto probeInput; |
| 5816 | |
| 5817 | LPDIRECTSOUND output; |
| 5818 | DSCAPS outCaps; |
| 5819 | result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL ); |
| 5820 | if ( FAILED( result ) ) { |
| 5821 | errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!"; |
| 5822 | errorText_ = errorStream_.str(); |
| 5823 | error( RTAUDIO_WARNING ); |
| 5824 | goto probeInput; |
| 5825 | } |
| 5826 | |
| 5827 | outCaps.dwSize = sizeof( outCaps ); |
| 5828 | result = output->GetCaps( &outCaps ); |
| 5829 | if ( FAILED( result ) ) { |
| 5830 | output->Release(); |
| 5831 | errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!"; |
| 5832 | errorText_ = errorStream_.str(); |
| 5833 | error( RTAUDIO_WARNING ); |
| 5834 | goto probeInput; |
| 5835 | } |
| 5836 | |
| 5837 | // Get output channel information. |
| 5838 | info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1; |
| 5839 | |
| 5840 | // Get sample rate information. |
| 5841 | info.sampleRates.clear(); |
| 5842 | for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) { |
| 5843 | if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate && |
| 5844 | SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) { |
| 5845 | info.sampleRates.push_back( SAMPLE_RATES[k] ); |
| 5846 | |
| 5847 | if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) ) |
| 5848 | info.preferredSampleRate = SAMPLE_RATES[k]; |
| 5849 | } |
| 5850 | } |
| 5851 | |
| 5852 | // Get format information. |
| 5853 | if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5854 | if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5855 | |
| 5856 | output->Release(); |
| 5857 | |
| 5858 | if ( getDefaultOutputDevice() == device ) |
| 5859 | info.isDefaultOutput = true; |
| 5860 | |
| 5861 | if ( dsDevices[ device ].validId[1] == false ) { |
| 5862 | info.name = dsDevices[ device ].name; |
| 5863 | info.probed = true; |
| 5864 | return info; |
| 5865 | } |
| 5866 | |
| 5867 | probeInput: |
| 5868 | |
| 5869 | LPDIRECTSOUNDCAPTURE input; |
| 5870 | result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL ); |
| 5871 | if ( FAILED( result ) ) { |
| 5872 | errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!"; |
| 5873 | errorText_ = errorStream_.str(); |
| 5874 | error( RTAUDIO_WARNING ); |
| 5875 | return info; |
| 5876 | } |
| 5877 | |
| 5878 | DSCCAPS inCaps; |
| 5879 | inCaps.dwSize = sizeof( inCaps ); |
| 5880 | result = input->GetCaps( &inCaps ); |
| 5881 | if ( FAILED( result ) ) { |
| 5882 | input->Release(); |
| 5883 | errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!"; |
| 5884 | errorText_ = errorStream_.str(); |
| 5885 | error( RTAUDIO_WARNING ); |
| 5886 | return info; |
| 5887 | } |
| 5888 | |
| 5889 | // Get input channel information. |
| 5890 | info.inputChannels = inCaps.dwChannels; |
| 5891 | |
| 5892 | // Get sample rate and format information. |
| 5893 | std::vector<unsigned int> rates; |
| 5894 | if ( inCaps.dwChannels >= 2 ) { |
| 5895 | if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5896 | if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5897 | if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5898 | if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5899 | if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5900 | if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5901 | if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5902 | if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5903 | |
| 5904 | if ( info.nativeFormats & RTAUDIO_SINT16 ) { |
| 5905 | if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 ); |
| 5906 | if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 ); |
| 5907 | if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 ); |
| 5908 | if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 ); |
| 5909 | } |
| 5910 | else if ( info.nativeFormats & RTAUDIO_SINT8 ) { |
| 5911 | if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 ); |
| 5912 | if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 ); |
| 5913 | if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 ); |
| 5914 | if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 ); |
| 5915 | } |
| 5916 | } |
| 5917 | else if ( inCaps.dwChannels == 1 ) { |
| 5918 | if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5919 | if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5920 | if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5921 | if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16; |
| 5922 | if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5923 | if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5924 | if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5925 | if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8; |
| 5926 | |
| 5927 | if ( info.nativeFormats & RTAUDIO_SINT16 ) { |
| 5928 | if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 ); |
| 5929 | if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 ); |
| 5930 | if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 ); |
| 5931 | if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 ); |
| 5932 | } |
| 5933 | else if ( info.nativeFormats & RTAUDIO_SINT8 ) { |
| 5934 | if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 ); |
| 5935 | if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 ); |
| 5936 | if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 ); |
| 5937 | if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 ); |
| 5938 | } |
| 5939 | } |
| 5940 | else info.inputChannels = 0; // technically, this would be an error |
| 5941 | |
| 5942 | input->Release(); |
| 5943 | |
| 5944 | if ( info.inputChannels == 0 ) return info; |
| 5945 | |
| 5946 | // Copy the supported rates to the info structure but avoid duplication. |
| 5947 | bool found; |
| 5948 | for ( unsigned int i=0; i<rates.size(); i++ ) { |
| 5949 | found = false; |
| 5950 | for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) { |
| 5951 | if ( rates[i] == info.sampleRates[j] ) { |
| 5952 | found = true; |
| 5953 | break; |
| 5954 | } |
| 5955 | } |
| 5956 | if ( found == false ) info.sampleRates.push_back( rates[i] ); |
| 5957 | } |
| 5958 | std::sort( info.sampleRates.begin(), info.sampleRates.end() ); |
| 5959 | |
| 5960 | // If device opens for both playback and capture, we determine the channels. |
| 5961 | if ( info.outputChannels > 0 && info.inputChannels > 0 ) |
| 5962 | info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels; |
| 5963 | |
| 5964 | if ( device == 0 ) info.isDefaultInput = true; |
| 5965 | |
| 5966 | // Copy name and return. |
| 5967 | info.name = dsDevices[ device ].name; |
| 5968 | info.probed = true; |
| 5969 | return info; |
| 5970 | } |
| 5971 | |
| 5972 | bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, |
| 5973 | unsigned int firstChannel, unsigned int sampleRate, |
| 5974 | RtAudioFormat format, unsigned int *bufferSize, |
| 5975 | RtAudio::StreamOptions *options ) |
| 5976 | { |
| 5977 | if ( channels + firstChannel > 2 ) { |
| 5978 | errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device."; |
| 5979 | return FAILURE; |
| 5980 | } |
| 5981 | |
| 5982 | size_t nDevices = dsDevices.size(); |
| 5983 | if ( nDevices == 0 ) { |
| 5984 | // This should not happen because a check is made before this function is called. |
| 5985 | errorText_ = "RtApiDs::probeDeviceOpen: no devices found!"; |
| 5986 | return FAILURE; |
| 5987 | } |
| 5988 | |
| 5989 | if ( device >= nDevices ) { |
| 5990 | // This should not happen because a check is made before this function is called. |
| 5991 | errorText_ = "RtApiDs::probeDeviceOpen: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 5992 | return FAILURE; |
| 5993 | } |
| 5994 | |
| 5995 | if ( mode == OUTPUT ) { |
| 5996 | if ( dsDevices[ device ].validId[0] == false ) { |
| 5997 | errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!"; |
| 5998 | errorText_ = errorStream_.str(); |
| 5999 | return FAILURE; |
| 6000 | } |
| 6001 | } |
| 6002 | else { // mode == INPUT |
| 6003 | if ( dsDevices[ device ].validId[1] == false ) { |
| 6004 | errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!"; |
| 6005 | errorText_ = errorStream_.str(); |
| 6006 | return FAILURE; |
| 6007 | } |
| 6008 | } |
| 6009 | |
| 6010 | // According to a note in PortAudio, using GetDesktopWindow() |
| 6011 | // instead of GetForegroundWindow() is supposed to avoid problems |
| 6012 | // that occur when the application's window is not the foreground |
| 6013 | // window. Also, if the application window closes before the |
| 6014 | // DirectSound buffer, DirectSound can crash. In the past, I had |
| 6015 | // problems when using GetDesktopWindow() but it seems fine now |
| 6016 | // (January 2010). I'll leave it commented here. |
| 6017 | // HWND hWnd = GetForegroundWindow(); |
| 6018 | HWND hWnd = GetDesktopWindow(); |
| 6019 | |
| 6020 | // Check the numberOfBuffers parameter and limit the lowest value to |
| 6021 | // two. This is a judgement call and a value of two is probably too |
| 6022 | // low for capture, but it should work for playback. |
| 6023 | int nBuffers = 0; |
| 6024 | if ( options ) nBuffers = options->numberOfBuffers; |
| 6025 | if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2; |
| 6026 | if ( nBuffers < 2 ) nBuffers = 3; |
| 6027 | |
| 6028 | // Check the lower range of the user-specified buffer size and set |
| 6029 | // (arbitrarily) to a lower bound of 32. |
| 6030 | if ( *bufferSize < 32 ) *bufferSize = 32; |
| 6031 | |
| 6032 | // Create the wave format structure. The data format setting will |
| 6033 | // be determined later. |
| 6034 | WAVEFORMATEX waveFormat; |
| 6035 | ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) ); |
| 6036 | waveFormat.wFormatTag = WAVE_FORMAT_PCM; |
| 6037 | waveFormat.nChannels = channels + firstChannel; |
| 6038 | waveFormat.nSamplesPerSec = (unsigned long) sampleRate; |
| 6039 | |
| 6040 | // Determine the device buffer size. By default, we'll use the value |
| 6041 | // defined above (32K), but we will grow it to make allowances for |
| 6042 | // very large software buffer sizes. |
| 6043 | DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE; |
| 6044 | DWORD dsPointerLeadTime = 0; |
| 6045 | |
| 6046 | void *ohandle = 0, *bhandle = 0; |
| 6047 | HRESULT result; |
| 6048 | if ( mode == OUTPUT ) { |
| 6049 | |
| 6050 | LPDIRECTSOUND output; |
| 6051 | result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL ); |
| 6052 | if ( FAILED( result ) ) { |
| 6053 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!"; |
| 6054 | errorText_ = errorStream_.str(); |
| 6055 | return FAILURE; |
| 6056 | } |
| 6057 | |
| 6058 | DSCAPS outCaps; |
| 6059 | outCaps.dwSize = sizeof( outCaps ); |
| 6060 | result = output->GetCaps( &outCaps ); |
| 6061 | if ( FAILED( result ) ) { |
| 6062 | output->Release(); |
| 6063 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!"; |
| 6064 | errorText_ = errorStream_.str(); |
| 6065 | return FAILURE; |
| 6066 | } |
| 6067 | |
| 6068 | // Check channel information. |
| 6069 | if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) { |
| 6070 | errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback."; |
| 6071 | errorText_ = errorStream_.str(); |
| 6072 | return FAILURE; |
| 6073 | } |
| 6074 | |
| 6075 | // Check format information. Use 16-bit format unless not |
| 6076 | // supported or user requests 8-bit. |
| 6077 | if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT && |
| 6078 | !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) { |
| 6079 | waveFormat.wBitsPerSample = 16; |
| 6080 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 6081 | } |
| 6082 | else { |
| 6083 | waveFormat.wBitsPerSample = 8; |
| 6084 | stream_.deviceFormat[mode] = RTAUDIO_SINT8; |
| 6085 | } |
| 6086 | stream_.userFormat = format; |
| 6087 | |
| 6088 | // Update wave format structure and buffer information. |
| 6089 | waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8; |
| 6090 | waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; |
| 6091 | dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels; |
| 6092 | |
| 6093 | // If the user wants an even bigger buffer, increase the device buffer size accordingly. |
| 6094 | while ( dsPointerLeadTime * 2U > dsBufferSize ) |
| 6095 | dsBufferSize *= 2; |
| 6096 | |
| 6097 | // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes. |
| 6098 | // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE ); |
| 6099 | // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes. |
| 6100 | result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY ); |
| 6101 | if ( FAILED( result ) ) { |
| 6102 | output->Release(); |
| 6103 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!"; |
| 6104 | errorText_ = errorStream_.str(); |
| 6105 | return FAILURE; |
| 6106 | } |
| 6107 | |
| 6108 | // Even though we will write to the secondary buffer, we need to |
| 6109 | // access the primary buffer to set the correct output format |
| 6110 | // (since the default is 8-bit, 22 kHz!). Setup the DS primary |
| 6111 | // buffer description. |
| 6112 | DSBUFFERDESC bufferDescription; |
| 6113 | ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) ); |
| 6114 | bufferDescription.dwSize = sizeof( DSBUFFERDESC ); |
| 6115 | bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER; |
| 6116 | |
| 6117 | // Obtain the primary buffer |
| 6118 | LPDIRECTSOUNDBUFFER buffer; |
| 6119 | result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL ); |
| 6120 | if ( FAILED( result ) ) { |
| 6121 | output->Release(); |
| 6122 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!"; |
| 6123 | errorText_ = errorStream_.str(); |
| 6124 | return FAILURE; |
| 6125 | } |
| 6126 | |
| 6127 | // Set the primary DS buffer sound format. |
| 6128 | result = buffer->SetFormat( &waveFormat ); |
| 6129 | if ( FAILED( result ) ) { |
| 6130 | output->Release(); |
| 6131 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!"; |
| 6132 | errorText_ = errorStream_.str(); |
| 6133 | return FAILURE; |
| 6134 | } |
| 6135 | |
| 6136 | // Setup the secondary DS buffer description. |
| 6137 | ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) ); |
| 6138 | bufferDescription.dwSize = sizeof( DSBUFFERDESC ); |
| 6139 | bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS | |
| 6140 | DSBCAPS_GLOBALFOCUS | |
| 6141 | DSBCAPS_GETCURRENTPOSITION2 | |
| 6142 | DSBCAPS_LOCHARDWARE ); // Force hardware mixing |
| 6143 | bufferDescription.dwBufferBytes = dsBufferSize; |
| 6144 | bufferDescription.lpwfxFormat = &waveFormat; |
| 6145 | |
| 6146 | // Try to create the secondary DS buffer. If that doesn't work, |
| 6147 | // try to use software mixing. Otherwise, there's a problem. |
| 6148 | result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL ); |
| 6149 | if ( FAILED( result ) ) { |
| 6150 | bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS | |
| 6151 | DSBCAPS_GLOBALFOCUS | |
| 6152 | DSBCAPS_GETCURRENTPOSITION2 | |
| 6153 | DSBCAPS_LOCSOFTWARE ); // Force software mixing |
| 6154 | result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL ); |
| 6155 | if ( FAILED( result ) ) { |
| 6156 | output->Release(); |
| 6157 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!"; |
| 6158 | errorText_ = errorStream_.str(); |
| 6159 | return FAILURE; |
| 6160 | } |
| 6161 | } |
| 6162 | |
| 6163 | // Get the buffer size ... might be different from what we specified. |
| 6164 | DSBCAPS dsbcaps; |
| 6165 | dsbcaps.dwSize = sizeof( DSBCAPS ); |
| 6166 | result = buffer->GetCaps( &dsbcaps ); |
| 6167 | if ( FAILED( result ) ) { |
| 6168 | output->Release(); |
| 6169 | buffer->Release(); |
| 6170 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!"; |
| 6171 | errorText_ = errorStream_.str(); |
| 6172 | return FAILURE; |
| 6173 | } |
| 6174 | |
| 6175 | dsBufferSize = dsbcaps.dwBufferBytes; |
| 6176 | |
| 6177 | // Lock the DS buffer |
| 6178 | LPVOID audioPtr; |
| 6179 | DWORD dataLen; |
| 6180 | result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 ); |
| 6181 | if ( FAILED( result ) ) { |
| 6182 | output->Release(); |
| 6183 | buffer->Release(); |
| 6184 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!"; |
| 6185 | errorText_ = errorStream_.str(); |
| 6186 | return FAILURE; |
| 6187 | } |
| 6188 | |
| 6189 | // Zero the DS buffer |
| 6190 | ZeroMemory( audioPtr, dataLen ); |
| 6191 | |
| 6192 | // Unlock the DS buffer |
| 6193 | result = buffer->Unlock( audioPtr, dataLen, NULL, 0 ); |
| 6194 | if ( FAILED( result ) ) { |
| 6195 | output->Release(); |
| 6196 | buffer->Release(); |
| 6197 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!"; |
| 6198 | errorText_ = errorStream_.str(); |
| 6199 | return FAILURE; |
| 6200 | } |
| 6201 | |
| 6202 | ohandle = (void *) output; |
| 6203 | bhandle = (void *) buffer; |
| 6204 | } |
| 6205 | |
| 6206 | if ( mode == INPUT ) { |
| 6207 | |
| 6208 | LPDIRECTSOUNDCAPTURE input; |
| 6209 | result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL ); |
| 6210 | if ( FAILED( result ) ) { |
| 6211 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!"; |
| 6212 | errorText_ = errorStream_.str(); |
| 6213 | return FAILURE; |
| 6214 | } |
| 6215 | |
| 6216 | DSCCAPS inCaps; |
| 6217 | inCaps.dwSize = sizeof( inCaps ); |
| 6218 | result = input->GetCaps( &inCaps ); |
| 6219 | if ( FAILED( result ) ) { |
| 6220 | input->Release(); |
| 6221 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!"; |
| 6222 | errorText_ = errorStream_.str(); |
| 6223 | return FAILURE; |
| 6224 | } |
| 6225 | |
| 6226 | // Check channel information. |
| 6227 | if ( inCaps.dwChannels < channels + firstChannel ) { |
| 6228 | errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels."; |
| 6229 | return FAILURE; |
| 6230 | } |
| 6231 | |
| 6232 | // Check format information. Use 16-bit format unless user |
| 6233 | // requests 8-bit. |
| 6234 | DWORD deviceFormats; |
| 6235 | if ( channels + firstChannel == 2 ) { |
| 6236 | deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08; |
| 6237 | if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) { |
| 6238 | waveFormat.wBitsPerSample = 8; |
| 6239 | stream_.deviceFormat[mode] = RTAUDIO_SINT8; |
| 6240 | } |
| 6241 | else { // assume 16-bit is supported |
| 6242 | waveFormat.wBitsPerSample = 16; |
| 6243 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 6244 | } |
| 6245 | } |
| 6246 | else { // channel == 1 |
| 6247 | deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08; |
| 6248 | if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) { |
| 6249 | waveFormat.wBitsPerSample = 8; |
| 6250 | stream_.deviceFormat[mode] = RTAUDIO_SINT8; |
| 6251 | } |
| 6252 | else { // assume 16-bit is supported |
| 6253 | waveFormat.wBitsPerSample = 16; |
| 6254 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 6255 | } |
| 6256 | } |
| 6257 | stream_.userFormat = format; |
| 6258 | |
| 6259 | // Update wave format structure and buffer information. |
| 6260 | waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8; |
| 6261 | waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; |
| 6262 | dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels; |
| 6263 | |
| 6264 | // If the user wants an even bigger buffer, increase the device buffer size accordingly. |
| 6265 | while ( dsPointerLeadTime * 2U > dsBufferSize ) |
| 6266 | dsBufferSize *= 2; |
| 6267 | |
| 6268 | // Setup the secondary DS buffer description. |
| 6269 | DSCBUFFERDESC bufferDescription; |
| 6270 | ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) ); |
| 6271 | bufferDescription.dwSize = sizeof( DSCBUFFERDESC ); |
| 6272 | bufferDescription.dwFlags = 0; |
| 6273 | bufferDescription.dwReserved = 0; |
| 6274 | bufferDescription.dwBufferBytes = dsBufferSize; |
| 6275 | bufferDescription.lpwfxFormat = &waveFormat; |
| 6276 | |
| 6277 | // Create the capture buffer. |
| 6278 | LPDIRECTSOUNDCAPTUREBUFFER buffer; |
| 6279 | result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL ); |
| 6280 | if ( FAILED( result ) ) { |
| 6281 | input->Release(); |
| 6282 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!"; |
| 6283 | errorText_ = errorStream_.str(); |
| 6284 | return FAILURE; |
| 6285 | } |
| 6286 | |
| 6287 | // Get the buffer size ... might be different from what we specified. |
| 6288 | DSCBCAPS dscbcaps; |
| 6289 | dscbcaps.dwSize = sizeof( DSCBCAPS ); |
| 6290 | result = buffer->GetCaps( &dscbcaps ); |
| 6291 | if ( FAILED( result ) ) { |
| 6292 | input->Release(); |
| 6293 | buffer->Release(); |
| 6294 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!"; |
| 6295 | errorText_ = errorStream_.str(); |
| 6296 | return FAILURE; |
| 6297 | } |
| 6298 | |
| 6299 | dsBufferSize = dscbcaps.dwBufferBytes; |
| 6300 | |
| 6301 | // NOTE: We could have a problem here if this is a duplex stream |
| 6302 | // and the play and capture hardware buffer sizes are different |
| 6303 | // (I'm actually not sure if that is a problem or not). |
| 6304 | // Currently, we are not verifying that. |
| 6305 | |
| 6306 | // Lock the capture buffer |
| 6307 | LPVOID audioPtr; |
| 6308 | DWORD dataLen; |
| 6309 | result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 ); |
| 6310 | if ( FAILED( result ) ) { |
| 6311 | input->Release(); |
| 6312 | buffer->Release(); |
| 6313 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!"; |
| 6314 | errorText_ = errorStream_.str(); |
| 6315 | return FAILURE; |
| 6316 | } |
| 6317 | |
| 6318 | // Zero the buffer |
| 6319 | ZeroMemory( audioPtr, dataLen ); |
| 6320 | |
| 6321 | // Unlock the buffer |
| 6322 | result = buffer->Unlock( audioPtr, dataLen, NULL, 0 ); |
| 6323 | if ( FAILED( result ) ) { |
| 6324 | input->Release(); |
| 6325 | buffer->Release(); |
| 6326 | errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!"; |
| 6327 | errorText_ = errorStream_.str(); |
| 6328 | return FAILURE; |
| 6329 | } |
| 6330 | |
| 6331 | ohandle = (void *) input; |
| 6332 | bhandle = (void *) buffer; |
| 6333 | } |
| 6334 | |
| 6335 | // Set various stream parameters |
| 6336 | DsHandle *handle = 0; |
| 6337 | stream_.nDeviceChannels[mode] = channels + firstChannel; |
| 6338 | stream_.nUserChannels[mode] = channels; |
| 6339 | stream_.bufferSize = *bufferSize; |
| 6340 | stream_.channelOffset[mode] = firstChannel; |
| 6341 | stream_.deviceInterleaved[mode] = true; |
| 6342 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false; |
| 6343 | else stream_.userInterleaved = true; |
| 6344 | |
| 6345 | // Set flag for buffer conversion |
| 6346 | stream_.doConvertBuffer[mode] = false; |
| 6347 | if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode]) |
| 6348 | stream_.doConvertBuffer[mode] = true; |
| 6349 | if (stream_.userFormat != stream_.deviceFormat[mode]) |
| 6350 | stream_.doConvertBuffer[mode] = true; |
| 6351 | if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] && |
| 6352 | stream_.nUserChannels[mode] > 1 ) |
| 6353 | stream_.doConvertBuffer[mode] = true; |
| 6354 | |
| 6355 | // Allocate necessary internal buffers |
| 6356 | long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat ); |
| 6357 | stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 ); |
| 6358 | if ( stream_.userBuffer[mode] == NULL ) { |
| 6359 | errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory."; |
| 6360 | goto error; |
| 6361 | } |
| 6362 | |
| 6363 | if ( stream_.doConvertBuffer[mode] ) { |
| 6364 | |
| 6365 | bool makeBuffer = true; |
| 6366 | bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] ); |
| 6367 | if ( mode == INPUT ) { |
| 6368 | if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) { |
| 6369 | unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] ); |
| 6370 | if ( bufferBytes <= (long) bytesOut ) makeBuffer = false; |
| 6371 | } |
| 6372 | } |
| 6373 | |
| 6374 | if ( makeBuffer ) { |
| 6375 | bufferBytes *= *bufferSize; |
| 6376 | if ( stream_.deviceBuffer ) free( stream_.deviceBuffer ); |
| 6377 | stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 ); |
| 6378 | if ( stream_.deviceBuffer == NULL ) { |
| 6379 | errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory."; |
| 6380 | goto error; |
| 6381 | } |
| 6382 | } |
| 6383 | } |
| 6384 | |
| 6385 | // Allocate our DsHandle structures for the stream. |
| 6386 | if ( stream_.apiHandle == 0 ) { |
| 6387 | try { |
| 6388 | handle = new DsHandle; |
| 6389 | } |
| 6390 | catch ( std::bad_alloc& ) { |
| 6391 | errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory."; |
| 6392 | goto error; |
| 6393 | } |
| 6394 | |
| 6395 | // Create a manual-reset event. |
| 6396 | handle->condition = CreateEvent( NULL, // no security |
| 6397 | TRUE, // manual-reset |
| 6398 | FALSE, // non-signaled initially |
| 6399 | NULL ); // unnamed |
| 6400 | stream_.apiHandle = (void *) handle; |
| 6401 | } |
| 6402 | else |
| 6403 | handle = (DsHandle *) stream_.apiHandle; |
| 6404 | handle->id[mode] = ohandle; |
| 6405 | handle->buffer[mode] = bhandle; |
| 6406 | handle->dsBufferSize[mode] = dsBufferSize; |
| 6407 | handle->dsPointerLeadTime[mode] = dsPointerLeadTime; |
| 6408 | |
| 6409 | stream_.device[mode] = device; |
| 6410 | stream_.state = STREAM_STOPPED; |
| 6411 | if ( stream_.mode == OUTPUT && mode == INPUT ) |
| 6412 | // We had already set up an output stream. |
| 6413 | stream_.mode = DUPLEX; |
| 6414 | else |
| 6415 | stream_.mode = mode; |
| 6416 | stream_.nBuffers = nBuffers; |
| 6417 | stream_.sampleRate = sampleRate; |
| 6418 | |
| 6419 | // Setup the buffer conversion information structure. |
| 6420 | if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel ); |
| 6421 | |
| 6422 | // Setup the callback thread. |
| 6423 | if ( stream_.callbackInfo.isRunning == false ) { |
| 6424 | unsigned threadId; |
| 6425 | stream_.callbackInfo.isRunning = true; |
| 6426 | stream_.callbackInfo.object = (void *) this; |
| 6427 | stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler, |
| 6428 | &stream_.callbackInfo, 0, &threadId ); |
| 6429 | if ( stream_.callbackInfo.thread == 0 ) { |
| 6430 | errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!"; |
| 6431 | goto error; |
| 6432 | } |
| 6433 | |
| 6434 | // Boost DS thread priority |
| 6435 | SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST ); |
| 6436 | } |
| 6437 | return SUCCESS; |
| 6438 | |
| 6439 | error: |
| 6440 | if ( handle ) { |
| 6441 | if ( handle->buffer[0] ) { // the object pointer can be NULL and valid |
| 6442 | LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0]; |
| 6443 | LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0]; |
| 6444 | if ( buffer ) buffer->Release(); |
| 6445 | object->Release(); |
| 6446 | } |
| 6447 | if ( handle->buffer[1] ) { |
| 6448 | LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1]; |
| 6449 | LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1]; |
| 6450 | if ( buffer ) buffer->Release(); |
| 6451 | object->Release(); |
| 6452 | } |
| 6453 | CloseHandle( handle->condition ); |
| 6454 | delete handle; |
| 6455 | stream_.apiHandle = 0; |
| 6456 | } |
| 6457 | |
| 6458 | for ( int i=0; i<2; i++ ) { |
| 6459 | if ( stream_.userBuffer[i] ) { |
| 6460 | free( stream_.userBuffer[i] ); |
| 6461 | stream_.userBuffer[i] = 0; |
| 6462 | } |
| 6463 | } |
| 6464 | |
| 6465 | if ( stream_.deviceBuffer ) { |
| 6466 | free( stream_.deviceBuffer ); |
| 6467 | stream_.deviceBuffer = 0; |
| 6468 | } |
| 6469 | |
| 6470 | stream_.state = STREAM_CLOSED; |
| 6471 | return FAILURE; |
| 6472 | } |
| 6473 | |
| 6474 | void RtApiDs :: closeStream() |
| 6475 | { |
| 6476 | if ( stream_.state == STREAM_CLOSED ) { |
| 6477 | errorText_ = "RtApiDs::closeStream(): no open stream to close!"; |
| 6478 | error( RTAUDIO_WARNING ); |
| 6479 | return; |
| 6480 | } |
| 6481 | |
| 6482 | // Stop the callback thread. |
| 6483 | stream_.callbackInfo.isRunning = false; |
| 6484 | WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE ); |
| 6485 | CloseHandle( (HANDLE) stream_.callbackInfo.thread ); |
| 6486 | |
| 6487 | DsHandle *handle = (DsHandle *) stream_.apiHandle; |
| 6488 | if ( handle ) { |
| 6489 | if ( handle->buffer[0] ) { // the object pointer can be NULL and valid |
| 6490 | LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0]; |
| 6491 | LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0]; |
| 6492 | if ( buffer ) { |
| 6493 | buffer->Stop(); |
| 6494 | buffer->Release(); |
| 6495 | } |
| 6496 | object->Release(); |
| 6497 | } |
| 6498 | if ( handle->buffer[1] ) { |
| 6499 | LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1]; |
| 6500 | LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1]; |
| 6501 | if ( buffer ) { |
| 6502 | buffer->Stop(); |
| 6503 | buffer->Release(); |
| 6504 | } |
| 6505 | object->Release(); |
| 6506 | } |
| 6507 | CloseHandle( handle->condition ); |
| 6508 | delete handle; |
| 6509 | stream_.apiHandle = 0; |
| 6510 | } |
| 6511 | |
| 6512 | for ( int i=0; i<2; i++ ) { |
| 6513 | if ( stream_.userBuffer[i] ) { |
| 6514 | free( stream_.userBuffer[i] ); |
| 6515 | stream_.userBuffer[i] = 0; |
| 6516 | } |
| 6517 | } |
| 6518 | |
| 6519 | if ( stream_.deviceBuffer ) { |
| 6520 | free( stream_.deviceBuffer ); |
| 6521 | stream_.deviceBuffer = 0; |
| 6522 | } |
| 6523 | |
| 6524 | clearStreamInfo(); |
| 6525 | //stream_.mode = UNINITIALIZED; |
| 6526 | //stream_.state = STREAM_CLOSED; |
| 6527 | } |
| 6528 | |
| 6529 | RtAudioErrorType RtApiDs :: startStream() |
| 6530 | { |
| 6531 | if ( stream_.state != STREAM_STOPPED ) { |
| 6532 | if ( stream_.state == STREAM_RUNNING ) |
| 6533 | errorText_ = "RtApiDs::startStream(): the stream is already running!"; |
| 6534 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 6535 | errorText_ = "RtApiDs::startStream(): the stream is stopping or closed!"; |
| 6536 | return error( RTAUDIO_WARNING ); |
| 6537 | } |
| 6538 | |
| 6539 | /* |
| 6540 | #if defined( HAVE_GETTIMEOFDAY ) |
| 6541 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 6542 | #endif |
| 6543 | */ |
| 6544 | |
| 6545 | DsHandle *handle = (DsHandle *) stream_.apiHandle; |
| 6546 | |
| 6547 | // Increase scheduler frequency on lesser windows (a side-effect of |
| 6548 | // increasing timer accuracy). On greater windows (Win2K or later), |
| 6549 | // this is already in effect. |
| 6550 | timeBeginPeriod( 1 ); |
| 6551 | |
| 6552 | buffersRolling = false; |
| 6553 | duplexPrerollBytes = 0; |
| 6554 | |
| 6555 | if ( stream_.mode == DUPLEX ) { |
| 6556 | // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize. |
| 6557 | duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] ); |
| 6558 | } |
| 6559 | |
| 6560 | HRESULT result = 0; |
| 6561 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 6562 | |
| 6563 | LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0]; |
| 6564 | result = buffer->Play( 0, 0, DSBPLAY_LOOPING ); |
| 6565 | if ( FAILED( result ) ) { |
| 6566 | errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!"; |
| 6567 | errorText_ = errorStream_.str(); |
| 6568 | goto unlock; |
| 6569 | } |
| 6570 | } |
| 6571 | |
| 6572 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) { |
| 6573 | |
| 6574 | LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1]; |
| 6575 | result = buffer->Start( DSCBSTART_LOOPING ); |
| 6576 | if ( FAILED( result ) ) { |
| 6577 | errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!"; |
| 6578 | errorText_ = errorStream_.str(); |
| 6579 | goto unlock; |
| 6580 | } |
| 6581 | } |
| 6582 | |
| 6583 | handle->drainCounter = 0; |
| 6584 | handle->internalDrain = false; |
| 6585 | ResetEvent( handle->condition ); |
| 6586 | stream_.state = STREAM_RUNNING; |
| 6587 | |
| 6588 | unlock: |
| 6589 | if ( FAILED( result ) ) error( RTAUDIO_SYSTEM_ERROR ); |
| 6590 | return RTAUDIO_NO_ERROR; |
| 6591 | } |
| 6592 | |
| 6593 | RtAudioErrorType RtApiDs :: stopStream() |
| 6594 | { |
| 6595 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 6596 | if ( stream_.state == STREAM_STOPPED ) |
| 6597 | errorText_ = "RtApiDs::stopStream(): the stream is already stopped!"; |
| 6598 | else if ( stream_.state == STREAM_CLOSED ) |
| 6599 | errorText_ = "RtApiDs::stopStream(): the stream is closed!"; |
| 6600 | return error( RTAUDIO_WARNING ); |
| 6601 | } |
| 6602 | |
| 6603 | HRESULT result = 0; |
| 6604 | LPVOID audioPtr; |
| 6605 | DWORD dataLen; |
| 6606 | DsHandle *handle = (DsHandle *) stream_.apiHandle; |
| 6607 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 6608 | if ( handle->drainCounter == 0 ) { |
| 6609 | handle->drainCounter = 2; |
| 6610 | WaitForSingleObject( handle->condition, INFINITE ); // block until signaled |
| 6611 | } |
| 6612 | |
| 6613 | stream_.state = STREAM_STOPPED; |
| 6614 | |
| 6615 | MUTEX_LOCK( &stream_.mutex ); |
| 6616 | |
| 6617 | // Stop the buffer and clear memory |
| 6618 | LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0]; |
| 6619 | result = buffer->Stop(); |
| 6620 | if ( FAILED( result ) ) { |
| 6621 | errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!"; |
| 6622 | errorText_ = errorStream_.str(); |
| 6623 | goto unlock; |
| 6624 | } |
| 6625 | |
| 6626 | // Lock the buffer and clear it so that if we start to play again, |
| 6627 | // we won't have old data playing. |
| 6628 | result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 ); |
| 6629 | if ( FAILED( result ) ) { |
| 6630 | errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!"; |
| 6631 | errorText_ = errorStream_.str(); |
| 6632 | goto unlock; |
| 6633 | } |
| 6634 | |
| 6635 | // Zero the DS buffer |
| 6636 | ZeroMemory( audioPtr, dataLen ); |
| 6637 | |
| 6638 | // Unlock the DS buffer |
| 6639 | result = buffer->Unlock( audioPtr, dataLen, NULL, 0 ); |
| 6640 | if ( FAILED( result ) ) { |
| 6641 | errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!"; |
| 6642 | errorText_ = errorStream_.str(); |
| 6643 | goto unlock; |
| 6644 | } |
| 6645 | |
| 6646 | // If we start playing again, we must begin at beginning of buffer. |
| 6647 | handle->bufferPointer[0] = 0; |
| 6648 | } |
| 6649 | |
| 6650 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) { |
| 6651 | LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1]; |
| 6652 | audioPtr = NULL; |
| 6653 | dataLen = 0; |
| 6654 | |
| 6655 | stream_.state = STREAM_STOPPED; |
| 6656 | |
| 6657 | if ( stream_.mode != DUPLEX ) |
| 6658 | MUTEX_LOCK( &stream_.mutex ); |
| 6659 | |
| 6660 | result = buffer->Stop(); |
| 6661 | if ( FAILED( result ) ) { |
| 6662 | errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!"; |
| 6663 | errorText_ = errorStream_.str(); |
| 6664 | goto unlock; |
| 6665 | } |
| 6666 | |
| 6667 | // Lock the buffer and clear it so that if we start to play again, |
| 6668 | // we won't have old data playing. |
| 6669 | result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 ); |
| 6670 | if ( FAILED( result ) ) { |
| 6671 | errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!"; |
| 6672 | errorText_ = errorStream_.str(); |
| 6673 | goto unlock; |
| 6674 | } |
| 6675 | |
| 6676 | // Zero the DS buffer |
| 6677 | ZeroMemory( audioPtr, dataLen ); |
| 6678 | |
| 6679 | // Unlock the DS buffer |
| 6680 | result = buffer->Unlock( audioPtr, dataLen, NULL, 0 ); |
| 6681 | if ( FAILED( result ) ) { |
| 6682 | errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!"; |
| 6683 | errorText_ = errorStream_.str(); |
| 6684 | goto unlock; |
| 6685 | } |
| 6686 | |
| 6687 | // If we start recording again, we must begin at beginning of buffer. |
| 6688 | handle->bufferPointer[1] = 0; |
| 6689 | } |
| 6690 | |
| 6691 | unlock: |
| 6692 | timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows. |
| 6693 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6694 | |
| 6695 | if ( FAILED( result ) ) error( RTAUDIO_SYSTEM_ERROR ); |
| 6696 | return RTAUDIO_NO_ERROR; |
| 6697 | } |
| 6698 | |
| 6699 | RtAudioErrorType RtApiDs :: abortStream() |
| 6700 | { |
| 6701 | if ( stream_.state != STREAM_RUNNING ) { |
| 6702 | if ( stream_.state == STREAM_STOPPED ) |
| 6703 | errorText_ = "RtApiDs::abortStream(): the stream is already stopped!"; |
| 6704 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 6705 | errorText_ = "RtApiDs::abortStream(): the stream is stopping or closed!"; |
| 6706 | return error( RTAUDIO_WARNING ); |
| 6707 | } |
| 6708 | |
| 6709 | DsHandle *handle = (DsHandle *) stream_.apiHandle; |
| 6710 | handle->drainCounter = 2; |
| 6711 | |
| 6712 | return stopStream(); |
| 6713 | } |
| 6714 | |
| 6715 | void RtApiDs :: callbackEvent() |
| 6716 | { |
| 6717 | if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) { |
| 6718 | Sleep( 50 ); // sleep 50 milliseconds |
| 6719 | return; |
| 6720 | } |
| 6721 | |
| 6722 | if ( stream_.state == STREAM_CLOSED ) { |
| 6723 | errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!"; |
| 6724 | error( RTAUDIO_WARNING ); |
| 6725 | return; |
| 6726 | } |
| 6727 | |
| 6728 | CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo; |
| 6729 | DsHandle *handle = (DsHandle *) stream_.apiHandle; |
| 6730 | |
| 6731 | // Check if we were draining the stream and signal is finished. |
| 6732 | if ( handle->drainCounter > stream_.nBuffers + 2 ) { |
| 6733 | |
| 6734 | stream_.state = STREAM_STOPPING; |
| 6735 | if ( handle->internalDrain == false ) |
| 6736 | SetEvent( handle->condition ); |
| 6737 | else |
| 6738 | stopStream(); |
| 6739 | return; |
| 6740 | } |
| 6741 | |
| 6742 | // Invoke user callback to get fresh output data UNLESS we are |
| 6743 | // draining stream. |
| 6744 | if ( handle->drainCounter == 0 ) { |
| 6745 | RtAudioCallback callback = (RtAudioCallback) info->callback; |
| 6746 | double streamTime = getStreamTime(); |
| 6747 | RtAudioStreamStatus status = 0; |
| 6748 | if ( stream_.mode != INPUT && handle->xrun[0] == true ) { |
| 6749 | status |= RTAUDIO_OUTPUT_UNDERFLOW; |
| 6750 | handle->xrun[0] = false; |
| 6751 | } |
| 6752 | if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) { |
| 6753 | status |= RTAUDIO_INPUT_OVERFLOW; |
| 6754 | handle->xrun[1] = false; |
| 6755 | } |
| 6756 | int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1], |
| 6757 | stream_.bufferSize, streamTime, status, info->userData ); |
| 6758 | if ( cbReturnValue == 2 ) { |
| 6759 | stream_.state = STREAM_STOPPING; |
| 6760 | handle->drainCounter = 2; |
| 6761 | abortStream(); |
| 6762 | return; |
| 6763 | } |
| 6764 | else if ( cbReturnValue == 1 ) { |
| 6765 | handle->drainCounter = 1; |
| 6766 | handle->internalDrain = true; |
| 6767 | } |
| 6768 | } |
| 6769 | |
| 6770 | HRESULT result; |
| 6771 | DWORD currentWritePointer, safeWritePointer; |
| 6772 | DWORD currentReadPointer, safeReadPointer; |
| 6773 | UINT nextWritePointer; |
| 6774 | |
| 6775 | LPVOID buffer1 = NULL; |
| 6776 | LPVOID buffer2 = NULL; |
| 6777 | DWORD bufferSize1 = 0; |
| 6778 | DWORD bufferSize2 = 0; |
| 6779 | |
| 6780 | char *buffer; |
| 6781 | long bufferBytes; |
| 6782 | |
| 6783 | MUTEX_LOCK( &stream_.mutex ); |
| 6784 | if ( stream_.state == STREAM_STOPPED ) { |
| 6785 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6786 | return; |
| 6787 | } |
| 6788 | |
| 6789 | if ( buffersRolling == false ) { |
| 6790 | if ( stream_.mode == DUPLEX ) { |
| 6791 | //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] ); |
| 6792 | |
| 6793 | // It takes a while for the devices to get rolling. As a result, |
| 6794 | // there's no guarantee that the capture and write device pointers |
| 6795 | // will move in lockstep. Wait here for both devices to start |
| 6796 | // rolling, and then set our buffer pointers accordingly. |
| 6797 | // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600 |
| 6798 | // bytes later than the write buffer. |
| 6799 | |
| 6800 | // Stub: a serious risk of having a pre-emptive scheduling round |
| 6801 | // take place between the two GetCurrentPosition calls... but I'm |
| 6802 | // really not sure how to solve the problem. Temporarily boost to |
| 6803 | // Realtime priority, maybe; but I'm not sure what priority the |
| 6804 | // DirectSound service threads run at. We *should* be roughly |
| 6805 | // within a ms or so of correct. |
| 6806 | |
| 6807 | LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0]; |
| 6808 | LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1]; |
| 6809 | |
| 6810 | DWORD startSafeWritePointer, startSafeReadPointer; |
| 6811 | |
| 6812 | result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer ); |
| 6813 | if ( FAILED( result ) ) { |
| 6814 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!"; |
| 6815 | errorText_ = errorStream_.str(); |
| 6816 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6817 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6818 | return; |
| 6819 | } |
| 6820 | result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer ); |
| 6821 | if ( FAILED( result ) ) { |
| 6822 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!"; |
| 6823 | errorText_ = errorStream_.str(); |
| 6824 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6825 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6826 | return; |
| 6827 | } |
| 6828 | while ( true ) { |
| 6829 | result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer ); |
| 6830 | if ( FAILED( result ) ) { |
| 6831 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!"; |
| 6832 | errorText_ = errorStream_.str(); |
| 6833 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6834 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6835 | return; |
| 6836 | } |
| 6837 | result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer ); |
| 6838 | if ( FAILED( result ) ) { |
| 6839 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!"; |
| 6840 | errorText_ = errorStream_.str(); |
| 6841 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6842 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6843 | return; |
| 6844 | } |
| 6845 | if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break; |
| 6846 | Sleep( 1 ); |
| 6847 | } |
| 6848 | |
| 6849 | //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] ); |
| 6850 | |
| 6851 | handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0]; |
| 6852 | if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0]; |
| 6853 | handle->bufferPointer[1] = safeReadPointer; |
| 6854 | } |
| 6855 | else if ( stream_.mode == OUTPUT ) { |
| 6856 | |
| 6857 | // Set the proper nextWritePosition after initial startup. |
| 6858 | LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0]; |
| 6859 | result = dsWriteBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer ); |
| 6860 | if ( FAILED( result ) ) { |
| 6861 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!"; |
| 6862 | errorText_ = errorStream_.str(); |
| 6863 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6864 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6865 | return; |
| 6866 | } |
| 6867 | handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0]; |
| 6868 | if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0]; |
| 6869 | } |
| 6870 | |
| 6871 | buffersRolling = true; |
| 6872 | } |
| 6873 | |
| 6874 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 6875 | |
| 6876 | LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0]; |
| 6877 | |
| 6878 | if ( handle->drainCounter > 1 ) { // write zeros to the output stream |
| 6879 | bufferBytes = stream_.bufferSize * stream_.nUserChannels[0]; |
| 6880 | bufferBytes *= formatBytes( stream_.userFormat ); |
| 6881 | memset( stream_.userBuffer[0], 0, bufferBytes ); |
| 6882 | } |
| 6883 | |
| 6884 | // Setup parameters and do buffer conversion if necessary. |
| 6885 | if ( stream_.doConvertBuffer[0] ) { |
| 6886 | buffer = stream_.deviceBuffer; |
| 6887 | convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] ); |
| 6888 | bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0]; |
| 6889 | bufferBytes *= formatBytes( stream_.deviceFormat[0] ); |
| 6890 | } |
| 6891 | else { |
| 6892 | buffer = stream_.userBuffer[0]; |
| 6893 | bufferBytes = stream_.bufferSize * stream_.nUserChannels[0]; |
| 6894 | bufferBytes *= formatBytes( stream_.userFormat ); |
| 6895 | } |
| 6896 | |
| 6897 | // No byte swapping necessary in DirectSound implementation. |
| 6898 | |
| 6899 | // Ahhh ... windoze. 16-bit data is signed but 8-bit data is |
| 6900 | // unsigned. So, we need to convert our signed 8-bit data here to |
| 6901 | // unsigned. |
| 6902 | if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 ) |
| 6903 | for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 ); |
| 6904 | |
| 6905 | DWORD dsBufferSize = handle->dsBufferSize[0]; |
| 6906 | nextWritePointer = handle->bufferPointer[0]; |
| 6907 | |
| 6908 | DWORD endWrite, leadPointer; |
| 6909 | while ( true ) { |
| 6910 | // Find out where the read and "safe write" pointers are. |
| 6911 | result = dsBuffer->GetCurrentPosition( ¤tWritePointer, &safeWritePointer ); |
| 6912 | if ( FAILED( result ) ) { |
| 6913 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!"; |
| 6914 | errorText_ = errorStream_.str(); |
| 6915 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6916 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6917 | return; |
| 6918 | } |
| 6919 | |
| 6920 | // We will copy our output buffer into the region between |
| 6921 | // safeWritePointer and leadPointer. If leadPointer is not |
| 6922 | // beyond the next endWrite position, wait until it is. |
| 6923 | leadPointer = safeWritePointer + handle->dsPointerLeadTime[0]; |
| 6924 | //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl; |
| 6925 | if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize; |
| 6926 | if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset |
| 6927 | endWrite = nextWritePointer + bufferBytes; |
| 6928 | |
| 6929 | // Check whether the entire write region is behind the play pointer. |
| 6930 | if ( leadPointer >= endWrite ) break; |
| 6931 | |
| 6932 | // If we are here, then we must wait until the leadPointer advances |
| 6933 | // beyond the end of our next write region. We use the |
| 6934 | // Sleep() function to suspend operation until that happens. |
| 6935 | double millis = ( endWrite - leadPointer ) * 1000.0; |
| 6936 | millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate); |
| 6937 | if ( millis < 1.0 ) millis = 1.0; |
| 6938 | Sleep( (DWORD) millis ); |
| 6939 | } |
| 6940 | |
| 6941 | if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize ) |
| 6942 | || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) { |
| 6943 | // We've strayed into the forbidden zone ... resync the read pointer. |
| 6944 | handle->xrun[0] = true; |
| 6945 | nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes; |
| 6946 | if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize; |
| 6947 | handle->bufferPointer[0] = nextWritePointer; |
| 6948 | endWrite = nextWritePointer + bufferBytes; |
| 6949 | } |
| 6950 | |
| 6951 | // Lock free space in the buffer |
| 6952 | result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1, |
| 6953 | &bufferSize1, &buffer2, &bufferSize2, 0 ); |
| 6954 | if ( FAILED( result ) ) { |
| 6955 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!"; |
| 6956 | errorText_ = errorStream_.str(); |
| 6957 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6958 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6959 | return; |
| 6960 | } |
| 6961 | |
| 6962 | // Copy our buffer into the DS buffer |
| 6963 | CopyMemory( buffer1, buffer, bufferSize1 ); |
| 6964 | if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 ); |
| 6965 | |
| 6966 | // Update our buffer offset and unlock sound buffer |
| 6967 | dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 ); |
| 6968 | if ( FAILED( result ) ) { |
| 6969 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!"; |
| 6970 | errorText_ = errorStream_.str(); |
| 6971 | MUTEX_UNLOCK( &stream_.mutex ); |
| 6972 | error( RTAUDIO_SYSTEM_ERROR ); |
| 6973 | return; |
| 6974 | } |
| 6975 | nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize; |
| 6976 | handle->bufferPointer[0] = nextWritePointer; |
| 6977 | } |
| 6978 | |
| 6979 | // Don't bother draining input |
| 6980 | if ( handle->drainCounter ) { |
| 6981 | handle->drainCounter++; |
| 6982 | goto unlock; |
| 6983 | } |
| 6984 | |
| 6985 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) { |
| 6986 | |
| 6987 | // Setup parameters. |
| 6988 | if ( stream_.doConvertBuffer[1] ) { |
| 6989 | buffer = stream_.deviceBuffer; |
| 6990 | bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1]; |
| 6991 | bufferBytes *= formatBytes( stream_.deviceFormat[1] ); |
| 6992 | } |
| 6993 | else { |
| 6994 | buffer = stream_.userBuffer[1]; |
| 6995 | bufferBytes = stream_.bufferSize * stream_.nUserChannels[1]; |
| 6996 | bufferBytes *= formatBytes( stream_.userFormat ); |
| 6997 | } |
| 6998 | |
| 6999 | LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1]; |
| 7000 | long nextReadPointer = handle->bufferPointer[1]; |
| 7001 | DWORD dsBufferSize = handle->dsBufferSize[1]; |
| 7002 | |
| 7003 | // Find out where the write and "safe read" pointers are. |
| 7004 | result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer ); |
| 7005 | if ( FAILED( result ) ) { |
| 7006 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!"; |
| 7007 | errorText_ = errorStream_.str(); |
| 7008 | MUTEX_UNLOCK( &stream_.mutex ); |
| 7009 | error( RTAUDIO_SYSTEM_ERROR ); |
| 7010 | return; |
| 7011 | } |
| 7012 | |
| 7013 | if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset |
| 7014 | DWORD endRead = nextReadPointer + bufferBytes; |
| 7015 | |
| 7016 | // Handling depends on whether we are INPUT or DUPLEX. |
| 7017 | // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode, |
| 7018 | // then a wait here will drag the write pointers into the forbidden zone. |
| 7019 | // |
| 7020 | // In DUPLEX mode, rather than wait, we will back off the read pointer until |
| 7021 | // it's in a safe position. This causes dropouts, but it seems to be the only |
| 7022 | // practical way to sync up the read and write pointers reliably, given the |
| 7023 | // the very complex relationship between phase and increment of the read and write |
| 7024 | // pointers. |
| 7025 | // |
| 7026 | // In order to minimize audible dropouts in DUPLEX mode, we will |
| 7027 | // provide a pre-roll period of 0.5 seconds in which we return |
| 7028 | // zeros from the read buffer while the pointers sync up. |
| 7029 | |
| 7030 | if ( stream_.mode == DUPLEX ) { |
| 7031 | if ( safeReadPointer < endRead ) { |
| 7032 | if ( duplexPrerollBytes <= 0 ) { |
| 7033 | // Pre-roll time over. Be more aggressive. |
| 7034 | int adjustment = endRead-safeReadPointer; |
| 7035 | |
| 7036 | handle->xrun[1] = true; |
| 7037 | // Two cases: |
| 7038 | // - large adjustments: we've probably run out of CPU cycles, so just resync exactly, |
| 7039 | // and perform fine adjustments later. |
| 7040 | // - small adjustments: back off by twice as much. |
| 7041 | if ( adjustment >= 2*bufferBytes ) |
| 7042 | nextReadPointer = safeReadPointer-2*bufferBytes; |
| 7043 | else |
| 7044 | nextReadPointer = safeReadPointer-bufferBytes-adjustment; |
| 7045 | |
| 7046 | if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize; |
| 7047 | |
| 7048 | } |
| 7049 | else { |
| 7050 | // In pre=roll time. Just do it. |
| 7051 | nextReadPointer = safeReadPointer - bufferBytes; |
| 7052 | while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize; |
| 7053 | } |
| 7054 | endRead = nextReadPointer + bufferBytes; |
| 7055 | } |
| 7056 | } |
| 7057 | else { // mode == INPUT |
| 7058 | while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) { |
| 7059 | // See comments for playback. |
| 7060 | double millis = (endRead - safeReadPointer) * 1000.0; |
| 7061 | millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate); |
| 7062 | if ( millis < 1.0 ) millis = 1.0; |
| 7063 | Sleep( (DWORD) millis ); |
| 7064 | |
| 7065 | // Wake up and find out where we are now. |
| 7066 | result = dsBuffer->GetCurrentPosition( ¤tReadPointer, &safeReadPointer ); |
| 7067 | if ( FAILED( result ) ) { |
| 7068 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!"; |
| 7069 | errorText_ = errorStream_.str(); |
| 7070 | MUTEX_UNLOCK( &stream_.mutex ); |
| 7071 | error( RTAUDIO_SYSTEM_ERROR ); |
| 7072 | return; |
| 7073 | } |
| 7074 | |
| 7075 | if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset |
| 7076 | } |
| 7077 | } |
| 7078 | |
| 7079 | // Lock free space in the buffer |
| 7080 | result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1, |
| 7081 | &bufferSize1, &buffer2, &bufferSize2, 0 ); |
| 7082 | if ( FAILED( result ) ) { |
| 7083 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!"; |
| 7084 | errorText_ = errorStream_.str(); |
| 7085 | MUTEX_UNLOCK( &stream_.mutex ); |
| 7086 | error( RTAUDIO_SYSTEM_ERROR ); |
| 7087 | return; |
| 7088 | } |
| 7089 | |
| 7090 | if ( duplexPrerollBytes <= 0 ) { |
| 7091 | // Copy our buffer into the DS buffer |
| 7092 | CopyMemory( buffer, buffer1, bufferSize1 ); |
| 7093 | if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 ); |
| 7094 | } |
| 7095 | else { |
| 7096 | memset( buffer, 0, bufferSize1 ); |
| 7097 | if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 ); |
| 7098 | duplexPrerollBytes -= bufferSize1 + bufferSize2; |
| 7099 | } |
| 7100 | |
| 7101 | // Update our buffer offset and unlock sound buffer |
| 7102 | nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize; |
| 7103 | dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 ); |
| 7104 | if ( FAILED( result ) ) { |
| 7105 | errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!"; |
| 7106 | errorText_ = errorStream_.str(); |
| 7107 | MUTEX_UNLOCK( &stream_.mutex ); |
| 7108 | error( RTAUDIO_SYSTEM_ERROR ); |
| 7109 | return; |
| 7110 | } |
| 7111 | handle->bufferPointer[1] = nextReadPointer; |
| 7112 | |
| 7113 | // No byte swapping necessary in DirectSound implementation. |
| 7114 | |
| 7115 | // If necessary, convert 8-bit data from unsigned to signed. |
| 7116 | if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 ) |
| 7117 | for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 ); |
| 7118 | |
| 7119 | // Do buffer conversion if necessary. |
| 7120 | if ( stream_.doConvertBuffer[1] ) |
| 7121 | convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] ); |
| 7122 | } |
| 7123 | |
| 7124 | unlock: |
| 7125 | MUTEX_UNLOCK( &stream_.mutex ); |
| 7126 | RtApi::tickStreamTime(); |
| 7127 | } |
| 7128 | |
| 7129 | // Definitions for utility functions and callbacks |
| 7130 | // specific to the DirectSound implementation. |
| 7131 | |
| 7132 | static unsigned __stdcall callbackHandler( void *ptr ) |
| 7133 | { |
| 7134 | CallbackInfo *info = (CallbackInfo *) ptr; |
| 7135 | RtApiDs *object = (RtApiDs *) info->object; |
| 7136 | bool* isRunning = &info->isRunning; |
| 7137 | |
| 7138 | while ( *isRunning == true ) { |
| 7139 | object->callbackEvent(); |
| 7140 | } |
| 7141 | |
| 7142 | _endthreadex( 0 ); |
| 7143 | return 0; |
| 7144 | } |
| 7145 | |
| 7146 | static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid, |
| 7147 | LPCTSTR description, |
| 7148 | LPCTSTR /*module*/, |
| 7149 | LPVOID lpContext ) |
| 7150 | { |
| 7151 | struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext; |
| 7152 | std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices; |
| 7153 | |
| 7154 | HRESULT hr; |
| 7155 | bool validDevice = false; |
| 7156 | if ( probeInfo.isInput == true ) { |
| 7157 | DSCCAPS caps; |
| 7158 | LPDIRECTSOUNDCAPTURE object; |
| 7159 | |
| 7160 | hr = DirectSoundCaptureCreate( lpguid, &object, NULL ); |
| 7161 | if ( hr != DS_OK ) return TRUE; |
| 7162 | |
| 7163 | caps.dwSize = sizeof(caps); |
| 7164 | hr = object->GetCaps( &caps ); |
| 7165 | if ( hr == DS_OK ) { |
| 7166 | if ( caps.dwChannels > 0 && caps.dwFormats > 0 ) |
| 7167 | validDevice = true; |
| 7168 | } |
| 7169 | object->Release(); |
| 7170 | } |
| 7171 | else { |
| 7172 | DSCAPS caps; |
| 7173 | LPDIRECTSOUND object; |
| 7174 | hr = DirectSoundCreate( lpguid, &object, NULL ); |
| 7175 | if ( hr != DS_OK ) return TRUE; |
| 7176 | |
| 7177 | caps.dwSize = sizeof(caps); |
| 7178 | hr = object->GetCaps( &caps ); |
| 7179 | if ( hr == DS_OK ) { |
| 7180 | if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO ) |
| 7181 | validDevice = true; |
| 7182 | } |
| 7183 | object->Release(); |
| 7184 | } |
| 7185 | |
| 7186 | // If good device, then save its name and guid. |
| 7187 | std::string name = convertCharPointerToStdString( description ); |
| 7188 | |
| 7189 | if ( validDevice ) { |
| 7190 | for ( unsigned int i=0; i<dsDevices.size(); i++ ) { |
| 7191 | if ( dsDevices[i].name == name ) { |
| 7192 | if ( probeInfo.isInput && dsDevices[i].id[1] == lpguid) |
| 7193 | { |
| 7194 | dsDevices[i].found = true; |
| 7195 | dsDevices[i].validId[1] = true; |
| 7196 | } |
| 7197 | else if (dsDevices[i].id[0] == lpguid) |
| 7198 | { |
| 7199 | dsDevices[i].found = true; |
| 7200 | dsDevices[i].validId[0] = true; |
| 7201 | } |
| 7202 | return TRUE; |
| 7203 | } |
| 7204 | } |
| 7205 | |
| 7206 | DsDevice device; |
| 7207 | device.name = name; |
| 7208 | device.found = true; |
| 7209 | if ( probeInfo.isInput ) { |
| 7210 | device.id[1] = lpguid; |
| 7211 | device.validId[1] = true; |
| 7212 | } |
| 7213 | else { |
| 7214 | device.id[0] = lpguid; |
| 7215 | device.validId[0] = true; |
| 7216 | } |
| 7217 | dsDevices.push_back( device ); |
| 7218 | } |
| 7219 | |
| 7220 | return TRUE; |
| 7221 | } |
| 7222 | |
| 7223 | static const char* getErrorString( int code ) |
| 7224 | { |
| 7225 | switch ( code ) { |
| 7226 | |
| 7227 | case DSERR_ALLOCATED: |
| 7228 | return "Already allocated"; |
| 7229 | |
| 7230 | case DSERR_CONTROLUNAVAIL: |
| 7231 | return "Control unavailable"; |
| 7232 | |
| 7233 | case DSERR_INVALIDPARAM: |
| 7234 | return "Invalid parameter"; |
| 7235 | |
| 7236 | case DSERR_INVALIDCALL: |
| 7237 | return "Invalid call"; |
| 7238 | |
| 7239 | case DSERR_GENERIC: |
| 7240 | return "Generic error"; |
| 7241 | |
| 7242 | case DSERR_PRIOLEVELNEEDED: |
| 7243 | return "Priority level needed"; |
| 7244 | |
| 7245 | case DSERR_OUTOFMEMORY: |
| 7246 | return "Out of memory"; |
| 7247 | |
| 7248 | case DSERR_BADFORMAT: |
| 7249 | return "The sample rate or the channel format is not supported"; |
| 7250 | |
| 7251 | case DSERR_UNSUPPORTED: |
| 7252 | return "Not supported"; |
| 7253 | |
| 7254 | case DSERR_NODRIVER: |
| 7255 | return "No driver"; |
| 7256 | |
| 7257 | case DSERR_ALREADYINITIALIZED: |
| 7258 | return "Already initialized"; |
| 7259 | |
| 7260 | case DSERR_NOAGGREGATION: |
| 7261 | return "No aggregation"; |
| 7262 | |
| 7263 | case DSERR_BUFFERLOST: |
| 7264 | return "Buffer lost"; |
| 7265 | |
| 7266 | case DSERR_OTHERAPPHASPRIO: |
| 7267 | return "Another application already has priority"; |
| 7268 | |
| 7269 | case DSERR_UNINITIALIZED: |
| 7270 | return "Uninitialized"; |
| 7271 | |
| 7272 | default: |
| 7273 | return "DirectSound unknown error"; |
| 7274 | } |
| 7275 | } |
| 7276 | //******************** End of __WINDOWS_DS__ *********************// |
| 7277 | #endif |
| 7278 | |
| 7279 | |
| 7280 | #if defined(__LINUX_ALSA__) |
| 7281 | |
| 7282 | #include <alsa/asoundlib.h> |
| 7283 | #include <unistd.h> |
| 7284 | |
| 7285 | // A structure to hold various information related to the ALSA API |
| 7286 | // implementation. |
| 7287 | struct AlsaHandle { |
| 7288 | snd_pcm_t *handles[2]; |
| 7289 | bool synchronized; |
| 7290 | bool xrun[2]; |
| 7291 | pthread_cond_t runnable_cv; |
| 7292 | bool runnable; |
| 7293 | |
| 7294 | AlsaHandle() |
| 7295 | #if _cplusplus >= 201103L |
| 7296 | :handles{nullptr, nullptr}, synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; } |
| 7297 | #else |
| 7298 | : synchronized(false), runnable(false) { handles[0] = NULL; handles[1] = NULL; xrun[0] = false; xrun[1] = false; } |
| 7299 | #endif |
| 7300 | }; |
| 7301 | |
| 7302 | static void *alsaCallbackHandler( void * ptr ); |
| 7303 | |
| 7304 | RtApiAlsa :: RtApiAlsa() |
| 7305 | { |
| 7306 | // Nothing to do here. |
| 7307 | } |
| 7308 | |
| 7309 | RtApiAlsa :: ~RtApiAlsa() |
| 7310 | { |
| 7311 | if ( stream_.state != STREAM_CLOSED ) closeStream(); |
| 7312 | } |
| 7313 | |
| 7314 | unsigned int RtApiAlsa :: getDeviceCount( void ) |
| 7315 | { |
| 7316 | unsigned nDevices = 0; |
| 7317 | int result, subdevice, card; |
| 7318 | char name[64]; |
| 7319 | snd_ctl_t *handle = 0; |
| 7320 | |
| 7321 | strcpy(name, "default"); |
| 7322 | result = snd_ctl_open( &handle, "default", 0 ); |
| 7323 | if (result == 0) { |
| 7324 | nDevices++; |
| 7325 | snd_ctl_close( handle ); |
| 7326 | } |
| 7327 | |
| 7328 | // Count cards and devices |
| 7329 | card = -1; |
| 7330 | snd_card_next( &card ); |
| 7331 | while ( card >= 0 ) { |
| 7332 | sprintf( name, "hw:%d", card ); |
| 7333 | result = snd_ctl_open( &handle, name, 0 ); |
| 7334 | if ( result < 0 ) { |
| 7335 | handle = 0; |
| 7336 | errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << "."; |
| 7337 | errorText_ = errorStream_.str(); |
| 7338 | error( RTAUDIO_WARNING ); |
| 7339 | goto nextcard; |
| 7340 | } |
| 7341 | subdevice = -1; |
| 7342 | while( 1 ) { |
| 7343 | result = snd_ctl_pcm_next_device( handle, &subdevice ); |
| 7344 | if ( result < 0 ) { |
| 7345 | errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << "."; |
| 7346 | errorText_ = errorStream_.str(); |
| 7347 | error( RTAUDIO_WARNING ); |
| 7348 | break; |
| 7349 | } |
| 7350 | if ( subdevice < 0 ) |
| 7351 | break; |
| 7352 | nDevices++; |
| 7353 | } |
| 7354 | nextcard: |
| 7355 | if ( handle ) |
| 7356 | snd_ctl_close( handle ); |
| 7357 | snd_card_next( &card ); |
| 7358 | } |
| 7359 | |
| 7360 | return nDevices; |
| 7361 | } |
| 7362 | |
| 7363 | RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device ) |
| 7364 | { |
| 7365 | RtAudio::DeviceInfo info; |
| 7366 | info.probed = false; |
| 7367 | |
| 7368 | unsigned nDevices = 0; |
| 7369 | int result=-1, subdevice=-1, card=-1; |
| 7370 | char name[64]; |
| 7371 | snd_ctl_t *chandle = 0; |
| 7372 | |
| 7373 | result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK ); |
| 7374 | if ( result == 0 ) { |
| 7375 | if ( nDevices++ == device ) { |
| 7376 | strcpy( name, "default" ); |
| 7377 | goto foundDevice; |
| 7378 | } |
| 7379 | } |
| 7380 | if ( chandle ) |
| 7381 | snd_ctl_close( chandle ); |
| 7382 | |
| 7383 | // Count cards and devices |
| 7384 | snd_card_next( &card ); |
| 7385 | while ( card >= 0 ) { |
| 7386 | sprintf( name, "hw:%d", card ); |
| 7387 | result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK ); |
| 7388 | if ( result < 0 ) { |
| 7389 | chandle = 0; |
| 7390 | errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << "."; |
| 7391 | errorText_ = errorStream_.str(); |
| 7392 | error( RTAUDIO_WARNING ); |
| 7393 | goto nextcard; |
| 7394 | } |
| 7395 | subdevice = -1; |
| 7396 | while( 1 ) { |
| 7397 | result = snd_ctl_pcm_next_device( chandle, &subdevice ); |
| 7398 | if ( result < 0 ) { |
| 7399 | errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << "."; |
| 7400 | errorText_ = errorStream_.str(); |
| 7401 | error( RTAUDIO_WARNING ); |
| 7402 | break; |
| 7403 | } |
| 7404 | if ( subdevice < 0 ) break; |
| 7405 | if ( nDevices == device ) { |
| 7406 | sprintf( name, "hw:%d,%d", card, subdevice ); |
| 7407 | goto foundDevice; |
| 7408 | } |
| 7409 | nDevices++; |
| 7410 | } |
| 7411 | nextcard: |
| 7412 | if ( chandle ) |
| 7413 | snd_ctl_close( chandle ); |
| 7414 | snd_card_next( &card ); |
| 7415 | } |
| 7416 | |
| 7417 | if ( nDevices == 0 ) { |
| 7418 | errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!"; |
| 7419 | error( RTAUDIO_INVALID_USE ); |
| 7420 | return info; |
| 7421 | } |
| 7422 | |
| 7423 | if ( device >= nDevices ) { |
| 7424 | errorText_ = "RtApiAlsa::getDeviceInfo: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 7425 | error( RTAUDIO_INVALID_USE ); |
| 7426 | return info; |
| 7427 | } |
| 7428 | |
| 7429 | foundDevice: |
| 7430 | |
| 7431 | // If a stream is already open, we cannot probe the stream devices. |
| 7432 | // Thus, use the saved results. |
| 7433 | if ( stream_.state != STREAM_CLOSED && |
| 7434 | ( stream_.device[0] == device || stream_.device[1] == device ) ) { |
| 7435 | snd_ctl_close( chandle ); |
| 7436 | if ( device >= devices_.size() ) { |
| 7437 | errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened."; |
| 7438 | error( RTAUDIO_WARNING ); |
| 7439 | return info; |
| 7440 | } |
| 7441 | return devices_[ device ]; |
| 7442 | } |
| 7443 | |
| 7444 | int openMode = SND_PCM_ASYNC; |
| 7445 | snd_pcm_stream_t stream; |
| 7446 | snd_pcm_info_t *pcminfo; |
| 7447 | snd_pcm_info_alloca( &pcminfo ); |
| 7448 | snd_pcm_t *phandle; |
| 7449 | snd_pcm_hw_params_t *params; |
| 7450 | snd_pcm_hw_params_alloca( ¶ms ); |
| 7451 | |
| 7452 | // First try for playback unless default device (which has subdev -1) |
| 7453 | stream = SND_PCM_STREAM_PLAYBACK; |
| 7454 | snd_pcm_info_set_stream( pcminfo, stream ); |
| 7455 | if ( subdevice != -1 ) { |
| 7456 | snd_pcm_info_set_device( pcminfo, subdevice ); |
| 7457 | snd_pcm_info_set_subdevice( pcminfo, 0 ); |
| 7458 | |
| 7459 | result = snd_ctl_pcm_info( chandle, pcminfo ); |
| 7460 | if ( result < 0 ) { |
| 7461 | // Device probably doesn't support playback. |
| 7462 | goto captureProbe; |
| 7463 | } |
| 7464 | } |
| 7465 | |
| 7466 | result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK ); |
| 7467 | if ( result < 0 ) { |
| 7468 | errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7469 | errorText_ = errorStream_.str(); |
| 7470 | error( RTAUDIO_WARNING ); |
| 7471 | goto captureProbe; |
| 7472 | } |
| 7473 | |
| 7474 | // The device is open ... fill the parameter structure. |
| 7475 | result = snd_pcm_hw_params_any( phandle, params ); |
| 7476 | if ( result < 0 ) { |
| 7477 | snd_pcm_close( phandle ); |
| 7478 | errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7479 | errorText_ = errorStream_.str(); |
| 7480 | error( RTAUDIO_WARNING ); |
| 7481 | goto captureProbe; |
| 7482 | } |
| 7483 | |
| 7484 | // Get output channel information. |
| 7485 | unsigned int value; |
| 7486 | result = snd_pcm_hw_params_get_channels_max( params, &value ); |
| 7487 | if ( result < 0 ) { |
| 7488 | snd_pcm_close( phandle ); |
| 7489 | errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << "."; |
| 7490 | errorText_ = errorStream_.str(); |
| 7491 | error( RTAUDIO_WARNING ); |
| 7492 | goto captureProbe; |
| 7493 | } |
| 7494 | info.outputChannels = value; |
| 7495 | snd_pcm_close( phandle ); |
| 7496 | |
| 7497 | captureProbe: |
| 7498 | stream = SND_PCM_STREAM_CAPTURE; |
| 7499 | snd_pcm_info_set_stream( pcminfo, stream ); |
| 7500 | |
| 7501 | // Now try for capture unless default device (with subdev = -1) |
| 7502 | if ( subdevice != -1 ) { |
| 7503 | result = snd_ctl_pcm_info( chandle, pcminfo ); |
| 7504 | snd_ctl_close( chandle ); |
| 7505 | if ( result < 0 ) { |
| 7506 | // Device probably doesn't support capture. |
| 7507 | if ( info.outputChannels == 0 ) return info; |
| 7508 | goto probeParameters; |
| 7509 | } |
| 7510 | } |
| 7511 | else |
| 7512 | snd_ctl_close( chandle ); |
| 7513 | |
| 7514 | result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK); |
| 7515 | if ( result < 0 ) { |
| 7516 | errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7517 | errorText_ = errorStream_.str(); |
| 7518 | error( RTAUDIO_WARNING ); |
| 7519 | if ( info.outputChannels == 0 ) return info; |
| 7520 | goto probeParameters; |
| 7521 | } |
| 7522 | |
| 7523 | // The device is open ... fill the parameter structure. |
| 7524 | result = snd_pcm_hw_params_any( phandle, params ); |
| 7525 | if ( result < 0 ) { |
| 7526 | snd_pcm_close( phandle ); |
| 7527 | errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7528 | errorText_ = errorStream_.str(); |
| 7529 | error( RTAUDIO_WARNING ); |
| 7530 | if ( info.outputChannels == 0 ) return info; |
| 7531 | goto probeParameters; |
| 7532 | } |
| 7533 | |
| 7534 | result = snd_pcm_hw_params_get_channels_max( params, &value ); |
| 7535 | if ( result < 0 ) { |
| 7536 | snd_pcm_close( phandle ); |
| 7537 | errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << "."; |
| 7538 | errorText_ = errorStream_.str(); |
| 7539 | error( RTAUDIO_WARNING ); |
| 7540 | if ( info.outputChannels == 0 ) return info; |
| 7541 | goto probeParameters; |
| 7542 | } |
| 7543 | info.inputChannels = value; |
| 7544 | snd_pcm_close( phandle ); |
| 7545 | |
| 7546 | // If device opens for both playback and capture, we determine the channels. |
| 7547 | if ( info.outputChannels > 0 && info.inputChannels > 0 ) |
| 7548 | info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels; |
| 7549 | |
| 7550 | // ALSA doesn't provide default devices so we'll use the first available one. |
| 7551 | if ( device == 0 && info.outputChannels > 0 ) |
| 7552 | info.isDefaultOutput = true; |
| 7553 | if ( device == 0 && info.inputChannels > 0 ) |
| 7554 | info.isDefaultInput = true; |
| 7555 | |
| 7556 | probeParameters: |
| 7557 | // At this point, we just need to figure out the supported data |
| 7558 | // formats and sample rates. We'll proceed by opening the device in |
| 7559 | // the direction with the maximum number of channels, or playback if |
| 7560 | // they are equal. This might limit our sample rate options, but so |
| 7561 | // be it. |
| 7562 | |
| 7563 | if ( info.outputChannels >= info.inputChannels ) |
| 7564 | stream = SND_PCM_STREAM_PLAYBACK; |
| 7565 | else |
| 7566 | stream = SND_PCM_STREAM_CAPTURE; |
| 7567 | snd_pcm_info_set_stream( pcminfo, stream ); |
| 7568 | |
| 7569 | result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK); |
| 7570 | if ( result < 0 ) { |
| 7571 | errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7572 | errorText_ = errorStream_.str(); |
| 7573 | error( RTAUDIO_WARNING ); |
| 7574 | return info; |
| 7575 | } |
| 7576 | |
| 7577 | // The device is open ... fill the parameter structure. |
| 7578 | result = snd_pcm_hw_params_any( phandle, params ); |
| 7579 | if ( result < 0 ) { |
| 7580 | snd_pcm_close( phandle ); |
| 7581 | errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7582 | errorText_ = errorStream_.str(); |
| 7583 | error( RTAUDIO_WARNING ); |
| 7584 | return info; |
| 7585 | } |
| 7586 | |
| 7587 | // Test our discrete set of sample rate values. |
| 7588 | info.sampleRates.clear(); |
| 7589 | for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) { |
| 7590 | if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) { |
| 7591 | info.sampleRates.push_back( SAMPLE_RATES[i] ); |
| 7592 | |
| 7593 | if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) ) |
| 7594 | info.preferredSampleRate = SAMPLE_RATES[i]; |
| 7595 | } |
| 7596 | } |
| 7597 | if ( info.sampleRates.size() == 0 ) { |
| 7598 | snd_pcm_close( phandle ); |
| 7599 | errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ")."; |
| 7600 | errorText_ = errorStream_.str(); |
| 7601 | error( RTAUDIO_WARNING ); |
| 7602 | return info; |
| 7603 | } |
| 7604 | |
| 7605 | // Probe the supported data formats ... we don't care about endian-ness just yet |
| 7606 | snd_pcm_format_t format; |
| 7607 | info.nativeFormats = 0; |
| 7608 | format = SND_PCM_FORMAT_S8; |
| 7609 | if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 ) |
| 7610 | info.nativeFormats |= RTAUDIO_SINT8; |
| 7611 | format = SND_PCM_FORMAT_S16; |
| 7612 | if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 ) |
| 7613 | info.nativeFormats |= RTAUDIO_SINT16; |
| 7614 | format = SND_PCM_FORMAT_S24; |
| 7615 | if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 ) |
| 7616 | info.nativeFormats |= RTAUDIO_SINT24; |
| 7617 | format = SND_PCM_FORMAT_S32; |
| 7618 | if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 ) |
| 7619 | info.nativeFormats |= RTAUDIO_SINT32; |
| 7620 | format = SND_PCM_FORMAT_FLOAT; |
| 7621 | if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 ) |
| 7622 | info.nativeFormats |= RTAUDIO_FLOAT32; |
| 7623 | format = SND_PCM_FORMAT_FLOAT64; |
| 7624 | if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 ) |
| 7625 | info.nativeFormats |= RTAUDIO_FLOAT64; |
| 7626 | |
| 7627 | // Check that we have at least one supported format |
| 7628 | if ( info.nativeFormats == 0 ) { |
| 7629 | snd_pcm_close( phandle ); |
| 7630 | errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio."; |
| 7631 | errorText_ = errorStream_.str(); |
| 7632 | error( RTAUDIO_WARNING ); |
| 7633 | return info; |
| 7634 | } |
| 7635 | |
| 7636 | // Get the device name |
| 7637 | if (strncmp(name, "default", 7)!=0) { |
| 7638 | char *cardname; |
| 7639 | result = snd_card_get_name( card, &cardname ); |
| 7640 | if ( result >= 0 ) { |
| 7641 | sprintf( name, "hw:%s,%d", cardname, subdevice ); |
| 7642 | free( cardname ); |
| 7643 | } |
| 7644 | } |
| 7645 | info.name = name; |
| 7646 | |
| 7647 | // That's all ... close the device and return |
| 7648 | snd_pcm_close( phandle ); |
| 7649 | info.probed = true; |
| 7650 | return info; |
| 7651 | } |
| 7652 | |
| 7653 | void RtApiAlsa :: saveDeviceInfo( void ) |
| 7654 | { |
| 7655 | devices_.clear(); |
| 7656 | |
| 7657 | unsigned int nDevices = getDeviceCount(); |
| 7658 | devices_.resize( nDevices ); |
| 7659 | for ( unsigned int i=0; i<nDevices; i++ ) |
| 7660 | devices_[i] = getDeviceInfo( i ); |
| 7661 | } |
| 7662 | |
| 7663 | bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, |
| 7664 | unsigned int firstChannel, unsigned int sampleRate, |
| 7665 | RtAudioFormat format, unsigned int *bufferSize, |
| 7666 | RtAudio::StreamOptions *options ) |
| 7667 | |
| 7668 | { |
| 7669 | #if defined(__RTAUDIO_DEBUG__) |
| 7670 | struct SndOutputTdealloc { |
| 7671 | SndOutputTdealloc() : _out(NULL) { snd_output_stdio_attach(&_out, stderr, 0); } |
| 7672 | ~SndOutputTdealloc() { snd_output_close(_out); } |
| 7673 | operator snd_output_t*() { return _out; } |
| 7674 | snd_output_t *_out; |
| 7675 | } out; |
| 7676 | #endif |
| 7677 | |
| 7678 | // I'm not using the "plug" interface ... too much inconsistent behavior. |
| 7679 | |
| 7680 | unsigned nDevices = 0; |
| 7681 | int result, subdevice, card; |
| 7682 | char name[64]; |
| 7683 | snd_ctl_t *chandle; |
| 7684 | |
| 7685 | if ( device == 0 |
| 7686 | || (options && options->flags & RTAUDIO_ALSA_USE_DEFAULT) ) |
| 7687 | { |
| 7688 | strcpy(name, "default"); |
| 7689 | result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK ); |
| 7690 | if ( result == 0 ) { |
| 7691 | if ( nDevices == device ) { |
| 7692 | strcpy( name, "default" ); |
| 7693 | snd_ctl_close( chandle ); |
| 7694 | goto foundDevice; |
| 7695 | } |
| 7696 | nDevices++; |
| 7697 | } |
| 7698 | } |
| 7699 | |
| 7700 | else { |
| 7701 | nDevices++; |
| 7702 | // Count cards and devices |
| 7703 | card = -1; |
| 7704 | snd_card_next( &card ); |
| 7705 | while ( card >= 0 ) { |
| 7706 | sprintf( name, "hw:%d", card ); |
| 7707 | result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK ); |
| 7708 | if ( result < 0 ) { |
| 7709 | errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << "."; |
| 7710 | errorText_ = errorStream_.str(); |
| 7711 | return FAILURE; |
| 7712 | } |
| 7713 | subdevice = -1; |
| 7714 | while( 1 ) { |
| 7715 | result = snd_ctl_pcm_next_device( chandle, &subdevice ); |
| 7716 | if ( result < 0 ) break; |
| 7717 | if ( subdevice < 0 ) break; |
| 7718 | if ( nDevices == device ) { |
| 7719 | sprintf( name, "hw:%d,%d", card, subdevice ); |
| 7720 | snd_ctl_close( chandle ); |
| 7721 | goto foundDevice; |
| 7722 | } |
| 7723 | nDevices++; |
| 7724 | } |
| 7725 | snd_ctl_close( chandle ); |
| 7726 | snd_card_next( &card ); |
| 7727 | } |
| 7728 | |
| 7729 | if ( nDevices == 0 ) { |
| 7730 | // This should not happen because a check is made before this function is called. |
| 7731 | errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!"; |
| 7732 | return FAILURE; |
| 7733 | } |
| 7734 | |
| 7735 | if ( device >= nDevices ) { |
| 7736 | // This should not happen because a check is made before this function is called. |
| 7737 | errorText_ = "RtApiAlsa::probeDeviceOpen: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 7738 | return FAILURE; |
| 7739 | } |
| 7740 | } |
| 7741 | |
| 7742 | foundDevice: |
| 7743 | |
| 7744 | // The getDeviceInfo() function will not work for a device that is |
| 7745 | // already open. Thus, we'll probe the system before opening a |
| 7746 | // stream and save the results for use by getDeviceInfo(). |
| 7747 | if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once |
| 7748 | this->saveDeviceInfo(); |
| 7749 | |
| 7750 | snd_pcm_stream_t stream; |
| 7751 | if ( mode == OUTPUT ) |
| 7752 | stream = SND_PCM_STREAM_PLAYBACK; |
| 7753 | else |
| 7754 | stream = SND_PCM_STREAM_CAPTURE; |
| 7755 | |
| 7756 | snd_pcm_t *phandle; |
| 7757 | int openMode = SND_PCM_ASYNC; |
| 7758 | result = snd_pcm_open( &phandle, name, stream, openMode ); |
| 7759 | if ( result < 0 ) { |
| 7760 | if ( mode == OUTPUT ) |
| 7761 | errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output."; |
| 7762 | else |
| 7763 | errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input."; |
| 7764 | errorText_ = errorStream_.str(); |
| 7765 | return FAILURE; |
| 7766 | } |
| 7767 | |
| 7768 | // Fill the parameter structure. |
| 7769 | snd_pcm_hw_params_t *hw_params; |
| 7770 | snd_pcm_hw_params_alloca( &hw_params ); |
| 7771 | result = snd_pcm_hw_params_any( phandle, hw_params ); |
| 7772 | if ( result < 0 ) { |
| 7773 | snd_pcm_close( phandle ); |
| 7774 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << "."; |
| 7775 | errorText_ = errorStream_.str(); |
| 7776 | return FAILURE; |
| 7777 | } |
| 7778 | |
| 7779 | #if defined(__RTAUDIO_DEBUG__) |
| 7780 | fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" ); |
| 7781 | snd_pcm_hw_params_dump( hw_params, out ); |
| 7782 | #endif |
| 7783 | |
| 7784 | // Set access ... check user preference. |
| 7785 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) { |
| 7786 | stream_.userInterleaved = false; |
| 7787 | result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED ); |
| 7788 | if ( result < 0 ) { |
| 7789 | result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED ); |
| 7790 | stream_.deviceInterleaved[mode] = true; |
| 7791 | } |
| 7792 | else |
| 7793 | stream_.deviceInterleaved[mode] = false; |
| 7794 | } |
| 7795 | else { |
| 7796 | stream_.userInterleaved = true; |
| 7797 | result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED ); |
| 7798 | if ( result < 0 ) { |
| 7799 | result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED ); |
| 7800 | stream_.deviceInterleaved[mode] = false; |
| 7801 | } |
| 7802 | else |
| 7803 | stream_.deviceInterleaved[mode] = true; |
| 7804 | } |
| 7805 | |
| 7806 | if ( result < 0 ) { |
| 7807 | snd_pcm_close( phandle ); |
| 7808 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << "."; |
| 7809 | errorText_ = errorStream_.str(); |
| 7810 | return FAILURE; |
| 7811 | } |
| 7812 | |
| 7813 | // Determine how to set the device format. |
| 7814 | stream_.userFormat = format; |
| 7815 | snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN; |
| 7816 | |
| 7817 | if ( format == RTAUDIO_SINT8 ) |
| 7818 | deviceFormat = SND_PCM_FORMAT_S8; |
| 7819 | else if ( format == RTAUDIO_SINT16 ) |
| 7820 | deviceFormat = SND_PCM_FORMAT_S16; |
| 7821 | else if ( format == RTAUDIO_SINT24 ) |
| 7822 | deviceFormat = SND_PCM_FORMAT_S24; |
| 7823 | else if ( format == RTAUDIO_SINT32 ) |
| 7824 | deviceFormat = SND_PCM_FORMAT_S32; |
| 7825 | else if ( format == RTAUDIO_FLOAT32 ) |
| 7826 | deviceFormat = SND_PCM_FORMAT_FLOAT; |
| 7827 | else if ( format == RTAUDIO_FLOAT64 ) |
| 7828 | deviceFormat = SND_PCM_FORMAT_FLOAT64; |
| 7829 | |
| 7830 | if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) { |
| 7831 | stream_.deviceFormat[mode] = format; |
| 7832 | goto setFormat; |
| 7833 | } |
| 7834 | |
| 7835 | // The user requested format is not natively supported by the device. |
| 7836 | deviceFormat = SND_PCM_FORMAT_FLOAT64; |
| 7837 | if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) { |
| 7838 | stream_.deviceFormat[mode] = RTAUDIO_FLOAT64; |
| 7839 | goto setFormat; |
| 7840 | } |
| 7841 | |
| 7842 | deviceFormat = SND_PCM_FORMAT_FLOAT; |
| 7843 | if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) { |
| 7844 | stream_.deviceFormat[mode] = RTAUDIO_FLOAT32; |
| 7845 | goto setFormat; |
| 7846 | } |
| 7847 | |
| 7848 | deviceFormat = SND_PCM_FORMAT_S32; |
| 7849 | if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) { |
| 7850 | stream_.deviceFormat[mode] = RTAUDIO_SINT32; |
| 7851 | goto setFormat; |
| 7852 | } |
| 7853 | |
| 7854 | deviceFormat = SND_PCM_FORMAT_S24; |
| 7855 | if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) { |
| 7856 | stream_.deviceFormat[mode] = RTAUDIO_SINT24; |
| 7857 | goto setFormat; |
| 7858 | } |
| 7859 | |
| 7860 | deviceFormat = SND_PCM_FORMAT_S16; |
| 7861 | if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) { |
| 7862 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 7863 | goto setFormat; |
| 7864 | } |
| 7865 | |
| 7866 | deviceFormat = SND_PCM_FORMAT_S8; |
| 7867 | if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) { |
| 7868 | stream_.deviceFormat[mode] = RTAUDIO_SINT8; |
| 7869 | goto setFormat; |
| 7870 | } |
| 7871 | |
| 7872 | // If we get here, no supported format was found. |
| 7873 | snd_pcm_close( phandle ); |
| 7874 | errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio."; |
| 7875 | errorText_ = errorStream_.str(); |
| 7876 | return FAILURE; |
| 7877 | |
| 7878 | setFormat: |
| 7879 | result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat ); |
| 7880 | if ( result < 0 ) { |
| 7881 | snd_pcm_close( phandle ); |
| 7882 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << "."; |
| 7883 | errorText_ = errorStream_.str(); |
| 7884 | return FAILURE; |
| 7885 | } |
| 7886 | |
| 7887 | // Determine whether byte-swaping is necessary. |
| 7888 | stream_.doByteSwap[mode] = false; |
| 7889 | if ( deviceFormat != SND_PCM_FORMAT_S8 ) { |
| 7890 | result = snd_pcm_format_cpu_endian( deviceFormat ); |
| 7891 | if ( result == 0 ) |
| 7892 | stream_.doByteSwap[mode] = true; |
| 7893 | else if (result < 0) { |
| 7894 | snd_pcm_close( phandle ); |
| 7895 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << "."; |
| 7896 | errorText_ = errorStream_.str(); |
| 7897 | return FAILURE; |
| 7898 | } |
| 7899 | } |
| 7900 | |
| 7901 | // Set the sample rate. |
| 7902 | result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 ); |
| 7903 | if ( result < 0 ) { |
| 7904 | snd_pcm_close( phandle ); |
| 7905 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << "."; |
| 7906 | errorText_ = errorStream_.str(); |
| 7907 | return FAILURE; |
| 7908 | } |
| 7909 | |
| 7910 | // Determine the number of channels for this device. We support a possible |
| 7911 | // minimum device channel number > than the value requested by the user. |
| 7912 | stream_.nUserChannels[mode] = channels; |
| 7913 | unsigned int value; |
| 7914 | result = snd_pcm_hw_params_get_channels_max( hw_params, &value ); |
| 7915 | unsigned int deviceChannels = value; |
| 7916 | if ( result < 0 || deviceChannels < channels + firstChannel ) { |
| 7917 | snd_pcm_close( phandle ); |
| 7918 | errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << "."; |
| 7919 | errorText_ = errorStream_.str(); |
| 7920 | return FAILURE; |
| 7921 | } |
| 7922 | |
| 7923 | result = snd_pcm_hw_params_get_channels_min( hw_params, &value ); |
| 7924 | if ( result < 0 ) { |
| 7925 | snd_pcm_close( phandle ); |
| 7926 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7927 | errorText_ = errorStream_.str(); |
| 7928 | return FAILURE; |
| 7929 | } |
| 7930 | deviceChannels = value; |
| 7931 | if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel; |
| 7932 | stream_.nDeviceChannels[mode] = deviceChannels; |
| 7933 | |
| 7934 | // Set the device channels. |
| 7935 | result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels ); |
| 7936 | if ( result < 0 ) { |
| 7937 | snd_pcm_close( phandle ); |
| 7938 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7939 | errorText_ = errorStream_.str(); |
| 7940 | return FAILURE; |
| 7941 | } |
| 7942 | |
| 7943 | // Set the buffer (or period) size. |
| 7944 | int dir = 0; |
| 7945 | snd_pcm_uframes_t periodSize = *bufferSize; |
| 7946 | result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir ); |
| 7947 | if ( result < 0 ) { |
| 7948 | snd_pcm_close( phandle ); |
| 7949 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7950 | errorText_ = errorStream_.str(); |
| 7951 | return FAILURE; |
| 7952 | } |
| 7953 | *bufferSize = periodSize; |
| 7954 | |
| 7955 | // Set the buffer number, which in ALSA is referred to as the "period". |
| 7956 | unsigned int periods = 0; |
| 7957 | if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2; |
| 7958 | if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers; |
| 7959 | if ( periods < 2 ) periods = 4; // a fairly safe default value |
| 7960 | result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir ); |
| 7961 | if ( result < 0 ) { |
| 7962 | snd_pcm_close( phandle ); |
| 7963 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << "."; |
| 7964 | errorText_ = errorStream_.str(); |
| 7965 | return FAILURE; |
| 7966 | } |
| 7967 | |
| 7968 | // If attempting to setup a duplex stream, the bufferSize parameter |
| 7969 | // MUST be the same in both directions! |
| 7970 | if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) { |
| 7971 | snd_pcm_close( phandle ); |
| 7972 | errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ")."; |
| 7973 | errorText_ = errorStream_.str(); |
| 7974 | return FAILURE; |
| 7975 | } |
| 7976 | |
| 7977 | stream_.bufferSize = *bufferSize; |
| 7978 | |
| 7979 | // Install the hardware configuration |
| 7980 | result = snd_pcm_hw_params( phandle, hw_params ); |
| 7981 | if ( result < 0 ) { |
| 7982 | snd_pcm_close( phandle ); |
| 7983 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << "."; |
| 7984 | errorText_ = errorStream_.str(); |
| 7985 | return FAILURE; |
| 7986 | } |
| 7987 | |
| 7988 | #if defined(__RTAUDIO_DEBUG__) |
| 7989 | fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n"); |
| 7990 | snd_pcm_hw_params_dump( hw_params, out ); |
| 7991 | #endif |
| 7992 | |
| 7993 | // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns. |
| 7994 | snd_pcm_sw_params_t *sw_params = NULL; |
| 7995 | snd_pcm_sw_params_alloca( &sw_params ); |
| 7996 | snd_pcm_sw_params_current( phandle, sw_params ); |
| 7997 | snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize ); |
| 7998 | snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX ); |
| 7999 | snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 ); |
| 8000 | |
| 8001 | // The following two settings were suggested by Theo Veenker |
| 8002 | //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize ); |
| 8003 | //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 ); |
| 8004 | |
| 8005 | // here are two options for a fix |
| 8006 | //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX ); |
| 8007 | snd_pcm_uframes_t val; |
| 8008 | snd_pcm_sw_params_get_boundary( sw_params, &val ); |
| 8009 | snd_pcm_sw_params_set_silence_size( phandle, sw_params, val ); |
| 8010 | |
| 8011 | result = snd_pcm_sw_params( phandle, sw_params ); |
| 8012 | if ( result < 0 ) { |
| 8013 | snd_pcm_close( phandle ); |
| 8014 | errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << "."; |
| 8015 | errorText_ = errorStream_.str(); |
| 8016 | return FAILURE; |
| 8017 | } |
| 8018 | |
| 8019 | #if defined(__RTAUDIO_DEBUG__) |
| 8020 | fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n"); |
| 8021 | snd_pcm_sw_params_dump( sw_params, out ); |
| 8022 | #endif |
| 8023 | |
| 8024 | // Set flags for buffer conversion |
| 8025 | stream_.doConvertBuffer[mode] = false; |
| 8026 | if ( stream_.userFormat != stream_.deviceFormat[mode] ) |
| 8027 | stream_.doConvertBuffer[mode] = true; |
| 8028 | if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] ) |
| 8029 | stream_.doConvertBuffer[mode] = true; |
| 8030 | if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] && |
| 8031 | stream_.nUserChannels[mode] > 1 ) |
| 8032 | stream_.doConvertBuffer[mode] = true; |
| 8033 | |
| 8034 | // Allocate the ApiHandle if necessary and then save. |
| 8035 | AlsaHandle *apiInfo = 0; |
| 8036 | if ( stream_.apiHandle == 0 ) { |
| 8037 | try { |
| 8038 | apiInfo = (AlsaHandle *) new AlsaHandle; |
| 8039 | } |
| 8040 | catch ( std::bad_alloc& ) { |
| 8041 | errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory."; |
| 8042 | goto error; |
| 8043 | } |
| 8044 | |
| 8045 | if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) { |
| 8046 | errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable."; |
| 8047 | goto error; |
| 8048 | } |
| 8049 | |
| 8050 | stream_.apiHandle = (void *) apiInfo; |
| 8051 | apiInfo->handles[0] = 0; |
| 8052 | apiInfo->handles[1] = 0; |
| 8053 | } |
| 8054 | else { |
| 8055 | apiInfo = (AlsaHandle *) stream_.apiHandle; |
| 8056 | } |
| 8057 | apiInfo->handles[mode] = phandle; |
| 8058 | phandle = 0; |
| 8059 | |
| 8060 | // Allocate necessary internal buffers. |
| 8061 | unsigned long bufferBytes; |
| 8062 | bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat ); |
| 8063 | stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 ); |
| 8064 | if ( stream_.userBuffer[mode] == NULL ) { |
| 8065 | errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory."; |
| 8066 | goto error; |
| 8067 | } |
| 8068 | |
| 8069 | if ( stream_.doConvertBuffer[mode] ) { |
| 8070 | |
| 8071 | bool makeBuffer = true; |
| 8072 | bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] ); |
| 8073 | if ( mode == INPUT ) { |
| 8074 | if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) { |
| 8075 | unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] ); |
| 8076 | if ( bufferBytes <= bytesOut ) makeBuffer = false; |
| 8077 | } |
| 8078 | } |
| 8079 | |
| 8080 | if ( makeBuffer ) { |
| 8081 | bufferBytes *= *bufferSize; |
| 8082 | if ( stream_.deviceBuffer ) free( stream_.deviceBuffer ); |
| 8083 | stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 ); |
| 8084 | if ( stream_.deviceBuffer == NULL ) { |
| 8085 | errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory."; |
| 8086 | goto error; |
| 8087 | } |
| 8088 | } |
| 8089 | } |
| 8090 | |
| 8091 | stream_.sampleRate = sampleRate; |
| 8092 | stream_.nBuffers = periods; |
| 8093 | stream_.device[mode] = device; |
| 8094 | stream_.state = STREAM_STOPPED; |
| 8095 | |
| 8096 | // Setup the buffer conversion information structure. |
| 8097 | if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel ); |
| 8098 | |
| 8099 | // Setup thread if necessary. |
| 8100 | if ( stream_.mode == OUTPUT && mode == INPUT ) { |
| 8101 | // We had already set up an output stream. |
| 8102 | stream_.mode = DUPLEX; |
| 8103 | // Link the streams if possible. |
| 8104 | apiInfo->synchronized = false; |
| 8105 | if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 ) |
| 8106 | apiInfo->synchronized = true; |
| 8107 | else { |
| 8108 | errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices."; |
| 8109 | error( RTAUDIO_WARNING ); |
| 8110 | } |
| 8111 | } |
| 8112 | else { |
| 8113 | stream_.mode = mode; |
| 8114 | |
| 8115 | // Setup callback thread. |
| 8116 | stream_.callbackInfo.object = (void *) this; |
| 8117 | |
| 8118 | // Set the thread attributes for joinable and realtime scheduling |
| 8119 | // priority (optional). The higher priority will only take affect |
| 8120 | // if the program is run as root or suid. Note, under Linux |
| 8121 | // processes with CAP_SYS_NICE privilege, a user can change |
| 8122 | // scheduling policy and priority (thus need not be root). See |
| 8123 | // POSIX "capabilities". |
| 8124 | pthread_attr_t attr; |
| 8125 | pthread_attr_init( &attr ); |
| 8126 | pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); |
| 8127 | #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread) |
| 8128 | if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) { |
| 8129 | stream_.callbackInfo.doRealtime = true; |
| 8130 | struct sched_param param; |
| 8131 | int priority = options->priority; |
| 8132 | int min = sched_get_priority_min( SCHED_RR ); |
| 8133 | int max = sched_get_priority_max( SCHED_RR ); |
| 8134 | if ( priority < min ) priority = min; |
| 8135 | else if ( priority > max ) priority = max; |
| 8136 | param.sched_priority = priority; |
| 8137 | |
| 8138 | // Set the policy BEFORE the priority. Otherwise it fails. |
| 8139 | pthread_attr_setschedpolicy(&attr, SCHED_RR); |
| 8140 | pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM); |
| 8141 | // This is definitely required. Otherwise it fails. |
| 8142 | pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); |
| 8143 | pthread_attr_setschedparam(&attr, ¶m); |
| 8144 | } |
| 8145 | else |
| 8146 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 8147 | #else |
| 8148 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 8149 | #endif |
| 8150 | |
| 8151 | stream_.callbackInfo.isRunning = true; |
| 8152 | result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo ); |
| 8153 | pthread_attr_destroy( &attr ); |
| 8154 | if ( result ) { |
| 8155 | // Failed. Try instead with default attributes. |
| 8156 | result = pthread_create( &stream_.callbackInfo.thread, NULL, alsaCallbackHandler, &stream_.callbackInfo ); |
| 8157 | if ( result ) { |
| 8158 | stream_.callbackInfo.isRunning = false; |
| 8159 | errorText_ = "RtApiAlsa::error creating callback thread!"; |
| 8160 | goto error; |
| 8161 | } |
| 8162 | } |
| 8163 | } |
| 8164 | |
| 8165 | return SUCCESS; |
| 8166 | |
| 8167 | error: |
| 8168 | if ( apiInfo ) { |
| 8169 | pthread_cond_destroy( &apiInfo->runnable_cv ); |
| 8170 | if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] ); |
| 8171 | if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] ); |
| 8172 | delete apiInfo; |
| 8173 | stream_.apiHandle = 0; |
| 8174 | } |
| 8175 | |
| 8176 | if ( phandle) snd_pcm_close( phandle ); |
| 8177 | |
| 8178 | for ( int i=0; i<2; i++ ) { |
| 8179 | if ( stream_.userBuffer[i] ) { |
| 8180 | free( stream_.userBuffer[i] ); |
| 8181 | stream_.userBuffer[i] = 0; |
| 8182 | } |
| 8183 | } |
| 8184 | |
| 8185 | if ( stream_.deviceBuffer ) { |
| 8186 | free( stream_.deviceBuffer ); |
| 8187 | stream_.deviceBuffer = 0; |
| 8188 | } |
| 8189 | |
| 8190 | stream_.state = STREAM_CLOSED; |
| 8191 | return FAILURE; |
| 8192 | } |
| 8193 | |
| 8194 | void RtApiAlsa :: closeStream() |
| 8195 | { |
| 8196 | if ( stream_.state == STREAM_CLOSED ) { |
| 8197 | errorText_ = "RtApiAlsa::closeStream(): no open stream to close!"; |
| 8198 | error( RTAUDIO_WARNING ); |
| 8199 | return; |
| 8200 | } |
| 8201 | |
| 8202 | AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle; |
| 8203 | stream_.callbackInfo.isRunning = false; |
| 8204 | MUTEX_LOCK( &stream_.mutex ); |
| 8205 | if ( stream_.state == STREAM_STOPPED ) { |
| 8206 | apiInfo->runnable = true; |
| 8207 | pthread_cond_signal( &apiInfo->runnable_cv ); |
| 8208 | } |
| 8209 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8210 | pthread_join( stream_.callbackInfo.thread, NULL ); |
| 8211 | |
| 8212 | if ( stream_.state == STREAM_RUNNING ) { |
| 8213 | stream_.state = STREAM_STOPPED; |
| 8214 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) |
| 8215 | snd_pcm_drop( apiInfo->handles[0] ); |
| 8216 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) |
| 8217 | snd_pcm_drop( apiInfo->handles[1] ); |
| 8218 | } |
| 8219 | |
| 8220 | if ( apiInfo ) { |
| 8221 | pthread_cond_destroy( &apiInfo->runnable_cv ); |
| 8222 | if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] ); |
| 8223 | if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] ); |
| 8224 | delete apiInfo; |
| 8225 | stream_.apiHandle = 0; |
| 8226 | } |
| 8227 | |
| 8228 | for ( int i=0; i<2; i++ ) { |
| 8229 | if ( stream_.userBuffer[i] ) { |
| 8230 | free( stream_.userBuffer[i] ); |
| 8231 | stream_.userBuffer[i] = 0; |
| 8232 | } |
| 8233 | } |
| 8234 | |
| 8235 | if ( stream_.deviceBuffer ) { |
| 8236 | free( stream_.deviceBuffer ); |
| 8237 | stream_.deviceBuffer = 0; |
| 8238 | } |
| 8239 | |
| 8240 | clearStreamInfo(); |
| 8241 | //stream_.mode = UNINITIALIZED; |
| 8242 | //stream_.state = STREAM_CLOSED; |
| 8243 | } |
| 8244 | |
| 8245 | RtAudioErrorType RtApiAlsa :: startStream() |
| 8246 | { |
| 8247 | // This method calls snd_pcm_prepare if the device isn't already in that state. |
| 8248 | |
| 8249 | if ( stream_.state != STREAM_STOPPED ) { |
| 8250 | if ( stream_.state == STREAM_RUNNING ) |
| 8251 | errorText_ = "RtApiAlsa::startStream(): the stream is already running!"; |
| 8252 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 8253 | errorText_ = "RtApiAlsa::startStream(): the stream is stopping or closed!"; |
| 8254 | return error( RTAUDIO_WARNING ); |
| 8255 | } |
| 8256 | |
| 8257 | MUTEX_LOCK( &stream_.mutex ); |
| 8258 | |
| 8259 | /* |
| 8260 | #if defined( HAVE_GETTIMEOFDAY ) |
| 8261 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 8262 | #endif |
| 8263 | */ |
| 8264 | |
| 8265 | int result = 0; |
| 8266 | snd_pcm_state_t state; |
| 8267 | AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle; |
| 8268 | snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles; |
| 8269 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 8270 | state = snd_pcm_state( handle[0] ); |
| 8271 | if ( state != SND_PCM_STATE_PREPARED ) { |
| 8272 | result = snd_pcm_prepare( handle[0] ); |
| 8273 | if ( result < 0 ) { |
| 8274 | errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << "."; |
| 8275 | errorText_ = errorStream_.str(); |
| 8276 | goto unlock; |
| 8277 | } |
| 8278 | } |
| 8279 | } |
| 8280 | |
| 8281 | if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) { |
| 8282 | result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open |
| 8283 | state = snd_pcm_state( handle[1] ); |
| 8284 | if ( state != SND_PCM_STATE_PREPARED ) { |
| 8285 | result = snd_pcm_prepare( handle[1] ); |
| 8286 | if ( result < 0 ) { |
| 8287 | errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << "."; |
| 8288 | errorText_ = errorStream_.str(); |
| 8289 | goto unlock; |
| 8290 | } |
| 8291 | } |
| 8292 | } |
| 8293 | |
| 8294 | stream_.state = STREAM_RUNNING; |
| 8295 | |
| 8296 | unlock: |
| 8297 | apiInfo->runnable = true; |
| 8298 | pthread_cond_signal( &apiInfo->runnable_cv ); |
| 8299 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8300 | |
| 8301 | // chuck-1.5.1.3 change result >= 0 to result < 0 to match above |
| 8302 | if ( result < 0 ) return error( RTAUDIO_SYSTEM_ERROR ); |
| 8303 | return RTAUDIO_NO_ERROR; |
| 8304 | } |
| 8305 | |
| 8306 | RtAudioErrorType RtApiAlsa :: stopStream() |
| 8307 | { |
| 8308 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 8309 | if ( stream_.state == STREAM_STOPPED ) |
| 8310 | errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!"; |
| 8311 | else if ( stream_.state == STREAM_CLOSED ) |
| 8312 | errorText_ = "RtApiAlsa::stopStream(): the stream is closed!"; |
| 8313 | return error( RTAUDIO_WARNING ); |
| 8314 | } |
| 8315 | |
| 8316 | stream_.state = STREAM_STOPPED; |
| 8317 | MUTEX_LOCK( &stream_.mutex ); |
| 8318 | |
| 8319 | int result = 0; |
| 8320 | AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle; |
| 8321 | snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles; |
| 8322 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 8323 | if ( apiInfo->synchronized ) |
| 8324 | result = snd_pcm_drop( handle[0] ); |
| 8325 | else |
| 8326 | result = snd_pcm_drain( handle[0] ); |
| 8327 | if ( result < 0 ) { |
| 8328 | errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << "."; |
| 8329 | errorText_ = errorStream_.str(); |
| 8330 | goto unlock; |
| 8331 | } |
| 8332 | } |
| 8333 | |
| 8334 | if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) { |
| 8335 | result = snd_pcm_drop( handle[1] ); |
| 8336 | if ( result < 0 ) { |
| 8337 | errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << "."; |
| 8338 | errorText_ = errorStream_.str(); |
| 8339 | goto unlock; |
| 8340 | } |
| 8341 | } |
| 8342 | |
| 8343 | unlock: |
| 8344 | apiInfo->runnable = false; // fixes high CPU usage when stopped |
| 8345 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8346 | |
| 8347 | // chuck-1.5.1.3 change result >= 0 to result < 0 to match above |
| 8348 | if ( result < 0 ) return error( RTAUDIO_SYSTEM_ERROR ); |
| 8349 | return RTAUDIO_NO_ERROR; |
| 8350 | } |
| 8351 | |
| 8352 | RtAudioErrorType RtApiAlsa :: abortStream() |
| 8353 | { |
| 8354 | if ( stream_.state != STREAM_RUNNING ) { |
| 8355 | if ( stream_.state == STREAM_STOPPED ) |
| 8356 | errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!"; |
| 8357 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 8358 | errorText_ = "RtApiAlsa::abortStream(): the stream is stopping or closed!"; |
| 8359 | return error( RTAUDIO_WARNING ); |
| 8360 | } |
| 8361 | |
| 8362 | stream_.state = STREAM_STOPPED; |
| 8363 | MUTEX_LOCK( &stream_.mutex ); |
| 8364 | |
| 8365 | int result = 0; |
| 8366 | AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle; |
| 8367 | snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles; |
| 8368 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 8369 | result = snd_pcm_drop( handle[0] ); |
| 8370 | if ( result < 0 ) { |
| 8371 | errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << "."; |
| 8372 | errorText_ = errorStream_.str(); |
| 8373 | goto unlock; |
| 8374 | } |
| 8375 | } |
| 8376 | |
| 8377 | if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) { |
| 8378 | result = snd_pcm_drop( handle[1] ); |
| 8379 | if ( result < 0 ) { |
| 8380 | errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << "."; |
| 8381 | errorText_ = errorStream_.str(); |
| 8382 | goto unlock; |
| 8383 | } |
| 8384 | } |
| 8385 | |
| 8386 | unlock: |
| 8387 | apiInfo->runnable = false; // fixes high CPU usage when stopped |
| 8388 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8389 | |
| 8390 | // chuck-1.5.1.3 change result >= 0 to result < 0 to match above |
| 8391 | if ( result < 0 ) return error( RTAUDIO_SYSTEM_ERROR ); |
| 8392 | return RTAUDIO_NO_ERROR; |
| 8393 | } |
| 8394 | |
| 8395 | void RtApiAlsa :: callbackEvent() |
| 8396 | { |
| 8397 | AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle; |
| 8398 | if ( stream_.state == STREAM_STOPPED ) { |
| 8399 | MUTEX_LOCK( &stream_.mutex ); |
| 8400 | while ( !apiInfo->runnable ) |
| 8401 | pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex ); |
| 8402 | |
| 8403 | if ( stream_.state != STREAM_RUNNING ) { |
| 8404 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8405 | return; |
| 8406 | } |
| 8407 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8408 | } |
| 8409 | |
| 8410 | if ( stream_.state == STREAM_CLOSED ) { |
| 8411 | errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!"; |
| 8412 | error( RTAUDIO_WARNING ); |
| 8413 | return; |
| 8414 | } |
| 8415 | |
| 8416 | int doStopStream = 0; |
| 8417 | RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback; |
| 8418 | double streamTime = getStreamTime(); |
| 8419 | RtAudioStreamStatus status = 0; |
| 8420 | if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) { |
| 8421 | status |= RTAUDIO_OUTPUT_UNDERFLOW; |
| 8422 | apiInfo->xrun[0] = false; |
| 8423 | } |
| 8424 | if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) { |
| 8425 | status |= RTAUDIO_INPUT_OVERFLOW; |
| 8426 | apiInfo->xrun[1] = false; |
| 8427 | } |
| 8428 | doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1], |
| 8429 | stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData ); |
| 8430 | |
| 8431 | if ( doStopStream == 2 ) { |
| 8432 | abortStream(); |
| 8433 | return; |
| 8434 | } |
| 8435 | |
| 8436 | MUTEX_LOCK( &stream_.mutex ); |
| 8437 | |
| 8438 | // The state might change while waiting on a mutex. |
| 8439 | if ( stream_.state == STREAM_STOPPED ) goto unlock; |
| 8440 | |
| 8441 | int result; |
| 8442 | char *buffer; |
| 8443 | int channels; |
| 8444 | snd_pcm_t **handle; |
| 8445 | snd_pcm_sframes_t frames; |
| 8446 | RtAudioFormat format; |
| 8447 | handle = (snd_pcm_t **) apiInfo->handles; |
| 8448 | |
| 8449 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) { |
| 8450 | |
| 8451 | // Setup parameters. |
| 8452 | if ( stream_.doConvertBuffer[1] ) { |
| 8453 | buffer = stream_.deviceBuffer; |
| 8454 | channels = stream_.nDeviceChannels[1]; |
| 8455 | format = stream_.deviceFormat[1]; |
| 8456 | } |
| 8457 | else { |
| 8458 | buffer = stream_.userBuffer[1]; |
| 8459 | channels = stream_.nUserChannels[1]; |
| 8460 | format = stream_.userFormat; |
| 8461 | } |
| 8462 | |
| 8463 | // Read samples from device in interleaved/non-interleaved format. |
| 8464 | if ( stream_.deviceInterleaved[1] ) |
| 8465 | result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize ); |
| 8466 | else { |
| 8467 | void *bufs[channels]; |
| 8468 | size_t offset = stream_.bufferSize * formatBytes( format ); |
| 8469 | for ( int i=0; i<channels; i++ ) |
| 8470 | bufs[i] = (void *) (buffer + (i * offset)); |
| 8471 | result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize ); |
| 8472 | } |
| 8473 | |
| 8474 | if ( result < (int) stream_.bufferSize ) { |
| 8475 | // Either an error or overrun occurred. |
| 8476 | if ( result == -EPIPE ) { |
| 8477 | snd_pcm_state_t state = snd_pcm_state( handle[1] ); |
| 8478 | if ( state == SND_PCM_STATE_XRUN ) { |
| 8479 | apiInfo->xrun[1] = true; |
| 8480 | result = snd_pcm_prepare( handle[1] ); |
| 8481 | if ( result < 0 ) { |
| 8482 | errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << "."; |
| 8483 | errorText_ = errorStream_.str(); |
| 8484 | } |
| 8485 | } |
| 8486 | else { |
| 8487 | errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << "."; |
| 8488 | errorText_ = errorStream_.str(); |
| 8489 | } |
| 8490 | } |
| 8491 | else { |
| 8492 | errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << "."; |
| 8493 | errorText_ = errorStream_.str(); |
| 8494 | } |
| 8495 | error( RTAUDIO_WARNING ); |
| 8496 | goto tryOutput; |
| 8497 | } |
| 8498 | |
| 8499 | // Do byte swapping if necessary. |
| 8500 | if ( stream_.doByteSwap[1] ) |
| 8501 | byteSwapBuffer( buffer, stream_.bufferSize * channels, format ); |
| 8502 | |
| 8503 | // Do buffer conversion if necessary. |
| 8504 | if ( stream_.doConvertBuffer[1] ) |
| 8505 | convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] ); |
| 8506 | |
| 8507 | // Check stream latency |
| 8508 | result = snd_pcm_delay( handle[1], &frames ); |
| 8509 | if ( result == 0 && frames > 0 ) stream_.latency[1] = frames; |
| 8510 | } |
| 8511 | |
| 8512 | tryOutput: |
| 8513 | |
| 8514 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 8515 | |
| 8516 | // Setup parameters and do buffer conversion if necessary. |
| 8517 | if ( stream_.doConvertBuffer[0] ) { |
| 8518 | buffer = stream_.deviceBuffer; |
| 8519 | convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] ); |
| 8520 | channels = stream_.nDeviceChannels[0]; |
| 8521 | format = stream_.deviceFormat[0]; |
| 8522 | } |
| 8523 | else { |
| 8524 | buffer = stream_.userBuffer[0]; |
| 8525 | channels = stream_.nUserChannels[0]; |
| 8526 | format = stream_.userFormat; |
| 8527 | } |
| 8528 | |
| 8529 | // Do byte swapping if necessary. |
| 8530 | if ( stream_.doByteSwap[0] ) |
| 8531 | byteSwapBuffer(buffer, stream_.bufferSize * channels, format); |
| 8532 | |
| 8533 | // Write samples to device in interleaved/non-interleaved format. |
| 8534 | if ( stream_.deviceInterleaved[0] ) |
| 8535 | result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize ); |
| 8536 | else { |
| 8537 | void *bufs[channels]; |
| 8538 | size_t offset = stream_.bufferSize * formatBytes( format ); |
| 8539 | for ( int i=0; i<channels; i++ ) |
| 8540 | bufs[i] = (void *) (buffer + (i * offset)); |
| 8541 | result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize ); |
| 8542 | } |
| 8543 | |
| 8544 | if ( result < (int) stream_.bufferSize ) { |
| 8545 | // Either an error or underrun occurred. |
| 8546 | if ( result == -EPIPE ) { |
| 8547 | snd_pcm_state_t state = snd_pcm_state( handle[0] ); |
| 8548 | if ( state == SND_PCM_STATE_XRUN ) { |
| 8549 | apiInfo->xrun[0] = true; |
| 8550 | result = snd_pcm_prepare( handle[0] ); |
| 8551 | if ( result < 0 ) { |
| 8552 | errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << "."; |
| 8553 | errorText_ = errorStream_.str(); |
| 8554 | } |
| 8555 | else |
| 8556 | errorText_ = "RtApiAlsa::callbackEvent: audio write error, underrun."; |
| 8557 | } |
| 8558 | else { |
| 8559 | errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << "."; |
| 8560 | errorText_ = errorStream_.str(); |
| 8561 | } |
| 8562 | } |
| 8563 | else { |
| 8564 | errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << "."; |
| 8565 | errorText_ = errorStream_.str(); |
| 8566 | } |
| 8567 | error( RTAUDIO_WARNING ); |
| 8568 | goto unlock; |
| 8569 | } |
| 8570 | |
| 8571 | // Check stream latency |
| 8572 | result = snd_pcm_delay( handle[0], &frames ); |
| 8573 | if ( result == 0 && frames > 0 ) stream_.latency[0] = frames; |
| 8574 | } |
| 8575 | |
| 8576 | unlock: |
| 8577 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8578 | |
| 8579 | RtApi::tickStreamTime(); |
| 8580 | if ( doStopStream == 1 ) this->stopStream(); |
| 8581 | } |
| 8582 | |
| 8583 | static void *alsaCallbackHandler( void *ptr ) |
| 8584 | { |
| 8585 | CallbackInfo *info = (CallbackInfo *) ptr; |
| 8586 | RtApiAlsa *object = (RtApiAlsa *) info->object; |
| 8587 | bool *isRunning = &info->isRunning; |
| 8588 | |
| 8589 | #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread) |
| 8590 | if ( info->doRealtime ) { |
| 8591 | std::cerr << "RtAudio alsa: " << |
| 8592 | (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") << |
| 8593 | "running realtime scheduling" << std::endl; |
| 8594 | } |
| 8595 | #endif |
| 8596 | |
| 8597 | while ( *isRunning == true ) { |
| 8598 | pthread_testcancel(); |
| 8599 | object->callbackEvent(); |
| 8600 | } |
| 8601 | |
| 8602 | pthread_exit( NULL ); |
| 8603 | } |
| 8604 | |
| 8605 | //******************** End of __LINUX_ALSA__ *********************// |
| 8606 | #endif |
| 8607 | |
| 8608 | #if defined(__LINUX_PULSE__) |
| 8609 | |
| 8610 | // Code written by Peter Meerwald, [email protected] |
| 8611 | // and Tristan Matthews. |
| 8612 | |
| 8613 | #include <pulse/error.h> |
| 8614 | #include <pulse/simple.h> |
| 8615 | #include <pulse/pulseaudio.h> |
| 8616 | #include <cstdio> |
| 8617 | |
| 8618 | static pa_mainloop_api *rt_pa_mainloop_api = NULL; |
| 8619 | struct PaDeviceInfo { |
| 8620 | PaDeviceInfo() : sink_index(-1), source_index(-1) {} |
| 8621 | int sink_index; |
| 8622 | int source_index; |
| 8623 | std::string sink_name; |
| 8624 | std::string source_name; |
| 8625 | RtAudio::DeviceInfo info; |
| 8626 | }; |
| 8627 | static struct { |
| 8628 | std::vector<PaDeviceInfo> dev; |
| 8629 | std::string default_sink_name; |
| 8630 | std::string default_source_name; |
| 8631 | int default_rate; |
| 8632 | } rt_pa_info; |
| 8633 | |
| 8634 | static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000, |
| 8635 | 44100, 48000, 96000, 192000, 0}; |
| 8636 | |
| 8637 | struct rtaudio_pa_format_mapping_t { |
| 8638 | RtAudioFormat rtaudio_format; |
| 8639 | pa_sample_format_t pa_format; |
| 8640 | }; |
| 8641 | |
| 8642 | static const rtaudio_pa_format_mapping_t supported_sampleformats[] = { |
| 8643 | {RTAUDIO_SINT16, PA_SAMPLE_S16LE}, |
| 8644 | {RTAUDIO_SINT24, PA_SAMPLE_S24LE}, |
| 8645 | {RTAUDIO_SINT32, PA_SAMPLE_S32LE}, |
| 8646 | {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE}, |
| 8647 | {0, PA_SAMPLE_INVALID}}; |
| 8648 | |
| 8649 | struct PulseAudioHandle { |
| 8650 | pa_simple *s_play; |
| 8651 | pa_simple *s_rec; |
| 8652 | pthread_t thread; |
| 8653 | pthread_cond_t runnable_cv; |
| 8654 | bool runnable; |
| 8655 | PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { } |
| 8656 | }; |
| 8657 | |
| 8658 | static void rt_pa_mainloop_api_quit(int ret) { |
| 8659 | rt_pa_mainloop_api->quit(rt_pa_mainloop_api, ret); |
| 8660 | } |
| 8661 | |
| 8662 | static void rt_pa_set_server_info(pa_context *context, const pa_server_info *info, void *data){ |
| 8663 | (void)context; |
| 8664 | (void)data; |
| 8665 | pa_sample_spec ss; |
| 8666 | |
| 8667 | if (!info) { |
| 8668 | rt_pa_mainloop_api_quit(1); |
| 8669 | return; |
| 8670 | } |
| 8671 | |
| 8672 | ss = info->sample_spec; |
| 8673 | |
| 8674 | rt_pa_info.default_rate = ss.rate; |
| 8675 | rt_pa_info.default_sink_name = info->default_sink_name; |
| 8676 | rt_pa_info.default_source_name = info->default_source_name; |
| 8677 | } |
| 8678 | |
| 8679 | static void rt_pa_set_sink_info(pa_context * /*c*/, const pa_sink_info *i, |
| 8680 | int eol, void * /*userdata*/) |
| 8681 | { |
| 8682 | if (eol) return; |
| 8683 | PaDeviceInfo inf; |
| 8684 | inf.info.name = pa_proplist_gets(i->proplist, "device.description"); |
| 8685 | inf.info.probed = true; |
| 8686 | inf.info.outputChannels = i->sample_spec.channels; |
| 8687 | inf.info.preferredSampleRate = i->sample_spec.rate; |
| 8688 | inf.info.isDefaultOutput = (rt_pa_info.default_sink_name == i->name); |
| 8689 | inf.sink_index = i->index; |
| 8690 | inf.sink_name = i->name; |
| 8691 | for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) |
| 8692 | inf.info.sampleRates.push_back( *sr ); |
| 8693 | for ( const rtaudio_pa_format_mapping_t *fm = supported_sampleformats; |
| 8694 | fm->rtaudio_format; ++fm ) |
| 8695 | inf.info.nativeFormats |= fm->rtaudio_format; |
| 8696 | for (size_t i=0; i < rt_pa_info.dev.size(); i++) |
| 8697 | { |
| 8698 | /* Attempt to match up sink and source records by device description. */ |
| 8699 | if (rt_pa_info.dev[i].info.name == inf.info.name) { |
| 8700 | rt_pa_info.dev[i].sink_index = inf.sink_index; |
| 8701 | rt_pa_info.dev[i].sink_name = inf.sink_name; |
| 8702 | rt_pa_info.dev[i].info.outputChannels = inf.info.outputChannels; |
| 8703 | rt_pa_info.dev[i].info.isDefaultOutput = inf.info.isDefaultOutput; |
| 8704 | /* Assume duplex channels are minimum of input and output channels. */ |
| 8705 | /* Uncomment if we add support for DUPLEX |
| 8706 | if (rt_pa_info.dev[i].source_index > -1) |
| 8707 | (inf.info.outputChannels < rt_pa_info.dev[i].info.inputChannels) |
| 8708 | ? inf.info.outputChannels : rt_pa_info.dev[i].info.inputChannels; |
| 8709 | */ |
| 8710 | return; |
| 8711 | } |
| 8712 | } |
| 8713 | /* try to ensure device #0 is the default */ |
| 8714 | if (inf.info.isDefaultOutput) |
| 8715 | rt_pa_info.dev.insert(rt_pa_info.dev.begin(), inf); |
| 8716 | else |
| 8717 | rt_pa_info.dev.push_back(inf); |
| 8718 | } |
| 8719 | |
| 8720 | static void rt_pa_set_source_info_and_quit(pa_context * /*c*/, const pa_source_info *i, |
| 8721 | int eol, void * /*userdata*/) |
| 8722 | { |
| 8723 | if (eol) { |
| 8724 | rt_pa_mainloop_api_quit(0); |
| 8725 | return; |
| 8726 | } |
| 8727 | PaDeviceInfo inf; |
| 8728 | inf.info.name = pa_proplist_gets(i->proplist, "device.description"); |
| 8729 | inf.info.probed = true; |
| 8730 | inf.info.inputChannels = i->sample_spec.channels; |
| 8731 | inf.info.preferredSampleRate = i->sample_spec.rate; |
| 8732 | inf.info.isDefaultInput = (rt_pa_info.default_source_name == i->name); |
| 8733 | inf.source_index = i->index; |
| 8734 | inf.source_name = i->name; |
| 8735 | for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) |
| 8736 | inf.info.sampleRates.push_back( *sr ); |
| 8737 | for ( const rtaudio_pa_format_mapping_t *fm = supported_sampleformats; |
| 8738 | fm->rtaudio_format; ++fm ) |
| 8739 | inf.info.nativeFormats |= fm->rtaudio_format; |
| 8740 | |
| 8741 | for (size_t i=0; i < rt_pa_info.dev.size(); i++) |
| 8742 | { |
| 8743 | /* Attempt to match up sink and source records by device description. */ |
| 8744 | if (rt_pa_info.dev[i].info.name == inf.info.name) { |
| 8745 | rt_pa_info.dev[i].source_index = inf.source_index; |
| 8746 | rt_pa_info.dev[i].source_name = inf.source_name; |
| 8747 | rt_pa_info.dev[i].info.inputChannels = inf.info.inputChannels; |
| 8748 | rt_pa_info.dev[i].info.isDefaultInput = inf.info.isDefaultInput; |
| 8749 | /* Assume duplex channels are minimum of input and output channels. */ |
| 8750 | /* Uncomment if we add support for DUPLEX |
| 8751 | if (rt_pa_info.dev[i].sink_index > -1) { |
| 8752 | rt_pa_info.dev[i].info.duplexChannels = |
| 8753 | (inf.info.inputChannels < rt_pa_info.dev[i].info.outputChannels) |
| 8754 | ? inf.info.inputChannels : rt_pa_info.dev[i].info.outputChannels; |
| 8755 | } |
| 8756 | */ |
| 8757 | return; |
| 8758 | } |
| 8759 | } |
| 8760 | /* try to ensure device #0 is the default */ |
| 8761 | if (inf.info.isDefaultInput) |
| 8762 | rt_pa_info.dev.insert(rt_pa_info.dev.begin(), inf); |
| 8763 | else |
| 8764 | rt_pa_info.dev.push_back(inf); |
| 8765 | } |
| 8766 | |
| 8767 | static void rt_pa_context_state_callback(pa_context *context, void *userdata) { |
| 8768 | (void)userdata; |
| 8769 | |
| 8770 | auto state = pa_context_get_state(context); |
| 8771 | switch (state) { |
| 8772 | case PA_CONTEXT_CONNECTING: |
| 8773 | case PA_CONTEXT_AUTHORIZING: |
| 8774 | case PA_CONTEXT_SETTING_NAME: |
| 8775 | break; |
| 8776 | |
| 8777 | case PA_CONTEXT_READY: |
| 8778 | rt_pa_info.dev.clear(); |
| 8779 | pa_context_get_server_info(context, rt_pa_set_server_info, NULL); |
| 8780 | pa_context_get_sink_info_list(context, rt_pa_set_sink_info, NULL); |
| 8781 | pa_context_get_source_info_list(context, rt_pa_set_source_info_and_quit, NULL); |
| 8782 | break; |
| 8783 | |
| 8784 | case PA_CONTEXT_TERMINATED: |
| 8785 | rt_pa_mainloop_api_quit(0); |
| 8786 | break; |
| 8787 | |
| 8788 | case PA_CONTEXT_FAILED: |
| 8789 | default: |
| 8790 | rt_pa_mainloop_api_quit(1); |
| 8791 | } |
| 8792 | } |
| 8793 | |
| 8794 | RtApiPulse::~RtApiPulse() |
| 8795 | { |
| 8796 | if ( stream_.state != STREAM_CLOSED ) |
| 8797 | closeStream(); |
| 8798 | } |
| 8799 | |
| 8800 | void RtApiPulse::collectDeviceInfo( void ) |
| 8801 | { |
| 8802 | pa_context *context = NULL; |
| 8803 | pa_mainloop *m = NULL; |
| 8804 | char *server = NULL; |
| 8805 | int ret = 1; |
| 8806 | |
| 8807 | if (!(m = pa_mainloop_new())) { |
| 8808 | errorStream_ << "RtApiPulse::DeviceInfo pa_mainloop_new() failed."; |
| 8809 | errorText_ = errorStream_.str(); |
| 8810 | error( RTAUDIO_WARNING ); |
| 8811 | goto quit; |
| 8812 | } |
| 8813 | |
| 8814 | rt_pa_mainloop_api = pa_mainloop_get_api(m); |
| 8815 | |
| 8816 | if (!(context = pa_context_new_with_proplist(rt_pa_mainloop_api, NULL, NULL))) { |
| 8817 | errorStream_ << "pa_context_new() failed."; |
| 8818 | errorText_ = errorStream_.str(); |
| 8819 | error( RTAUDIO_WARNING ); |
| 8820 | goto quit; |
| 8821 | } |
| 8822 | |
| 8823 | pa_context_set_state_callback(context, rt_pa_context_state_callback, NULL); |
| 8824 | |
| 8825 | if (pa_context_connect(context, server, PA_CONTEXT_NOFLAGS, NULL) < 0) { |
| 8826 | errorStream_ << "RtApiPulse::DeviceInfo pa_context_connect() failed: " |
| 8827 | << pa_strerror(pa_context_errno(context)); |
| 8828 | errorText_ = errorStream_.str(); |
| 8829 | error( RTAUDIO_WARNING ); |
| 8830 | goto quit; |
| 8831 | } |
| 8832 | |
| 8833 | if (pa_mainloop_run(m, &ret) < 0) { |
| 8834 | errorStream_ << "pa_mainloop_run() failed."; |
| 8835 | errorText_ = errorStream_.str(); |
| 8836 | error( RTAUDIO_WARNING ); |
| 8837 | goto quit; |
| 8838 | } |
| 8839 | |
| 8840 | if (ret != 0) { |
| 8841 | errorStream_ << "could not get server info."; |
| 8842 | errorText_ = errorStream_.str(); |
| 8843 | error( RTAUDIO_WARNING ); |
| 8844 | goto quit; |
| 8845 | } |
| 8846 | |
| 8847 | quit: |
| 8848 | if (context) |
| 8849 | pa_context_unref(context); |
| 8850 | |
| 8851 | if (m) { |
| 8852 | pa_mainloop_free(m); |
| 8853 | } |
| 8854 | |
| 8855 | pa_xfree(server); |
| 8856 | } |
| 8857 | |
| 8858 | unsigned int RtApiPulse::getDeviceCount( void ) |
| 8859 | { |
| 8860 | collectDeviceInfo(); |
| 8861 | return rt_pa_info.dev.size(); |
| 8862 | } |
| 8863 | |
| 8864 | RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int device ) |
| 8865 | { |
| 8866 | if (rt_pa_info.dev.size()==0) |
| 8867 | collectDeviceInfo(); |
| 8868 | if (device < rt_pa_info.dev.size()) |
| 8869 | return rt_pa_info.dev[device].info; |
| 8870 | return RtAudio::DeviceInfo(); |
| 8871 | } |
| 8872 | |
| 8873 | static void *pulseaudio_callback( void * user ) |
| 8874 | { |
| 8875 | CallbackInfo *cbi = static_cast<CallbackInfo *>( user ); |
| 8876 | RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object ); |
| 8877 | volatile bool *isRunning = &cbi->isRunning; |
| 8878 | |
| 8879 | #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread) |
| 8880 | if (cbi->doRealtime) { |
| 8881 | std::cerr << "RtAudio pulse: " << |
| 8882 | (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") << |
| 8883 | "running realtime scheduling" << std::endl; |
| 8884 | } |
| 8885 | #endif |
| 8886 | |
| 8887 | while ( *isRunning ) { |
| 8888 | pthread_testcancel(); |
| 8889 | context->callbackEvent(); |
| 8890 | } |
| 8891 | |
| 8892 | pthread_exit( NULL ); |
| 8893 | } |
| 8894 | |
| 8895 | void RtApiPulse::closeStream( void ) |
| 8896 | { |
| 8897 | PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle ); |
| 8898 | |
| 8899 | stream_.callbackInfo.isRunning = false; |
| 8900 | if ( pah ) { |
| 8901 | MUTEX_LOCK( &stream_.mutex ); |
| 8902 | if ( stream_.state == STREAM_STOPPED ) { |
| 8903 | pah->runnable = true; |
| 8904 | pthread_cond_signal( &pah->runnable_cv ); |
| 8905 | } |
| 8906 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8907 | |
| 8908 | pthread_join( pah->thread, 0 ); |
| 8909 | if ( pah->s_play ) { |
| 8910 | pa_simple_flush( pah->s_play, NULL ); |
| 8911 | pa_simple_free( pah->s_play ); |
| 8912 | } |
| 8913 | if ( pah->s_rec ) |
| 8914 | pa_simple_free( pah->s_rec ); |
| 8915 | |
| 8916 | pthread_cond_destroy( &pah->runnable_cv ); |
| 8917 | delete pah; |
| 8918 | stream_.apiHandle = 0; |
| 8919 | } |
| 8920 | |
| 8921 | if ( stream_.userBuffer[0] ) { |
| 8922 | free( stream_.userBuffer[0] ); |
| 8923 | stream_.userBuffer[0] = 0; |
| 8924 | } |
| 8925 | if ( stream_.userBuffer[1] ) { |
| 8926 | free( stream_.userBuffer[1] ); |
| 8927 | stream_.userBuffer[1] = 0; |
| 8928 | } |
| 8929 | |
| 8930 | clearStreamInfo(); |
| 8931 | //stream_.state = STREAM_CLOSED; |
| 8932 | //stream_.mode = UNINITIALIZED; |
| 8933 | } |
| 8934 | |
| 8935 | void RtApiPulse::callbackEvent( void ) |
| 8936 | { |
| 8937 | PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle ); |
| 8938 | |
| 8939 | if ( stream_.state == STREAM_STOPPED ) { |
| 8940 | MUTEX_LOCK( &stream_.mutex ); |
| 8941 | while ( !pah->runnable ) |
| 8942 | pthread_cond_wait( &pah->runnable_cv, &stream_.mutex ); |
| 8943 | |
| 8944 | if ( stream_.state != STREAM_RUNNING ) { |
| 8945 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8946 | return; |
| 8947 | } |
| 8948 | MUTEX_UNLOCK( &stream_.mutex ); |
| 8949 | } |
| 8950 | |
| 8951 | if ( stream_.state == STREAM_CLOSED ) { |
| 8952 | errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... " |
| 8953 | "this shouldn't happen!"; |
| 8954 | error( RTAUDIO_WARNING ); |
| 8955 | return; |
| 8956 | } |
| 8957 | |
| 8958 | RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback; |
| 8959 | double streamTime = getStreamTime(); |
| 8960 | RtAudioStreamStatus status = 0; |
| 8961 | int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT], |
| 8962 | stream_.bufferSize, streamTime, status, |
| 8963 | stream_.callbackInfo.userData ); |
| 8964 | |
| 8965 | if ( doStopStream == 2 ) { |
| 8966 | abortStream(); |
| 8967 | return; |
| 8968 | } |
| 8969 | |
| 8970 | MUTEX_LOCK( &stream_.mutex ); |
| 8971 | void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT]; |
| 8972 | void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT]; |
| 8973 | |
| 8974 | if ( stream_.state != STREAM_RUNNING ) |
| 8975 | goto unlock; |
| 8976 | |
| 8977 | int pa_error; |
| 8978 | size_t bytes; |
| 8979 | if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 8980 | if ( stream_.doConvertBuffer[OUTPUT] ) { |
| 8981 | convertBuffer( stream_.deviceBuffer, |
| 8982 | stream_.userBuffer[OUTPUT], |
| 8983 | stream_.convertInfo[OUTPUT] ); |
| 8984 | bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize * |
| 8985 | formatBytes( stream_.deviceFormat[OUTPUT] ); |
| 8986 | } else |
| 8987 | bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize * |
| 8988 | formatBytes( stream_.userFormat ); |
| 8989 | |
| 8990 | if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) { |
| 8991 | errorStream_ << "RtApiPulse::callbackEvent: audio write error, " << |
| 8992 | pa_strerror( pa_error ) << "."; |
| 8993 | errorText_ = errorStream_.str(); |
| 8994 | error( RTAUDIO_WARNING ); |
| 8995 | } |
| 8996 | } |
| 8997 | |
| 8998 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX) { |
| 8999 | if ( stream_.doConvertBuffer[INPUT] ) |
| 9000 | bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize * |
| 9001 | formatBytes( stream_.deviceFormat[INPUT] ); |
| 9002 | else |
| 9003 | bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize * |
| 9004 | formatBytes( stream_.userFormat ); |
| 9005 | |
| 9006 | if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) { |
| 9007 | errorStream_ << "RtApiPulse::callbackEvent: audio read error, " << |
| 9008 | pa_strerror( pa_error ) << "."; |
| 9009 | errorText_ = errorStream_.str(); |
| 9010 | error( RTAUDIO_WARNING ); |
| 9011 | } |
| 9012 | if ( stream_.doConvertBuffer[INPUT] ) { |
| 9013 | convertBuffer( stream_.userBuffer[INPUT], |
| 9014 | stream_.deviceBuffer, |
| 9015 | stream_.convertInfo[INPUT] ); |
| 9016 | } |
| 9017 | } |
| 9018 | |
| 9019 | unlock: |
| 9020 | MUTEX_UNLOCK( &stream_.mutex ); |
| 9021 | RtApi::tickStreamTime(); |
| 9022 | |
| 9023 | if ( doStopStream == 1 ) |
| 9024 | stopStream(); |
| 9025 | } |
| 9026 | |
| 9027 | RtAudioErrorType RtApiPulse::startStream( void ) |
| 9028 | { |
| 9029 | if ( stream_.state != STREAM_STOPPED ) { |
| 9030 | if ( stream_.state == STREAM_RUNNING ) |
| 9031 | errorText_ = "RtApiPulse::startStream(): the stream is already running!"; |
| 9032 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 9033 | errorText_ = "RtApiPulse::startStream(): the stream is stopping or closed!"; |
| 9034 | return error( RTAUDIO_WARNING ); |
| 9035 | } |
| 9036 | |
| 9037 | PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle ); |
| 9038 | |
| 9039 | MUTEX_LOCK( &stream_.mutex ); |
| 9040 | |
| 9041 | /* |
| 9042 | #if defined( HAVE_GETTIMEOFDAY ) |
| 9043 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 9044 | #endif |
| 9045 | */ |
| 9046 | |
| 9047 | stream_.state = STREAM_RUNNING; |
| 9048 | |
| 9049 | pah->runnable = true; |
| 9050 | pthread_cond_signal( &pah->runnable_cv ); |
| 9051 | MUTEX_UNLOCK( &stream_.mutex ); |
| 9052 | return RTAUDIO_NO_ERROR; |
| 9053 | } |
| 9054 | |
| 9055 | RtAudioErrorType RtApiPulse::stopStream( void ) |
| 9056 | { |
| 9057 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 9058 | if ( stream_.state == STREAM_STOPPED ) |
| 9059 | errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!"; |
| 9060 | else if ( stream_.state == STREAM_CLOSED ) |
| 9061 | errorText_ = "RtApiPulse::stopStream(): the stream is closed!"; |
| 9062 | return error( RTAUDIO_WARNING ); |
| 9063 | } |
| 9064 | |
| 9065 | PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle ); |
| 9066 | |
| 9067 | stream_.state = STREAM_STOPPED; |
| 9068 | MUTEX_LOCK( &stream_.mutex ); |
| 9069 | |
| 9070 | if ( pah ) { |
| 9071 | pah->runnable = false; |
| 9072 | if ( pah->s_play ) { |
| 9073 | int pa_error; |
| 9074 | if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) { |
| 9075 | errorStream_ << "RtApiPulse::stopStream: error draining output device, " << |
| 9076 | pa_strerror( pa_error ) << "."; |
| 9077 | errorText_ = errorStream_.str(); |
| 9078 | MUTEX_UNLOCK( &stream_.mutex ); |
| 9079 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 9080 | } |
| 9081 | } |
| 9082 | } |
| 9083 | |
| 9084 | stream_.state = STREAM_STOPPED; |
| 9085 | MUTEX_UNLOCK( &stream_.mutex ); |
| 9086 | return RTAUDIO_NO_ERROR; |
| 9087 | } |
| 9088 | |
| 9089 | RtAudioErrorType RtApiPulse::abortStream( void ) |
| 9090 | { |
| 9091 | if ( stream_.state != STREAM_RUNNING ) { |
| 9092 | if ( stream_.state == STREAM_STOPPED ) |
| 9093 | errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!"; |
| 9094 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 9095 | errorText_ = "RtApiPulse::abortStream(): the stream is stopping or closed!"; |
| 9096 | return error( RTAUDIO_WARNING ); |
| 9097 | } |
| 9098 | |
| 9099 | PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle ); |
| 9100 | |
| 9101 | stream_.state = STREAM_STOPPED; |
| 9102 | MUTEX_LOCK( &stream_.mutex ); |
| 9103 | |
| 9104 | if ( pah ) { |
| 9105 | pah->runnable = false; |
| 9106 | if ( pah->s_play ) { |
| 9107 | int pa_error; |
| 9108 | if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) { |
| 9109 | errorStream_ << "RtApiPulse::abortStream: error flushing output device, " << |
| 9110 | pa_strerror( pa_error ) << "."; |
| 9111 | errorText_ = errorStream_.str(); |
| 9112 | MUTEX_UNLOCK( &stream_.mutex ); |
| 9113 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 9114 | } |
| 9115 | } |
| 9116 | } |
| 9117 | |
| 9118 | stream_.state = STREAM_STOPPED; |
| 9119 | MUTEX_UNLOCK( &stream_.mutex ); |
| 9120 | return RTAUDIO_NO_ERROR; |
| 9121 | } |
| 9122 | |
| 9123 | bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode, |
| 9124 | unsigned int channels, unsigned int firstChannel, |
| 9125 | unsigned int sampleRate, RtAudioFormat format, |
| 9126 | unsigned int *bufferSize, RtAudio::StreamOptions *options ) |
| 9127 | { |
| 9128 | PulseAudioHandle *pah = 0; |
| 9129 | unsigned long bufferBytes = 0; |
| 9130 | pa_sample_spec ss; |
| 9131 | |
| 9132 | if ( device >= rt_pa_info.dev.size() ) return false; |
| 9133 | if ( firstChannel != 0 ) { |
| 9134 | errorText_ = "PulseAudio does not support channel offset mapping."; |
| 9135 | return false; |
| 9136 | } |
| 9137 | |
| 9138 | /* these may be NULL for default, but we've already got the names */ |
| 9139 | const char *dev_input = NULL; |
| 9140 | const char *dev_output = NULL; |
| 9141 | if (!rt_pa_info.dev[device].source_name.empty()) |
| 9142 | dev_input = rt_pa_info.dev[device].source_name.c_str(); |
| 9143 | if (!rt_pa_info.dev[device].sink_name.empty()) |
| 9144 | dev_output = rt_pa_info.dev[device].sink_name.c_str(); |
| 9145 | |
| 9146 | if (mode==INPUT && rt_pa_info.dev[device].info.inputChannels == 0) { |
| 9147 | errorText_ = "PulseAudio device does not support input."; |
| 9148 | return false; |
| 9149 | } |
| 9150 | if (mode==OUTPUT && rt_pa_info.dev[device].info.outputChannels == 0) { |
| 9151 | errorText_ = "PulseAudio device does not support output."; |
| 9152 | return false; |
| 9153 | } |
| 9154 | if (mode==DUPLEX && rt_pa_info.dev[device].info.duplexChannels == 0) { |
| 9155 | /* Note: will always error, DUPLEX not yet supported */ |
| 9156 | errorText_ = "PulseAudio device does not support duplex."; |
| 9157 | return false; |
| 9158 | } |
| 9159 | |
| 9160 | if (mode==INPUT && rt_pa_info.dev[device].info.inputChannels < channels) { |
| 9161 | errorText_ = "PulseAudio: unsupported number of input channels."; |
| 9162 | return false; |
| 9163 | } |
| 9164 | |
| 9165 | if (mode==OUTPUT && rt_pa_info.dev[device].info.outputChannels < channels) { |
| 9166 | errorText_ = "PulseAudio: unsupported number of output channels."; |
| 9167 | return false; |
| 9168 | } |
| 9169 | |
| 9170 | if (mode==DUPLEX && rt_pa_info.dev[device].info.duplexChannels < channels) { |
| 9171 | /* Note: will always error, DUPLEX not yet supported */ |
| 9172 | errorText_ = "PulseAudio: unsupported number of duplex channels."; |
| 9173 | return false; |
| 9174 | } |
| 9175 | |
| 9176 | ss.channels = channels; |
| 9177 | |
| 9178 | bool sr_found = false; |
| 9179 | for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) { |
| 9180 | if ( sampleRate == *sr ) { |
| 9181 | sr_found = true; |
| 9182 | stream_.sampleRate = sampleRate; |
| 9183 | ss.rate = sampleRate; |
| 9184 | break; |
| 9185 | } |
| 9186 | } |
| 9187 | if ( !sr_found ) { |
| 9188 | stream_.sampleRate = sampleRate; |
| 9189 | ss.rate = sampleRate; |
| 9190 | } |
| 9191 | |
| 9192 | bool sf_found = 0; |
| 9193 | for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats; |
| 9194 | sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) { |
| 9195 | if ( format == sf->rtaudio_format ) { |
| 9196 | sf_found = true; |
| 9197 | stream_.userFormat = sf->rtaudio_format; |
| 9198 | stream_.deviceFormat[mode] = stream_.userFormat; |
| 9199 | ss.format = sf->pa_format; |
| 9200 | break; |
| 9201 | } |
| 9202 | } |
| 9203 | if ( !sf_found ) { // Use internal data format conversion. |
| 9204 | stream_.userFormat = format; |
| 9205 | stream_.deviceFormat[mode] = RTAUDIO_FLOAT32; |
| 9206 | ss.format = PA_SAMPLE_FLOAT32LE; |
| 9207 | } |
| 9208 | |
| 9209 | // Set other stream parameters. |
| 9210 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false; |
| 9211 | else stream_.userInterleaved = true; |
| 9212 | stream_.deviceInterleaved[mode] = true; |
| 9213 | stream_.nBuffers = options ? options->numberOfBuffers : 1; |
| 9214 | stream_.doByteSwap[mode] = false; |
| 9215 | stream_.nUserChannels[mode] = channels; |
| 9216 | stream_.nDeviceChannels[mode] = channels + firstChannel; |
| 9217 | stream_.channelOffset[mode] = 0; |
| 9218 | std::string streamName = "RtAudio"; |
| 9219 | |
| 9220 | // Set flags for buffer conversion. |
| 9221 | stream_.doConvertBuffer[mode] = false; |
| 9222 | if ( stream_.userFormat != stream_.deviceFormat[mode] ) |
| 9223 | stream_.doConvertBuffer[mode] = true; |
| 9224 | if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] ) |
| 9225 | stream_.doConvertBuffer[mode] = true; |
| 9226 | if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] ) |
| 9227 | stream_.doConvertBuffer[mode] = true; |
| 9228 | |
| 9229 | // Allocate necessary internal buffers. |
| 9230 | bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat ); |
| 9231 | stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 ); |
| 9232 | if ( stream_.userBuffer[mode] == NULL ) { |
| 9233 | errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory."; |
| 9234 | goto error; |
| 9235 | } |
| 9236 | stream_.bufferSize = *bufferSize; |
| 9237 | |
| 9238 | if ( stream_.doConvertBuffer[mode] ) { |
| 9239 | |
| 9240 | bool makeBuffer = true; |
| 9241 | bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] ); |
| 9242 | if ( mode == INPUT ) { |
| 9243 | if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) { |
| 9244 | unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] ); |
| 9245 | if ( bufferBytes <= bytesOut ) makeBuffer = false; |
| 9246 | } |
| 9247 | } |
| 9248 | |
| 9249 | if ( makeBuffer ) { |
| 9250 | bufferBytes *= *bufferSize; |
| 9251 | if ( stream_.deviceBuffer ) free( stream_.deviceBuffer ); |
| 9252 | stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 ); |
| 9253 | if ( stream_.deviceBuffer == NULL ) { |
| 9254 | errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory."; |
| 9255 | goto error; |
| 9256 | } |
| 9257 | } |
| 9258 | } |
| 9259 | |
| 9260 | stream_.device[mode] = device; |
| 9261 | |
| 9262 | // Setup the buffer conversion information structure. |
| 9263 | if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel ); |
| 9264 | |
| 9265 | if ( !stream_.apiHandle ) { |
| 9266 | PulseAudioHandle *pah = new PulseAudioHandle; |
| 9267 | if ( !pah ) { |
| 9268 | errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle."; |
| 9269 | goto error; |
| 9270 | } |
| 9271 | |
| 9272 | stream_.apiHandle = pah; |
| 9273 | if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) { |
| 9274 | errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable."; |
| 9275 | goto error; |
| 9276 | } |
| 9277 | } |
| 9278 | pah = static_cast<PulseAudioHandle *>( stream_.apiHandle ); |
| 9279 | |
| 9280 | int error; |
| 9281 | if ( options && !options->streamName.empty() ) streamName = options->streamName; |
| 9282 | switch ( mode ) { |
| 9283 | pa_buffer_attr buffer_attr; |
| 9284 | case INPUT: |
| 9285 | buffer_attr.fragsize = bufferBytes; |
| 9286 | buffer_attr.maxlength = -1; |
| 9287 | |
| 9288 | pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, |
| 9289 | dev_input, "Record", &ss, NULL, &buffer_attr, &error ); |
| 9290 | if ( !pah->s_rec ) { |
| 9291 | errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server."; |
| 9292 | goto error; |
| 9293 | } |
| 9294 | break; |
| 9295 | case OUTPUT: { |
| 9296 | pa_buffer_attr * attr_ptr; |
| 9297 | |
| 9298 | if ( options && options->numberOfBuffers > 0 ) { |
| 9299 | // pa_buffer_attr::fragsize is recording-only. |
| 9300 | // Hopefully PortAudio won't access uninitialized fields. |
| 9301 | buffer_attr.maxlength = bufferBytes * options->numberOfBuffers; |
| 9302 | buffer_attr.minreq = -1; |
| 9303 | buffer_attr.prebuf = -1; |
| 9304 | buffer_attr.tlength = -1; |
| 9305 | attr_ptr = &buffer_attr; |
| 9306 | } else { |
| 9307 | attr_ptr = nullptr; |
| 9308 | } |
| 9309 | |
| 9310 | pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, |
| 9311 | dev_output, "Playback", &ss, NULL, attr_ptr, &error ); |
| 9312 | if ( !pah->s_play ) { |
| 9313 | errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server."; |
| 9314 | goto error; |
| 9315 | } |
| 9316 | break; |
| 9317 | } |
| 9318 | case DUPLEX: |
| 9319 | /* Note: We could add DUPLEX by synchronizing multiple streams, |
| 9320 | but it would mean moving from Simple API to Asynchronous API: |
| 9321 | https://freedesktop.org/software/pulseaudio/doxygen/streams.html#sync_streams */ |
| 9322 | errorText_ = "RtApiPulse::probeDeviceOpen: duplex not supported for PulseAudio."; |
| 9323 | goto error; |
| 9324 | default: |
| 9325 | goto error; |
| 9326 | } |
| 9327 | |
| 9328 | if ( stream_.mode == UNINITIALIZED ) |
| 9329 | stream_.mode = mode; |
| 9330 | else if ( stream_.mode == mode ) |
| 9331 | goto error; |
| 9332 | else |
| 9333 | stream_.mode = DUPLEX; |
| 9334 | |
| 9335 | if ( !stream_.callbackInfo.isRunning ) { |
| 9336 | stream_.callbackInfo.object = this; |
| 9337 | |
| 9338 | stream_.state = STREAM_STOPPED; |
| 9339 | // Set the thread attributes for joinable and realtime scheduling |
| 9340 | // priority (optional). The higher priority will only take affect |
| 9341 | // if the program is run as root or suid. Note, under Linux |
| 9342 | // processes with CAP_SYS_NICE privilege, a user can change |
| 9343 | // scheduling policy and priority (thus need not be root). See |
| 9344 | // POSIX "capabilities". |
| 9345 | pthread_attr_t attr; |
| 9346 | pthread_attr_init( &attr ); |
| 9347 | pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); |
| 9348 | #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread) |
| 9349 | if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) { |
| 9350 | stream_.callbackInfo.doRealtime = true; |
| 9351 | struct sched_param param; |
| 9352 | int priority = options->priority; |
| 9353 | int min = sched_get_priority_min( SCHED_RR ); |
| 9354 | int max = sched_get_priority_max( SCHED_RR ); |
| 9355 | if ( priority < min ) priority = min; |
| 9356 | else if ( priority > max ) priority = max; |
| 9357 | param.sched_priority = priority; |
| 9358 | |
| 9359 | // Set the policy BEFORE the priority. Otherwise it fails. |
| 9360 | pthread_attr_setschedpolicy(&attr, SCHED_RR); |
| 9361 | pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM); |
| 9362 | // This is definitely required. Otherwise it fails. |
| 9363 | pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); |
| 9364 | pthread_attr_setschedparam(&attr, ¶m); |
| 9365 | } |
| 9366 | else |
| 9367 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 9368 | #else |
| 9369 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 9370 | #endif |
| 9371 | |
| 9372 | stream_.callbackInfo.isRunning = true; |
| 9373 | int result = pthread_create( &pah->thread, &attr, pulseaudio_callback, (void *)&stream_.callbackInfo); |
| 9374 | pthread_attr_destroy(&attr); |
| 9375 | if(result != 0) { |
| 9376 | // Failed. Try instead with default attributes. |
| 9377 | result = pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo); |
| 9378 | if(result != 0) { |
| 9379 | stream_.callbackInfo.isRunning = false; |
| 9380 | errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread."; |
| 9381 | goto error; |
| 9382 | } |
| 9383 | } |
| 9384 | } |
| 9385 | |
| 9386 | return SUCCESS; |
| 9387 | |
| 9388 | error: |
| 9389 | if ( pah && stream_.callbackInfo.isRunning ) { |
| 9390 | pthread_cond_destroy( &pah->runnable_cv ); |
| 9391 | delete pah; |
| 9392 | stream_.apiHandle = 0; |
| 9393 | } |
| 9394 | |
| 9395 | for ( int i=0; i<2; i++ ) { |
| 9396 | if ( stream_.userBuffer[i] ) { |
| 9397 | free( stream_.userBuffer[i] ); |
| 9398 | stream_.userBuffer[i] = 0; |
| 9399 | } |
| 9400 | } |
| 9401 | |
| 9402 | if ( stream_.deviceBuffer ) { |
| 9403 | free( stream_.deviceBuffer ); |
| 9404 | stream_.deviceBuffer = 0; |
| 9405 | } |
| 9406 | |
| 9407 | stream_.state = STREAM_CLOSED; |
| 9408 | return FAILURE; |
| 9409 | } |
| 9410 | |
| 9411 | //******************** End of __LINUX_PULSE__ *********************// |
| 9412 | #endif |
| 9413 | |
| 9414 | #if defined(__LINUX_OSS__) |
| 9415 | |
| 9416 | #include <unistd.h> |
| 9417 | #include <sys/ioctl.h> |
| 9418 | #include <unistd.h> |
| 9419 | #include <fcntl.h> |
| 9420 | #include <sys/soundcard.h> |
| 9421 | #include <errno.h> |
| 9422 | #include <math.h> |
| 9423 | |
| 9424 | static void *ossCallbackHandler(void * ptr); |
| 9425 | |
| 9426 | // A structure to hold various information related to the OSS API |
| 9427 | // implementation. |
| 9428 | struct OssHandle { |
| 9429 | int id[2]; // device ids |
| 9430 | bool xrun[2]; |
| 9431 | bool triggered; |
| 9432 | pthread_cond_t runnable; |
| 9433 | |
| 9434 | OssHandle() |
| 9435 | :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; } |
| 9436 | }; |
| 9437 | |
| 9438 | RtApiOss :: RtApiOss() |
| 9439 | { |
| 9440 | // Nothing to do here. |
| 9441 | } |
| 9442 | |
| 9443 | RtApiOss :: ~RtApiOss() |
| 9444 | { |
| 9445 | if ( stream_.state != STREAM_CLOSED ) closeStream(); |
| 9446 | } |
| 9447 | |
| 9448 | unsigned int RtApiOss :: getDeviceCount( void ) |
| 9449 | { |
| 9450 | int mixerfd = open( "/dev/mixer", O_RDWR, 0 ); |
| 9451 | if ( mixerfd == -1 ) { |
| 9452 | errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'."; |
| 9453 | error( RTAUDIO_WARNING ); |
| 9454 | return 0; |
| 9455 | } |
| 9456 | |
| 9457 | oss_sysinfo sysinfo; |
| 9458 | if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) { |
| 9459 | close( mixerfd ); |
| 9460 | errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required."; |
| 9461 | error( RTAUDIO_WARNING ); |
| 9462 | return 0; |
| 9463 | } |
| 9464 | |
| 9465 | close( mixerfd ); |
| 9466 | return sysinfo.numaudios; |
| 9467 | } |
| 9468 | |
| 9469 | RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device ) |
| 9470 | { |
| 9471 | RtAudio::DeviceInfo info; |
| 9472 | info.probed = false; |
| 9473 | |
| 9474 | int mixerfd = open( "/dev/mixer", O_RDWR, 0 ); |
| 9475 | if ( mixerfd == -1 ) { |
| 9476 | errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'."; |
| 9477 | error( RTAUDIO_WARNING ); |
| 9478 | return info; |
| 9479 | } |
| 9480 | |
| 9481 | oss_sysinfo sysinfo; |
| 9482 | int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ); |
| 9483 | if ( result == -1 ) { |
| 9484 | close( mixerfd ); |
| 9485 | errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required."; |
| 9486 | error( RTAUDIO_WARNING ); |
| 9487 | return info; |
| 9488 | } |
| 9489 | |
| 9490 | unsigned nDevices = sysinfo.numaudios; |
| 9491 | if ( nDevices == 0 ) { |
| 9492 | close( mixerfd ); |
| 9493 | errorText_ = "RtApiOss::getDeviceInfo: no devices found!"; |
| 9494 | error( RTAUDIO_INVALID_USE ); |
| 9495 | return info; |
| 9496 | } |
| 9497 | |
| 9498 | if ( device >= nDevices ) { |
| 9499 | close( mixerfd ); |
| 9500 | errorText_ = "RtApiOss::getDeviceInfo: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 9501 | error( RTAUDIO_INVALID_USE ); |
| 9502 | return info; |
| 9503 | } |
| 9504 | |
| 9505 | oss_audioinfo ainfo; |
| 9506 | ainfo.dev = device; |
| 9507 | result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo ); |
| 9508 | close( mixerfd ); |
| 9509 | if ( result == -1 ) { |
| 9510 | errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info."; |
| 9511 | errorText_ = errorStream_.str(); |
| 9512 | error( RTAUDIO_WARNING ); |
| 9513 | return info; |
| 9514 | } |
| 9515 | |
| 9516 | // Probe channels |
| 9517 | if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels; |
| 9518 | if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels; |
| 9519 | if ( ainfo.caps & PCM_CAP_DUPLEX ) { |
| 9520 | if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX ) |
| 9521 | info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels; |
| 9522 | } |
| 9523 | |
| 9524 | // Probe data formats ... do for input |
| 9525 | unsigned long mask = ainfo.iformats; |
| 9526 | if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE ) |
| 9527 | info.nativeFormats |= RTAUDIO_SINT16; |
| 9528 | if ( mask & AFMT_S8 ) |
| 9529 | info.nativeFormats |= RTAUDIO_SINT8; |
| 9530 | if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE ) |
| 9531 | info.nativeFormats |= RTAUDIO_SINT32; |
| 9532 | #ifdef AFMT_FLOAT |
| 9533 | if ( mask & AFMT_FLOAT ) |
| 9534 | info.nativeFormats |= RTAUDIO_FLOAT32; |
| 9535 | #endif |
| 9536 | if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE ) |
| 9537 | info.nativeFormats |= RTAUDIO_SINT24; |
| 9538 | |
| 9539 | // Check that we have at least one supported format |
| 9540 | if ( info.nativeFormats == 0 ) { |
| 9541 | errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio."; |
| 9542 | errorText_ = errorStream_.str(); |
| 9543 | error( RTAUDIO_WARNING ); |
| 9544 | return info; |
| 9545 | } |
| 9546 | |
| 9547 | // Probe the supported sample rates. |
| 9548 | info.sampleRates.clear(); |
| 9549 | if ( ainfo.nrates ) { |
| 9550 | for ( unsigned int i=0; i<ainfo.nrates; i++ ) { |
| 9551 | for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) { |
| 9552 | if ( ainfo.rates[i] == SAMPLE_RATES[k] ) { |
| 9553 | info.sampleRates.push_back( SAMPLE_RATES[k] ); |
| 9554 | |
| 9555 | if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) ) |
| 9556 | info.preferredSampleRate = SAMPLE_RATES[k]; |
| 9557 | |
| 9558 | break; |
| 9559 | } |
| 9560 | } |
| 9561 | } |
| 9562 | } |
| 9563 | else { |
| 9564 | // Check min and max rate values; |
| 9565 | for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) { |
| 9566 | if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) { |
| 9567 | info.sampleRates.push_back( SAMPLE_RATES[k] ); |
| 9568 | |
| 9569 | if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) ) |
| 9570 | info.preferredSampleRate = SAMPLE_RATES[k]; |
| 9571 | } |
| 9572 | } |
| 9573 | } |
| 9574 | |
| 9575 | if ( info.sampleRates.size() == 0 ) { |
| 9576 | errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ")."; |
| 9577 | errorText_ = errorStream_.str(); |
| 9578 | error( RTAUDIO_WARNING ); |
| 9579 | } |
| 9580 | else { |
| 9581 | info.probed = true; |
| 9582 | info.name = ainfo.name; |
| 9583 | } |
| 9584 | |
| 9585 | return info; |
| 9586 | } |
| 9587 | |
| 9588 | |
| 9589 | bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels, |
| 9590 | unsigned int firstChannel, unsigned int sampleRate, |
| 9591 | RtAudioFormat format, unsigned int *bufferSize, |
| 9592 | RtAudio::StreamOptions *options ) |
| 9593 | { |
| 9594 | int mixerfd = open( "/dev/mixer", O_RDWR, 0 ); |
| 9595 | if ( mixerfd == -1 ) { |
| 9596 | errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'."; |
| 9597 | return FAILURE; |
| 9598 | } |
| 9599 | |
| 9600 | oss_sysinfo sysinfo; |
| 9601 | int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ); |
| 9602 | if ( result == -1 ) { |
| 9603 | close( mixerfd ); |
| 9604 | errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required."; |
| 9605 | return FAILURE; |
| 9606 | } |
| 9607 | |
| 9608 | unsigned nDevices = sysinfo.numaudios; |
| 9609 | if ( nDevices == 0 ) { |
| 9610 | // This should not happen because a check is made before this function is called. |
| 9611 | close( mixerfd ); |
| 9612 | errorText_ = "RtApiOss::probeDeviceOpen: no devices found!"; |
| 9613 | return FAILURE; |
| 9614 | } |
| 9615 | |
| 9616 | if ( device >= nDevices ) { |
| 9617 | // This should not happen because a check is made before this function is called. |
| 9618 | close( mixerfd ); |
| 9619 | errorText_ = "RtApiOss::probeDeviceOpen: device " + std::to_string(device) + " (probed ID:" + std::to_string(device+1) + ") is invalid."; // 1.5.2.5 (ge) add device # |
| 9620 | return FAILURE; |
| 9621 | } |
| 9622 | |
| 9623 | oss_audioinfo ainfo; |
| 9624 | ainfo.dev = device; |
| 9625 | result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo ); |
| 9626 | close( mixerfd ); |
| 9627 | if ( result == -1 ) { |
| 9628 | errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info."; |
| 9629 | errorText_ = errorStream_.str(); |
| 9630 | return FAILURE; |
| 9631 | } |
| 9632 | |
| 9633 | // Check if device supports input or output |
| 9634 | if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) || |
| 9635 | ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) { |
| 9636 | if ( mode == OUTPUT ) |
| 9637 | errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output."; |
| 9638 | else |
| 9639 | errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input."; |
| 9640 | errorText_ = errorStream_.str(); |
| 9641 | return FAILURE; |
| 9642 | } |
| 9643 | |
| 9644 | int flags = 0; |
| 9645 | OssHandle *handle = (OssHandle *) stream_.apiHandle; |
| 9646 | if ( mode == OUTPUT ) |
| 9647 | flags |= O_WRONLY; |
| 9648 | else { // mode == INPUT |
| 9649 | if (stream_.mode == OUTPUT && stream_.device[0] == device) { |
| 9650 | // We just set the same device for playback ... close and reopen for duplex (OSS only). |
| 9651 | close( handle->id[0] ); |
| 9652 | handle->id[0] = 0; |
| 9653 | if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) { |
| 9654 | errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode."; |
| 9655 | errorText_ = errorStream_.str(); |
| 9656 | return FAILURE; |
| 9657 | } |
| 9658 | // Check that the number previously set channels is the same. |
| 9659 | if ( stream_.nUserChannels[0] != channels ) { |
| 9660 | errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ")."; |
| 9661 | errorText_ = errorStream_.str(); |
| 9662 | return FAILURE; |
| 9663 | } |
| 9664 | flags |= O_RDWR; |
| 9665 | } |
| 9666 | else |
| 9667 | flags |= O_RDONLY; |
| 9668 | } |
| 9669 | |
| 9670 | // Set exclusive access if specified. |
| 9671 | if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL; |
| 9672 | |
| 9673 | // Try to open the device. |
| 9674 | int fd; |
| 9675 | fd = open( ainfo.devnode, flags, 0 ); |
| 9676 | if ( fd == -1 ) { |
| 9677 | if ( errno == EBUSY ) |
| 9678 | errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy."; |
| 9679 | else |
| 9680 | errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ")."; |
| 9681 | errorText_ = errorStream_.str(); |
| 9682 | return FAILURE; |
| 9683 | } |
| 9684 | |
| 9685 | // For duplex operation, specifically set this mode (this doesn't seem to work). |
| 9686 | /* |
| 9687 | if ( flags | O_RDWR ) { |
| 9688 | result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL ); |
| 9689 | if ( result == -1) { |
| 9690 | errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ")."; |
| 9691 | errorText_ = errorStream_.str(); |
| 9692 | return FAILURE; |
| 9693 | } |
| 9694 | } |
| 9695 | */ |
| 9696 | |
| 9697 | // Check the device channel support. |
| 9698 | stream_.nUserChannels[mode] = channels; |
| 9699 | if ( ainfo.max_channels < (int)(channels + firstChannel) ) { |
| 9700 | close( fd ); |
| 9701 | errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters."; |
| 9702 | errorText_ = errorStream_.str(); |
| 9703 | return FAILURE; |
| 9704 | } |
| 9705 | |
| 9706 | // Set the number of channels. |
| 9707 | int deviceChannels = channels + firstChannel; |
| 9708 | result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels ); |
| 9709 | if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) { |
| 9710 | close( fd ); |
| 9711 | errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ")."; |
| 9712 | errorText_ = errorStream_.str(); |
| 9713 | return FAILURE; |
| 9714 | } |
| 9715 | stream_.nDeviceChannels[mode] = deviceChannels; |
| 9716 | |
| 9717 | // Get the data format mask |
| 9718 | int mask; |
| 9719 | result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask ); |
| 9720 | if ( result == -1 ) { |
| 9721 | close( fd ); |
| 9722 | errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats."; |
| 9723 | errorText_ = errorStream_.str(); |
| 9724 | return FAILURE; |
| 9725 | } |
| 9726 | |
| 9727 | // Determine how to set the device format. |
| 9728 | stream_.userFormat = format; |
| 9729 | int deviceFormat = -1; |
| 9730 | stream_.doByteSwap[mode] = false; |
| 9731 | if ( format == RTAUDIO_SINT8 ) { |
| 9732 | if ( mask & AFMT_S8 ) { |
| 9733 | deviceFormat = AFMT_S8; |
| 9734 | stream_.deviceFormat[mode] = RTAUDIO_SINT8; |
| 9735 | } |
| 9736 | } |
| 9737 | else if ( format == RTAUDIO_SINT16 ) { |
| 9738 | if ( mask & AFMT_S16_NE ) { |
| 9739 | deviceFormat = AFMT_S16_NE; |
| 9740 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 9741 | } |
| 9742 | else if ( mask & AFMT_S16_OE ) { |
| 9743 | deviceFormat = AFMT_S16_OE; |
| 9744 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 9745 | stream_.doByteSwap[mode] = true; |
| 9746 | } |
| 9747 | } |
| 9748 | else if ( format == RTAUDIO_SINT24 ) { |
| 9749 | if ( mask & AFMT_S24_NE ) { |
| 9750 | deviceFormat = AFMT_S24_NE; |
| 9751 | stream_.deviceFormat[mode] = RTAUDIO_SINT24; |
| 9752 | } |
| 9753 | else if ( mask & AFMT_S24_OE ) { |
| 9754 | deviceFormat = AFMT_S24_OE; |
| 9755 | stream_.deviceFormat[mode] = RTAUDIO_SINT24; |
| 9756 | stream_.doByteSwap[mode] = true; |
| 9757 | } |
| 9758 | } |
| 9759 | else if ( format == RTAUDIO_SINT32 ) { |
| 9760 | if ( mask & AFMT_S32_NE ) { |
| 9761 | deviceFormat = AFMT_S32_NE; |
| 9762 | stream_.deviceFormat[mode] = RTAUDIO_SINT32; |
| 9763 | } |
| 9764 | else if ( mask & AFMT_S32_OE ) { |
| 9765 | deviceFormat = AFMT_S32_OE; |
| 9766 | stream_.deviceFormat[mode] = RTAUDIO_SINT32; |
| 9767 | stream_.doByteSwap[mode] = true; |
| 9768 | } |
| 9769 | } |
| 9770 | |
| 9771 | if ( deviceFormat == -1 ) { |
| 9772 | // The user requested format is not natively supported by the device. |
| 9773 | if ( mask & AFMT_S16_NE ) { |
| 9774 | deviceFormat = AFMT_S16_NE; |
| 9775 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 9776 | } |
| 9777 | else if ( mask & AFMT_S32_NE ) { |
| 9778 | deviceFormat = AFMT_S32_NE; |
| 9779 | stream_.deviceFormat[mode] = RTAUDIO_SINT32; |
| 9780 | } |
| 9781 | else if ( mask & AFMT_S24_NE ) { |
| 9782 | deviceFormat = AFMT_S24_NE; |
| 9783 | stream_.deviceFormat[mode] = RTAUDIO_SINT24; |
| 9784 | } |
| 9785 | else if ( mask & AFMT_S16_OE ) { |
| 9786 | deviceFormat = AFMT_S16_OE; |
| 9787 | stream_.deviceFormat[mode] = RTAUDIO_SINT16; |
| 9788 | stream_.doByteSwap[mode] = true; |
| 9789 | } |
| 9790 | else if ( mask & AFMT_S32_OE ) { |
| 9791 | deviceFormat = AFMT_S32_OE; |
| 9792 | stream_.deviceFormat[mode] = RTAUDIO_SINT32; |
| 9793 | stream_.doByteSwap[mode] = true; |
| 9794 | } |
| 9795 | else if ( mask & AFMT_S24_OE ) { |
| 9796 | deviceFormat = AFMT_S24_OE; |
| 9797 | stream_.deviceFormat[mode] = RTAUDIO_SINT24; |
| 9798 | stream_.doByteSwap[mode] = true; |
| 9799 | } |
| 9800 | else if ( mask & AFMT_S8) { |
| 9801 | deviceFormat = AFMT_S8; |
| 9802 | stream_.deviceFormat[mode] = RTAUDIO_SINT8; |
| 9803 | } |
| 9804 | } |
| 9805 | |
| 9806 | if ( stream_.deviceFormat[mode] == 0 ) { |
| 9807 | // This really shouldn't happen ... |
| 9808 | close( fd ); |
| 9809 | errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio."; |
| 9810 | errorText_ = errorStream_.str(); |
| 9811 | return FAILURE; |
| 9812 | } |
| 9813 | |
| 9814 | // Set the data format. |
| 9815 | int temp = deviceFormat; |
| 9816 | result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat ); |
| 9817 | if ( result == -1 || deviceFormat != temp ) { |
| 9818 | close( fd ); |
| 9819 | errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ")."; |
| 9820 | errorText_ = errorStream_.str(); |
| 9821 | return FAILURE; |
| 9822 | } |
| 9823 | |
| 9824 | // Attempt to set the buffer size. According to OSS, the minimum |
| 9825 | // number of buffers is two. The supposed minimum buffer size is 16 |
| 9826 | // bytes, so that will be our lower bound. The argument to this |
| 9827 | // call is in the form 0xMMMMSSSS (hex), where the buffer size (in |
| 9828 | // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM. |
| 9829 | // We'll check the actual value used near the end of the setup |
| 9830 | // procedure. |
| 9831 | int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels; |
| 9832 | if ( ossBufferBytes < 16 ) ossBufferBytes = 16; |
| 9833 | int buffers = 0; |
| 9834 | if ( options ) buffers = options->numberOfBuffers; |
| 9835 | if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2; |
| 9836 | if ( buffers < 2 ) buffers = 3; |
| 9837 | temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) ); |
| 9838 | result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp ); |
| 9839 | if ( result == -1 ) { |
| 9840 | close( fd ); |
| 9841 | errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ")."; |
| 9842 | errorText_ = errorStream_.str(); |
| 9843 | return FAILURE; |
| 9844 | } |
| 9845 | stream_.nBuffers = buffers; |
| 9846 | |
| 9847 | // Save buffer size (in sample frames). |
| 9848 | *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels ); |
| 9849 | stream_.bufferSize = *bufferSize; |
| 9850 | |
| 9851 | // Set the sample rate. |
| 9852 | int srate = sampleRate; |
| 9853 | result = ioctl( fd, SNDCTL_DSP_SPEED, &srate ); |
| 9854 | if ( result == -1 ) { |
| 9855 | close( fd ); |
| 9856 | errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ")."; |
| 9857 | errorText_ = errorStream_.str(); |
| 9858 | return FAILURE; |
| 9859 | } |
| 9860 | |
| 9861 | // Verify the sample rate setup worked. |
| 9862 | if ( abs( srate - (int)sampleRate ) > 100 ) { |
| 9863 | close( fd ); |
| 9864 | errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ")."; |
| 9865 | errorText_ = errorStream_.str(); |
| 9866 | return FAILURE; |
| 9867 | } |
| 9868 | stream_.sampleRate = sampleRate; |
| 9869 | |
| 9870 | if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) { |
| 9871 | // We're doing duplex setup here. |
| 9872 | stream_.deviceFormat[0] = stream_.deviceFormat[1]; |
| 9873 | stream_.nDeviceChannels[0] = deviceChannels; |
| 9874 | } |
| 9875 | |
| 9876 | // Set interleaving parameters. |
| 9877 | stream_.userInterleaved = true; |
| 9878 | stream_.deviceInterleaved[mode] = true; |
| 9879 | if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) |
| 9880 | stream_.userInterleaved = false; |
| 9881 | |
| 9882 | // Set flags for buffer conversion |
| 9883 | stream_.doConvertBuffer[mode] = false; |
| 9884 | if ( stream_.userFormat != stream_.deviceFormat[mode] ) |
| 9885 | stream_.doConvertBuffer[mode] = true; |
| 9886 | if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] ) |
| 9887 | stream_.doConvertBuffer[mode] = true; |
| 9888 | if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] && |
| 9889 | stream_.nUserChannels[mode] > 1 ) |
| 9890 | stream_.doConvertBuffer[mode] = true; |
| 9891 | |
| 9892 | // Allocate the stream handles if necessary and then save. |
| 9893 | if ( stream_.apiHandle == 0 ) { |
| 9894 | try { |
| 9895 | handle = new OssHandle; |
| 9896 | } |
| 9897 | catch ( std::bad_alloc& ) { |
| 9898 | errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory."; |
| 9899 | goto error; |
| 9900 | } |
| 9901 | |
| 9902 | if ( pthread_cond_init( &handle->runnable, NULL ) ) { |
| 9903 | errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable."; |
| 9904 | goto error; |
| 9905 | } |
| 9906 | |
| 9907 | stream_.apiHandle = (void *) handle; |
| 9908 | } |
| 9909 | else { |
| 9910 | handle = (OssHandle *) stream_.apiHandle; |
| 9911 | } |
| 9912 | handle->id[mode] = fd; |
| 9913 | |
| 9914 | // Allocate necessary internal buffers. |
| 9915 | unsigned long bufferBytes; |
| 9916 | bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat ); |
| 9917 | stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 ); |
| 9918 | if ( stream_.userBuffer[mode] == NULL ) { |
| 9919 | errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory."; |
| 9920 | goto error; |
| 9921 | } |
| 9922 | |
| 9923 | if ( stream_.doConvertBuffer[mode] ) { |
| 9924 | |
| 9925 | bool makeBuffer = true; |
| 9926 | bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] ); |
| 9927 | if ( mode == INPUT ) { |
| 9928 | if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) { |
| 9929 | unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] ); |
| 9930 | if ( bufferBytes <= bytesOut ) makeBuffer = false; |
| 9931 | } |
| 9932 | } |
| 9933 | |
| 9934 | if ( makeBuffer ) { |
| 9935 | bufferBytes *= *bufferSize; |
| 9936 | if ( stream_.deviceBuffer ) free( stream_.deviceBuffer ); |
| 9937 | stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 ); |
| 9938 | if ( stream_.deviceBuffer == NULL ) { |
| 9939 | errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory."; |
| 9940 | goto error; |
| 9941 | } |
| 9942 | } |
| 9943 | } |
| 9944 | |
| 9945 | stream_.device[mode] = device; |
| 9946 | stream_.state = STREAM_STOPPED; |
| 9947 | |
| 9948 | // Setup the buffer conversion information structure. |
| 9949 | if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel ); |
| 9950 | |
| 9951 | // Setup thread if necessary. |
| 9952 | if ( stream_.mode == OUTPUT && mode == INPUT ) { |
| 9953 | // We had already set up an output stream. |
| 9954 | stream_.mode = DUPLEX; |
| 9955 | if ( stream_.device[0] == device ) handle->id[0] = fd; |
| 9956 | } |
| 9957 | else { |
| 9958 | stream_.mode = mode; |
| 9959 | |
| 9960 | // Setup callback thread. |
| 9961 | stream_.callbackInfo.object = (void *) this; |
| 9962 | |
| 9963 | // Set the thread attributes for joinable and realtime scheduling |
| 9964 | // priority. The higher priority will only take affect if the |
| 9965 | // program is run as root or suid. |
| 9966 | pthread_attr_t attr; |
| 9967 | pthread_attr_init( &attr ); |
| 9968 | pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); |
| 9969 | #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread) |
| 9970 | if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) { |
| 9971 | stream_.callbackInfo.doRealtime = true; |
| 9972 | struct sched_param param; |
| 9973 | int priority = options->priority; |
| 9974 | int min = sched_get_priority_min( SCHED_RR ); |
| 9975 | int max = sched_get_priority_max( SCHED_RR ); |
| 9976 | if ( priority < min ) priority = min; |
| 9977 | else if ( priority > max ) priority = max; |
| 9978 | param.sched_priority = priority; |
| 9979 | |
| 9980 | // Set the policy BEFORE the priority. Otherwise it fails. |
| 9981 | pthread_attr_setschedpolicy(&attr, SCHED_RR); |
| 9982 | pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM); |
| 9983 | // This is definitely required. Otherwise it fails. |
| 9984 | pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); |
| 9985 | pthread_attr_setschedparam(&attr, ¶m); |
| 9986 | } |
| 9987 | else |
| 9988 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 9989 | #else |
| 9990 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 9991 | #endif |
| 9992 | |
| 9993 | stream_.callbackInfo.isRunning = true; |
| 9994 | result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo ); |
| 9995 | pthread_attr_destroy( &attr ); |
| 9996 | if ( result ) { |
| 9997 | // Failed. Try instead with default attributes. |
| 9998 | result = pthread_create( &stream_.callbackInfo.thread, NULL, ossCallbackHandler, &stream_.callbackInfo ); |
| 9999 | if ( result ) { |
| 10000 | stream_.callbackInfo.isRunning = false; |
| 10001 | errorText_ = "RtApiOss::error creating callback thread!"; |
| 10002 | goto error; |
| 10003 | } |
| 10004 | } |
| 10005 | } |
| 10006 | |
| 10007 | return SUCCESS; |
| 10008 | |
| 10009 | error: |
| 10010 | if ( handle ) { |
| 10011 | pthread_cond_destroy( &handle->runnable ); |
| 10012 | if ( handle->id[0] ) close( handle->id[0] ); |
| 10013 | if ( handle->id[1] ) close( handle->id[1] ); |
| 10014 | delete handle; |
| 10015 | stream_.apiHandle = 0; |
| 10016 | } |
| 10017 | |
| 10018 | for ( int i=0; i<2; i++ ) { |
| 10019 | if ( stream_.userBuffer[i] ) { |
| 10020 | free( stream_.userBuffer[i] ); |
| 10021 | stream_.userBuffer[i] = 0; |
| 10022 | } |
| 10023 | } |
| 10024 | |
| 10025 | if ( stream_.deviceBuffer ) { |
| 10026 | free( stream_.deviceBuffer ); |
| 10027 | stream_.deviceBuffer = 0; |
| 10028 | } |
| 10029 | |
| 10030 | stream_.state = STREAM_CLOSED; |
| 10031 | return FAILURE; |
| 10032 | } |
| 10033 | |
| 10034 | void RtApiOss :: closeStream() |
| 10035 | { |
| 10036 | if ( stream_.state == STREAM_CLOSED ) { |
| 10037 | errorText_ = "RtApiOss::closeStream(): no open stream to close!"; |
| 10038 | error( RTAUDIO_WARNING ); |
| 10039 | return; |
| 10040 | } |
| 10041 | |
| 10042 | OssHandle *handle = (OssHandle *) stream_.apiHandle; |
| 10043 | stream_.callbackInfo.isRunning = false; |
| 10044 | MUTEX_LOCK( &stream_.mutex ); |
| 10045 | if ( stream_.state == STREAM_STOPPED ) |
| 10046 | pthread_cond_signal( &handle->runnable ); |
| 10047 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10048 | pthread_join( stream_.callbackInfo.thread, NULL ); |
| 10049 | |
| 10050 | if ( stream_.state == STREAM_RUNNING ) { |
| 10051 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) |
| 10052 | ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 ); |
| 10053 | else |
| 10054 | ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 ); |
| 10055 | stream_.state = STREAM_STOPPED; |
| 10056 | } |
| 10057 | |
| 10058 | if ( handle ) { |
| 10059 | pthread_cond_destroy( &handle->runnable ); |
| 10060 | if ( handle->id[0] ) close( handle->id[0] ); |
| 10061 | if ( handle->id[1] ) close( handle->id[1] ); |
| 10062 | delete handle; |
| 10063 | stream_.apiHandle = 0; |
| 10064 | } |
| 10065 | |
| 10066 | for ( int i=0; i<2; i++ ) { |
| 10067 | if ( stream_.userBuffer[i] ) { |
| 10068 | free( stream_.userBuffer[i] ); |
| 10069 | stream_.userBuffer[i] = 0; |
| 10070 | } |
| 10071 | } |
| 10072 | |
| 10073 | if ( stream_.deviceBuffer ) { |
| 10074 | free( stream_.deviceBuffer ); |
| 10075 | stream_.deviceBuffer = 0; |
| 10076 | } |
| 10077 | |
| 10078 | clearStreamInfo(); |
| 10079 | //stream_.mode = UNINITIALIZED; |
| 10080 | //stream_.state = STREAM_CLOSED; |
| 10081 | } |
| 10082 | |
| 10083 | RtAudioErrorType RtApiOss :: startStream() |
| 10084 | { |
| 10085 | if ( stream_.state != STREAM_STOPPED ) { |
| 10086 | if ( stream_.state == STREAM_RUNNING ) |
| 10087 | errorText_ = "RtApiOss::startStream(): the stream is already running!"; |
| 10088 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 10089 | errorText_ = "RtApiOss::startStream(): the stream is stopping or closed!"; |
| 10090 | return error( RTAUDIO_WARNING ); |
| 10091 | } |
| 10092 | |
| 10093 | MUTEX_LOCK( &stream_.mutex ); |
| 10094 | |
| 10095 | /* |
| 10096 | #if defined( HAVE_GETTIMEOFDAY ) |
| 10097 | gettimeofday( &stream_.lastTickTimestamp, NULL ); |
| 10098 | #endif |
| 10099 | */ |
| 10100 | |
| 10101 | stream_.state = STREAM_RUNNING; |
| 10102 | |
| 10103 | // No need to do anything else here ... OSS automatically starts |
| 10104 | // when fed samples. |
| 10105 | |
| 10106 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10107 | |
| 10108 | OssHandle *handle = (OssHandle *) stream_.apiHandle; |
| 10109 | pthread_cond_signal( &handle->runnable ); |
| 10110 | return RTAUDIO_NO_ERROR; |
| 10111 | } |
| 10112 | |
| 10113 | RtAudioErrorType RtApiOss :: stopStream() |
| 10114 | { |
| 10115 | if ( stream_.state != STREAM_RUNNING && stream_.state != STREAM_STOPPING ) { |
| 10116 | if ( stream_.state == STREAM_STOPPED ) |
| 10117 | errorText_ = "RtApiOss::stopStream(): the stream is already stopped!"; |
| 10118 | else if ( stream_.state == STREAM_CLOSED ) |
| 10119 | errorText_ = "RtApiOss::stopStream(): the stream is closed!"; |
| 10120 | return error( RTAUDIO_WARNING ); |
| 10121 | } |
| 10122 | |
| 10123 | MUTEX_LOCK( &stream_.mutex ); |
| 10124 | |
| 10125 | // The state might change while waiting on a mutex. |
| 10126 | if ( stream_.state == STREAM_STOPPED ) { |
| 10127 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10128 | return RTAUDIO_NO_ERROR; |
| 10129 | } |
| 10130 | |
| 10131 | int result = 0; |
| 10132 | OssHandle *handle = (OssHandle *) stream_.apiHandle; |
| 10133 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 10134 | |
| 10135 | // Flush the output with zeros a few times. |
| 10136 | char *buffer; |
| 10137 | int samples; |
| 10138 | RtAudioFormat format; |
| 10139 | |
| 10140 | if ( stream_.doConvertBuffer[0] ) { |
| 10141 | buffer = stream_.deviceBuffer; |
| 10142 | samples = stream_.bufferSize * stream_.nDeviceChannels[0]; |
| 10143 | format = stream_.deviceFormat[0]; |
| 10144 | } |
| 10145 | else { |
| 10146 | buffer = stream_.userBuffer[0]; |
| 10147 | samples = stream_.bufferSize * stream_.nUserChannels[0]; |
| 10148 | format = stream_.userFormat; |
| 10149 | } |
| 10150 | |
| 10151 | memset( buffer, 0, samples * formatBytes(format) ); |
| 10152 | for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) { |
| 10153 | result = write( handle->id[0], buffer, samples * formatBytes(format) ); |
| 10154 | if ( result == -1 ) { |
| 10155 | errorText_ = "RtApiOss::stopStream: audio write error."; |
| 10156 | error( RTAUDIO_WARNING ); |
| 10157 | } |
| 10158 | } |
| 10159 | |
| 10160 | result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 ); |
| 10161 | if ( result == -1 ) { |
| 10162 | errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ")."; |
| 10163 | errorText_ = errorStream_.str(); |
| 10164 | goto unlock; |
| 10165 | } |
| 10166 | handle->triggered = false; |
| 10167 | } |
| 10168 | |
| 10169 | if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) { |
| 10170 | result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 ); |
| 10171 | if ( result == -1 ) { |
| 10172 | errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ")."; |
| 10173 | errorText_ = errorStream_.str(); |
| 10174 | goto unlock; |
| 10175 | } |
| 10176 | } |
| 10177 | |
| 10178 | unlock: |
| 10179 | stream_.state = STREAM_STOPPED; |
| 10180 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10181 | |
| 10182 | if ( result != -1 ) return RTAUDIO_NO_ERROR; |
| 10183 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 10184 | } |
| 10185 | |
| 10186 | RtAudioErrorType RtApiOss :: abortStream() |
| 10187 | { |
| 10188 | if ( stream_.state != STREAM_RUNNING ) { |
| 10189 | if ( stream_.state == STREAM_STOPPED ) |
| 10190 | errorText_ = "RtApiOss::abortStream(): the stream is already stopped!"; |
| 10191 | else if ( stream_.state == STREAM_STOPPING || stream_.state == STREAM_CLOSED ) |
| 10192 | errorText_ = "RtApiOss::abortStream(): the stream is stopping or closed!"; |
| 10193 | return error( RTAUDIO_WARNING ); |
| 10194 | } |
| 10195 | |
| 10196 | MUTEX_LOCK( &stream_.mutex ); |
| 10197 | |
| 10198 | // The state might change while waiting on a mutex. |
| 10199 | if ( stream_.state == STREAM_STOPPED ) { |
| 10200 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10201 | return RTAUDIO_NO_ERROR; |
| 10202 | } |
| 10203 | |
| 10204 | int result = 0; |
| 10205 | OssHandle *handle = (OssHandle *) stream_.apiHandle; |
| 10206 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 10207 | result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 ); |
| 10208 | if ( result == -1 ) { |
| 10209 | errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ")."; |
| 10210 | errorText_ = errorStream_.str(); |
| 10211 | goto unlock; |
| 10212 | } |
| 10213 | handle->triggered = false; |
| 10214 | } |
| 10215 | |
| 10216 | if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) { |
| 10217 | result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 ); |
| 10218 | if ( result == -1 ) { |
| 10219 | errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ")."; |
| 10220 | errorText_ = errorStream_.str(); |
| 10221 | goto unlock; |
| 10222 | } |
| 10223 | } |
| 10224 | |
| 10225 | unlock: |
| 10226 | stream_.state = STREAM_STOPPED; |
| 10227 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10228 | |
| 10229 | if ( result != -1 ) return RTAUDIO_SYSTEM_ERROR; |
| 10230 | return error( RTAUDIO_SYSTEM_ERROR ); |
| 10231 | } |
| 10232 | |
| 10233 | void RtApiOss :: callbackEvent() |
| 10234 | { |
| 10235 | OssHandle *handle = (OssHandle *) stream_.apiHandle; |
| 10236 | if ( stream_.state == STREAM_STOPPED ) { |
| 10237 | MUTEX_LOCK( &stream_.mutex ); |
| 10238 | pthread_cond_wait( &handle->runnable, &stream_.mutex ); |
| 10239 | if ( stream_.state != STREAM_RUNNING ) { |
| 10240 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10241 | return; |
| 10242 | } |
| 10243 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10244 | } |
| 10245 | |
| 10246 | if ( stream_.state == STREAM_CLOSED ) { |
| 10247 | errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!"; |
| 10248 | error( RTAUDIO_WARNING ); |
| 10249 | return; |
| 10250 | } |
| 10251 | |
| 10252 | // Invoke user callback to get fresh output data. |
| 10253 | int doStopStream = 0; |
| 10254 | RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback; |
| 10255 | double streamTime = getStreamTime(); |
| 10256 | RtAudioStreamStatus status = 0; |
| 10257 | if ( stream_.mode != INPUT && handle->xrun[0] == true ) { |
| 10258 | status |= RTAUDIO_OUTPUT_UNDERFLOW; |
| 10259 | handle->xrun[0] = false; |
| 10260 | } |
| 10261 | if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) { |
| 10262 | status |= RTAUDIO_INPUT_OVERFLOW; |
| 10263 | handle->xrun[1] = false; |
| 10264 | } |
| 10265 | doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1], |
| 10266 | stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData ); |
| 10267 | if ( doStopStream == 2 ) { |
| 10268 | this->abortStream(); |
| 10269 | return; |
| 10270 | } |
| 10271 | |
| 10272 | MUTEX_LOCK( &stream_.mutex ); |
| 10273 | |
| 10274 | // The state might change while waiting on a mutex. |
| 10275 | if ( stream_.state == STREAM_STOPPED ) goto unlock; |
| 10276 | |
| 10277 | int result; |
| 10278 | char *buffer; |
| 10279 | int samples; |
| 10280 | RtAudioFormat format; |
| 10281 | |
| 10282 | if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) { |
| 10283 | |
| 10284 | // Setup parameters and do buffer conversion if necessary. |
| 10285 | if ( stream_.doConvertBuffer[0] ) { |
| 10286 | buffer = stream_.deviceBuffer; |
| 10287 | convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] ); |
| 10288 | samples = stream_.bufferSize * stream_.nDeviceChannels[0]; |
| 10289 | format = stream_.deviceFormat[0]; |
| 10290 | } |
| 10291 | else { |
| 10292 | buffer = stream_.userBuffer[0]; |
| 10293 | samples = stream_.bufferSize * stream_.nUserChannels[0]; |
| 10294 | format = stream_.userFormat; |
| 10295 | } |
| 10296 | |
| 10297 | // Do byte swapping if necessary. |
| 10298 | if ( stream_.doByteSwap[0] ) |
| 10299 | byteSwapBuffer( buffer, samples, format ); |
| 10300 | |
| 10301 | if ( stream_.mode == DUPLEX && handle->triggered == false ) { |
| 10302 | int trig = 0; |
| 10303 | ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig ); |
| 10304 | result = write( handle->id[0], buffer, samples * formatBytes(format) ); |
| 10305 | trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT; |
| 10306 | ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig ); |
| 10307 | handle->triggered = true; |
| 10308 | } |
| 10309 | else |
| 10310 | // Write samples to device. |
| 10311 | result = write( handle->id[0], buffer, samples * formatBytes(format) ); |
| 10312 | |
| 10313 | if ( result == -1 ) { |
| 10314 | // We'll assume this is an underrun, though there isn't a |
| 10315 | // specific means for determining that. |
| 10316 | handle->xrun[0] = true; |
| 10317 | errorText_ = "RtApiOss::callbackEvent: audio write error."; |
| 10318 | error( RTAUDIO_WARNING ); |
| 10319 | // Continue on to input section. |
| 10320 | } |
| 10321 | } |
| 10322 | |
| 10323 | if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) { |
| 10324 | |
| 10325 | // Setup parameters. |
| 10326 | if ( stream_.doConvertBuffer[1] ) { |
| 10327 | buffer = stream_.deviceBuffer; |
| 10328 | samples = stream_.bufferSize * stream_.nDeviceChannels[1]; |
| 10329 | format = stream_.deviceFormat[1]; |
| 10330 | } |
| 10331 | else { |
| 10332 | buffer = stream_.userBuffer[1]; |
| 10333 | samples = stream_.bufferSize * stream_.nUserChannels[1]; |
| 10334 | format = stream_.userFormat; |
| 10335 | } |
| 10336 | |
| 10337 | // Read samples from device. |
| 10338 | result = read( handle->id[1], buffer, samples * formatBytes(format) ); |
| 10339 | |
| 10340 | if ( result == -1 ) { |
| 10341 | // We'll assume this is an overrun, though there isn't a |
| 10342 | // specific means for determining that. |
| 10343 | handle->xrun[1] = true; |
| 10344 | errorText_ = "RtApiOss::callbackEvent: audio read error."; |
| 10345 | error( RTAUDIO_WARNING ); |
| 10346 | goto unlock; |
| 10347 | } |
| 10348 | |
| 10349 | // Do byte swapping if necessary. |
| 10350 | if ( stream_.doByteSwap[1] ) |
| 10351 | byteSwapBuffer( buffer, samples, format ); |
| 10352 | |
| 10353 | // Do buffer conversion if necessary. |
| 10354 | if ( stream_.doConvertBuffer[1] ) |
| 10355 | convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] ); |
| 10356 | } |
| 10357 | |
| 10358 | unlock: |
| 10359 | MUTEX_UNLOCK( &stream_.mutex ); |
| 10360 | |
| 10361 | RtApi::tickStreamTime(); |
| 10362 | if ( doStopStream == 1 ) this->stopStream(); |
| 10363 | } |
| 10364 | |
| 10365 | static void *ossCallbackHandler( void *ptr ) |
| 10366 | { |
| 10367 | CallbackInfo *info = (CallbackInfo *) ptr; |
| 10368 | RtApiOss *object = (RtApiOss *) info->object; |
| 10369 | bool *isRunning = &info->isRunning; |
| 10370 | |
| 10371 | #ifdef SCHED_RR // Undefined with some OSes (e.g. NetBSD 1.6.x with GNU Pthread) |
| 10372 | if (info->doRealtime) { |
| 10373 | std::cerr << "RtAudio oss: " << |
| 10374 | (sched_getscheduler(0) == SCHED_RR ? "" : "_NOT_ ") << |
| 10375 | "running realtime scheduling" << std::endl; |
| 10376 | } |
| 10377 | #endif |
| 10378 | |
| 10379 | while ( *isRunning == true ) { |
| 10380 | pthread_testcancel(); |
| 10381 | object->callbackEvent(); |
| 10382 | } |
| 10383 | |
| 10384 | pthread_exit( NULL ); |
| 10385 | } |
| 10386 | |
| 10387 | //******************** End of __LINUX_OSS__ *********************// |
| 10388 | #endif |
| 10389 | |
| 10390 | |
| 10391 | // *************************************************** // |
| 10392 | // |
| 10393 | // Protected common (OS-independent) RtAudio methods. |
| 10394 | // |
| 10395 | // *************************************************** // |
| 10396 | |
| 10397 | // This method can be modified to control the behavior of error |
| 10398 | // message printing. |
| 10399 | RtAudioErrorType RtApi :: error( RtAudioErrorType type ) |
| 10400 | { |
| 10401 | errorStream_.str(""); // clear the ostringstream to avoid repeated messages |
| 10402 | |
| 10403 | // Don't output warnings if showWarnings_ is false |
| 10404 | if ( type == RTAUDIO_WARNING && showWarnings_ == false ) return type; |
| 10405 | |
| 10406 | if ( errorCallback_ ) { |
| 10407 | const std::string errorMessage = errorText_; |
| 10408 | errorCallback_( type, errorMessage ); |
| 10409 | } |
| 10410 | else |
| 10411 | std::cerr << '\n' << errorText_ << "\n\n"; |
| 10412 | return type; |
| 10413 | } |
| 10414 | |
| 10415 | /* |
| 10416 | void RtApi :: verifyStream() |
| 10417 | { |
| 10418 | if ( stream_.state == STREAM_CLOSED ) { |
| 10419 | errorText_ = "RtApi:: a stream is not open!"; |
| 10420 | error( RtAudioError::INVALID_USE ); |
| 10421 | } |
| 10422 | } |
| 10423 | */ |
| 10424 | |
| 10425 | void RtApi :: clearStreamInfo() |
| 10426 | { |
| 10427 | stream_.mode = UNINITIALIZED; |
| 10428 | stream_.state = STREAM_CLOSED; |
| 10429 | stream_.sampleRate = 0; |
| 10430 | stream_.bufferSize = 0; |
| 10431 | stream_.nBuffers = 0; |
| 10432 | stream_.userFormat = 0; |
| 10433 | stream_.userInterleaved = true; |
| 10434 | stream_.streamTime = 0.0; |
| 10435 | stream_.apiHandle = 0; |
| 10436 | stream_.deviceBuffer = 0; |
| 10437 | stream_.callbackInfo.callback = 0; |
| 10438 | stream_.callbackInfo.userData = 0; |
| 10439 | stream_.callbackInfo.isRunning = false; |
| 10440 | stream_.callbackInfo.deviceDisconnected = false; |
| 10441 | for ( int i=0; i<2; i++ ) { |
| 10442 | stream_.device[i] = 11111; |
| 10443 | stream_.doConvertBuffer[i] = false; |
| 10444 | stream_.deviceInterleaved[i] = true; |
| 10445 | stream_.doByteSwap[i] = false; |
| 10446 | stream_.nUserChannels[i] = 0; |
| 10447 | stream_.nDeviceChannels[i] = 0; |
| 10448 | stream_.channelOffset[i] = 0; |
| 10449 | stream_.deviceFormat[i] = 0; |
| 10450 | stream_.latency[i] = 0; |
| 10451 | stream_.userBuffer[i] = 0; |
| 10452 | stream_.convertInfo[i].channels = 0; |
| 10453 | stream_.convertInfo[i].inJump = 0; |
| 10454 | stream_.convertInfo[i].outJump = 0; |
| 10455 | stream_.convertInfo[i].inFormat = 0; |
| 10456 | stream_.convertInfo[i].outFormat = 0; |
| 10457 | stream_.convertInfo[i].inOffset.clear(); |
| 10458 | stream_.convertInfo[i].outOffset.clear(); |
| 10459 | } |
| 10460 | } |
| 10461 | |
| 10462 | unsigned int RtApi :: formatBytes( RtAudioFormat format ) |
| 10463 | { |
| 10464 | if ( format == RTAUDIO_SINT16 ) |
| 10465 | return 2; |
| 10466 | else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 ) |
| 10467 | return 4; |
| 10468 | else if ( format == RTAUDIO_FLOAT64 ) |
| 10469 | return 8; |
| 10470 | else if ( format == RTAUDIO_SINT24 ) |
| 10471 | return 3; |
| 10472 | else if ( format == RTAUDIO_SINT8 ) |
| 10473 | return 1; |
| 10474 | |
| 10475 | errorText_ = "RtApi::formatBytes: undefined format."; |
| 10476 | error( RTAUDIO_WARNING ); |
| 10477 | |
| 10478 | return 0; |
| 10479 | } |
| 10480 | |
| 10481 | void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel ) |
| 10482 | { |
| 10483 | if ( mode == INPUT ) { // convert device to user buffer |
| 10484 | stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1]; |
| 10485 | stream_.convertInfo[mode].outJump = stream_.nUserChannels[1]; |
| 10486 | stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1]; |
| 10487 | stream_.convertInfo[mode].outFormat = stream_.userFormat; |
| 10488 | } |
| 10489 | else { // convert user to device buffer |
| 10490 | stream_.convertInfo[mode].inJump = stream_.nUserChannels[0]; |
| 10491 | stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0]; |
| 10492 | stream_.convertInfo[mode].inFormat = stream_.userFormat; |
| 10493 | stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0]; |
| 10494 | } |
| 10495 | |
| 10496 | if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump ) |
| 10497 | stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump; |
| 10498 | else |
| 10499 | stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump; |
| 10500 | |
| 10501 | // Set up the interleave/deinterleave offsets. |
| 10502 | if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) { |
| 10503 | if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) || |
| 10504 | ( mode == INPUT && stream_.userInterleaved ) ) { |
| 10505 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) { |
| 10506 | stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize ); |
| 10507 | stream_.convertInfo[mode].outOffset.push_back( k ); |
| 10508 | stream_.convertInfo[mode].inJump = 1; |
| 10509 | } |
| 10510 | } |
| 10511 | else { |
| 10512 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) { |
| 10513 | stream_.convertInfo[mode].inOffset.push_back( k ); |
| 10514 | stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize ); |
| 10515 | stream_.convertInfo[mode].outJump = 1; |
| 10516 | } |
| 10517 | } |
| 10518 | } |
| 10519 | else { // no (de)interleaving |
| 10520 | if ( stream_.userInterleaved ) { |
| 10521 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) { |
| 10522 | stream_.convertInfo[mode].inOffset.push_back( k ); |
| 10523 | stream_.convertInfo[mode].outOffset.push_back( k ); |
| 10524 | } |
| 10525 | } |
| 10526 | else { |
| 10527 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) { |
| 10528 | stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize ); |
| 10529 | stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize ); |
| 10530 | stream_.convertInfo[mode].inJump = 1; |
| 10531 | stream_.convertInfo[mode].outJump = 1; |
| 10532 | } |
| 10533 | } |
| 10534 | } |
| 10535 | |
| 10536 | // Add channel offset. |
| 10537 | if ( firstChannel > 0 ) { |
| 10538 | if ( stream_.deviceInterleaved[mode] ) { |
| 10539 | if ( mode == OUTPUT ) { |
| 10540 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) |
| 10541 | stream_.convertInfo[mode].outOffset[k] += firstChannel; |
| 10542 | } |
| 10543 | else { |
| 10544 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) |
| 10545 | stream_.convertInfo[mode].inOffset[k] += firstChannel; |
| 10546 | } |
| 10547 | } |
| 10548 | else { |
| 10549 | if ( mode == OUTPUT ) { |
| 10550 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) |
| 10551 | stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize ); |
| 10552 | } |
| 10553 | else { |
| 10554 | for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) |
| 10555 | stream_.convertInfo[mode].inOffset[k] += ( firstChannel * stream_.bufferSize ); |
| 10556 | } |
| 10557 | } |
| 10558 | } |
| 10559 | } |
| 10560 | |
| 10561 | void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info ) |
| 10562 | { |
| 10563 | // This function does format conversion, input/output channel compensation, and |
| 10564 | // data interleaving/deinterleaving. 24-bit integers are assumed to occupy |
| 10565 | // the lower three bytes of a 32-bit integer. |
| 10566 | |
| 10567 | // Clear our duplex device output buffer if there are more device outputs than user outputs |
| 10568 | if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX && info.outJump > info.inJump ) |
| 10569 | memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) ); |
| 10570 | |
| 10571 | int j; |
| 10572 | if (info.outFormat == RTAUDIO_FLOAT64) { |
| 10573 | Float64 *out = (Float64 *)outBuffer; |
| 10574 | |
| 10575 | if (info.inFormat == RTAUDIO_SINT8) { |
| 10576 | signed char *in = (signed char *)inBuffer; |
| 10577 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10578 | for (j=0; j<info.channels; j++) { |
| 10579 | out[info.outOffset[j]] = (Float64) in[info.inOffset[j]] / 128.0; |
| 10580 | } |
| 10581 | in += info.inJump; |
| 10582 | out += info.outJump; |
| 10583 | } |
| 10584 | } |
| 10585 | else if (info.inFormat == RTAUDIO_SINT16) { |
| 10586 | Int16 *in = (Int16 *)inBuffer; |
| 10587 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10588 | for (j=0; j<info.channels; j++) { |
| 10589 | out[info.outOffset[j]] = (Float64) in[info.inOffset[j]] / 32768.0; |
| 10590 | } |
| 10591 | in += info.inJump; |
| 10592 | out += info.outJump; |
| 10593 | } |
| 10594 | } |
| 10595 | else if (info.inFormat == RTAUDIO_SINT24) { |
| 10596 | Int24 *in = (Int24 *)inBuffer; |
| 10597 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10598 | for (j=0; j<info.channels; j++) { |
| 10599 | out[info.outOffset[j]] = (Float64) in[info.inOffset[j]].asInt() / 8388608.0; |
| 10600 | } |
| 10601 | in += info.inJump; |
| 10602 | out += info.outJump; |
| 10603 | } |
| 10604 | } |
| 10605 | else if (info.inFormat == RTAUDIO_SINT32) { |
| 10606 | Int32 *in = (Int32 *)inBuffer; |
| 10607 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10608 | for (j=0; j<info.channels; j++) { |
| 10609 | out[info.outOffset[j]] = (Float64) in[info.inOffset[j]] / 2147483648.0; |
| 10610 | } |
| 10611 | in += info.inJump; |
| 10612 | out += info.outJump; |
| 10613 | } |
| 10614 | } |
| 10615 | else if (info.inFormat == RTAUDIO_FLOAT32) { |
| 10616 | Float32 *in = (Float32 *)inBuffer; |
| 10617 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10618 | for (j=0; j<info.channels; j++) { |
| 10619 | out[info.outOffset[j]] = (Float64) in[info.inOffset[j]]; |
| 10620 | } |
| 10621 | in += info.inJump; |
| 10622 | out += info.outJump; |
| 10623 | } |
| 10624 | } |
| 10625 | else if (info.inFormat == RTAUDIO_FLOAT64) { |
| 10626 | // Channel compensation and/or (de)interleaving only. |
| 10627 | Float64 *in = (Float64 *)inBuffer; |
| 10628 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10629 | for (j=0; j<info.channels; j++) { |
| 10630 | out[info.outOffset[j]] = in[info.inOffset[j]]; |
| 10631 | } |
| 10632 | in += info.inJump; |
| 10633 | out += info.outJump; |
| 10634 | } |
| 10635 | } |
| 10636 | } |
| 10637 | else if (info.outFormat == RTAUDIO_FLOAT32) { |
| 10638 | Float32 *out = (Float32 *)outBuffer; |
| 10639 | |
| 10640 | if (info.inFormat == RTAUDIO_SINT8) { |
| 10641 | signed char *in = (signed char *)inBuffer; |
| 10642 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10643 | for (j=0; j<info.channels; j++) { |
| 10644 | out[info.outOffset[j]] = (Float32) in[info.inOffset[j]] / 128.f; |
| 10645 | } |
| 10646 | in += info.inJump; |
| 10647 | out += info.outJump; |
| 10648 | } |
| 10649 | } |
| 10650 | else if (info.inFormat == RTAUDIO_SINT16) { |
| 10651 | Int16 *in = (Int16 *)inBuffer; |
| 10652 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10653 | for (j=0; j<info.channels; j++) { |
| 10654 | out[info.outOffset[j]] = (Float32) in[info.inOffset[j]] / 32768.f; |
| 10655 | } |
| 10656 | in += info.inJump; |
| 10657 | out += info.outJump; |
| 10658 | } |
| 10659 | } |
| 10660 | else if (info.inFormat == RTAUDIO_SINT24) { |
| 10661 | Int24 *in = (Int24 *)inBuffer; |
| 10662 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10663 | for (j=0; j<info.channels; j++) { |
| 10664 | out[info.outOffset[j]] = (Float32) in[info.inOffset[j]].asInt() / 8388608.f; |
| 10665 | } |
| 10666 | in += info.inJump; |
| 10667 | out += info.outJump; |
| 10668 | } |
| 10669 | } |
| 10670 | else if (info.inFormat == RTAUDIO_SINT32) { |
| 10671 | Int32 *in = (Int32 *)inBuffer; |
| 10672 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10673 | for (j=0; j<info.channels; j++) { |
| 10674 | out[info.outOffset[j]] = (Float32) in[info.inOffset[j]] / 2147483648.f; |
| 10675 | } |
| 10676 | in += info.inJump; |
| 10677 | out += info.outJump; |
| 10678 | } |
| 10679 | } |
| 10680 | else if (info.inFormat == RTAUDIO_FLOAT32) { |
| 10681 | // Channel compensation and/or (de)interleaving only. |
| 10682 | Float32 *in = (Float32 *)inBuffer; |
| 10683 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10684 | for (j=0; j<info.channels; j++) { |
| 10685 | out[info.outOffset[j]] = in[info.inOffset[j]]; |
| 10686 | } |
| 10687 | in += info.inJump; |
| 10688 | out += info.outJump; |
| 10689 | } |
| 10690 | } |
| 10691 | else if (info.inFormat == RTAUDIO_FLOAT64) { |
| 10692 | Float64 *in = (Float64 *)inBuffer; |
| 10693 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10694 | for (j=0; j<info.channels; j++) { |
| 10695 | out[info.outOffset[j]] = (Float32) in[info.inOffset[j]]; |
| 10696 | } |
| 10697 | in += info.inJump; |
| 10698 | out += info.outJump; |
| 10699 | } |
| 10700 | } |
| 10701 | } |
| 10702 | else if (info.outFormat == RTAUDIO_SINT32) { |
| 10703 | Int32 *out = (Int32 *)outBuffer; |
| 10704 | if (info.inFormat == RTAUDIO_SINT8) { |
| 10705 | signed char *in = (signed char *)inBuffer; |
| 10706 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10707 | for (j=0; j<info.channels; j++) { |
| 10708 | out[info.outOffset[j]] = (Int32) in[info.inOffset[j]]; |
| 10709 | out[info.outOffset[j]] <<= 24; |
| 10710 | } |
| 10711 | in += info.inJump; |
| 10712 | out += info.outJump; |
| 10713 | } |
| 10714 | } |
| 10715 | else if (info.inFormat == RTAUDIO_SINT16) { |
| 10716 | Int16 *in = (Int16 *)inBuffer; |
| 10717 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10718 | for (j=0; j<info.channels; j++) { |
| 10719 | out[info.outOffset[j]] = (Int32) in[info.inOffset[j]]; |
| 10720 | out[info.outOffset[j]] <<= 16; |
| 10721 | } |
| 10722 | in += info.inJump; |
| 10723 | out += info.outJump; |
| 10724 | } |
| 10725 | } |
| 10726 | else if (info.inFormat == RTAUDIO_SINT24) { |
| 10727 | Int24 *in = (Int24 *)inBuffer; |
| 10728 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10729 | for (j=0; j<info.channels; j++) { |
| 10730 | out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt(); |
| 10731 | out[info.outOffset[j]] <<= 8; |
| 10732 | } |
| 10733 | in += info.inJump; |
| 10734 | out += info.outJump; |
| 10735 | } |
| 10736 | } |
| 10737 | else if (info.inFormat == RTAUDIO_SINT32) { |
| 10738 | // Channel compensation and/or (de)interleaving only. |
| 10739 | Int32 *in = (Int32 *)inBuffer; |
| 10740 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10741 | for (j=0; j<info.channels; j++) { |
| 10742 | out[info.outOffset[j]] = in[info.inOffset[j]]; |
| 10743 | } |
| 10744 | in += info.inJump; |
| 10745 | out += info.outJump; |
| 10746 | } |
| 10747 | } |
| 10748 | else if (info.inFormat == RTAUDIO_FLOAT32) { |
| 10749 | Float32 *in = (Float32 *)inBuffer; |
| 10750 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10751 | for (j=0; j<info.channels; j++) { |
| 10752 | // Use llround() which returns `long long` which is guaranteed to be at least 64 bits. |
| 10753 | out[info.outOffset[j]] = (Int32) std::min(std::llround(in[info.inOffset[j]] * 2147483648.f), 2147483647LL); |
| 10754 | } |
| 10755 | in += info.inJump; |
| 10756 | out += info.outJump; |
| 10757 | } |
| 10758 | } |
| 10759 | else if (info.inFormat == RTAUDIO_FLOAT64) { |
| 10760 | Float64 *in = (Float64 *)inBuffer; |
| 10761 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10762 | for (j=0; j<info.channels; j++) { |
| 10763 | out[info.outOffset[j]] = (Int32) std::min(std::llround(in[info.inOffset[j]] * 2147483648.0), 2147483647LL); |
| 10764 | } |
| 10765 | in += info.inJump; |
| 10766 | out += info.outJump; |
| 10767 | } |
| 10768 | } |
| 10769 | } |
| 10770 | else if (info.outFormat == RTAUDIO_SINT24) { |
| 10771 | Int24 *out = (Int24 *)outBuffer; |
| 10772 | if (info.inFormat == RTAUDIO_SINT8) { |
| 10773 | signed char *in = (signed char *)inBuffer; |
| 10774 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10775 | for (j=0; j<info.channels; j++) { |
| 10776 | out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16); |
| 10777 | //out[info.outOffset[j]] <<= 16; |
| 10778 | } |
| 10779 | in += info.inJump; |
| 10780 | out += info.outJump; |
| 10781 | } |
| 10782 | } |
| 10783 | else if (info.inFormat == RTAUDIO_SINT16) { |
| 10784 | Int16 *in = (Int16 *)inBuffer; |
| 10785 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10786 | for (j=0; j<info.channels; j++) { |
| 10787 | out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8); |
| 10788 | //out[info.outOffset[j]] <<= 8; |
| 10789 | } |
| 10790 | in += info.inJump; |
| 10791 | out += info.outJump; |
| 10792 | } |
| 10793 | } |
| 10794 | else if (info.inFormat == RTAUDIO_SINT24) { |
| 10795 | // Channel compensation and/or (de)interleaving only. |
| 10796 | Int24 *in = (Int24 *)inBuffer; |
| 10797 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10798 | for (j=0; j<info.channels; j++) { |
| 10799 | out[info.outOffset[j]] = in[info.inOffset[j]]; |
| 10800 | } |
| 10801 | in += info.inJump; |
| 10802 | out += info.outJump; |
| 10803 | } |
| 10804 | } |
| 10805 | else if (info.inFormat == RTAUDIO_SINT32) { |
| 10806 | Int32 *in = (Int32 *)inBuffer; |
| 10807 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10808 | for (j=0; j<info.channels; j++) { |
| 10809 | out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8); |
| 10810 | //out[info.outOffset[j]] >>= 8; |
| 10811 | } |
| 10812 | in += info.inJump; |
| 10813 | out += info.outJump; |
| 10814 | } |
| 10815 | } |
| 10816 | else if (info.inFormat == RTAUDIO_FLOAT32) { |
| 10817 | Float32 *in = (Float32 *)inBuffer; |
| 10818 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10819 | for (j=0; j<info.channels; j++) { |
| 10820 | out[info.outOffset[j]] = (Int32) std::min(std::llround(in[info.inOffset[j]] * 8388608.f), 8388607LL); |
| 10821 | } |
| 10822 | in += info.inJump; |
| 10823 | out += info.outJump; |
| 10824 | } |
| 10825 | } |
| 10826 | else if (info.inFormat == RTAUDIO_FLOAT64) { |
| 10827 | Float64 *in = (Float64 *)inBuffer; |
| 10828 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10829 | for (j=0; j<info.channels; j++) { |
| 10830 | out[info.outOffset[j]] = (Int32) std::min(std::llround(in[info.inOffset[j]] * 8388608.0), 8388607LL); |
| 10831 | } |
| 10832 | in += info.inJump; |
| 10833 | out += info.outJump; |
| 10834 | } |
| 10835 | } |
| 10836 | } |
| 10837 | else if (info.outFormat == RTAUDIO_SINT16) { |
| 10838 | Int16 *out = (Int16 *)outBuffer; |
| 10839 | if (info.inFormat == RTAUDIO_SINT8) { |
| 10840 | signed char *in = (signed char *)inBuffer; |
| 10841 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10842 | for (j=0; j<info.channels; j++) { |
| 10843 | out[info.outOffset[j]] = (Int16) in[info.inOffset[j]]; |
| 10844 | out[info.outOffset[j]] <<= 8; |
| 10845 | } |
| 10846 | in += info.inJump; |
| 10847 | out += info.outJump; |
| 10848 | } |
| 10849 | } |
| 10850 | else if (info.inFormat == RTAUDIO_SINT16) { |
| 10851 | // Channel compensation and/or (de)interleaving only. |
| 10852 | Int16 *in = (Int16 *)inBuffer; |
| 10853 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10854 | for (j=0; j<info.channels; j++) { |
| 10855 | out[info.outOffset[j]] = in[info.inOffset[j]]; |
| 10856 | } |
| 10857 | in += info.inJump; |
| 10858 | out += info.outJump; |
| 10859 | } |
| 10860 | } |
| 10861 | else if (info.inFormat == RTAUDIO_SINT24) { |
| 10862 | Int24 *in = (Int24 *)inBuffer; |
| 10863 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10864 | for (j=0; j<info.channels; j++) { |
| 10865 | out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8); |
| 10866 | } |
| 10867 | in += info.inJump; |
| 10868 | out += info.outJump; |
| 10869 | } |
| 10870 | } |
| 10871 | else if (info.inFormat == RTAUDIO_SINT32) { |
| 10872 | Int32 *in = (Int32 *)inBuffer; |
| 10873 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10874 | for (j=0; j<info.channels; j++) { |
| 10875 | out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff); |
| 10876 | } |
| 10877 | in += info.inJump; |
| 10878 | out += info.outJump; |
| 10879 | } |
| 10880 | } |
| 10881 | else if (info.inFormat == RTAUDIO_FLOAT32) { |
| 10882 | Float32 *in = (Float32 *)inBuffer; |
| 10883 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10884 | for (j=0; j<info.channels; j++) { |
| 10885 | out[info.outOffset[j]] = (Int16) std::min(std::llround(in[info.inOffset[j]] * 32768.f), 32767LL); |
| 10886 | } |
| 10887 | in += info.inJump; |
| 10888 | out += info.outJump; |
| 10889 | } |
| 10890 | } |
| 10891 | else if (info.inFormat == RTAUDIO_FLOAT64) { |
| 10892 | Float64 *in = (Float64 *)inBuffer; |
| 10893 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10894 | for (j=0; j<info.channels; j++) { |
| 10895 | out[info.outOffset[j]] = (Int16) std::min(std::llround(in[info.inOffset[j]] * 32768.0), 32767LL); |
| 10896 | } |
| 10897 | in += info.inJump; |
| 10898 | out += info.outJump; |
| 10899 | } |
| 10900 | } |
| 10901 | } |
| 10902 | else if (info.outFormat == RTAUDIO_SINT8) { |
| 10903 | signed char *out = (signed char *)outBuffer; |
| 10904 | if (info.inFormat == RTAUDIO_SINT8) { |
| 10905 | // Channel compensation and/or (de)interleaving only. |
| 10906 | signed char *in = (signed char *)inBuffer; |
| 10907 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10908 | for (j=0; j<info.channels; j++) { |
| 10909 | out[info.outOffset[j]] = in[info.inOffset[j]]; |
| 10910 | } |
| 10911 | in += info.inJump; |
| 10912 | out += info.outJump; |
| 10913 | } |
| 10914 | } |
| 10915 | if (info.inFormat == RTAUDIO_SINT16) { |
| 10916 | Int16 *in = (Int16 *)inBuffer; |
| 10917 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10918 | for (j=0; j<info.channels; j++) { |
| 10919 | out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff); |
| 10920 | } |
| 10921 | in += info.inJump; |
| 10922 | out += info.outJump; |
| 10923 | } |
| 10924 | } |
| 10925 | else if (info.inFormat == RTAUDIO_SINT24) { |
| 10926 | Int24 *in = (Int24 *)inBuffer; |
| 10927 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10928 | for (j=0; j<info.channels; j++) { |
| 10929 | out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16); |
| 10930 | } |
| 10931 | in += info.inJump; |
| 10932 | out += info.outJump; |
| 10933 | } |
| 10934 | } |
| 10935 | else if (info.inFormat == RTAUDIO_SINT32) { |
| 10936 | Int32 *in = (Int32 *)inBuffer; |
| 10937 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10938 | for (j=0; j<info.channels; j++) { |
| 10939 | out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff); |
| 10940 | } |
| 10941 | in += info.inJump; |
| 10942 | out += info.outJump; |
| 10943 | } |
| 10944 | } |
| 10945 | else if (info.inFormat == RTAUDIO_FLOAT32) { |
| 10946 | Float32 *in = (Float32 *)inBuffer; |
| 10947 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10948 | for (j=0; j<info.channels; j++) { |
| 10949 | out[info.outOffset[j]] = (signed char) std::min(std::llround(in[info.inOffset[j]] * 128.f), 127LL); |
| 10950 | } |
| 10951 | in += info.inJump; |
| 10952 | out += info.outJump; |
| 10953 | } |
| 10954 | } |
| 10955 | else if (info.inFormat == RTAUDIO_FLOAT64) { |
| 10956 | Float64 *in = (Float64 *)inBuffer; |
| 10957 | for (unsigned int i=0; i<stream_.bufferSize; i++) { |
| 10958 | for (j=0; j<info.channels; j++) { |
| 10959 | out[info.outOffset[j]] = (signed char) std::min(std::llround(in[info.inOffset[j]] * 128.0), 127LL); |
| 10960 | } |
| 10961 | in += info.inJump; |
| 10962 | out += info.outJump; |
| 10963 | } |
| 10964 | } |
| 10965 | } |
| 10966 | } |
| 10967 | |
| 10968 | //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); } |
| 10969 | //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); } |
| 10970 | //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); } |
| 10971 | |
| 10972 | void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format ) |
| 10973 | { |
| 10974 | char val; |
| 10975 | char *ptr; |
| 10976 | |
| 10977 | ptr = buffer; |
| 10978 | if ( format == RTAUDIO_SINT16 ) { |
| 10979 | for ( unsigned int i=0; i<samples; i++ ) { |
| 10980 | // Swap 1st and 2nd bytes. |
| 10981 | val = *(ptr); |
| 10982 | *(ptr) = *(ptr+1); |
| 10983 | *(ptr+1) = val; |
| 10984 | |
| 10985 | // Increment 2 bytes. |
| 10986 | ptr += 2; |
| 10987 | } |
| 10988 | } |
| 10989 | else if ( format == RTAUDIO_SINT32 || |
| 10990 | format == RTAUDIO_FLOAT32 ) { |
| 10991 | for ( unsigned int i=0; i<samples; i++ ) { |
| 10992 | // Swap 1st and 4th bytes. |
| 10993 | val = *(ptr); |
| 10994 | *(ptr) = *(ptr+3); |
| 10995 | *(ptr+3) = val; |
| 10996 | |
| 10997 | // Swap 2nd and 3rd bytes. |
| 10998 | ptr += 1; |
| 10999 | val = *(ptr); |
| 11000 | *(ptr) = *(ptr+1); |
| 11001 | *(ptr+1) = val; |
| 11002 | |
| 11003 | // Increment 3 more bytes. |
| 11004 | ptr += 3; |
| 11005 | } |
| 11006 | } |
| 11007 | else if ( format == RTAUDIO_SINT24 ) { |
| 11008 | for ( unsigned int i=0; i<samples; i++ ) { |
| 11009 | // Swap 1st and 3rd bytes. |
| 11010 | val = *(ptr); |
| 11011 | *(ptr) = *(ptr+2); |
| 11012 | *(ptr+2) = val; |
| 11013 | |
| 11014 | // Increment 2 more bytes. |
| 11015 | ptr += 2; |
| 11016 | } |
| 11017 | } |
| 11018 | else if ( format == RTAUDIO_FLOAT64 ) { |
| 11019 | for ( unsigned int i=0; i<samples; i++ ) { |
| 11020 | // Swap 1st and 8th bytes |
| 11021 | val = *(ptr); |
| 11022 | *(ptr) = *(ptr+7); |
| 11023 | *(ptr+7) = val; |
| 11024 | |
| 11025 | // Swap 2nd and 7th bytes |
| 11026 | ptr += 1; |
| 11027 | val = *(ptr); |
| 11028 | *(ptr) = *(ptr+5); |
| 11029 | *(ptr+5) = val; |
| 11030 | |
| 11031 | // Swap 3rd and 6th bytes |
| 11032 | ptr += 1; |
| 11033 | val = *(ptr); |
| 11034 | *(ptr) = *(ptr+3); |
| 11035 | *(ptr+3) = val; |
| 11036 | |
| 11037 | // Swap 4th and 5th bytes |
| 11038 | ptr += 1; |
| 11039 | val = *(ptr); |
| 11040 | *(ptr) = *(ptr+1); |
| 11041 | *(ptr+1) = val; |
| 11042 | |
| 11043 | // Increment 5 more bytes. |
| 11044 | ptr += 5; |
| 11045 | } |
| 11046 | } |
| 11047 | } |
| 11048 | |
| 11049 | // Indentation settings for Vim and Emacs |
| 11050 | // |
| 11051 | // Local Variables: |
| 11052 | // c-basic-offset: 2 |
| 11053 | // indent-tabs-mode: nil |
| 11054 | // End: |
| 11055 | // |
| 11056 | // vim: et sts=2 sw=2 |
| 11057 |