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