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