AudioTrack.cpp revision 7064fd2dcdfeafea53cd5a992bb78c413542f29f
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 <sys/resource.h> 23#include <audio_utils/primitives.h> 24#include <binder/IPCThreadState.h> 25#include <media/AudioTrack.h> 26#include <utils/Log.h> 27#include <private/media/AudioTrackShared.h> 28#include <media/IAudioFlinger.h> 29 30#define WAIT_PERIOD_MS 10 31#define WAIT_STREAM_END_TIMEOUT_SEC 120 32 33 34namespace android { 35// --------------------------------------------------------------------------- 36 37// static 38status_t AudioTrack::getMinFrameCount( 39 size_t* frameCount, 40 audio_stream_type_t streamType, 41 uint32_t sampleRate) 42{ 43 if (frameCount == NULL) { 44 return BAD_VALUE; 45 } 46 47 // FIXME merge with similar code in createTrack_l(), except we're missing 48 // some information here that is available in createTrack_l(): 49 // audio_io_handle_t output 50 // audio_format_t format 51 // audio_channel_mask_t channelMask 52 // audio_output_flags_t flags 53 uint32_t afSampleRate; 54 status_t status; 55 status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType); 56 if (status != NO_ERROR) { 57 ALOGE("Unable to query output sample rate for stream type %d; status %d", 58 streamType, status); 59 return status; 60 } 61 size_t afFrameCount; 62 status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType); 63 if (status != NO_ERROR) { 64 ALOGE("Unable to query output frame count for stream type %d; status %d", 65 streamType, status); 66 return status; 67 } 68 uint32_t afLatency; 69 status = AudioSystem::getOutputLatency(&afLatency, streamType); 70 if (status != NO_ERROR) { 71 ALOGE("Unable to query output latency for stream type %d; status %d", 72 streamType, status); 73 return status; 74 } 75 76 // Ensure that buffer depth covers at least audio hardware latency 77 uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate); 78 if (minBufCount < 2) { 79 minBufCount = 2; 80 } 81 82 *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount : 83 afFrameCount * minBufCount * sampleRate / afSampleRate; 84 // The formula above should always produce a non-zero value, but return an error 85 // in the unlikely event that it does not, as that's part of the API contract. 86 if (*frameCount == 0) { 87 ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d", 88 streamType, sampleRate); 89 return BAD_VALUE; 90 } 91 ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d", 92 *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency); 93 return NO_ERROR; 94} 95 96// --------------------------------------------------------------------------- 97 98AudioTrack::AudioTrack() 99 : mStatus(NO_INIT), 100 mIsTimed(false), 101 mPreviousPriority(ANDROID_PRIORITY_NORMAL), 102 mPreviousSchedulingGroup(SP_DEFAULT), 103 mPausedPosition(0) 104{ 105} 106 107AudioTrack::AudioTrack( 108 audio_stream_type_t streamType, 109 uint32_t sampleRate, 110 audio_format_t format, 111 audio_channel_mask_t channelMask, 112 size_t frameCount, 113 audio_output_flags_t flags, 114 callback_t cbf, 115 void* user, 116 uint32_t notificationFrames, 117 int sessionId, 118 transfer_type transferType, 119 const audio_offload_info_t *offloadInfo, 120 int uid, 121 pid_t pid) 122 : mStatus(NO_INIT), 123 mIsTimed(false), 124 mPreviousPriority(ANDROID_PRIORITY_NORMAL), 125 mPreviousSchedulingGroup(SP_DEFAULT), 126 mPausedPosition(0) 127{ 128 mStatus = set(streamType, sampleRate, format, channelMask, 129 frameCount, flags, cbf, user, notificationFrames, 130 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, 131 offloadInfo, uid, pid); 132} 133 134AudioTrack::AudioTrack( 135 audio_stream_type_t streamType, 136 uint32_t sampleRate, 137 audio_format_t format, 138 audio_channel_mask_t channelMask, 139 const sp<IMemory>& sharedBuffer, 140 audio_output_flags_t flags, 141 callback_t cbf, 142 void* user, 143 uint32_t notificationFrames, 144 int sessionId, 145 transfer_type transferType, 146 const audio_offload_info_t *offloadInfo, 147 int uid, 148 pid_t pid) 149 : mStatus(NO_INIT), 150 mIsTimed(false), 151 mPreviousPriority(ANDROID_PRIORITY_NORMAL), 152 mPreviousSchedulingGroup(SP_DEFAULT), 153 mPausedPosition(0) 154{ 155 mStatus = set(streamType, sampleRate, format, channelMask, 156 0 /*frameCount*/, flags, cbf, user, notificationFrames, 157 sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo, 158 uid, pid); 159} 160 161AudioTrack::~AudioTrack() 162{ 163 if (mStatus == NO_ERROR) { 164 // Make sure that callback function exits in the case where 165 // it is looping on buffer full condition in obtainBuffer(). 166 // Otherwise the callback thread will never exit. 167 stop(); 168 if (mAudioTrackThread != 0) { 169 mProxy->interrupt(); 170 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h 171 mAudioTrackThread->requestExitAndWait(); 172 mAudioTrackThread.clear(); 173 } 174 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this); 175 mAudioTrack.clear(); 176 IPCThreadState::self()->flushCommands(); 177 ALOGV("~AudioTrack, releasing session id from %d on behalf of %d", 178 IPCThreadState::self()->getCallingPid(), mClientPid); 179 AudioSystem::releaseAudioSessionId(mSessionId, mClientPid); 180 } 181} 182 183status_t AudioTrack::set( 184 audio_stream_type_t streamType, 185 uint32_t sampleRate, 186 audio_format_t format, 187 audio_channel_mask_t channelMask, 188 size_t frameCount, 189 audio_output_flags_t flags, 190 callback_t cbf, 191 void* user, 192 uint32_t notificationFrames, 193 const sp<IMemory>& sharedBuffer, 194 bool threadCanCallJava, 195 int sessionId, 196 transfer_type transferType, 197 const audio_offload_info_t *offloadInfo, 198 int uid, 199 pid_t pid) 200{ 201 ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, " 202 "flags #%x, notificationFrames %u, sessionId %d, transferType %d", 203 streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames, 204 sessionId, transferType); 205 206 switch (transferType) { 207 case TRANSFER_DEFAULT: 208 if (sharedBuffer != 0) { 209 transferType = TRANSFER_SHARED; 210 } else if (cbf == NULL || threadCanCallJava) { 211 transferType = TRANSFER_SYNC; 212 } else { 213 transferType = TRANSFER_CALLBACK; 214 } 215 break; 216 case TRANSFER_CALLBACK: 217 if (cbf == NULL || sharedBuffer != 0) { 218 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0"); 219 return BAD_VALUE; 220 } 221 break; 222 case TRANSFER_OBTAIN: 223 case TRANSFER_SYNC: 224 if (sharedBuffer != 0) { 225 ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0"); 226 return BAD_VALUE; 227 } 228 break; 229 case TRANSFER_SHARED: 230 if (sharedBuffer == 0) { 231 ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0"); 232 return BAD_VALUE; 233 } 234 break; 235 default: 236 ALOGE("Invalid transfer type %d", transferType); 237 return BAD_VALUE; 238 } 239 mSharedBuffer = sharedBuffer; 240 mTransfer = transferType; 241 242 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), 243 sharedBuffer->size()); 244 245 ALOGV("set() streamType %d frameCount %u flags %04x", streamType, frameCount, flags); 246 247 AutoMutex lock(mLock); 248 249 // invariant that mAudioTrack != 0 is true only after set() returns successfully 250 if (mAudioTrack != 0) { 251 ALOGE("Track already in use"); 252 return INVALID_OPERATION; 253 } 254 255 // handle default values first. 256 if (streamType == AUDIO_STREAM_DEFAULT) { 257 streamType = AUDIO_STREAM_MUSIC; 258 } 259 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 260 ALOGE("Invalid stream type %d", streamType); 261 return BAD_VALUE; 262 } 263 mStreamType = streamType; 264 265 status_t status; 266 if (sampleRate == 0) { 267 status = AudioSystem::getOutputSamplingRate(&sampleRate, streamType); 268 if (status != NO_ERROR) { 269 ALOGE("Could not get output sample rate for stream type %d; status %d", 270 streamType, status); 271 return status; 272 } 273 } 274 mSampleRate = sampleRate; 275 276 // these below should probably come from the audioFlinger too... 277 if (format == AUDIO_FORMAT_DEFAULT) { 278 format = AUDIO_FORMAT_PCM_16_BIT; 279 } 280 281 // validate parameters 282 if (!audio_is_valid_format(format)) { 283 ALOGE("Invalid format %#x", format); 284 return BAD_VALUE; 285 } 286 mFormat = format; 287 288 if (!audio_is_output_channel(channelMask)) { 289 ALOGE("Invalid channel mask %#x", channelMask); 290 return BAD_VALUE; 291 } 292 mChannelMask = channelMask; 293 uint32_t channelCount = popcount(channelMask); 294 mChannelCount = channelCount; 295 296 // AudioFlinger does not currently support 8-bit data in shared memory 297 if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) { 298 ALOGE("8-bit data in shared memory is not supported"); 299 return BAD_VALUE; 300 } 301 302 // force direct flag if format is not linear PCM 303 // or offload was requested 304 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) 305 || !audio_is_linear_pcm(format)) { 306 ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) 307 ? "Offload request, forcing to Direct Output" 308 : "Not linear PCM, forcing to Direct Output"); 309 flags = (audio_output_flags_t) 310 // FIXME why can't we allow direct AND fast? 311 ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST); 312 } 313 // only allow deep buffering for music stream type 314 if (streamType != AUDIO_STREAM_MUSIC) { 315 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER); 316 } 317 318 if (audio_is_linear_pcm(format)) { 319 mFrameSize = channelCount * audio_bytes_per_sample(format); 320 mFrameSizeAF = channelCount * sizeof(int16_t); 321 } else { 322 mFrameSize = sizeof(uint8_t); 323 mFrameSizeAF = sizeof(uint8_t); 324 } 325 326 // Make copy of input parameter offloadInfo so that in the future: 327 // (a) createTrack_l doesn't need it as an input parameter 328 // (b) we can support re-creation of offloaded tracks 329 if (offloadInfo != NULL) { 330 mOffloadInfoCopy = *offloadInfo; 331 mOffloadInfo = &mOffloadInfoCopy; 332 } else { 333 mOffloadInfo = NULL; 334 } 335 336 mVolume[LEFT] = 1.0f; 337 mVolume[RIGHT] = 1.0f; 338 mSendLevel = 0.0f; 339 // mFrameCount is initialized in createTrack_l 340 mReqFrameCount = frameCount; 341 mNotificationFramesReq = notificationFrames; 342 mNotificationFramesAct = 0; 343 mSessionId = sessionId; 344 int callingpid = IPCThreadState::self()->getCallingPid(); 345 int mypid = getpid(); 346 if (uid == -1 || (callingpid != mypid)) { 347 mClientUid = IPCThreadState::self()->getCallingUid(); 348 } else { 349 mClientUid = uid; 350 } 351 if (pid == -1 || (callingpid != mypid)) { 352 mClientPid = callingpid; 353 } else { 354 mClientPid = pid; 355 } 356 mAuxEffectId = 0; 357 mFlags = flags; 358 mCbf = cbf; 359 360 if (cbf != NULL) { 361 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava); 362 mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/); 363 } 364 365 // create the IAudioTrack 366 status = createTrack_l(0 /*epoch*/); 367 368 if (status != NO_ERROR) { 369 if (mAudioTrackThread != 0) { 370 mAudioTrackThread->requestExit(); // see comment in AudioTrack.h 371 mAudioTrackThread->requestExitAndWait(); 372 mAudioTrackThread.clear(); 373 } 374 // Use of direct and offloaded output streams is ref counted by audio policy manager. 375#if 0 // FIXME This should no longer be needed 376 //Use of direct and offloaded output streams is ref counted by audio policy manager. 377 // As getOutput was called above and resulted in an output stream to be opened, 378 // we need to release it. 379 if (mOutput != 0) { 380 AudioSystem::releaseOutput(mOutput); 381 mOutput = 0; 382 } 383#endif 384 return status; 385 } 386 387 mStatus = NO_ERROR; 388 mState = STATE_STOPPED; 389 mUserData = user; 390 mLoopPeriod = 0; 391 mMarkerPosition = 0; 392 mMarkerReached = false; 393 mNewPosition = 0; 394 mUpdatePeriod = 0; 395 AudioSystem::acquireAudioSessionId(mSessionId, mClientPid); 396 mSequence = 1; 397 mObservedSequence = mSequence; 398 mInUnderrun = false; 399 400 return NO_ERROR; 401} 402 403// ------------------------------------------------------------------------- 404 405status_t AudioTrack::start() 406{ 407 AutoMutex lock(mLock); 408 409 if (mState == STATE_ACTIVE) { 410 return INVALID_OPERATION; 411 } 412 413 mInUnderrun = true; 414 415 State previousState = mState; 416 if (previousState == STATE_PAUSED_STOPPING) { 417 mState = STATE_STOPPING; 418 } else { 419 mState = STATE_ACTIVE; 420 } 421 if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) { 422 // reset current position as seen by client to 0 423 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition()); 424 // force refresh of remaining frames by processAudioBuffer() as last 425 // write before stop could be partial. 426 mRefreshRemaining = true; 427 } 428 mNewPosition = mProxy->getPosition() + mUpdatePeriod; 429 int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags); 430 431 sp<AudioTrackThread> t = mAudioTrackThread; 432 if (t != 0) { 433 if (previousState == STATE_STOPPING) { 434 mProxy->interrupt(); 435 } else { 436 t->resume(); 437 } 438 } else { 439 mPreviousPriority = getpriority(PRIO_PROCESS, 0); 440 get_sched_policy(0, &mPreviousSchedulingGroup); 441 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO); 442 } 443 444 status_t status = NO_ERROR; 445 if (!(flags & CBLK_INVALID)) { 446 status = mAudioTrack->start(); 447 if (status == DEAD_OBJECT) { 448 flags |= CBLK_INVALID; 449 } 450 } 451 if (flags & CBLK_INVALID) { 452 status = restoreTrack_l("start"); 453 } 454 455 if (status != NO_ERROR) { 456 ALOGE("start() status %d", status); 457 mState = previousState; 458 if (t != 0) { 459 if (previousState != STATE_STOPPING) { 460 t->pause(); 461 } 462 } else { 463 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 464 set_sched_policy(0, mPreviousSchedulingGroup); 465 } 466 } 467 468 return status; 469} 470 471void AudioTrack::stop() 472{ 473 AutoMutex lock(mLock); 474 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) { 475 return; 476 } 477 478 if (isOffloaded_l()) { 479 mState = STATE_STOPPING; 480 } else { 481 mState = STATE_STOPPED; 482 } 483 484 mProxy->interrupt(); 485 mAudioTrack->stop(); 486 // the playback head position will reset to 0, so if a marker is set, we need 487 // to activate it again 488 mMarkerReached = false; 489#if 0 490 // Force flush if a shared buffer is used otherwise audioflinger 491 // will not stop before end of buffer is reached. 492 // It may be needed to make sure that we stop playback, likely in case looping is on. 493 if (mSharedBuffer != 0) { 494 flush_l(); 495 } 496#endif 497 498 sp<AudioTrackThread> t = mAudioTrackThread; 499 if (t != 0) { 500 if (!isOffloaded_l()) { 501 t->pause(); 502 } 503 } else { 504 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 505 set_sched_policy(0, mPreviousSchedulingGroup); 506 } 507} 508 509bool AudioTrack::stopped() const 510{ 511 AutoMutex lock(mLock); 512 return mState != STATE_ACTIVE; 513} 514 515void AudioTrack::flush() 516{ 517 if (mSharedBuffer != 0) { 518 return; 519 } 520 AutoMutex lock(mLock); 521 if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) { 522 return; 523 } 524 flush_l(); 525} 526 527void AudioTrack::flush_l() 528{ 529 ALOG_ASSERT(mState != STATE_ACTIVE); 530 531 // clear playback marker and periodic update counter 532 mMarkerPosition = 0; 533 mMarkerReached = false; 534 mUpdatePeriod = 0; 535 mRefreshRemaining = true; 536 537 mState = STATE_FLUSHED; 538 if (isOffloaded_l()) { 539 mProxy->interrupt(); 540 } 541 mProxy->flush(); 542 mAudioTrack->flush(); 543} 544 545void AudioTrack::pause() 546{ 547 AutoMutex lock(mLock); 548 if (mState == STATE_ACTIVE) { 549 mState = STATE_PAUSED; 550 } else if (mState == STATE_STOPPING) { 551 mState = STATE_PAUSED_STOPPING; 552 } else { 553 return; 554 } 555 mProxy->interrupt(); 556 mAudioTrack->pause(); 557 558 if (isOffloaded()) { 559 if (mOutput != 0) { 560 uint32_t halFrames; 561 // OffloadThread sends HAL pause in its threadLoop.. time saved 562 // here can be slightly off 563 AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition); 564 ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition); 565 } 566 } 567} 568 569status_t AudioTrack::setVolume(float left, float right) 570{ 571 if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) { 572 return BAD_VALUE; 573 } 574 575 AutoMutex lock(mLock); 576 mVolume[LEFT] = left; 577 mVolume[RIGHT] = right; 578 579 mProxy->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000)); 580 581 if (isOffloaded_l()) { 582 mAudioTrack->signal(); 583 } 584 return NO_ERROR; 585} 586 587status_t AudioTrack::setVolume(float volume) 588{ 589 return setVolume(volume, volume); 590} 591 592status_t AudioTrack::setAuxEffectSendLevel(float level) 593{ 594 if (level < 0.0f || level > 1.0f) { 595 return BAD_VALUE; 596 } 597 598 AutoMutex lock(mLock); 599 mSendLevel = level; 600 mProxy->setSendLevel(level); 601 602 return NO_ERROR; 603} 604 605void AudioTrack::getAuxEffectSendLevel(float* level) const 606{ 607 if (level != NULL) { 608 *level = mSendLevel; 609 } 610} 611 612status_t AudioTrack::setSampleRate(uint32_t rate) 613{ 614 if (mIsTimed || isOffloaded()) { 615 return INVALID_OPERATION; 616 } 617 618 uint32_t afSamplingRate; 619 if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) { 620 return NO_INIT; 621 } 622 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 623 if (rate == 0 || rate > afSamplingRate*2 ) { 624 return BAD_VALUE; 625 } 626 627 AutoMutex lock(mLock); 628 mSampleRate = rate; 629 mProxy->setSampleRate(rate); 630 631 return NO_ERROR; 632} 633 634uint32_t AudioTrack::getSampleRate() const 635{ 636 if (mIsTimed) { 637 return 0; 638 } 639 640 AutoMutex lock(mLock); 641 642 // sample rate can be updated during playback by the offloaded decoder so we need to 643 // query the HAL and update if needed. 644// FIXME use Proxy return channel to update the rate from server and avoid polling here 645 if (isOffloaded_l()) { 646 if (mOutput != 0) { 647 uint32_t sampleRate = 0; 648 status_t status = AudioSystem::getSamplingRate(mOutput, mStreamType, &sampleRate); 649 if (status == NO_ERROR) { 650 mSampleRate = sampleRate; 651 } 652 } 653 } 654 return mSampleRate; 655} 656 657status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount) 658{ 659 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) { 660 return INVALID_OPERATION; 661 } 662 663 if (loopCount == 0) { 664 ; 665 } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount && 666 loopEnd - loopStart >= MIN_LOOP) { 667 ; 668 } else { 669 return BAD_VALUE; 670 } 671 672 AutoMutex lock(mLock); 673 // See setPosition() regarding setting parameters such as loop points or position while active 674 if (mState == STATE_ACTIVE) { 675 return INVALID_OPERATION; 676 } 677 setLoop_l(loopStart, loopEnd, loopCount); 678 return NO_ERROR; 679} 680 681void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount) 682{ 683 // FIXME If setting a loop also sets position to start of loop, then 684 // this is correct. Otherwise it should be removed. 685 mNewPosition = mProxy->getPosition() + mUpdatePeriod; 686 mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0; 687 mStaticProxy->setLoop(loopStart, loopEnd, loopCount); 688} 689 690status_t AudioTrack::setMarkerPosition(uint32_t marker) 691{ 692 // The only purpose of setting marker position is to get a callback 693 if (mCbf == NULL || isOffloaded()) { 694 return INVALID_OPERATION; 695 } 696 697 AutoMutex lock(mLock); 698 mMarkerPosition = marker; 699 mMarkerReached = false; 700 701 return NO_ERROR; 702} 703 704status_t AudioTrack::getMarkerPosition(uint32_t *marker) const 705{ 706 if (isOffloaded()) { 707 return INVALID_OPERATION; 708 } 709 if (marker == NULL) { 710 return BAD_VALUE; 711 } 712 713 AutoMutex lock(mLock); 714 *marker = mMarkerPosition; 715 716 return NO_ERROR; 717} 718 719status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod) 720{ 721 // The only purpose of setting position update period is to get a callback 722 if (mCbf == NULL || isOffloaded()) { 723 return INVALID_OPERATION; 724 } 725 726 AutoMutex lock(mLock); 727 mNewPosition = mProxy->getPosition() + updatePeriod; 728 mUpdatePeriod = updatePeriod; 729 730 return NO_ERROR; 731} 732 733status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const 734{ 735 if (isOffloaded()) { 736 return INVALID_OPERATION; 737 } 738 if (updatePeriod == NULL) { 739 return BAD_VALUE; 740 } 741 742 AutoMutex lock(mLock); 743 *updatePeriod = mUpdatePeriod; 744 745 return NO_ERROR; 746} 747 748status_t AudioTrack::setPosition(uint32_t position) 749{ 750 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) { 751 return INVALID_OPERATION; 752 } 753 if (position > mFrameCount) { 754 return BAD_VALUE; 755 } 756 757 AutoMutex lock(mLock); 758 // Currently we require that the player is inactive before setting parameters such as position 759 // or loop points. Otherwise, there could be a race condition: the application could read the 760 // current position, compute a new position or loop parameters, and then set that position or 761 // loop parameters but it would do the "wrong" thing since the position has continued to advance 762 // in the mean time. If we ever provide a sequencer in server, we could allow a way for the app 763 // to specify how it wants to handle such scenarios. 764 if (mState == STATE_ACTIVE) { 765 return INVALID_OPERATION; 766 } 767 mNewPosition = mProxy->getPosition() + mUpdatePeriod; 768 mLoopPeriod = 0; 769 // FIXME Check whether loops and setting position are incompatible in old code. 770 // If we use setLoop for both purposes we lose the capability to set the position while looping. 771 mStaticProxy->setLoop(position, mFrameCount, 0); 772 773 return NO_ERROR; 774} 775 776status_t AudioTrack::getPosition(uint32_t *position) const 777{ 778 if (position == NULL) { 779 return BAD_VALUE; 780 } 781 782 AutoMutex lock(mLock); 783 if (isOffloaded_l()) { 784 uint32_t dspFrames = 0; 785 786 if ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING)) { 787 ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition); 788 *position = mPausedPosition; 789 return NO_ERROR; 790 } 791 792 if (mOutput != 0) { 793 uint32_t halFrames; 794 AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames); 795 } 796 *position = dspFrames; 797 } else { 798 // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes 799 *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 : 800 mProxy->getPosition(); 801 } 802 return NO_ERROR; 803} 804 805status_t AudioTrack::getBufferPosition(uint32_t *position) 806{ 807 if (mSharedBuffer == 0 || mIsTimed) { 808 return INVALID_OPERATION; 809 } 810 if (position == NULL) { 811 return BAD_VALUE; 812 } 813 814 AutoMutex lock(mLock); 815 *position = mStaticProxy->getBufferPosition(); 816 return NO_ERROR; 817} 818 819status_t AudioTrack::reload() 820{ 821 if (mSharedBuffer == 0 || mIsTimed || isOffloaded()) { 822 return INVALID_OPERATION; 823 } 824 825 AutoMutex lock(mLock); 826 // See setPosition() regarding setting parameters such as loop points or position while active 827 if (mState == STATE_ACTIVE) { 828 return INVALID_OPERATION; 829 } 830 mNewPosition = mUpdatePeriod; 831 mLoopPeriod = 0; 832 // FIXME The new code cannot reload while keeping a loop specified. 833 // Need to check how the old code handled this, and whether it's a significant change. 834 mStaticProxy->setLoop(0, mFrameCount, 0); 835 return NO_ERROR; 836} 837 838audio_io_handle_t AudioTrack::getOutput() const 839{ 840 AutoMutex lock(mLock); 841 return mOutput; 842} 843 844status_t AudioTrack::attachAuxEffect(int effectId) 845{ 846 AutoMutex lock(mLock); 847 status_t status = mAudioTrack->attachAuxEffect(effectId); 848 if (status == NO_ERROR) { 849 mAuxEffectId = effectId; 850 } 851 return status; 852} 853 854// ------------------------------------------------------------------------- 855 856// must be called with mLock held 857status_t AudioTrack::createTrack_l(size_t epoch) 858{ 859 status_t status; 860 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger(); 861 if (audioFlinger == 0) { 862 ALOGE("Could not get audioflinger"); 863 return NO_INIT; 864 } 865 866 audio_io_handle_t output = AudioSystem::getOutput(mStreamType, mSampleRate, mFormat, 867 mChannelMask, mFlags, mOffloadInfo); 868 if (output == 0) { 869 ALOGE("Could not get audio output for stream type %d, sample rate %u, format %#x, " 870 "channel mask %#x, flags %#x", 871 mStreamType, mSampleRate, mFormat, mChannelMask, mFlags); 872 return BAD_VALUE; 873 } 874 { 875 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger, 876 // we must release it ourselves if anything goes wrong. 877 878 // Not all of these values are needed under all conditions, but it is easier to get them all 879 880 uint32_t afLatency; 881 status = AudioSystem::getLatency(output, mStreamType, &afLatency); 882 if (status != NO_ERROR) { 883 ALOGE("getLatency(%d) failed status %d", output, status); 884 goto release; 885 } 886 887 size_t afFrameCount; 888 status = AudioSystem::getFrameCount(output, mStreamType, &afFrameCount); 889 if (status != NO_ERROR) { 890 ALOGE("getFrameCount(output=%d, streamType=%d) status %d", output, mStreamType, status); 891 goto release; 892 } 893 894 uint32_t afSampleRate; 895 status = AudioSystem::getSamplingRate(output, mStreamType, &afSampleRate); 896 if (status != NO_ERROR) { 897 ALOGE("getSamplingRate(output=%d, streamType=%d) status %d", output, mStreamType, status); 898 goto release; 899 } 900 901 // Client decides whether the track is TIMED (see below), but can only express a preference 902 // for FAST. Server will perform additional tests. 903 if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !(( 904 // either of these use cases: 905 // use case 1: shared buffer 906 (mSharedBuffer != 0) || 907 // use case 2: callback transfer mode 908 (mTransfer == TRANSFER_CALLBACK)) && 909 // matching sample rate 910 (mSampleRate == afSampleRate))) { 911 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client"); 912 // once denied, do not request again if IAudioTrack is re-created 913 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST); 914 } 915 ALOGV("createTrack_l() output %d afLatency %d", output, afLatency); 916 917 // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where 918 // n = 1 fast track with single buffering; nBuffering is ignored 919 // n = 2 fast track with double buffering 920 // n = 2 normal track, no sample rate conversion 921 // n = 3 normal track, with sample rate conversion 922 // (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering) 923 // n > 3 very high latency or very small notification interval; nBuffering is ignored 924 const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3; 925 926 mNotificationFramesAct = mNotificationFramesReq; 927 928 size_t frameCount = mReqFrameCount; 929 if (!audio_is_linear_pcm(mFormat)) { 930 931 if (mSharedBuffer != 0) { 932 // Same comment as below about ignoring frameCount parameter for set() 933 frameCount = mSharedBuffer->size(); 934 } else if (frameCount == 0) { 935 frameCount = afFrameCount; 936 } 937 if (mNotificationFramesAct != frameCount) { 938 mNotificationFramesAct = frameCount; 939 } 940 } else if (mSharedBuffer != 0) { 941 942 // Ensure that buffer alignment matches channel count 943 // 8-bit data in shared memory is not currently supported by AudioFlinger 944 size_t alignment = /* mFormat == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2; 945 if (mChannelCount > 1) { 946 // More than 2 channels does not require stronger alignment than stereo 947 alignment <<= 1; 948 } 949 if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) { 950 ALOGE("Invalid buffer alignment: address %p, channel count %u", 951 mSharedBuffer->pointer(), mChannelCount); 952 status = BAD_VALUE; 953 goto release; 954 } 955 956 // When initializing a shared buffer AudioTrack via constructors, 957 // there's no frameCount parameter. 958 // But when initializing a shared buffer AudioTrack via set(), 959 // there _is_ a frameCount parameter. We silently ignore it. 960 frameCount = mSharedBuffer->size()/mChannelCount/sizeof(int16_t); 961 962 } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) { 963 964 // FIXME move these calculations and associated checks to server 965 966 // Ensure that buffer depth covers at least audio hardware latency 967 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate); 968 ALOGV("afFrameCount=%d, minBufCount=%d, afSampleRate=%u, afLatency=%d", 969 afFrameCount, minBufCount, afSampleRate, afLatency); 970 if (minBufCount <= nBuffering) { 971 minBufCount = nBuffering; 972 } 973 974 size_t minFrameCount = (afFrameCount*mSampleRate*minBufCount)/afSampleRate; 975 ALOGV("minFrameCount: %u, afFrameCount=%d, minBufCount=%d, sampleRate=%u, afSampleRate=%u" 976 ", afLatency=%d", 977 minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency); 978 979 if (frameCount == 0) { 980 frameCount = minFrameCount; 981 } else if (frameCount < minFrameCount) { 982 // not ALOGW because it happens all the time when playing key clicks over A2DP 983 ALOGV("Minimum buffer size corrected from %d to %d", 984 frameCount, minFrameCount); 985 frameCount = minFrameCount; 986 } 987 // Make sure that application is notified with sufficient margin before underrun 988 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) { 989 mNotificationFramesAct = frameCount/nBuffering; 990 } 991 992 } else { 993 // For fast tracks, the frame count calculations and checks are done by server 994 } 995 996 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT; 997 if (mIsTimed) { 998 trackFlags |= IAudioFlinger::TRACK_TIMED; 999 } 1000 1001 pid_t tid = -1; 1002 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) { 1003 trackFlags |= IAudioFlinger::TRACK_FAST; 1004 if (mAudioTrackThread != 0) { 1005 tid = mAudioTrackThread->getTid(); 1006 } 1007 } 1008 1009 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1010 trackFlags |= IAudioFlinger::TRACK_OFFLOAD; 1011 } 1012 1013 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount, 1014 // but we will still need the original value also 1015 sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType, 1016 mSampleRate, 1017 // AudioFlinger only sees 16-bit PCM 1018 mFormat == AUDIO_FORMAT_PCM_8_BIT ? 1019 AUDIO_FORMAT_PCM_16_BIT : mFormat, 1020 mChannelMask, 1021 &temp, 1022 &trackFlags, 1023 mSharedBuffer, 1024 output, 1025 tid, 1026 &mSessionId, 1027 mName, 1028 mClientUid, 1029 &status); 1030 1031 if (status != NO_ERROR) { 1032 ALOGE("AudioFlinger could not create track, status: %d", status); 1033 goto release; 1034 } 1035 ALOG_ASSERT(track != 0); 1036 1037 // AudioFlinger now owns the reference to the I/O handle, 1038 // so we are no longer responsible for releasing it. 1039 1040 sp<IMemory> iMem = track->getCblk(); 1041 if (iMem == 0) { 1042 ALOGE("Could not get control block"); 1043 return NO_INIT; 1044 } 1045 void *iMemPointer = iMem->pointer(); 1046 if (iMemPointer == NULL) { 1047 ALOGE("Could not get control block pointer"); 1048 return NO_INIT; 1049 } 1050 // invariant that mAudioTrack != 0 is true only after set() returns successfully 1051 if (mAudioTrack != 0) { 1052 mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this); 1053 mDeathNotifier.clear(); 1054 } 1055 mAudioTrack = track; 1056 1057 mCblkMemory = iMem; 1058 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer); 1059 mCblk = cblk; 1060 // note that temp is the (possibly revised) value of frameCount 1061 if (temp < frameCount || (frameCount == 0 && temp == 0)) { 1062 // In current design, AudioTrack client checks and ensures frame count validity before 1063 // passing it to AudioFlinger so AudioFlinger should not return a different value except 1064 // for fast track as it uses a special method of assigning frame count. 1065 ALOGW("Requested frameCount %u but received frameCount %u", frameCount, temp); 1066 } 1067 frameCount = temp; 1068 1069 mAwaitBoost = false; 1070 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) { 1071 if (trackFlags & IAudioFlinger::TRACK_FAST) { 1072 ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", frameCount); 1073 mAwaitBoost = true; 1074 if (mSharedBuffer == 0) { 1075 // Theoretically double-buffering is not required for fast tracks, 1076 // due to tighter scheduling. But in practice, to accommodate kernels with 1077 // scheduling jitter, and apps with computation jitter, we use double-buffering. 1078 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) { 1079 mNotificationFramesAct = frameCount/nBuffering; 1080 } 1081 } 1082 } else { 1083 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", frameCount); 1084 // once denied, do not request again if IAudioTrack is re-created 1085 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST); 1086 if (mSharedBuffer == 0) { 1087 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) { 1088 mNotificationFramesAct = frameCount/nBuffering; 1089 } 1090 } 1091 } 1092 } 1093 if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) { 1094 if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) { 1095 ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful"); 1096 } else { 1097 ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server"); 1098 mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD); 1099 // FIXME This is a warning, not an error, so don't return error status 1100 //return NO_INIT; 1101 } 1102 } 1103 1104 // We retain a copy of the I/O handle, but don't own the reference 1105 mOutput = output; 1106 mRefreshRemaining = true; 1107 1108 // Starting address of buffers in shared memory. If there is a shared buffer, buffers 1109 // is the value of pointer() for the shared buffer, otherwise buffers points 1110 // immediately after the control block. This address is for the mapping within client 1111 // address space. AudioFlinger::TrackBase::mBuffer is for the server address space. 1112 void* buffers; 1113 if (mSharedBuffer == 0) { 1114 buffers = (char*)cblk + sizeof(audio_track_cblk_t); 1115 } else { 1116 buffers = mSharedBuffer->pointer(); 1117 } 1118 1119 mAudioTrack->attachAuxEffect(mAuxEffectId); 1120 // FIXME don't believe this lie 1121 mLatency = afLatency + (1000*frameCount) / mSampleRate; 1122 1123 mFrameCount = frameCount; 1124 // If IAudioTrack is re-created, don't let the requested frameCount 1125 // decrease. This can confuse clients that cache frameCount(). 1126 if (frameCount > mReqFrameCount) { 1127 mReqFrameCount = frameCount; 1128 } 1129 1130 // update proxy 1131 if (mSharedBuffer == 0) { 1132 mStaticProxy.clear(); 1133 mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF); 1134 } else { 1135 mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF); 1136 mProxy = mStaticProxy; 1137 } 1138 mProxy->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | 1139 uint16_t(mVolume[LEFT] * 0x1000)); 1140 mProxy->setSendLevel(mSendLevel); 1141 mProxy->setSampleRate(mSampleRate); 1142 mProxy->setEpoch(epoch); 1143 mProxy->setMinimum(mNotificationFramesAct); 1144 1145 mDeathNotifier = new DeathNotifier(this); 1146 mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this); 1147 1148 return NO_ERROR; 1149 } 1150 1151release: 1152 AudioSystem::releaseOutput(output); 1153 if (status == NO_ERROR) { 1154 status = NO_INIT; 1155 } 1156 return status; 1157} 1158 1159status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 1160{ 1161 if (audioBuffer == NULL) { 1162 return BAD_VALUE; 1163 } 1164 if (mTransfer != TRANSFER_OBTAIN) { 1165 audioBuffer->frameCount = 0; 1166 audioBuffer->size = 0; 1167 audioBuffer->raw = NULL; 1168 return INVALID_OPERATION; 1169 } 1170 1171 const struct timespec *requested; 1172 struct timespec timeout; 1173 if (waitCount == -1) { 1174 requested = &ClientProxy::kForever; 1175 } else if (waitCount == 0) { 1176 requested = &ClientProxy::kNonBlocking; 1177 } else if (waitCount > 0) { 1178 long long ms = WAIT_PERIOD_MS * (long long) waitCount; 1179 timeout.tv_sec = ms / 1000; 1180 timeout.tv_nsec = (int) (ms % 1000) * 1000000; 1181 requested = &timeout; 1182 } else { 1183 ALOGE("%s invalid waitCount %d", __func__, waitCount); 1184 requested = NULL; 1185 } 1186 return obtainBuffer(audioBuffer, requested); 1187} 1188 1189status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested, 1190 struct timespec *elapsed, size_t *nonContig) 1191{ 1192 // previous and new IAudioTrack sequence numbers are used to detect track re-creation 1193 uint32_t oldSequence = 0; 1194 uint32_t newSequence; 1195 1196 Proxy::Buffer buffer; 1197 status_t status = NO_ERROR; 1198 1199 static const int32_t kMaxTries = 5; 1200 int32_t tryCounter = kMaxTries; 1201 1202 do { 1203 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to 1204 // keep them from going away if another thread re-creates the track during obtainBuffer() 1205 sp<AudioTrackClientProxy> proxy; 1206 sp<IMemory> iMem; 1207 1208 { // start of lock scope 1209 AutoMutex lock(mLock); 1210 1211 newSequence = mSequence; 1212 // did previous obtainBuffer() fail due to media server death or voluntary invalidation? 1213 if (status == DEAD_OBJECT) { 1214 // re-create track, unless someone else has already done so 1215 if (newSequence == oldSequence) { 1216 status = restoreTrack_l("obtainBuffer"); 1217 if (status != NO_ERROR) { 1218 buffer.mFrameCount = 0; 1219 buffer.mRaw = NULL; 1220 buffer.mNonContig = 0; 1221 break; 1222 } 1223 } 1224 } 1225 oldSequence = newSequence; 1226 1227 // Keep the extra references 1228 proxy = mProxy; 1229 iMem = mCblkMemory; 1230 1231 if (mState == STATE_STOPPING) { 1232 status = -EINTR; 1233 buffer.mFrameCount = 0; 1234 buffer.mRaw = NULL; 1235 buffer.mNonContig = 0; 1236 break; 1237 } 1238 1239 // Non-blocking if track is stopped or paused 1240 if (mState != STATE_ACTIVE) { 1241 requested = &ClientProxy::kNonBlocking; 1242 } 1243 1244 } // end of lock scope 1245 1246 buffer.mFrameCount = audioBuffer->frameCount; 1247 // FIXME starts the requested timeout and elapsed over from scratch 1248 status = proxy->obtainBuffer(&buffer, requested, elapsed); 1249 1250 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0)); 1251 1252 audioBuffer->frameCount = buffer.mFrameCount; 1253 audioBuffer->size = buffer.mFrameCount * mFrameSizeAF; 1254 audioBuffer->raw = buffer.mRaw; 1255 if (nonContig != NULL) { 1256 *nonContig = buffer.mNonContig; 1257 } 1258 return status; 1259} 1260 1261void AudioTrack::releaseBuffer(Buffer* audioBuffer) 1262{ 1263 if (mTransfer == TRANSFER_SHARED) { 1264 return; 1265 } 1266 1267 size_t stepCount = audioBuffer->size / mFrameSizeAF; 1268 if (stepCount == 0) { 1269 return; 1270 } 1271 1272 Proxy::Buffer buffer; 1273 buffer.mFrameCount = stepCount; 1274 buffer.mRaw = audioBuffer->raw; 1275 1276 AutoMutex lock(mLock); 1277 mInUnderrun = false; 1278 mProxy->releaseBuffer(&buffer); 1279 1280 // restart track if it was disabled by audioflinger due to previous underrun 1281 if (mState == STATE_ACTIVE) { 1282 audio_track_cblk_t* cblk = mCblk; 1283 if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) { 1284 ALOGW("releaseBuffer() track %p name=%s disabled due to previous underrun, restarting", 1285 this, mName.string()); 1286 // FIXME ignoring status 1287 mAudioTrack->start(); 1288 } 1289 } 1290} 1291 1292// ------------------------------------------------------------------------- 1293 1294ssize_t AudioTrack::write(const void* buffer, size_t userSize) 1295{ 1296 if (mTransfer != TRANSFER_SYNC || mIsTimed) { 1297 return INVALID_OPERATION; 1298 } 1299 1300 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) { 1301 // Sanity-check: user is most-likely passing an error code, and it would 1302 // make the return value ambiguous (actualSize vs error). 1303 ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize); 1304 return BAD_VALUE; 1305 } 1306 1307 size_t written = 0; 1308 Buffer audioBuffer; 1309 1310 while (userSize >= mFrameSize) { 1311 audioBuffer.frameCount = userSize / mFrameSize; 1312 1313 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever); 1314 if (err < 0) { 1315 if (written > 0) { 1316 break; 1317 } 1318 return ssize_t(err); 1319 } 1320 1321 size_t toWrite; 1322 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1323 // Divide capacity by 2 to take expansion into account 1324 toWrite = audioBuffer.size >> 1; 1325 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite); 1326 } else { 1327 toWrite = audioBuffer.size; 1328 memcpy(audioBuffer.i8, buffer, toWrite); 1329 } 1330 buffer = ((const char *) buffer) + toWrite; 1331 userSize -= toWrite; 1332 written += toWrite; 1333 1334 releaseBuffer(&audioBuffer); 1335 } 1336 1337 return written; 1338} 1339 1340// ------------------------------------------------------------------------- 1341 1342TimedAudioTrack::TimedAudioTrack() { 1343 mIsTimed = true; 1344} 1345 1346status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer) 1347{ 1348 AutoMutex lock(mLock); 1349 status_t result = UNKNOWN_ERROR; 1350 1351#if 1 1352 // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed 1353 // while we are accessing the cblk 1354 sp<IAudioTrack> audioTrack = mAudioTrack; 1355 sp<IMemory> iMem = mCblkMemory; 1356#endif 1357 1358 // If the track is not invalid already, try to allocate a buffer. alloc 1359 // fails indicating that the server is dead, flag the track as invalid so 1360 // we can attempt to restore in just a bit. 1361 audio_track_cblk_t* cblk = mCblk; 1362 if (!(cblk->mFlags & CBLK_INVALID)) { 1363 result = mAudioTrack->allocateTimedBuffer(size, buffer); 1364 if (result == DEAD_OBJECT) { 1365 android_atomic_or(CBLK_INVALID, &cblk->mFlags); 1366 } 1367 } 1368 1369 // If the track is invalid at this point, attempt to restore it. and try the 1370 // allocation one more time. 1371 if (cblk->mFlags & CBLK_INVALID) { 1372 result = restoreTrack_l("allocateTimedBuffer"); 1373 1374 if (result == NO_ERROR) { 1375 result = mAudioTrack->allocateTimedBuffer(size, buffer); 1376 } 1377 } 1378 1379 return result; 1380} 1381 1382status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer, 1383 int64_t pts) 1384{ 1385 status_t status = mAudioTrack->queueTimedBuffer(buffer, pts); 1386 { 1387 AutoMutex lock(mLock); 1388 audio_track_cblk_t* cblk = mCblk; 1389 // restart track if it was disabled by audioflinger due to previous underrun 1390 if (buffer->size() != 0 && status == NO_ERROR && 1391 (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) { 1392 android_atomic_and(~CBLK_DISABLED, &cblk->mFlags); 1393 ALOGW("queueTimedBuffer() track %p disabled, restarting", this); 1394 // FIXME ignoring status 1395 mAudioTrack->start(); 1396 } 1397 } 1398 return status; 1399} 1400 1401status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform, 1402 TargetTimeline target) 1403{ 1404 return mAudioTrack->setMediaTimeTransform(xform, target); 1405} 1406 1407// ------------------------------------------------------------------------- 1408 1409nsecs_t AudioTrack::processAudioBuffer() 1410{ 1411 // Currently the AudioTrack thread is not created if there are no callbacks. 1412 // Would it ever make sense to run the thread, even without callbacks? 1413 // If so, then replace this by checks at each use for mCbf != NULL. 1414 LOG_ALWAYS_FATAL_IF(mCblk == NULL); 1415 1416 mLock.lock(); 1417 if (mAwaitBoost) { 1418 mAwaitBoost = false; 1419 mLock.unlock(); 1420 static const int32_t kMaxTries = 5; 1421 int32_t tryCounter = kMaxTries; 1422 uint32_t pollUs = 10000; 1423 do { 1424 int policy = sched_getscheduler(0); 1425 if (policy == SCHED_FIFO || policy == SCHED_RR) { 1426 break; 1427 } 1428 usleep(pollUs); 1429 pollUs <<= 1; 1430 } while (tryCounter-- > 0); 1431 if (tryCounter < 0) { 1432 ALOGE("did not receive expected priority boost on time"); 1433 } 1434 // Run again immediately 1435 return 0; 1436 } 1437 1438 // Can only reference mCblk while locked 1439 int32_t flags = android_atomic_and( 1440 ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags); 1441 1442 // Check for track invalidation 1443 if (flags & CBLK_INVALID) { 1444 // for offloaded tracks restoreTrack_l() will just update the sequence and clear 1445 // AudioSystem cache. We should not exit here but after calling the callback so 1446 // that the upper layers can recreate the track 1447 if (!isOffloaded_l() || (mSequence == mObservedSequence)) { 1448 status_t status = restoreTrack_l("processAudioBuffer"); 1449 mLock.unlock(); 1450 // Run again immediately, but with a new IAudioTrack 1451 return 0; 1452 } 1453 } 1454 1455 bool waitStreamEnd = mState == STATE_STOPPING; 1456 bool active = mState == STATE_ACTIVE; 1457 1458 // Manage underrun callback, must be done under lock to avoid race with releaseBuffer() 1459 bool newUnderrun = false; 1460 if (flags & CBLK_UNDERRUN) { 1461#if 0 1462 // Currently in shared buffer mode, when the server reaches the end of buffer, 1463 // the track stays active in continuous underrun state. It's up to the application 1464 // to pause or stop the track, or set the position to a new offset within buffer. 1465 // This was some experimental code to auto-pause on underrun. Keeping it here 1466 // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content. 1467 if (mTransfer == TRANSFER_SHARED) { 1468 mState = STATE_PAUSED; 1469 active = false; 1470 } 1471#endif 1472 if (!mInUnderrun) { 1473 mInUnderrun = true; 1474 newUnderrun = true; 1475 } 1476 } 1477 1478 // Get current position of server 1479 size_t position = mProxy->getPosition(); 1480 1481 // Manage marker callback 1482 bool markerReached = false; 1483 size_t markerPosition = mMarkerPosition; 1484 // FIXME fails for wraparound, need 64 bits 1485 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) { 1486 mMarkerReached = markerReached = true; 1487 } 1488 1489 // Determine number of new position callback(s) that will be needed, while locked 1490 size_t newPosCount = 0; 1491 size_t newPosition = mNewPosition; 1492 size_t updatePeriod = mUpdatePeriod; 1493 // FIXME fails for wraparound, need 64 bits 1494 if (updatePeriod > 0 && position >= newPosition) { 1495 newPosCount = ((position - newPosition) / updatePeriod) + 1; 1496 mNewPosition += updatePeriod * newPosCount; 1497 } 1498 1499 // Cache other fields that will be needed soon 1500 uint32_t loopPeriod = mLoopPeriod; 1501 uint32_t sampleRate = mSampleRate; 1502 uint32_t notificationFrames = mNotificationFramesAct; 1503 if (mRefreshRemaining) { 1504 mRefreshRemaining = false; 1505 mRemainingFrames = notificationFrames; 1506 mRetryOnPartialBuffer = false; 1507 } 1508 size_t misalignment = mProxy->getMisalignment(); 1509 uint32_t sequence = mSequence; 1510 1511 // These fields don't need to be cached, because they are assigned only by set(): 1512 // mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags 1513 // mFlags is also assigned by createTrack_l(), but not the bit we care about. 1514 1515 mLock.unlock(); 1516 1517 if (waitStreamEnd) { 1518 AutoMutex lock(mLock); 1519 1520 sp<AudioTrackClientProxy> proxy = mProxy; 1521 sp<IMemory> iMem = mCblkMemory; 1522 1523 struct timespec timeout; 1524 timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC; 1525 timeout.tv_nsec = 0; 1526 1527 mLock.unlock(); 1528 status_t status = mProxy->waitStreamEndDone(&timeout); 1529 mLock.lock(); 1530 switch (status) { 1531 case NO_ERROR: 1532 case DEAD_OBJECT: 1533 case TIMED_OUT: 1534 mLock.unlock(); 1535 mCbf(EVENT_STREAM_END, mUserData, NULL); 1536 mLock.lock(); 1537 if (mState == STATE_STOPPING) { 1538 mState = STATE_STOPPED; 1539 if (status != DEAD_OBJECT) { 1540 return NS_INACTIVE; 1541 } 1542 } 1543 return 0; 1544 default: 1545 return 0; 1546 } 1547 } 1548 1549 // perform callbacks while unlocked 1550 if (newUnderrun) { 1551 mCbf(EVENT_UNDERRUN, mUserData, NULL); 1552 } 1553 // FIXME we will miss loops if loop cycle was signaled several times since last call 1554 // to processAudioBuffer() 1555 if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) { 1556 mCbf(EVENT_LOOP_END, mUserData, NULL); 1557 } 1558 if (flags & CBLK_BUFFER_END) { 1559 mCbf(EVENT_BUFFER_END, mUserData, NULL); 1560 } 1561 if (markerReached) { 1562 mCbf(EVENT_MARKER, mUserData, &markerPosition); 1563 } 1564 while (newPosCount > 0) { 1565 size_t temp = newPosition; 1566 mCbf(EVENT_NEW_POS, mUserData, &temp); 1567 newPosition += updatePeriod; 1568 newPosCount--; 1569 } 1570 1571 if (mObservedSequence != sequence) { 1572 mObservedSequence = sequence; 1573 mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL); 1574 // for offloaded tracks, just wait for the upper layers to recreate the track 1575 if (isOffloaded()) { 1576 return NS_INACTIVE; 1577 } 1578 } 1579 1580 // if inactive, then don't run me again until re-started 1581 if (!active) { 1582 return NS_INACTIVE; 1583 } 1584 1585 // Compute the estimated time until the next timed event (position, markers, loops) 1586 // FIXME only for non-compressed audio 1587 uint32_t minFrames = ~0; 1588 if (!markerReached && position < markerPosition) { 1589 minFrames = markerPosition - position; 1590 } 1591 if (loopPeriod > 0 && loopPeriod < minFrames) { 1592 minFrames = loopPeriod; 1593 } 1594 if (updatePeriod > 0 && updatePeriod < minFrames) { 1595 minFrames = updatePeriod; 1596 } 1597 1598 // If > 0, poll periodically to recover from a stuck server. A good value is 2. 1599 static const uint32_t kPoll = 0; 1600 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) { 1601 minFrames = kPoll * notificationFrames; 1602 } 1603 1604 // Convert frame units to time units 1605 nsecs_t ns = NS_WHENEVER; 1606 if (minFrames != (uint32_t) ~0) { 1607 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server 1608 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms 1609 ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs; 1610 } 1611 1612 // If not supplying data by EVENT_MORE_DATA, then we're done 1613 if (mTransfer != TRANSFER_CALLBACK) { 1614 return ns; 1615 } 1616 1617 struct timespec timeout; 1618 const struct timespec *requested = &ClientProxy::kForever; 1619 if (ns != NS_WHENEVER) { 1620 timeout.tv_sec = ns / 1000000000LL; 1621 timeout.tv_nsec = ns % 1000000000LL; 1622 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000); 1623 requested = &timeout; 1624 } 1625 1626 while (mRemainingFrames > 0) { 1627 1628 Buffer audioBuffer; 1629 audioBuffer.frameCount = mRemainingFrames; 1630 size_t nonContig; 1631 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig); 1632 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0), 1633 "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount); 1634 requested = &ClientProxy::kNonBlocking; 1635 size_t avail = audioBuffer.frameCount + nonContig; 1636 ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d", 1637 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err); 1638 if (err != NO_ERROR) { 1639 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR || 1640 (isOffloaded() && (err == DEAD_OBJECT))) { 1641 return 0; 1642 } 1643 ALOGE("Error %d obtaining an audio buffer, giving up.", err); 1644 return NS_NEVER; 1645 } 1646 1647 if (mRetryOnPartialBuffer && !isOffloaded()) { 1648 mRetryOnPartialBuffer = false; 1649 if (avail < mRemainingFrames) { 1650 int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate; 1651 if (ns < 0 || myns < ns) { 1652 ns = myns; 1653 } 1654 return ns; 1655 } 1656 } 1657 1658 // Divide buffer size by 2 to take into account the expansion 1659 // due to 8 to 16 bit conversion: the callback must fill only half 1660 // of the destination buffer 1661 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1662 audioBuffer.size >>= 1; 1663 } 1664 1665 size_t reqSize = audioBuffer.size; 1666 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); 1667 size_t writtenSize = audioBuffer.size; 1668 1669 // Sanity check on returned size 1670 if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) { 1671 ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes", 1672 reqSize, (int) writtenSize); 1673 return NS_NEVER; 1674 } 1675 1676 if (writtenSize == 0) { 1677 // The callback is done filling buffers 1678 // Keep this thread going to handle timed events and 1679 // still try to get more data in intervals of WAIT_PERIOD_MS 1680 // but don't just loop and block the CPU, so wait 1681 return WAIT_PERIOD_MS * 1000000LL; 1682 } 1683 1684 if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) { 1685 // 8 to 16 bit conversion, note that source and destination are the same address 1686 memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize); 1687 audioBuffer.size <<= 1; 1688 } 1689 1690 size_t releasedFrames = audioBuffer.size / mFrameSizeAF; 1691 audioBuffer.frameCount = releasedFrames; 1692 mRemainingFrames -= releasedFrames; 1693 if (misalignment >= releasedFrames) { 1694 misalignment -= releasedFrames; 1695 } else { 1696 misalignment = 0; 1697 } 1698 1699 releaseBuffer(&audioBuffer); 1700 1701 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer 1702 // if callback doesn't like to accept the full chunk 1703 if (writtenSize < reqSize) { 1704 continue; 1705 } 1706 1707 // There could be enough non-contiguous frames available to satisfy the remaining request 1708 if (mRemainingFrames <= nonContig) { 1709 continue; 1710 } 1711 1712#if 0 1713 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a 1714 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA 1715 // that total to a sum == notificationFrames. 1716 if (0 < misalignment && misalignment <= mRemainingFrames) { 1717 mRemainingFrames = misalignment; 1718 return (mRemainingFrames * 1100000000LL) / sampleRate; 1719 } 1720#endif 1721 1722 } 1723 mRemainingFrames = notificationFrames; 1724 mRetryOnPartialBuffer = true; 1725 1726 // A lot has transpired since ns was calculated, so run again immediately and re-calculate 1727 return 0; 1728} 1729 1730status_t AudioTrack::restoreTrack_l(const char *from) 1731{ 1732 ALOGW("dead IAudioTrack, %s, creating a new one from %s()", 1733 isOffloaded_l() ? "Offloaded" : "PCM", from); 1734 ++mSequence; 1735 status_t result; 1736 1737 // refresh the audio configuration cache in this process to make sure we get new 1738 // output parameters in createTrack_l() 1739 AudioSystem::clearAudioConfigCache(); 1740 1741 if (isOffloaded_l()) { 1742 // FIXME re-creation of offloaded tracks is not yet implemented 1743 return DEAD_OBJECT; 1744 } 1745 1746 // if the new IAudioTrack is created, createTrack_l() will modify the 1747 // following member variables: mAudioTrack, mCblkMemory and mCblk. 1748 // It will also delete the strong references on previous IAudioTrack and IMemory 1749 1750 // take the frames that will be lost by track recreation into account in saved position 1751 size_t position = mProxy->getPosition() + mProxy->getFramesFilled(); 1752 size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0; 1753 result = createTrack_l(position /*epoch*/); 1754 1755 if (result == NO_ERROR) { 1756 // continue playback from last known position, but 1757 // don't attempt to restore loop after invalidation; it's difficult and not worthwhile 1758 if (mStaticProxy != NULL) { 1759 mLoopPeriod = 0; 1760 mStaticProxy->setLoop(bufferPosition, mFrameCount, 0); 1761 } 1762 // FIXME How do we simulate the fact that all frames present in the buffer at the time of 1763 // track destruction have been played? This is critical for SoundPool implementation 1764 // This must be broken, and needs to be tested/debugged. 1765#if 0 1766 // restore write index and set other indexes to reflect empty buffer status 1767 if (!strcmp(from, "start")) { 1768 // Make sure that a client relying on callback events indicating underrun or 1769 // the actual amount of audio frames played (e.g SoundPool) receives them. 1770 if (mSharedBuffer == 0) { 1771 // restart playback even if buffer is not completely filled. 1772 android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags); 1773 } 1774 } 1775#endif 1776 if (mState == STATE_ACTIVE) { 1777 result = mAudioTrack->start(); 1778 } 1779 } 1780 if (result != NO_ERROR) { 1781 // Use of direct and offloaded output streams is ref counted by audio policy manager. 1782#if 0 // FIXME This should no longer be needed 1783 //Use of direct and offloaded output streams is ref counted by audio policy manager. 1784 // As getOutput was called above and resulted in an output stream to be opened, 1785 // we need to release it. 1786 if (mOutput != 0) { 1787 AudioSystem::releaseOutput(mOutput); 1788 mOutput = 0; 1789 } 1790#endif 1791 ALOGW("restoreTrack_l() failed status %d", result); 1792 mState = STATE_STOPPED; 1793 } 1794 1795 return result; 1796} 1797 1798status_t AudioTrack::setParameters(const String8& keyValuePairs) 1799{ 1800 AutoMutex lock(mLock); 1801 return mAudioTrack->setParameters(keyValuePairs); 1802} 1803 1804status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp) 1805{ 1806 AutoMutex lock(mLock); 1807 // FIXME not implemented for fast tracks; should use proxy and SSQ 1808 if (mFlags & AUDIO_OUTPUT_FLAG_FAST) { 1809 return INVALID_OPERATION; 1810 } 1811 if (mState != STATE_ACTIVE && mState != STATE_PAUSED) { 1812 return INVALID_OPERATION; 1813 } 1814 status_t status = mAudioTrack->getTimestamp(timestamp); 1815 if (status == NO_ERROR) { 1816 timestamp.mPosition += mProxy->getEpoch(); 1817 } 1818 return status; 1819} 1820 1821String8 AudioTrack::getParameters(const String8& keys) 1822{ 1823 audio_io_handle_t output = getOutput(); 1824 if (output != 0) { 1825 return AudioSystem::getParameters(output, keys); 1826 } else { 1827 return String8::empty(); 1828 } 1829} 1830 1831bool AudioTrack::isOffloaded() const 1832{ 1833 AutoMutex lock(mLock); 1834 return isOffloaded_l(); 1835} 1836 1837status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const 1838{ 1839 1840 const size_t SIZE = 256; 1841 char buffer[SIZE]; 1842 String8 result; 1843 1844 result.append(" AudioTrack::dump\n"); 1845 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, 1846 mVolume[0], mVolume[1]); 1847 result.append(buffer); 1848 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%zu)\n", mFormat, 1849 mChannelCount, mFrameCount); 1850 result.append(buffer); 1851 snprintf(buffer, 255, " sample rate(%u), status(%d)\n", mSampleRate, mStatus); 1852 result.append(buffer); 1853 snprintf(buffer, 255, " state(%d), latency (%d)\n", mState, mLatency); 1854 result.append(buffer); 1855 ::write(fd, result.string(), result.size()); 1856 return NO_ERROR; 1857} 1858 1859uint32_t AudioTrack::getUnderrunFrames() const 1860{ 1861 AutoMutex lock(mLock); 1862 return mProxy->getUnderrunFrames(); 1863} 1864 1865// ========================================================================= 1866 1867void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused) 1868{ 1869 sp<AudioTrack> audioTrack = mAudioTrack.promote(); 1870 if (audioTrack != 0) { 1871 AutoMutex lock(audioTrack->mLock); 1872 audioTrack->mProxy->binderDied(); 1873 } 1874} 1875 1876// ========================================================================= 1877 1878AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava) 1879 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL), 1880 mIgnoreNextPausedInt(false) 1881{ 1882} 1883 1884AudioTrack::AudioTrackThread::~AudioTrackThread() 1885{ 1886} 1887 1888bool AudioTrack::AudioTrackThread::threadLoop() 1889{ 1890 { 1891 AutoMutex _l(mMyLock); 1892 if (mPaused) { 1893 mMyCond.wait(mMyLock); 1894 // caller will check for exitPending() 1895 return true; 1896 } 1897 if (mIgnoreNextPausedInt) { 1898 mIgnoreNextPausedInt = false; 1899 mPausedInt = false; 1900 } 1901 if (mPausedInt) { 1902 if (mPausedNs > 0) { 1903 (void) mMyCond.waitRelative(mMyLock, mPausedNs); 1904 } else { 1905 mMyCond.wait(mMyLock); 1906 } 1907 mPausedInt = false; 1908 return true; 1909 } 1910 } 1911 nsecs_t ns = mReceiver.processAudioBuffer(); 1912 switch (ns) { 1913 case 0: 1914 return true; 1915 case NS_INACTIVE: 1916 pauseInternal(); 1917 return true; 1918 case NS_NEVER: 1919 return false; 1920 case NS_WHENEVER: 1921 // FIXME increase poll interval, or make event-driven 1922 ns = 1000000000LL; 1923 // fall through 1924 default: 1925 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns); 1926 pauseInternal(ns); 1927 return true; 1928 } 1929} 1930 1931void AudioTrack::AudioTrackThread::requestExit() 1932{ 1933 // must be in this order to avoid a race condition 1934 Thread::requestExit(); 1935 resume(); 1936} 1937 1938void AudioTrack::AudioTrackThread::pause() 1939{ 1940 AutoMutex _l(mMyLock); 1941 mPaused = true; 1942} 1943 1944void AudioTrack::AudioTrackThread::resume() 1945{ 1946 AutoMutex _l(mMyLock); 1947 mIgnoreNextPausedInt = true; 1948 if (mPaused || mPausedInt) { 1949 mPaused = false; 1950 mPausedInt = false; 1951 mMyCond.signal(); 1952 } 1953} 1954 1955void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns) 1956{ 1957 AutoMutex _l(mMyLock); 1958 mPausedInt = true; 1959 mPausedNs = ns; 1960} 1961 1962}; // namespace android 1963