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