AudioTrack.cpp revision 511754b5839fd9b09fc56b89ae007fbc39084a33
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 46#include <audio_utils/primitives.h> 47 48namespace android { 49// --------------------------------------------------------------------------- 50 51// static 52status_t AudioTrack::getMinFrameCount( 53 int* frameCount, 54 audio_stream_type_t streamType, 55 uint32_t sampleRate) 56{ 57 int afSampleRate; 58 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { 59 return NO_INIT; 60 } 61 int afFrameCount; 62 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) { 63 return NO_INIT; 64 } 65 uint32_t afLatency; 66 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) { 67 return NO_INIT; 68 } 69 70 // Ensure that buffer depth covers at least audio hardware latency 71 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate); 72 if (minBufCount < 2) minBufCount = 2; 73 74 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount : 75 afFrameCount * minBufCount * sampleRate / afSampleRate; 76 return NO_ERROR; 77} 78 79// --------------------------------------------------------------------------- 80 81AudioTrack::AudioTrack() 82 : mStatus(NO_INIT), 83 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT) 84{ 85} 86 87AudioTrack::AudioTrack( 88 audio_stream_type_t streamType, 89 uint32_t sampleRate, 90 audio_format_t format, 91 int channelMask, 92 int frameCount, 93 uint32_t flags, 94 callback_t cbf, 95 void* user, 96 int notificationFrames, 97 int sessionId) 98 : mStatus(NO_INIT), 99 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT) 100{ 101 mStatus = set(streamType, sampleRate, format, channelMask, 102 frameCount, flags, cbf, user, notificationFrames, 103 0, false, sessionId); 104} 105 106AudioTrack::AudioTrack( 107 audio_stream_type_t streamType, 108 uint32_t sampleRate, 109 audio_format_t format, 110 int channelMask, 111 const sp<IMemory>& sharedBuffer, 112 uint32_t flags, 113 callback_t cbf, 114 void* user, 115 int notificationFrames, 116 int sessionId) 117 : mStatus(NO_INIT), 118 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT) 119{ 120 mStatus = set(streamType, sampleRate, format, channelMask, 121 0, flags, cbf, user, notificationFrames, 122 sharedBuffer, false, sessionId); 123} 124 125AudioTrack::~AudioTrack() 126{ 127 ALOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer()); 128 129 if (mStatus == NO_ERROR) { 130 // Make sure that callback function exits in the case where 131 // it is looping on buffer full condition in obtainBuffer(). 132 // Otherwise the callback thread will never exit. 133 stop(); 134 if (mAudioTrackThread != 0) { 135 mAudioTrackThread->requestExitAndWait(); 136 mAudioTrackThread.clear(); 137 } 138 mAudioTrack.clear(); 139 IPCThreadState::self()->flushCommands(); 140 AudioSystem::releaseAudioSessionId(mSessionId); 141 } 142} 143 144status_t AudioTrack::set( 145 audio_stream_type_t streamType, 146 uint32_t sampleRate, 147 audio_format_t format, 148 int channelMask, 149 int frameCount, 150 uint32_t flags, 151 callback_t cbf, 152 void* user, 153 int notificationFrames, 154 const sp<IMemory>& sharedBuffer, 155 bool threadCanCallJava, 156 int sessionId) 157{ 158 159 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size()); 160 161 AutoMutex lock(mLock); 162 if (mAudioTrack != 0) { 163 ALOGE("Track already in use"); 164 return INVALID_OPERATION; 165 } 166 167 int afSampleRate; 168 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { 169 return NO_INIT; 170 } 171 uint32_t afLatency; 172 if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) { 173 return NO_INIT; 174 } 175 176 // handle default values first. 177 if (streamType == AUDIO_STREAM_DEFAULT) { 178 streamType = AUDIO_STREAM_MUSIC; 179 } 180 if (sampleRate == 0) { 181 sampleRate = afSampleRate; 182 } 183 // these below should probably come from the audioFlinger too... 184 if (format == AUDIO_FORMAT_DEFAULT) { 185 format = AUDIO_FORMAT_PCM_16_BIT; 186 } 187 if (channelMask == 0) { 188 channelMask = AUDIO_CHANNEL_OUT_STEREO; 189 } 190 191 // validate parameters 192 if (!audio_is_valid_format(format)) { 193 ALOGE("Invalid format"); 194 return BAD_VALUE; 195 } 196 197 // force direct flag if format is not linear PCM 198 if (!audio_is_linear_pcm(format)) { 199 flags |= AUDIO_POLICY_OUTPUT_FLAG_DIRECT; 200 } 201 202 if (!audio_is_output_channel(channelMask)) { 203 ALOGE("Invalid channel mask"); 204 return BAD_VALUE; 205 } 206 uint32_t channelCount = popcount(channelMask); 207 208 audio_io_handle_t output = AudioSystem::getOutput( 209 streamType, 210 sampleRate, format, channelMask, 211 (audio_policy_output_flags_t)flags); 212 213 if (output == 0) { 214 ALOGE("Could not get audio output for stream type %d", streamType); 215 return BAD_VALUE; 216 } 217 218 mVolume[LEFT] = 1.0f; 219 mVolume[RIGHT] = 1.0f; 220 mSendLevel = 0.0f; 221 mFrameCount = frameCount; 222 mNotificationFramesReq = notificationFrames; 223 mSessionId = sessionId; 224 mAuxEffectId = 0; 225 226 // create the IAudioTrack 227 status_t status = createTrack_l(streamType, 228 sampleRate, 229 format, 230 (uint32_t)channelMask, 231 frameCount, 232 flags, 233 sharedBuffer, 234 output, 235 true); 236 237 if (status != NO_ERROR) { 238 return status; 239 } 240 241 if (cbf != 0) { 242 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava); 243 } 244 245 mStatus = NO_ERROR; 246 247 mStreamType = streamType; 248 mFormat = format; 249 mChannelMask = (uint32_t)channelMask; 250 mChannelCount = channelCount; 251 mSharedBuffer = sharedBuffer; 252 mMuted = false; 253 mActive = false; 254 mCbf = cbf; 255 mUserData = user; 256 mLoopCount = 0; 257 mMarkerPosition = 0; 258 mMarkerReached = false; 259 mNewPosition = 0; 260 mUpdatePeriod = 0; 261 mFlushed = false; 262 mFlags = flags; 263 AudioSystem::acquireAudioSessionId(mSessionId); 264 mRestoreStatus = NO_ERROR; 265 return NO_ERROR; 266} 267 268status_t AudioTrack::initCheck() const 269{ 270 return mStatus; 271} 272 273// ------------------------------------------------------------------------- 274 275uint32_t AudioTrack::latency() const 276{ 277 return mLatency; 278} 279 280audio_stream_type_t AudioTrack::streamType() const 281{ 282 return mStreamType; 283} 284 285audio_format_t AudioTrack::format() const 286{ 287 return mFormat; 288} 289 290int AudioTrack::channelCount() const 291{ 292 return mChannelCount; 293} 294 295uint32_t AudioTrack::frameCount() const 296{ 297 return mCblk->frameCount; 298} 299 300size_t AudioTrack::frameSize() const 301{ 302 if (audio_is_linear_pcm(mFormat)) { 303 return channelCount()*audio_bytes_per_sample(mFormat); 304 } else { 305 return sizeof(uint8_t); 306 } 307} 308 309sp<IMemory>& AudioTrack::sharedBuffer() 310{ 311 return mSharedBuffer; 312} 313 314// ------------------------------------------------------------------------- 315 316void AudioTrack::start() 317{ 318 sp<AudioTrackThread> t = mAudioTrackThread; 319 status_t status = NO_ERROR; 320 321 ALOGV("start %p", this); 322 if (t != 0) { 323 if (t->exitPending()) { 324 if (t->requestExitAndWait() == WOULD_BLOCK) { 325 ALOGE("AudioTrack::start called from thread"); 326 return; 327 } 328 } 329 t->mLock.lock(); 330 } 331 332 AutoMutex lock(mLock); 333 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 334 // while we are accessing the cblk 335 sp <IAudioTrack> audioTrack = mAudioTrack; 336 sp <IMemory> iMem = mCblkMemory; 337 audio_track_cblk_t* cblk = mCblk; 338 339 if (!mActive) { 340 mFlushed = false; 341 mActive = true; 342 mNewPosition = cblk->server + mUpdatePeriod; 343 cblk->lock.lock(); 344 cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS; 345 cblk->waitTimeMs = 0; 346 android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags); 347 if (t != 0) { 348 t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO); 349 } else { 350 mPreviousPriority = getpriority(PRIO_PROCESS, 0); 351 mPreviousSchedulingGroup = androidGetThreadSchedulingGroup(0); 352 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO); 353 } 354 355 ALOGV("start %p before lock cblk %p", this, mCblk); 356 if (!(cblk->flags & CBLK_INVALID_MSK)) { 357 cblk->lock.unlock(); 358 status = mAudioTrack->start(); 359 cblk->lock.lock(); 360 if (status == DEAD_OBJECT) { 361 android_atomic_or(CBLK_INVALID_ON, &cblk->flags); 362 } 363 } 364 if (cblk->flags & CBLK_INVALID_MSK) { 365 status = restoreTrack_l(cblk, true); 366 } 367 cblk->lock.unlock(); 368 if (status != NO_ERROR) { 369 ALOGV("start() failed"); 370 mActive = false; 371 if (t != 0) { 372 t->requestExit(); 373 } else { 374 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 375 androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup); 376 } 377 } 378 } 379 380 if (t != 0) { 381 t->mLock.unlock(); 382 } 383} 384 385void AudioTrack::stop() 386{ 387 sp<AudioTrackThread> t = mAudioTrackThread; 388 389 ALOGV("stop %p", this); 390 if (t != 0) { 391 t->mLock.lock(); 392 } 393 394 AutoMutex lock(mLock); 395 if (mActive) { 396 mActive = false; 397 mCblk->cv.signal(); 398 mAudioTrack->stop(); 399 // Cancel loops (If we are in the middle of a loop, playback 400 // would not stop until loopCount reaches 0). 401 setLoop_l(0, 0, 0); 402 // the playback head position will reset to 0, so if a marker is set, we need 403 // to activate it again 404 mMarkerReached = false; 405 // Force flush if a shared buffer is used otherwise audioflinger 406 // will not stop before end of buffer is reached. 407 if (mSharedBuffer != 0) { 408 flush_l(); 409 } 410 if (t != 0) { 411 t->requestExit(); 412 } else { 413 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 414 androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup); 415 } 416 } 417 418 if (t != 0) { 419 t->mLock.unlock(); 420 } 421} 422 423bool AudioTrack::stopped() const 424{ 425 AutoMutex lock(mLock); 426 return stopped_l(); 427} 428 429void AudioTrack::flush() 430{ 431 AutoMutex lock(mLock); 432 flush_l(); 433} 434 435// must be called with mLock held 436void AudioTrack::flush_l() 437{ 438 ALOGV("flush"); 439 440 // clear playback marker and periodic update counter 441 mMarkerPosition = 0; 442 mMarkerReached = false; 443 mUpdatePeriod = 0; 444 445 if (!mActive) { 446 mFlushed = true; 447 mAudioTrack->flush(); 448 // Release AudioTrack callback thread in case it was waiting for new buffers 449 // in AudioTrack::obtainBuffer() 450 mCblk->cv.signal(); 451 } 452} 453 454void AudioTrack::pause() 455{ 456 ALOGV("pause"); 457 AutoMutex lock(mLock); 458 if (mActive) { 459 mActive = false; 460 mAudioTrack->pause(); 461 } 462} 463 464void AudioTrack::mute(bool e) 465{ 466 mAudioTrack->mute(e); 467 mMuted = e; 468} 469 470bool AudioTrack::muted() const 471{ 472 return mMuted; 473} 474 475status_t AudioTrack::setVolume(float left, float right) 476{ 477 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) { 478 return BAD_VALUE; 479 } 480 481 AutoMutex lock(mLock); 482 mVolume[LEFT] = left; 483 mVolume[RIGHT] = right; 484 485 // write must be atomic 486 mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000); 487 488 return NO_ERROR; 489} 490 491void AudioTrack::getVolume(float* left, float* right) 492{ 493 if (left != NULL) { 494 *left = mVolume[LEFT]; 495 } 496 if (right != NULL) { 497 *right = mVolume[RIGHT]; 498 } 499} 500 501status_t AudioTrack::setAuxEffectSendLevel(float level) 502{ 503 ALOGV("setAuxEffectSendLevel(%f)", level); 504 if (level < 0.0f || level > 1.0f) { 505 return BAD_VALUE; 506 } 507 AutoMutex lock(mLock); 508 509 mSendLevel = level; 510 511 mCblk->setSendLevel(level); 512 513 return NO_ERROR; 514} 515 516void AudioTrack::getAuxEffectSendLevel(float* level) 517{ 518 if (level != NULL) { 519 *level = mSendLevel; 520 } 521} 522 523status_t AudioTrack::setSampleRate(int rate) 524{ 525 int afSamplingRate; 526 527 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) { 528 return NO_INIT; 529 } 530 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 531 if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE; 532 533 AutoMutex lock(mLock); 534 mCblk->sampleRate = rate; 535 return NO_ERROR; 536} 537 538uint32_t AudioTrack::getSampleRate() 539{ 540 AutoMutex lock(mLock); 541 return mCblk->sampleRate; 542} 543 544status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount) 545{ 546 AutoMutex lock(mLock); 547 return setLoop_l(loopStart, loopEnd, loopCount); 548} 549 550// must be called with mLock held 551status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount) 552{ 553 audio_track_cblk_t* cblk = mCblk; 554 555 Mutex::Autolock _l(cblk->lock); 556 557 if (loopCount == 0) { 558 cblk->loopStart = UINT_MAX; 559 cblk->loopEnd = UINT_MAX; 560 cblk->loopCount = 0; 561 mLoopCount = 0; 562 return NO_ERROR; 563 } 564 565 if (loopStart >= loopEnd || 566 loopEnd - loopStart > cblk->frameCount || 567 cblk->server > loopStart) { 568 ALOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, cblk->frameCount, cblk->user); 569 return BAD_VALUE; 570 } 571 572 if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) { 573 ALOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, framecount %d", 574 loopStart, loopEnd, cblk->frameCount); 575 return BAD_VALUE; 576 } 577 578 cblk->loopStart = loopStart; 579 cblk->loopEnd = loopEnd; 580 cblk->loopCount = loopCount; 581 mLoopCount = loopCount; 582 583 return NO_ERROR; 584} 585 586status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount) 587{ 588 AutoMutex lock(mLock); 589 if (loopStart != 0) { 590 *loopStart = mCblk->loopStart; 591 } 592 if (loopEnd != 0) { 593 *loopEnd = mCblk->loopEnd; 594 } 595 if (loopCount != 0) { 596 if (mCblk->loopCount < 0) { 597 *loopCount = -1; 598 } else { 599 *loopCount = mCblk->loopCount; 600 } 601 } 602 603 return NO_ERROR; 604} 605 606status_t AudioTrack::setMarkerPosition(uint32_t marker) 607{ 608 if (mCbf == 0) return INVALID_OPERATION; 609 610 mMarkerPosition = marker; 611 mMarkerReached = false; 612 613 return NO_ERROR; 614} 615 616status_t AudioTrack::getMarkerPosition(uint32_t *marker) 617{ 618 if (marker == 0) return BAD_VALUE; 619 620 *marker = mMarkerPosition; 621 622 return NO_ERROR; 623} 624 625status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod) 626{ 627 if (mCbf == 0) return INVALID_OPERATION; 628 629 uint32_t curPosition; 630 getPosition(&curPosition); 631 mNewPosition = curPosition + updatePeriod; 632 mUpdatePeriod = updatePeriod; 633 634 return NO_ERROR; 635} 636 637status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) 638{ 639 if (updatePeriod == 0) return BAD_VALUE; 640 641 *updatePeriod = mUpdatePeriod; 642 643 return NO_ERROR; 644} 645 646status_t AudioTrack::setPosition(uint32_t position) 647{ 648 AutoMutex lock(mLock); 649 650 if (!stopped_l()) return INVALID_OPERATION; 651 652 Mutex::Autolock _l(mCblk->lock); 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_l()) 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(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 audio_stream_type_t 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 ALOGE("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 ALOGE("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 ALOGE("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 ALOGE("AudioFlinger could not create track, status: %d", status); 803 return status; 804 } 805 sp<IMemory> cblk = track->getCblk(); 806 if (cblk == 0) { 807 ALOGE("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->setSendLevel(mSendLevel); 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 bool 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) { 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 ALOGW( "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 ALOGW("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 ALOGW("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 ALOGE("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 = 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 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) src, toWrite); 1005 } else { 1006 toWrite = audioBuffer.size; 1007 memcpy(audioBuffer.i8, src, toWrite); 1008 src += toWrite; 1009 } 1010 userSize -= toWrite; 1011 written += toWrite; 1012 1013 releaseBuffer(&audioBuffer); 1014 } while (userSize >= frameSz); 1015 1016 return written; 1017} 1018 1019// ------------------------------------------------------------------------- 1020 1021bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread) 1022{ 1023 Buffer audioBuffer; 1024 uint32_t frames; 1025 size_t writtenSize; 1026 1027 mLock.lock(); 1028 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 1029 // while we are accessing the cblk 1030 sp <IAudioTrack> audioTrack = mAudioTrack; 1031 sp <IMemory> iMem = mCblkMemory; 1032 audio_track_cblk_t* cblk = mCblk; 1033 bool active = mActive; 1034 mLock.unlock(); 1035 1036 // Manage underrun callback 1037 if (active && (cblk->framesAvailable() == cblk->frameCount)) { 1038 ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags); 1039 if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) { 1040 mCbf(EVENT_UNDERRUN, mUserData, 0); 1041 if (cblk->server == cblk->frameCount) { 1042 mCbf(EVENT_BUFFER_END, mUserData, 0); 1043 } 1044 if (mSharedBuffer != 0) return false; 1045 } 1046 } 1047 1048 // Manage loop end callback 1049 while (mLoopCount > cblk->loopCount) { 1050 int loopCount = -1; 1051 mLoopCount--; 1052 if (mLoopCount >= 0) loopCount = mLoopCount; 1053 1054 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount); 1055 } 1056 1057 // Manage marker callback 1058 if (!mMarkerReached && (mMarkerPosition > 0)) { 1059 if (cblk->server >= mMarkerPosition) { 1060 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition); 1061 mMarkerReached = true; 1062 } 1063 } 1064 1065 // Manage new position callback 1066 if (mUpdatePeriod > 0) { 1067 while (cblk->server >= mNewPosition) { 1068 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition); 1069 mNewPosition += mUpdatePeriod; 1070 } 1071 } 1072 1073 // If Shared buffer is used, no data is requested from client. 1074 if (mSharedBuffer != 0) { 1075 frames = 0; 1076 } else { 1077 frames = mRemainingFrames; 1078 } 1079 1080 int32_t waitCount = -1; 1081 if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) { 1082 waitCount = 1; 1083 } 1084 1085 do { 1086 1087 audioBuffer.frameCount = frames; 1088 1089 // Calling obtainBuffer() with a wait count of 1 1090 // limits wait time to WAIT_PERIOD_MS. This prevents from being 1091 // stuck here not being able to handle timed events (position, markers, loops). 1092 status_t err = obtainBuffer(&audioBuffer, waitCount); 1093 if (err < NO_ERROR) { 1094 if (err != TIMED_OUT) { 1095 ALOGE_IF(err != status_t(NO_MORE_BUFFERS), "Error obtaining an audio buffer, giving up."); 1096 return false; 1097 } 1098 break; 1099 } 1100 if (err == status_t(STOPPED)) return false; 1101 1102 // Divide buffer size by 2 to take into account the expansion 1103 // due to 8 to 16 bit conversion: the callback must fill only half 1104 // of the destination buffer 1105 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) { 1106 audioBuffer.size >>= 1; 1107 } 1108 1109 size_t reqSize = audioBuffer.size; 1110 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); 1111 writtenSize = audioBuffer.size; 1112 1113 // Sanity check on returned size 1114 if (ssize_t(writtenSize) <= 0) { 1115 // The callback is done filling buffers 1116 // Keep this thread going to handle timed events and 1117 // still try to get more data in intervals of WAIT_PERIOD_MS 1118 // but don't just loop and block the CPU, so wait 1119 usleep(WAIT_PERIOD_MS*1000); 1120 break; 1121 } 1122 if (writtenSize > reqSize) writtenSize = reqSize; 1123 1124 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) { 1125 // 8 to 16 bit conversion, note that source and destination are the same address 1126 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize); 1127 writtenSize <<= 1; 1128 } 1129 1130 audioBuffer.size = writtenSize; 1131 // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for 1132 // 8 bit PCM data: in this case, mCblk->frameSize is based on a sample size of 1133 // 16 bit. 1134 audioBuffer.frameCount = writtenSize/mCblk->frameSize; 1135 1136 frames -= audioBuffer.frameCount; 1137 1138 releaseBuffer(&audioBuffer); 1139 } 1140 while (frames); 1141 1142 if (frames == 0) { 1143 mRemainingFrames = mNotificationFramesAct; 1144 } else { 1145 mRemainingFrames = frames; 1146 } 1147 return true; 1148} 1149 1150// must be called with mLock and cblk.lock held. Callers must also hold strong references on 1151// the IAudioTrack and IMemory in case they are recreated here. 1152// If the IAudioTrack is successfully restored, the cblk pointer is updated 1153status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart) 1154{ 1155 status_t result; 1156 1157 if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) { 1158 ALOGW("dead IAudioTrack, creating a new one from %s TID %d", 1159 fromStart ? "start()" : "obtainBuffer()", gettid()); 1160 1161 // signal old cblk condition so that other threads waiting for available buffers stop 1162 // waiting now 1163 cblk->cv.broadcast(); 1164 cblk->lock.unlock(); 1165 1166 // refresh the audio configuration cache in this process to make sure we get new 1167 // output parameters in getOutput_l() and createTrack_l() 1168 AudioSystem::clearAudioConfigCache(); 1169 1170 // if the new IAudioTrack is created, createTrack_l() will modify the 1171 // following member variables: mAudioTrack, mCblkMemory and mCblk. 1172 // It will also delete the strong references on previous IAudioTrack and IMemory 1173 result = createTrack_l(mStreamType, 1174 cblk->sampleRate, 1175 mFormat, 1176 mChannelMask, 1177 mFrameCount, 1178 mFlags, 1179 mSharedBuffer, 1180 getOutput_l(), 1181 false); 1182 1183 if (result == NO_ERROR) { 1184 uint32_t user = cblk->user; 1185 uint32_t server = cblk->server; 1186 // restore write index and set other indexes to reflect empty buffer status 1187 mCblk->user = user; 1188 mCblk->server = user; 1189 mCblk->userBase = user; 1190 mCblk->serverBase = user; 1191 // restore loop: this is not guaranteed to succeed if new frame count is not 1192 // compatible with loop length 1193 setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount); 1194 if (!fromStart) { 1195 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS; 1196 // Make sure that a client relying on callback events indicating underrun or 1197 // the actual amount of audio frames played (e.g SoundPool) receives them. 1198 if (mSharedBuffer == 0) { 1199 uint32_t frames = 0; 1200 if (user > server) { 1201 frames = ((user - server) > mCblk->frameCount) ? 1202 mCblk->frameCount : (user - server); 1203 memset(mCblk->buffers, 0, frames * mCblk->frameSize); 1204 } 1205 // restart playback even if buffer is not completely filled. 1206 android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags); 1207 // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to 1208 // the client 1209 mCblk->stepUser(frames); 1210 } 1211 } 1212 if (mActive) { 1213 result = mAudioTrack->start(); 1214 ALOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result); 1215 } 1216 if (fromStart && result == NO_ERROR) { 1217 mNewPosition = mCblk->server + mUpdatePeriod; 1218 } 1219 } 1220 if (result != NO_ERROR) { 1221 android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags); 1222 ALOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result); 1223 } 1224 mRestoreStatus = result; 1225 // signal old cblk condition for other threads waiting for restore completion 1226 android_atomic_or(CBLK_RESTORED_ON, &cblk->flags); 1227 cblk->cv.broadcast(); 1228 } else { 1229 if (!(cblk->flags & CBLK_RESTORED_MSK)) { 1230 ALOGW("dead IAudioTrack, waiting for a new one TID %d", gettid()); 1231 mLock.unlock(); 1232 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS)); 1233 if (result == NO_ERROR) { 1234 result = mRestoreStatus; 1235 } 1236 cblk->lock.unlock(); 1237 mLock.lock(); 1238 } else { 1239 ALOGW("dead IAudioTrack, already restored TID %d", gettid()); 1240 result = mRestoreStatus; 1241 cblk->lock.unlock(); 1242 } 1243 } 1244 ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x", 1245 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags); 1246 1247 if (result == NO_ERROR) { 1248 // from now on we switch to the newly created cblk 1249 cblk = mCblk; 1250 } 1251 cblk->lock.lock(); 1252 1253 ALOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid()); 1254 1255 return result; 1256} 1257 1258status_t AudioTrack::dump(int fd, const Vector<String16>& args) const 1259{ 1260 1261 const size_t SIZE = 256; 1262 char buffer[SIZE]; 1263 String8 result; 1264 1265 result.append(" AudioTrack::dump\n"); 1266 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]); 1267 result.append(buffer); 1268 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mCblk->frameCount); 1269 result.append(buffer); 1270 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted); 1271 result.append(buffer); 1272 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency); 1273 result.append(buffer); 1274 ::write(fd, result.string(), result.size()); 1275 return NO_ERROR; 1276} 1277 1278// ========================================================================= 1279 1280AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava) 1281 : Thread(bCanCallJava), mReceiver(receiver) 1282{ 1283} 1284 1285bool AudioTrack::AudioTrackThread::threadLoop() 1286{ 1287 return mReceiver.processAudioBuffer(this); 1288} 1289 1290status_t AudioTrack::AudioTrackThread::readyToRun() 1291{ 1292 return NO_ERROR; 1293} 1294 1295void AudioTrack::AudioTrackThread::onFirstRef() 1296{ 1297} 1298 1299// ========================================================================= 1300 1301 1302audio_track_cblk_t::audio_track_cblk_t() 1303 : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0), 1304 userBase(0), serverBase(0), buffers(0), frameCount(0), 1305 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), 1306 mSendLevel(0), flags(0) 1307{ 1308} 1309 1310uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount) 1311{ 1312 uint32_t u = user; 1313 1314 u += frameCount; 1315 // Ensure that user is never ahead of server for AudioRecord 1316 if (flags & CBLK_DIRECTION_MSK) { 1317 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period 1318 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) { 1319 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS; 1320 } 1321 } else if (u > server) { 1322 ALOGW("stepServer occurred after track reset"); 1323 u = server; 1324 } 1325 1326 if (u >= userBase + this->frameCount) { 1327 userBase += this->frameCount; 1328 } 1329 1330 user = u; 1331 1332 // Clear flow control error condition as new data has been written/read to/from buffer. 1333 if (flags & CBLK_UNDERRUN_MSK) { 1334 android_atomic_and(~CBLK_UNDERRUN_MSK, &flags); 1335 } 1336 1337 return u; 1338} 1339 1340bool audio_track_cblk_t::stepServer(uint32_t frameCount) 1341{ 1342 if (!tryLock()) { 1343 ALOGW("stepServer() could not lock cblk"); 1344 return false; 1345 } 1346 1347 uint32_t s = server; 1348 1349 s += frameCount; 1350 if (flags & CBLK_DIRECTION_MSK) { 1351 // Mark that we have read the first buffer so that next time stepUser() is called 1352 // we switch to normal obtainBuffer() timeout period 1353 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) { 1354 bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1; 1355 } 1356 // It is possible that we receive a flush() 1357 // while the mixer is processing a block: in this case, 1358 // stepServer() is called After the flush() has reset u & s and 1359 // we have s > u 1360 if (s > user) { 1361 ALOGW("stepServer occurred after track reset"); 1362 s = user; 1363 } 1364 } 1365 1366 if (s >= loopEnd) { 1367 ALOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd); 1368 s = loopStart; 1369 if (--loopCount == 0) { 1370 loopEnd = UINT_MAX; 1371 loopStart = UINT_MAX; 1372 } 1373 } 1374 if (s >= serverBase + this->frameCount) { 1375 serverBase += this->frameCount; 1376 } 1377 1378 server = s; 1379 1380 if (!(flags & CBLK_INVALID_MSK)) { 1381 cv.signal(); 1382 } 1383 lock.unlock(); 1384 return true; 1385} 1386 1387void* audio_track_cblk_t::buffer(uint32_t offset) const 1388{ 1389 return (int8_t *)buffers + (offset - userBase) * frameSize; 1390} 1391 1392uint32_t audio_track_cblk_t::framesAvailable() 1393{ 1394 Mutex::Autolock _l(lock); 1395 return framesAvailable_l(); 1396} 1397 1398uint32_t audio_track_cblk_t::framesAvailable_l() 1399{ 1400 uint32_t u = user; 1401 uint32_t s = server; 1402 1403 if (flags & CBLK_DIRECTION_MSK) { 1404 uint32_t limit = (s < loopStart) ? s : loopStart; 1405 return limit + frameCount - u; 1406 } else { 1407 return frameCount + u - s; 1408 } 1409} 1410 1411uint32_t audio_track_cblk_t::framesReady() 1412{ 1413 uint32_t u = user; 1414 uint32_t s = server; 1415 1416 if (flags & CBLK_DIRECTION_MSK) { 1417 if (u < loopEnd) { 1418 return u - s; 1419 } else { 1420 // do not block on mutex shared with client on AudioFlinger side 1421 if (!tryLock()) { 1422 ALOGW("framesReady() could not lock cblk"); 1423 return 0; 1424 } 1425 uint32_t frames = UINT_MAX; 1426 if (loopCount >= 0) { 1427 frames = (loopEnd - loopStart)*loopCount + u - s; 1428 } 1429 lock.unlock(); 1430 return frames; 1431 } 1432 } else { 1433 return s - u; 1434 } 1435} 1436 1437bool audio_track_cblk_t::tryLock() 1438{ 1439 // the code below simulates lock-with-timeout 1440 // we MUST do this to protect the AudioFlinger server 1441 // as this lock is shared with the client. 1442 status_t err; 1443 1444 err = lock.tryLock(); 1445 if (err == -EBUSY) { // just wait a bit 1446 usleep(1000); 1447 err = lock.tryLock(); 1448 } 1449 if (err != NO_ERROR) { 1450 // probably, the client just died. 1451 return false; 1452 } 1453 return true; 1454} 1455 1456// ------------------------------------------------------------------------- 1457 1458}; // namespace android 1459