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