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