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