1 /* 2 ** 3 ** Copyright 2007, The Android Open Source Project 4 ** 5 ** Licensed under the Apache License, Version 2.0 (the "License"); 6 ** you may not use this file except in compliance with the License. 7 ** You may obtain a copy of the License at 8 ** 9 ** http://www.apache.org/licenses/LICENSE-2.0 10 ** 11 ** Unless required by applicable law or agreed to in writing, software 12 ** distributed under the License is distributed on an "AS IS" BASIS, 13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 ** See the License for the specific language governing permissions and 15 ** limitations under the License. 16 */ 17 18 19 //#define LOG_NDEBUG 0 20 #define LOG_TAG "AudioTrack" 21 22 #include <stdint.h> 23 #include <sys/types.h> 24 #include <limits.h> 25 26 #include <sched.h> 27 #include <sys/resource.h> 28 29 #include <private/media/AudioTrackShared.h> 30 31 #include <media/AudioSystem.h> 32 #include <media/AudioTrack.h> 33 34 #include <utils/Log.h> 35 #include <binder/Parcel.h> 36 #include <binder/IPCThreadState.h> 37 #include <utils/Timers.h> 38 #include <utils/Atomic.h> 39 40 #include <cutils/bitops.h> 41 #include <cutils/compiler.h> 42 43 #include <system/audio.h> 44 #include <system/audio_policy.h> 45 46 #include <audio_utils/primitives.h> 47 48 namespace android { 49 // --------------------------------------------------------------------------- 50 51 // static 52 status_t AudioTrack::getMinFrameCount( 53 size_t* frameCount, 54 audio_stream_type_t streamType, 55 uint32_t sampleRate) 56 { 57 if (frameCount == NULL) { 58 return BAD_VALUE; 59 } 60 61 // default to 0 in case of error 62 *frameCount = 0; 63 64 // FIXME merge with similar code in createTrack_l(), except we're missing 65 // some information here that is available in createTrack_l(): 66 // audio_io_handle_t output 67 // audio_format_t format 68 // audio_channel_mask_t channelMask 69 // audio_output_flags_t flags 70 uint32_t afSampleRate; 71 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { 72 return NO_INIT; 73 } 74 size_t afFrameCount; 75 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) { 76 return NO_INIT; 77 } 78 uint32_t afLatency; 79 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) { 80 return NO_INIT; 81 } 82 83 // Ensure that buffer depth covers at least audio hardware latency 84 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate); 85 if (minBufCount < 2) minBufCount = 2; 86 87 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount : 88 afFrameCount * minBufCount * sampleRate / afSampleRate; 89 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d", 90 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency); 91 return NO_ERROR; 92 } 93 94 // --------------------------------------------------------------------------- 95 96 AudioTrack::AudioTrack() 97 : mStatus(NO_INIT), 98 mIsTimed(false), 99 mPreviousPriority(ANDROID_PRIORITY_NORMAL), 100 mPreviousSchedulingGroup(SP_DEFAULT), 101 mProxy(NULL) 102 { 103 } 104 105 AudioTrack::AudioTrack( 106 audio_stream_type_t streamType, 107 uint32_t sampleRate, 108 audio_format_t format, 109 audio_channel_mask_t channelMask, 110 int frameCount, 111 audio_output_flags_t flags, 112 callback_t cbf, 113 void* user, 114 int notificationFrames, 115 int sessionId) 116 : mStatus(NO_INIT), 117 mIsTimed(false), 118 mPreviousPriority(ANDROID_PRIORITY_NORMAL), 119 mPreviousSchedulingGroup(SP_DEFAULT), 120 mProxy(NULL) 121 { 122 mStatus = set(streamType, sampleRate, format, channelMask, 123 frameCount, flags, cbf, user, notificationFrames, 124 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId); 125 } 126 127 AudioTrack::AudioTrack( 128 audio_stream_type_t streamType, 129 uint32_t sampleRate, 130 audio_format_t format, 131 audio_channel_mask_t channelMask, 132 const sp<IMemory>& sharedBuffer, 133 audio_output_flags_t flags, 134 callback_t cbf, 135 void* user, 136 int notificationFrames, 137 int sessionId) 138 : mStatus(NO_INIT), 139 mIsTimed(false), 140 mPreviousPriority(ANDROID_PRIORITY_NORMAL), 141 mPreviousSchedulingGroup(SP_DEFAULT), 142 mProxy(NULL) 143 { 144 if (sharedBuffer == 0) { 145 ALOGE("sharedBuffer must be non-0"); 146 mStatus = BAD_VALUE; 147 return; 148 } 149 mStatus = set(streamType, sampleRate, format, channelMask, 150 0 /*frameCount*/, flags, cbf, user, notificationFrames, 151 sharedBuffer, false /*threadCanCallJava*/, sessionId); 152 } 153 154 AudioTrack::~AudioTrack() 155 { 156 ALOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer()); 157 158 if (mStatus == NO_ERROR) { 159 // Make sure that callback function exits in the case where 160 // it is looping on buffer full condition in obtainBuffer(). 161 // Otherwise the callback thread will never exit. 162 stop(); 163 if (mAudioTrackThread != 0) { 164 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h 165 mAudioTrackThread->requestExitAndWait(); 166 mAudioTrackThread.clear(); 167 } 168 mAudioTrack.clear(); 169 IPCThreadState::self()->flushCommands(); 170 AudioSystem::releaseAudioSessionId(mSessionId); 171 } 172 delete mProxy; 173 } 174 175 status_t AudioTrack::set( 176 audio_stream_type_t streamType, 177 uint32_t sampleRate, 178 audio_format_t format, 179 audio_channel_mask_t channelMask, 180 int frameCountInt, 181 audio_output_flags_t flags, 182 callback_t cbf, 183 void* user, 184 int notificationFrames, 185 const sp<IMemory>& sharedBuffer, 186 bool threadCanCallJava, 187 int sessionId) 188 { 189 // FIXME "int" here is legacy and will be replaced by size_t later 190 if (frameCountInt < 0) { 191 ALOGE("Invalid frame count %d", frameCountInt); 192 return BAD_VALUE; 193 } 194 size_t frameCount = frameCountInt; 195 196 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), 197 sharedBuffer->size()); 198 199 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags); 200 201 AutoMutex lock(mLock); 202 if (mAudioTrack != 0) { 203 ALOGE("Track already in use"); 204 return INVALID_OPERATION; 205 } 206 207 // handle default values first. 208 if (streamType == AUDIO_STREAM_DEFAULT) { 209 streamType = AUDIO_STREAM_MUSIC; 210 } 211 212 if (sampleRate == 0) { 213 uint32_t afSampleRate; 214 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { 215 return NO_INIT; 216 } 217 sampleRate = afSampleRate; 218 } 219 mSampleRate = sampleRate; 220 221 // these below should probably come from the audioFlinger too... 222 if (format == AUDIO_FORMAT_DEFAULT) { 223 format = AUDIO_FORMAT_PCM_16_BIT; 224 } 225 if (channelMask == 0) { 226 channelMask = AUDIO_CHANNEL_OUT_STEREO; 227 } 228 229 // validate parameters 230 if (!audio_is_valid_format(format)) { 231 ALOGE("Invalid format"); 232 return BAD_VALUE; 233 } 234 235 // AudioFlinger does not currently support 8-bit data in shared memory 236 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) { 237 ALOGE("8-bit data in shared memory is not supported"); 238 return BAD_VALUE; 239 } 240 241 // force direct flag if format is not linear PCM 242 if (!audio_is_linear_pcm(format)) { 243 flags = (audio_output_flags_t) 244 // FIXME why can't we allow direct AND fast? 245 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST); 246 } 247 // only allow deep buffering for music stream type 248 if (streamType != AUDIO_STREAM_MUSIC) { 249 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER); 250 } 251 252 if (!audio_is_output_channel(channelMask)) { 253 ALOGE("Invalid channel mask %#x", channelMask); 254 return BAD_VALUE; 255 } 256 mChannelMask = channelMask; 257 uint32_t channelCount = popcount(channelMask); 258 mChannelCount = channelCount; 259 260 if (audio_is_linear_pcm(format)) { 261 mFrameSize = channelCount * audio_bytes_per_sample(format); 262 mFrameSizeAF = channelCount * sizeof(int16_t); 263 } else { 264 mFrameSize = sizeof(uint8_t); 265 mFrameSizeAF = sizeof(uint8_t); 266 } 267 268 audio_io_handle_t output = AudioSystem::getOutput( 269 streamType, 270 sampleRate, format, channelMask, 271 flags); 272 273 if (output == 0) { 274 ALOGE("Could not get audio output for stream type %d", streamType); 275 return BAD_VALUE; 276 } 277 278 mVolume[LEFT] = 1.0f; 279 mVolume[RIGHT] = 1.0f; 280 mSendLevel = 0.0f; 281 mFrameCount = frameCount; 282 mReqFrameCount = frameCount; 283 mNotificationFramesReq = notificationFrames; 284 mSessionId = sessionId; 285 mAuxEffectId = 0; 286 mFlags = flags; 287 mCbf = cbf; 288 289 if (cbf != NULL) { 290 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava); 291 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/); 292 } 293 294 // create the IAudioTrack 295 status_t status = createTrack_l(streamType, 296 sampleRate, 297 format, 298 frameCount, 299 flags, 300 sharedBuffer, 301 output); 302 303 if (status != NO_ERROR) { 304 if (mAudioTrackThread != 0) { 305 mAudioTrackThread->requestExit(); 306 mAudioTrackThread.clear(); 307 } 308 return status; 309 } 310 311 mStatus = NO_ERROR; 312 313 mStreamType = streamType; 314 mFormat = format; 315 316 mSharedBuffer = sharedBuffer; 317 mActive = false; 318 mUserData = user; 319 mLoopCount = 0; 320 mMarkerPosition = 0; 321 mMarkerReached = false; 322 mNewPosition = 0; 323 mUpdatePeriod = 0; 324 mFlushed = false; 325 AudioSystem::acquireAudioSessionId(mSessionId); 326 return NO_ERROR; 327 } 328 329 // ------------------------------------------------------------------------- 330 331 void AudioTrack::start() 332 { 333 sp<AudioTrackThread> t = mAudioTrackThread; 334 335 ALOGV("start %p", this); 336 337 AutoMutex lock(mLock); 338 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 339 // while we are accessing the cblk 340 sp<IAudioTrack> audioTrack = mAudioTrack; 341 sp<IMemory> iMem = mCblkMemory; 342 audio_track_cblk_t* cblk = mCblk; 343 344 if (!mActive) { 345 mFlushed = false; 346 mActive = true; 347 mNewPosition = cblk->server + mUpdatePeriod; 348 cblk->lock.lock(); 349 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS; 350 cblk->waitTimeMs = 0; 351 android_atomic_and(~CBLK_DISABLED, &cblk->flags); 352 if (t != 0) { 353 t->resume(); 354 } else { 355 mPreviousPriority = getpriority(PRIO_PROCESS, 0); 356 get_sched_policy(0, &mPreviousSchedulingGroup); 357 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO); 358 } 359 360 ALOGV("start %p before lock cblk %p", this, cblk); 361 status_t status = NO_ERROR; 362 if (!(cblk->flags & CBLK_INVALID)) { 363 cblk->lock.unlock(); 364 ALOGV("mAudioTrack->start()"); 365 status = mAudioTrack->start(); 366 cblk->lock.lock(); 367 if (status == DEAD_OBJECT) { 368 android_atomic_or(CBLK_INVALID, &cblk->flags); 369 } 370 } 371 if (cblk->flags & CBLK_INVALID) { 372 audio_track_cblk_t* temp = cblk; 373 status = restoreTrack_l(temp, true /*fromStart*/); 374 cblk = temp; 375 } 376 cblk->lock.unlock(); 377 if (status != NO_ERROR) { 378 ALOGV("start() failed"); 379 mActive = false; 380 if (t != 0) { 381 t->pause(); 382 } else { 383 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 384 set_sched_policy(0, mPreviousSchedulingGroup); 385 } 386 } 387 } 388 389 } 390 391 void AudioTrack::stop() 392 { 393 sp<AudioTrackThread> t = mAudioTrackThread; 394 395 ALOGV("stop %p", this); 396 397 AutoMutex lock(mLock); 398 if (mActive) { 399 mActive = false; 400 mCblk->cv.signal(); 401 mAudioTrack->stop(); 402 // Cancel loops (If we are in the middle of a loop, playback 403 // would not stop until loopCount reaches 0). 404 setLoop_l(0, 0, 0); 405 // the playback head position will reset to 0, so if a marker is set, we need 406 // to activate it again 407 mMarkerReached = false; 408 // Force flush if a shared buffer is used otherwise audioflinger 409 // will not stop before end of buffer is reached. 410 // It may be needed to make sure that we stop playback, likely in case looping is on. 411 if (mSharedBuffer != 0) { 412 flush_l(); 413 } 414 if (t != 0) { 415 t->pause(); 416 } else { 417 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 418 set_sched_policy(0, mPreviousSchedulingGroup); 419 } 420 } 421 422 } 423 424 bool AudioTrack::stopped() const 425 { 426 AutoMutex lock(mLock); 427 return stopped_l(); 428 } 429 430 void AudioTrack::flush() 431 { 432 AutoMutex lock(mLock); 433 if (!mActive && mSharedBuffer == 0) { 434 flush_l(); 435 } 436 } 437 438 void AudioTrack::flush_l() 439 { 440 ALOGV("flush"); 441 ALOG_ASSERT(!mActive); 442 443 // clear playback marker and periodic update counter 444 mMarkerPosition = 0; 445 mMarkerReached = false; 446 mUpdatePeriod = 0; 447 448 mFlushed = true; 449 mAudioTrack->flush(); 450 // Release AudioTrack callback thread in case it was waiting for new buffers 451 // in AudioTrack::obtainBuffer() 452 mCblk->cv.signal(); 453 } 454 455 void AudioTrack::pause() 456 { 457 ALOGV("pause"); 458 AutoMutex lock(mLock); 459 if (mActive) { 460 mActive = false; 461 mCblk->cv.signal(); 462 mAudioTrack->pause(); 463 } 464 } 465 466 status_t AudioTrack::setVolume(float left, float right) 467 { 468 if (mStatus != NO_ERROR) { 469 return mStatus; 470 } 471 ALOG_ASSERT(mProxy != NULL); 472 473 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) { 474 return BAD_VALUE; 475 } 476 477 AutoMutex lock(mLock); 478 mVolume[LEFT] = left; 479 mVolume[RIGHT] = right; 480 481 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000)); 482 483 return NO_ERROR; 484 } 485 486 status_t AudioTrack::setVolume(float volume) 487 { 488 return setVolume(volume, volume); 489 } 490 491 status_t AudioTrack::setAuxEffectSendLevel(float level) 492 { 493 ALOGV("setAuxEffectSendLevel(%f)", level); 494 495 if (mStatus != NO_ERROR) { 496 return mStatus; 497 } 498 ALOG_ASSERT(mProxy != NULL); 499 500 if (level < 0.0f || level > 1.0f) { 501 return BAD_VALUE; 502 } 503 AutoMutex lock(mLock); 504 505 mSendLevel = level; 506 mProxy->setSendLevel(level); 507 508 return NO_ERROR; 509 } 510 511 void AudioTrack::getAuxEffectSendLevel(float* level) const 512 { 513 if (level != NULL) { 514 *level = mSendLevel; 515 } 516 } 517 518 status_t AudioTrack::setSampleRate(uint32_t rate) 519 { 520 uint32_t afSamplingRate; 521 522 if (mIsTimed) { 523 return INVALID_OPERATION; 524 } 525 526 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) { 527 return NO_INIT; 528 } 529 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 530 if (rate == 0 || rate > afSamplingRate*2 ) { 531 return BAD_VALUE; 532 } 533 534 AutoMutex lock(mLock); 535 mSampleRate = rate; 536 mProxy->setSampleRate(rate); 537 538 return NO_ERROR; 539 } 540 541 uint32_t AudioTrack::getSampleRate() const 542 { 543 if (mIsTimed) { 544 return 0; 545 } 546 547 AutoMutex lock(mLock); 548 return mSampleRate; 549 } 550 551 status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount) 552 { 553 AutoMutex lock(mLock); 554 return setLoop_l(loopStart, loopEnd, loopCount); 555 } 556 557 // must be called with mLock held 558 status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount) 559 { 560 if (mSharedBuffer == 0 || mIsTimed) { 561 return INVALID_OPERATION; 562 } 563 564 audio_track_cblk_t* cblk = mCblk; 565 566 Mutex::Autolock _l(cblk->lock); 567 568 if (loopCount == 0) { 569 cblk->loopStart = UINT_MAX; 570 cblk->loopEnd = UINT_MAX; 571 cblk->loopCount = 0; 572 mLoopCount = 0; 573 return NO_ERROR; 574 } 575 576 if (loopStart >= loopEnd || 577 loopEnd - loopStart > mFrameCount || 578 cblk->server > loopStart) { 579 ALOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, " 580 "user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user); 581 return BAD_VALUE; 582 } 583 584 if ((mSharedBuffer != 0) && (loopEnd > mFrameCount)) { 585 ALOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, " 586 "framecount %d", 587 loopStart, loopEnd, mFrameCount); 588 return BAD_VALUE; 589 } 590 591 cblk->loopStart = loopStart; 592 cblk->loopEnd = loopEnd; 593 cblk->loopCount = loopCount; 594 mLoopCount = loopCount; 595 596 return NO_ERROR; 597 } 598 599 status_t AudioTrack::setMarkerPosition(uint32_t marker) 600 { 601 if (mCbf == NULL) { 602 return INVALID_OPERATION; 603 } 604 605 mMarkerPosition = marker; 606 mMarkerReached = false; 607 608 return NO_ERROR; 609 } 610 611 status_t AudioTrack::getMarkerPosition(uint32_t *marker) const 612 { 613 if (marker == NULL) { 614 return BAD_VALUE; 615 } 616 617 *marker = mMarkerPosition; 618 619 return NO_ERROR; 620 } 621 622 status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod) 623 { 624 if (mCbf == NULL) { 625 return INVALID_OPERATION; 626 } 627 628 uint32_t curPosition; 629 getPosition(&curPosition); 630 mNewPosition = curPosition + updatePeriod; 631 mUpdatePeriod = updatePeriod; 632 633 return NO_ERROR; 634 } 635 636 status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const 637 { 638 if (updatePeriod == NULL) { 639 return BAD_VALUE; 640 } 641 642 *updatePeriod = mUpdatePeriod; 643 644 return NO_ERROR; 645 } 646 647 status_t AudioTrack::setPosition(uint32_t position) 648 { 649 if (mSharedBuffer == 0 || mIsTimed) { 650 return INVALID_OPERATION; 651 } 652 653 AutoMutex lock(mLock); 654 655 if (!stopped_l()) { 656 return INVALID_OPERATION; 657 } 658 659 audio_track_cblk_t* cblk = mCblk; 660 Mutex::Autolock _l(cblk->lock); 661 662 if (position > cblk->user) { 663 return BAD_VALUE; 664 } 665 666 cblk->server = position; 667 android_atomic_or(CBLK_FORCEREADY, &cblk->flags); 668 669 return NO_ERROR; 670 } 671 672 status_t AudioTrack::getPosition(uint32_t *position) 673 { 674 if (position == NULL) { 675 return BAD_VALUE; 676 } 677 AutoMutex lock(mLock); 678 *position = mFlushed ? 0 : mCblk->server; 679 680 return NO_ERROR; 681 } 682 683 status_t AudioTrack::reload() 684 { 685 if (mStatus != NO_ERROR) { 686 return mStatus; 687 } 688 ALOG_ASSERT(mProxy != NULL); 689 690 if (mSharedBuffer == 0 || mIsTimed) { 691 return INVALID_OPERATION; 692 } 693 694 AutoMutex lock(mLock); 695 696 if (!stopped_l()) { 697 return INVALID_OPERATION; 698 } 699 700 flush_l(); 701 702 (void) mProxy->stepUser(mFrameCount); 703 704 return NO_ERROR; 705 } 706 707 audio_io_handle_t AudioTrack::getOutput() 708 { 709 AutoMutex lock(mLock); 710 return getOutput_l(); 711 } 712 713 // must be called with mLock held 714 audio_io_handle_t AudioTrack::getOutput_l() 715 { 716 return AudioSystem::getOutput(mStreamType, 717 mSampleRate, mFormat, mChannelMask, mFlags); 718 } 719 720 status_t AudioTrack::attachAuxEffect(int effectId) 721 { 722 ALOGV("attachAuxEffect(%d)", effectId); 723 status_t status = mAudioTrack->attachAuxEffect(effectId); 724 if (status == NO_ERROR) { 725 mAuxEffectId = effectId; 726 } 727 return status; 728 } 729 730 // ------------------------------------------------------------------------- 731 732 // must be called with mLock held 733 status_t AudioTrack::createTrack_l( 734 audio_stream_type_t streamType, 735 uint32_t sampleRate, 736 audio_format_t format, 737 size_t frameCount, 738 audio_output_flags_t flags, 739 const sp<IMemory>& sharedBuffer, 740 audio_io_handle_t output) 741 { 742 status_t status; 743 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger(); 744 if (audioFlinger == 0) { 745 ALOGE("Could not get audioflinger"); 746 return NO_INIT; 747 } 748 749 uint32_t afLatency; 750 if (AudioSystem::getLatency(output, streamType, &afLatency) != NO_ERROR) { 751 return NO_INIT; 752 } 753 754 // Client decides whether the track is TIMED (see below), but can only express a preference 755 // for FAST. Server will perform additional tests. 756 if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !( 757 // either of these use cases: 758 // use case 1: shared buffer 759 (sharedBuffer != 0) || 760 // use case 2: callback handler 761 (mCbf != NULL))) { 762 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client"); 763 // once denied, do not request again if IAudioTrack is re-created 764 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST); 765 mFlags = flags; 766 } 767 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency); 768 769 mNotificationFramesAct = mNotificationFramesReq; 770 771 if (!audio_is_linear_pcm(format)) { 772 773 if (sharedBuffer != 0) { 774 // Same comment as below about ignoring frameCount parameter for set() 775 frameCount = sharedBuffer->size(); 776 } else if (frameCount == 0) { 777 size_t afFrameCount; 778 if (AudioSystem::getFrameCount(output, streamType, &afFrameCount) != NO_ERROR) { 779 return NO_INIT; 780 } 781 frameCount = afFrameCount; 782 } 783 784 } else if (sharedBuffer != 0) { 785 786 // Ensure that buffer alignment matches channel count 787 // 8-bit data in shared memory is not currently supported by AudioFlinger 788 size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2; 789 if (mChannelCount > 1) { 790 // More than 2 channels does not require stronger alignment than stereo 791 alignment <<= 1; 792 } 793 if (((size_t)sharedBuffer->pointer() & (alignment - 1)) != 0) { 794 ALOGE("Invalid buffer alignment: address %p, channel count %u", 795 sharedBuffer->pointer(), mChannelCount); 796 return BAD_VALUE; 797 } 798 799 // When initializing a shared buffer AudioTrack via constructors, 800 // there's no frameCount parameter. 801 // But when initializing a shared buffer AudioTrack via set(), 802 // there _is_ a frameCount parameter. We silently ignore it. 803 frameCount = sharedBuffer->size()/mChannelCount/sizeof(int16_t); 804 805 } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) { 806 807 // FIXME move these calculations and associated checks to server 808 uint32_t afSampleRate; 809 if (AudioSystem::getSamplingRate(output, streamType, &afSampleRate) != NO_ERROR) { 810 return NO_INIT; 811 } 812 size_t afFrameCount; 813 if (AudioSystem::getFrameCount(output, streamType, &afFrameCount) != NO_ERROR) { 814 return NO_INIT; 815 } 816 817 // Ensure that buffer depth covers at least audio hardware latency 818 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate); 819 if (minBufCount < 2) minBufCount = 2; 820 821 size_t minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate; 822 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u" 823 ", afLatency=%d", 824 minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency); 825 826 if (frameCount == 0) { 827 frameCount = minFrameCount; 828 } 829 if (mNotificationFramesAct == 0) { 830 mNotificationFramesAct = frameCount/2; 831 } 832 // Make sure that application is notified with sufficient margin 833 // before underrun 834 if (mNotificationFramesAct > frameCount/2) { 835 mNotificationFramesAct = frameCount/2; 836 } 837 if (frameCount < minFrameCount) { 838 // not ALOGW because it happens all the time when playing key clicks over A2DP 839 ALOGV("Minimum buffer size corrected from %d to %d", 840 frameCount, minFrameCount); 841 frameCount = minFrameCount; 842 } 843 844 } else { 845 // For fast tracks, the frame count calculations and checks are done by server 846 } 847 848 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT; 849 if (mIsTimed) { 850 trackFlags |= IAudioFlinger::TRACK_TIMED; 851 } 852 853 pid_t tid = -1; 854 if (flags & AUDIO_OUTPUT_FLAG_FAST) { 855 trackFlags |= IAudioFlinger::TRACK_FAST; 856 if (mAudioTrackThread != 0) { 857 tid = mAudioTrackThread->getTid(); 858 } 859 } 860 861 sp<IAudioTrack> track = audioFlinger->createTrack(streamType, 862 sampleRate, 863 // AudioFlinger only sees 16-bit PCM 864 format == AUDIO_FORMAT_PCM_8_BIT ? 865 AUDIO_FORMAT_PCM_16_BIT : format, 866 mChannelMask, 867 frameCount, 868 &trackFlags, 869 sharedBuffer, 870 output, 871 tid, 872 &mSessionId, 873 &status); 874 875 if (track == 0) { 876 ALOGE("AudioFlinger could not create track, status: %d", status); 877 return status; 878 } 879 sp<IMemory> iMem = track->getCblk(); 880 if (iMem == 0) { 881 ALOGE("Could not get control block"); 882 return NO_INIT; 883 } 884 mAudioTrack = track; 885 mCblkMemory = iMem; 886 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer()); 887 mCblk = cblk; 888 size_t temp = cblk->frameCount_; 889 if (temp < frameCount || (frameCount == 0 && temp == 0)) { 890 // In current design, AudioTrack client checks and ensures frame count validity before 891 // passing it to AudioFlinger so AudioFlinger should not return a different value except 892 // for fast track as it uses a special method of assigning frame count. 893 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp); 894 } 895 frameCount = temp; 896 mAwaitBoost = false; 897 if (flags & AUDIO_OUTPUT_FLAG_FAST) { 898 if (trackFlags & IAudioFlinger::TRACK_FAST) { 899 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount); 900 mAwaitBoost = true; 901 } else { 902 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount); 903 // once denied, do not request again if IAudioTrack is re-created 904 flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST); 905 mFlags = flags; 906 } 907 if (sharedBuffer == 0) { 908 mNotificationFramesAct = frameCount/2; 909 } 910 } 911 if (sharedBuffer == 0) { 912 mBuffers = (char*)cblk + sizeof(audio_track_cblk_t); 913 } else { 914 mBuffers = sharedBuffer->pointer(); 915 } 916 917 mAudioTrack->attachAuxEffect(mAuxEffectId); 918 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS; 919 cblk->waitTimeMs = 0; 920 mRemainingFrames = mNotificationFramesAct; 921 // FIXME don't believe this lie 922 mLatency = afLatency + (1000*frameCount) / sampleRate; 923 mFrameCount = frameCount; 924 // If IAudioTrack is re-created, don't let the requested frameCount 925 // decrease. This can confuse clients that cache frameCount(). 926 if (frameCount > mReqFrameCount) { 927 mReqFrameCount = frameCount; 928 } 929 930 // update proxy 931 delete mProxy; 932 mProxy = new AudioTrackClientProxy(cblk, mBuffers, frameCount, mFrameSizeAF); 933 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | 934 uint16_t(mVolume[LEFT] * 0x1000)); 935 mProxy->setSendLevel(mSendLevel); 936 mProxy->setSampleRate(mSampleRate); 937 if (sharedBuffer != 0) { 938 // Force buffer full condition as data is already present in shared memory 939 mProxy->stepUser(frameCount); 940 } 941 942 return NO_ERROR; 943 } 944 945 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 946 { 947 ALOG_ASSERT(mStatus == NO_ERROR && mProxy != NULL); 948 949 AutoMutex lock(mLock); 950 bool active; 951 status_t result = NO_ERROR; 952 audio_track_cblk_t* cblk = mCblk; 953 uint32_t framesReq = audioBuffer->frameCount; 954 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS; 955 956 audioBuffer->frameCount = 0; 957 audioBuffer->size = 0; 958 959 size_t framesAvail = mProxy->framesAvailable(); 960 961 cblk->lock.lock(); 962 if (cblk->flags & CBLK_INVALID) { 963 goto create_new_track; 964 } 965 cblk->lock.unlock(); 966 967 if (framesAvail == 0) { 968 cblk->lock.lock(); 969 goto start_loop_here; 970 while (framesAvail == 0) { 971 active = mActive; 972 if (CC_UNLIKELY(!active)) { 973 ALOGV("Not active and NO_MORE_BUFFERS"); 974 cblk->lock.unlock(); 975 return NO_MORE_BUFFERS; 976 } 977 if (CC_UNLIKELY(!waitCount)) { 978 cblk->lock.unlock(); 979 return WOULD_BLOCK; 980 } 981 if (!(cblk->flags & CBLK_INVALID)) { 982 mLock.unlock(); 983 // this condition is in shared memory, so if IAudioTrack and control block 984 // are replaced due to mediaserver death or IAudioTrack invalidation then 985 // cv won't be signalled, but fortunately the timeout will limit the wait 986 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs)); 987 cblk->lock.unlock(); 988 mLock.lock(); 989 if (!mActive) { 990 return status_t(STOPPED); 991 } 992 // IAudioTrack may have been re-created while mLock was unlocked 993 cblk = mCblk; 994 cblk->lock.lock(); 995 } 996 997 if (cblk->flags & CBLK_INVALID) { 998 goto create_new_track; 999 } 1000 if (CC_UNLIKELY(result != NO_ERROR)) { 1001 cblk->waitTimeMs += waitTimeMs; 1002 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) { 1003 // timing out when a loop has been set and we have already written upto loop end 1004 // is a normal condition: no need to wake AudioFlinger up. 1005 if (cblk->user < cblk->loopEnd) { 1006 ALOGW("obtainBuffer timed out (is the CPU pegged?) %p name=%#x user=%08x, " 1007 "server=%08x", this, cblk->mName, cblk->user, cblk->server); 1008 //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140) 1009 cblk->lock.unlock(); 1010 result = mAudioTrack->start(); 1011 cblk->lock.lock(); 1012 if (result == DEAD_OBJECT) { 1013 android_atomic_or(CBLK_INVALID, &cblk->flags); 1014 create_new_track: 1015 audio_track_cblk_t* temp = cblk; 1016 result = restoreTrack_l(temp, false /*fromStart*/); 1017 cblk = temp; 1018 } 1019 if (result != NO_ERROR) { 1020 ALOGW("obtainBuffer create Track error %d", result); 1021 cblk->lock.unlock(); 1022 return result; 1023 } 1024 } 1025 cblk->waitTimeMs = 0; 1026 } 1027 1028 if (--waitCount == 0) { 1029 cblk->lock.unlock(); 1030 return TIMED_OUT; 1031 } 1032 } 1033 // read the server count again 1034 start_loop_here: 1035 framesAvail = mProxy->framesAvailable_l(); 1036 } 1037 cblk->lock.unlock(); 1038 } 1039 1040 cblk->waitTimeMs = 0; 1041 1042 if (framesReq > framesAvail) { 1043 framesReq = framesAvail; 1044 } 1045 1046 uint32_t u = cblk->user; 1047 uint32_t bufferEnd = cblk->userBase + mFrameCount; 1048 1049 if (framesReq > bufferEnd - u) { 1050 framesReq = bufferEnd - u; 1051 } 1052 1053 audioBuffer->frameCount = framesReq; 1054 audioBuffer->size = framesReq * mFrameSizeAF; 1055 audioBuffer->raw = mProxy->buffer(u); 1056 active = mActive; 1057 return active ? status_t(NO_ERROR) : status_t(STOPPED); 1058 } 1059 1060 void AudioTrack::releaseBuffer(Buffer* audioBuffer) 1061 { 1062 ALOG_ASSERT(mStatus == NO_ERROR && mProxy != NULL); 1063 1064 AutoMutex lock(mLock); 1065 audio_track_cblk_t* cblk = mCblk; 1066 (void) mProxy->stepUser(audioBuffer->frameCount); 1067 if (audioBuffer->frameCount > 0) { 1068 // restart track if it was disabled by audioflinger due to previous underrun 1069 if (mActive && (cblk->flags & CBLK_DISABLED)) { 1070 android_atomic_and(~CBLK_DISABLED, &cblk->flags); 1071 ALOGW("releaseBuffer() track %p name=%#x disabled, restarting", this, cblk->mName); 1072 mAudioTrack->start(); 1073 } 1074 } 1075 } 1076 1077 // ------------------------------------------------------------------------- 1078 1079 ssize_t AudioTrack::write(const void* buffer, size_t userSize) 1080 { 1081 1082 if (mSharedBuffer != 0 || mIsTimed) { 1083 return INVALID_OPERATION; 1084 } 1085 1086 if (ssize_t(userSize) < 0) { 1087 // Sanity-check: user is most-likely passing an error code, and it would 1088 // make the return value ambiguous (actualSize vs error). 1089 ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", 1090 buffer, userSize, userSize); 1091 return BAD_VALUE; 1092 } 1093 1094 ALOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive); 1095 1096 if (userSize == 0) { 1097 return 0; 1098 } 1099 1100 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 1101 // while we are accessing the cblk 1102 mLock.lock(); 1103 sp<IAudioTrack> audioTrack = mAudioTrack; 1104 sp<IMemory> iMem = mCblkMemory; 1105 mLock.unlock(); 1106 1107 // since mLock is unlocked the IAudioTrack and shared memory may be re-created, 1108 // so all cblk references might still refer to old shared memory, but that should be benign 1109 1110 ssize_t written = 0; 1111 const int8_t *src = (const int8_t *)buffer; 1112 Buffer audioBuffer; 1113 size_t frameSz = frameSize(); 1114 1115 do { 1116 audioBuffer.frameCount = userSize/frameSz; 1117 1118 status_t err = obtainBuffer(&audioBuffer, -1); 1119 if (err < 0) { 1120 // out of buffers, return #bytes written 1121 if (err == status_t(NO_MORE_BUFFERS)) { 1122 break; 1123 } 1124 return ssize_t(err); 1125 } 1126 1127 size_t toWrite; 1128 1129 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1130 // Divide capacity by 2 to take expansion into account 1131 toWrite = audioBuffer.size>>1; 1132 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) src, toWrite); 1133 } else { 1134 toWrite = audioBuffer.size; 1135 memcpy(audioBuffer.i8, src, toWrite); 1136 } 1137 src += toWrite; 1138 userSize -= toWrite; 1139 written += toWrite; 1140 1141 releaseBuffer(&audioBuffer); 1142 } while (userSize >= frameSz); 1143 1144 return written; 1145 } 1146 1147 // ------------------------------------------------------------------------- 1148 1149 TimedAudioTrack::TimedAudioTrack() { 1150 mIsTimed = true; 1151 } 1152 1153 status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer) 1154 { 1155 AutoMutex lock(mLock); 1156 status_t result = UNKNOWN_ERROR; 1157 1158 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 1159 // while we are accessing the cblk 1160 sp<IAudioTrack> audioTrack = mAudioTrack; 1161 sp<IMemory> iMem = mCblkMemory; 1162 1163 // If the track is not invalid already, try to allocate a buffer. alloc 1164 // fails indicating that the server is dead, flag the track as invalid so 1165 // we can attempt to restore in just a bit. 1166 audio_track_cblk_t* cblk = mCblk; 1167 if (!(cblk->flags & CBLK_INVALID)) { 1168 result = mAudioTrack->allocateTimedBuffer(size, buffer); 1169 if (result == DEAD_OBJECT) { 1170 android_atomic_or(CBLK_INVALID, &cblk->flags); 1171 } 1172 } 1173 1174 // If the track is invalid at this point, attempt to restore it. and try the 1175 // allocation one more time. 1176 if (cblk->flags & CBLK_INVALID) { 1177 cblk->lock.lock(); 1178 audio_track_cblk_t* temp = cblk; 1179 result = restoreTrack_l(temp, false /*fromStart*/); 1180 cblk = temp; 1181 cblk->lock.unlock(); 1182 1183 if (result == OK) { 1184 result = mAudioTrack->allocateTimedBuffer(size, buffer); 1185 } 1186 } 1187 1188 return result; 1189 } 1190 1191 status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer, 1192 int64_t pts) 1193 { 1194 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts); 1195 { 1196 AutoMutex lock(mLock); 1197 audio_track_cblk_t* cblk = mCblk; 1198 // restart track if it was disabled by audioflinger due to previous underrun 1199 if (buffer->size() != 0 && status == NO_ERROR && 1200 mActive && (cblk->flags & CBLK_DISABLED)) { 1201 android_atomic_and(~CBLK_DISABLED, &cblk->flags); 1202 ALOGW("queueTimedBuffer() track %p disabled, restarting", this); 1203 mAudioTrack->start(); 1204 } 1205 } 1206 return status; 1207 } 1208 1209 status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform, 1210 TargetTimeline target) 1211 { 1212 return mAudioTrack->setMediaTimeTransform(xform, target); 1213 } 1214 1215 // ------------------------------------------------------------------------- 1216 1217 bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread) 1218 { 1219 Buffer audioBuffer; 1220 uint32_t frames; 1221 size_t writtenSize; 1222 1223 mLock.lock(); 1224 if (mAwaitBoost) { 1225 mAwaitBoost = false; 1226 mLock.unlock(); 1227 static const int32_t kMaxTries = 5; 1228 int32_t tryCounter = kMaxTries; 1229 uint32_t pollUs = 10000; 1230 do { 1231 int policy = sched_getscheduler(0); 1232 if (policy == SCHED_FIFO || policy == SCHED_RR) { 1233 break; 1234 } 1235 usleep(pollUs); 1236 pollUs <<= 1; 1237 } while (tryCounter-- > 0); 1238 if (tryCounter < 0) { 1239 ALOGE("did not receive expected priority boost on time"); 1240 } 1241 return true; 1242 } 1243 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 1244 // while we are accessing the cblk 1245 sp<IAudioTrack> audioTrack = mAudioTrack; 1246 sp<IMemory> iMem = mCblkMemory; 1247 audio_track_cblk_t* cblk = mCblk; 1248 bool active = mActive; 1249 mLock.unlock(); 1250 1251 // since mLock is unlocked the IAudioTrack and shared memory may be re-created, 1252 // so all cblk references might still refer to old shared memory, but that should be benign 1253 1254 // Manage underrun callback 1255 if (active && (mProxy->framesAvailable() == mFrameCount)) { 1256 ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags); 1257 if (!(android_atomic_or(CBLK_UNDERRUN, &cblk->flags) & CBLK_UNDERRUN)) { 1258 mCbf(EVENT_UNDERRUN, mUserData, 0); 1259 if (cblk->server == mFrameCount) { 1260 mCbf(EVENT_BUFFER_END, mUserData, 0); 1261 } 1262 if (mSharedBuffer != 0) { 1263 return false; 1264 } 1265 } 1266 } 1267 1268 // Manage loop end callback 1269 while (mLoopCount > cblk->loopCount) { 1270 int loopCount = -1; 1271 mLoopCount--; 1272 if (mLoopCount >= 0) loopCount = mLoopCount; 1273 1274 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount); 1275 } 1276 1277 // Manage marker callback 1278 if (!mMarkerReached && (mMarkerPosition > 0)) { 1279 if (cblk->server >= mMarkerPosition) { 1280 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition); 1281 mMarkerReached = true; 1282 } 1283 } 1284 1285 // Manage new position callback 1286 if (mUpdatePeriod > 0) { 1287 while (cblk->server >= mNewPosition) { 1288 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition); 1289 mNewPosition += mUpdatePeriod; 1290 } 1291 } 1292 1293 // If Shared buffer is used, no data is requested from client. 1294 if (mSharedBuffer != 0) { 1295 frames = 0; 1296 } else { 1297 frames = mRemainingFrames; 1298 } 1299 1300 // See description of waitCount parameter at declaration of obtainBuffer(). 1301 // The logic below prevents us from being stuck below at obtainBuffer() 1302 // not being able to handle timed events (position, markers, loops). 1303 int32_t waitCount = -1; 1304 if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) { 1305 waitCount = 1; 1306 } 1307 1308 do { 1309 1310 audioBuffer.frameCount = frames; 1311 1312 status_t err = obtainBuffer(&audioBuffer, waitCount); 1313 if (err < NO_ERROR) { 1314 if (err != TIMED_OUT) { 1315 ALOGE_IF(err != status_t(NO_MORE_BUFFERS), 1316 "Error obtaining an audio buffer, giving up."); 1317 return false; 1318 } 1319 break; 1320 } 1321 if (err == status_t(STOPPED)) { 1322 return false; 1323 } 1324 1325 // Divide buffer size by 2 to take into account the expansion 1326 // due to 8 to 16 bit conversion: the callback must fill only half 1327 // of the destination buffer 1328 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1329 audioBuffer.size >>= 1; 1330 } 1331 1332 size_t reqSize = audioBuffer.size; 1333 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); 1334 writtenSize = audioBuffer.size; 1335 1336 // Sanity check on returned size 1337 if (ssize_t(writtenSize) <= 0) { 1338 // The callback is done filling buffers 1339 // Keep this thread going to handle timed events and 1340 // still try to get more data in intervals of WAIT_PERIOD_MS 1341 // but don't just loop and block the CPU, so wait 1342 usleep(WAIT_PERIOD_MS*1000); 1343 break; 1344 } 1345 1346 if (writtenSize > reqSize) { 1347 writtenSize = reqSize; 1348 } 1349 1350 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1351 // 8 to 16 bit conversion, note that source and destination are the same address 1352 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize); 1353 writtenSize <<= 1; 1354 } 1355 1356 audioBuffer.size = writtenSize; 1357 // NOTE: cblk->frameSize is not equal to AudioTrack::frameSize() for 1358 // 8 bit PCM data: in this case, cblk->frameSize is based on a sample size of 1359 // 16 bit. 1360 audioBuffer.frameCount = writtenSize / mFrameSizeAF; 1361 1362 frames -= audioBuffer.frameCount; 1363 1364 releaseBuffer(&audioBuffer); 1365 } 1366 while (frames); 1367 1368 if (frames == 0) { 1369 mRemainingFrames = mNotificationFramesAct; 1370 } else { 1371 mRemainingFrames = frames; 1372 } 1373 return true; 1374 } 1375 1376 // must be called with mLock and refCblk.lock held. Callers must also hold strong references on 1377 // the IAudioTrack and IMemory in case they are recreated here. 1378 // If the IAudioTrack is successfully restored, the refCblk pointer is updated 1379 // FIXME Don't depend on caller to hold strong references. 1380 status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& refCblk, bool fromStart) 1381 { 1382 status_t result; 1383 1384 audio_track_cblk_t* cblk = refCblk; 1385 audio_track_cblk_t* newCblk = cblk; 1386 ALOGW("dead IAudioTrack, creating a new one from %s", 1387 fromStart ? "start()" : "obtainBuffer()"); 1388 1389 // signal old cblk condition so that other threads waiting for available buffers stop 1390 // waiting now 1391 cblk->cv.broadcast(); 1392 cblk->lock.unlock(); 1393 1394 // refresh the audio configuration cache in this process to make sure we get new 1395 // output parameters in getOutput_l() and createTrack_l() 1396 AudioSystem::clearAudioConfigCache(); 1397 1398 // if the new IAudioTrack is created, createTrack_l() will modify the 1399 // following member variables: mAudioTrack, mCblkMemory and mCblk. 1400 // It will also delete the strong references on previous IAudioTrack and IMemory 1401 result = createTrack_l(mStreamType, 1402 mSampleRate, 1403 mFormat, 1404 mReqFrameCount, // so that frame count never goes down 1405 mFlags, 1406 mSharedBuffer, 1407 getOutput_l()); 1408 1409 if (result == NO_ERROR) { 1410 uint32_t user = cblk->user; 1411 uint32_t server = cblk->server; 1412 // restore write index and set other indexes to reflect empty buffer status 1413 newCblk = mCblk; 1414 newCblk->user = user; 1415 newCblk->server = user; 1416 newCblk->userBase = user; 1417 newCblk->serverBase = user; 1418 // restore loop: this is not guaranteed to succeed if new frame count is not 1419 // compatible with loop length 1420 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount); 1421 size_t frames = 0; 1422 if (!fromStart) { 1423 newCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS; 1424 // Make sure that a client relying on callback events indicating underrun or 1425 // the actual amount of audio frames played (e.g SoundPool) receives them. 1426 if (mSharedBuffer == 0) { 1427 if (user > server) { 1428 frames = ((user - server) > mFrameCount) ? 1429 mFrameCount : (user - server); 1430 memset(mBuffers, 0, frames * mFrameSizeAF); 1431 } 1432 // restart playback even if buffer is not completely filled. 1433 android_atomic_or(CBLK_FORCEREADY, &newCblk->flags); 1434 } 1435 } 1436 if (mSharedBuffer != 0) { 1437 frames = mFrameCount; 1438 } 1439 if (frames > 0) { 1440 // stepUser() clears CBLK_UNDERRUN flag enabling underrun callbacks to 1441 // the client 1442 mProxy->stepUser(frames); 1443 } 1444 if (mActive) { 1445 result = mAudioTrack->start(); 1446 ALOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result); 1447 } 1448 if (fromStart && result == NO_ERROR) { 1449 mNewPosition = newCblk->server + mUpdatePeriod; 1450 } 1451 } 1452 ALOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result); 1453 ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x", 1454 result, mActive, newCblk, cblk, newCblk->flags, cblk->flags); 1455 1456 if (result == NO_ERROR) { 1457 // from now on we switch to the newly created cblk 1458 refCblk = newCblk; 1459 } 1460 newCblk->lock.lock(); 1461 1462 ALOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d", result); 1463 1464 return result; 1465 } 1466 1467 status_t AudioTrack::dump(int fd, const Vector<String16>& args) const 1468 { 1469 1470 const size_t SIZE = 256; 1471 char buffer[SIZE]; 1472 String8 result; 1473 1474 result.append(" AudioTrack::dump\n"); 1475 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, 1476 mVolume[0], mVolume[1]); 1477 result.append(buffer); 1478 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, 1479 mChannelCount, mFrameCount); 1480 result.append(buffer); 1481 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus); 1482 result.append(buffer); 1483 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency); 1484 result.append(buffer); 1485 ::write(fd, result.string(), result.size()); 1486 return NO_ERROR; 1487 } 1488 1489 // ========================================================================= 1490 1491 AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava) 1492 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true) 1493 { 1494 } 1495 1496 AudioTrack::AudioTrackThread::~AudioTrackThread() 1497 { 1498 } 1499 1500 bool AudioTrack::AudioTrackThread::threadLoop() 1501 { 1502 { 1503 AutoMutex _l(mMyLock); 1504 if (mPaused) { 1505 mMyCond.wait(mMyLock); 1506 // caller will check for exitPending() 1507 return true; 1508 } 1509 } 1510 if (!mReceiver.processAudioBuffer(this)) { 1511 pause(); 1512 } 1513 return true; 1514 } 1515 1516 void AudioTrack::AudioTrackThread::requestExit() 1517 { 1518 // must be in this order to avoid a race condition 1519 Thread::requestExit(); 1520 resume(); 1521 } 1522 1523 void AudioTrack::AudioTrackThread::pause() 1524 { 1525 AutoMutex _l(mMyLock); 1526 mPaused = true; 1527 } 1528 1529 void AudioTrack::AudioTrackThread::resume() 1530 { 1531 AutoMutex _l(mMyLock); 1532 if (mPaused) { 1533 mPaused = false; 1534 mMyCond.signal(); 1535 } 1536 } 1537 1538 }; // namespace android 1539