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