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