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