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