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