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