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