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