1 /* 2 ** 3 ** Copyright 2012, 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_TAG "AudioFlinger" 20 //#define LOG_NDEBUG 0 21 22 #include "Configuration.h" 23 #include <math.h> 24 #include <utils/Log.h> 25 26 #include <private/media/AudioTrackShared.h> 27 28 #include <common_time/cc_helper.h> 29 #include <common_time/local_clock.h> 30 31 #include "AudioMixer.h" 32 #include "AudioFlinger.h" 33 #include "ServiceUtilities.h" 34 35 #include <media/nbaio/Pipe.h> 36 #include <media/nbaio/PipeReader.h> 37 38 // ---------------------------------------------------------------------------- 39 40 // Note: the following macro is used for extremely verbose logging message. In 41 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 42 // 0; but one side effect of this is to turn all LOGV's as well. Some messages 43 // are so verbose that we want to suppress them even when we have ALOG_ASSERT 44 // turned on. Do not uncomment the #def below unless you really know what you 45 // are doing and want to see all of the extremely verbose messages. 46 //#define VERY_VERY_VERBOSE_LOGGING 47 #ifdef VERY_VERY_VERBOSE_LOGGING 48 #define ALOGVV ALOGV 49 #else 50 #define ALOGVV(a...) do { } while(0) 51 #endif 52 53 namespace android { 54 55 // ---------------------------------------------------------------------------- 56 // TrackBase 57 // ---------------------------------------------------------------------------- 58 59 static volatile int32_t nextTrackId = 55; 60 61 // TrackBase constructor must be called with AudioFlinger::mLock held 62 AudioFlinger::ThreadBase::TrackBase::TrackBase( 63 ThreadBase *thread, 64 const sp<Client>& client, 65 uint32_t sampleRate, 66 audio_format_t format, 67 audio_channel_mask_t channelMask, 68 size_t frameCount, 69 const sp<IMemory>& sharedBuffer, 70 int sessionId, 71 bool isOut) 72 : RefBase(), 73 mThread(thread), 74 mClient(client), 75 mCblk(NULL), 76 // mBuffer 77 mState(IDLE), 78 mSampleRate(sampleRate), 79 mFormat(format), 80 mChannelMask(channelMask), 81 mChannelCount(popcount(channelMask)), 82 mFrameSize(audio_is_linear_pcm(format) ? 83 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)), 84 mFrameCount(frameCount), 85 mSessionId(sessionId), 86 mIsOut(isOut), 87 mServerProxy(NULL), 88 mId(android_atomic_inc(&nextTrackId)), 89 mTerminated(false) 90 { 91 // client == 0 implies sharedBuffer == 0 92 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0)); 93 94 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), 95 sharedBuffer->size()); 96 97 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize); 98 size_t size = sizeof(audio_track_cblk_t); 99 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize; 100 if (sharedBuffer == 0) { 101 size += bufferSize; 102 } 103 104 if (client != 0) { 105 mCblkMemory = client->heap()->allocate(size); 106 if (mCblkMemory != 0) { 107 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer()); 108 // can't assume mCblk != NULL 109 } else { 110 ALOGE("not enough memory for AudioTrack size=%u", size); 111 client->heap()->dump("AudioTrack"); 112 return; 113 } 114 } else { 115 // this syntax avoids calling the audio_track_cblk_t constructor twice 116 mCblk = (audio_track_cblk_t *) new uint8_t[size]; 117 // assume mCblk != NULL 118 } 119 120 // construct the shared structure in-place. 121 if (mCblk != NULL) { 122 new(mCblk) audio_track_cblk_t(); 123 // clear all buffers 124 mCblk->frameCount_ = frameCount; 125 if (sharedBuffer == 0) { 126 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); 127 memset(mBuffer, 0, bufferSize); 128 } else { 129 mBuffer = sharedBuffer->pointer(); 130 #if 0 131 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic 132 #endif 133 } 134 135 #ifdef TEE_SINK 136 if (mTeeSinkTrackEnabled) { 137 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount); 138 if (pipeFormat != Format_Invalid) { 139 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat); 140 size_t numCounterOffers = 0; 141 const NBAIO_Format offers[1] = {pipeFormat}; 142 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 143 ALOG_ASSERT(index == 0); 144 PipeReader *pipeReader = new PipeReader(*pipe); 145 numCounterOffers = 0; 146 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 147 ALOG_ASSERT(index == 0); 148 mTeeSink = pipe; 149 mTeeSource = pipeReader; 150 } 151 } 152 #endif 153 154 } 155 } 156 157 AudioFlinger::ThreadBase::TrackBase::~TrackBase() 158 { 159 #ifdef TEE_SINK 160 dumpTee(-1, mTeeSource, mId); 161 #endif 162 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference 163 delete mServerProxy; 164 if (mCblk != NULL) { 165 if (mClient == 0) { 166 delete mCblk; 167 } else { 168 mCblk->~audio_track_cblk_t(); // destroy our shared-structure. 169 } 170 } 171 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 172 if (mClient != 0) { 173 // Client destructor must run with AudioFlinger mutex locked 174 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 175 // If the client's reference count drops to zero, the associated destructor 176 // must run with AudioFlinger lock held. Thus the explicit clear() rather than 177 // relying on the automatic clear() at end of scope. 178 mClient.clear(); 179 } 180 } 181 182 // AudioBufferProvider interface 183 // getNextBuffer() = 0; 184 // This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack 185 void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) 186 { 187 #ifdef TEE_SINK 188 if (mTeeSink != 0) { 189 (void) mTeeSink->write(buffer->raw, buffer->frameCount); 190 } 191 #endif 192 193 ServerProxy::Buffer buf; 194 buf.mFrameCount = buffer->frameCount; 195 buf.mRaw = buffer->raw; 196 buffer->frameCount = 0; 197 buffer->raw = NULL; 198 mServerProxy->releaseBuffer(&buf); 199 } 200 201 status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event) 202 { 203 mSyncEvents.add(event); 204 return NO_ERROR; 205 } 206 207 // ---------------------------------------------------------------------------- 208 // Playback 209 // ---------------------------------------------------------------------------- 210 211 AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track) 212 : BnAudioTrack(), 213 mTrack(track) 214 { 215 } 216 217 AudioFlinger::TrackHandle::~TrackHandle() { 218 // just stop the track on deletion, associated resources 219 // will be freed from the main thread once all pending buffers have 220 // been played. Unless it's not in the active track list, in which 221 // case we free everything now... 222 mTrack->destroy(); 223 } 224 225 sp<IMemory> AudioFlinger::TrackHandle::getCblk() const { 226 return mTrack->getCblk(); 227 } 228 229 status_t AudioFlinger::TrackHandle::start() { 230 return mTrack->start(); 231 } 232 233 void AudioFlinger::TrackHandle::stop() { 234 mTrack->stop(); 235 } 236 237 void AudioFlinger::TrackHandle::flush() { 238 mTrack->flush(); 239 } 240 241 void AudioFlinger::TrackHandle::pause() { 242 mTrack->pause(); 243 } 244 245 status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId) 246 { 247 return mTrack->attachAuxEffect(EffectId); 248 } 249 250 status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size, 251 sp<IMemory>* buffer) { 252 if (!mTrack->isTimedTrack()) 253 return INVALID_OPERATION; 254 255 PlaybackThread::TimedTrack* tt = 256 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 257 return tt->allocateTimedBuffer(size, buffer); 258 } 259 260 status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer, 261 int64_t pts) { 262 if (!mTrack->isTimedTrack()) 263 return INVALID_OPERATION; 264 265 PlaybackThread::TimedTrack* tt = 266 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 267 return tt->queueTimedBuffer(buffer, pts); 268 } 269 270 status_t AudioFlinger::TrackHandle::setMediaTimeTransform( 271 const LinearTransform& xform, int target) { 272 273 if (!mTrack->isTimedTrack()) 274 return INVALID_OPERATION; 275 276 PlaybackThread::TimedTrack* tt = 277 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 278 return tt->setMediaTimeTransform( 279 xform, static_cast<TimedAudioTrack::TargetTimeline>(target)); 280 } 281 282 status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) { 283 return mTrack->setParameters(keyValuePairs); 284 } 285 286 status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp) 287 { 288 return mTrack->getTimestamp(timestamp); 289 } 290 291 292 void AudioFlinger::TrackHandle::signal() 293 { 294 return mTrack->signal(); 295 } 296 297 status_t AudioFlinger::TrackHandle::onTransact( 298 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 299 { 300 return BnAudioTrack::onTransact(code, data, reply, flags); 301 } 302 303 // ---------------------------------------------------------------------------- 304 305 // Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held 306 AudioFlinger::PlaybackThread::Track::Track( 307 PlaybackThread *thread, 308 const sp<Client>& client, 309 audio_stream_type_t streamType, 310 uint32_t sampleRate, 311 audio_format_t format, 312 audio_channel_mask_t channelMask, 313 size_t frameCount, 314 const sp<IMemory>& sharedBuffer, 315 int sessionId, 316 IAudioFlinger::track_flags_t flags) 317 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, 318 sessionId, true /*isOut*/), 319 mFillingUpStatus(FS_INVALID), 320 // mRetryCount initialized later when needed 321 mSharedBuffer(sharedBuffer), 322 mStreamType(streamType), 323 mName(-1), // see note below 324 mMainBuffer(thread->mixBuffer()), 325 mAuxBuffer(NULL), 326 mAuxEffectId(0), mHasVolumeController(false), 327 mPresentationCompleteFrames(0), 328 mFlags(flags), 329 mFastIndex(-1), 330 mCachedVolume(1.0), 331 mIsInvalid(false), 332 mAudioTrackServerProxy(NULL), 333 mResumeToStopping(false) 334 { 335 if (mCblk != NULL) { 336 if (sharedBuffer == 0) { 337 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount, 338 mFrameSize); 339 } else { 340 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount, 341 mFrameSize); 342 } 343 mServerProxy = mAudioTrackServerProxy; 344 // to avoid leaking a track name, do not allocate one unless there is an mCblk 345 mName = thread->getTrackName_l(channelMask, sessionId); 346 if (mName < 0) { 347 ALOGE("no more track names available"); 348 return; 349 } 350 // only allocate a fast track index if we were able to allocate a normal track name 351 if (flags & IAudioFlinger::TRACK_FAST) { 352 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads(); 353 ALOG_ASSERT(thread->mFastTrackAvailMask != 0); 354 int i = __builtin_ctz(thread->mFastTrackAvailMask); 355 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks); 356 // FIXME This is too eager. We allocate a fast track index before the 357 // fast track becomes active. Since fast tracks are a scarce resource, 358 // this means we are potentially denying other more important fast tracks from 359 // being created. It would be better to allocate the index dynamically. 360 mFastIndex = i; 361 // Read the initial underruns because this field is never cleared by the fast mixer 362 mObservedUnderruns = thread->getFastTrackUnderruns(i); 363 thread->mFastTrackAvailMask &= ~(1 << i); 364 } 365 } 366 ALOGV("Track constructor name %d, calling pid %d", mName, 367 IPCThreadState::self()->getCallingPid()); 368 } 369 370 AudioFlinger::PlaybackThread::Track::~Track() 371 { 372 ALOGV("PlaybackThread::Track destructor"); 373 374 // The destructor would clear mSharedBuffer, 375 // but it will not push the decremented reference count, 376 // leaving the client's IMemory dangling indefinitely. 377 // This prevents that leak. 378 if (mSharedBuffer != 0) { 379 mSharedBuffer.clear(); 380 // flush the binder command buffer 381 IPCThreadState::self()->flushCommands(); 382 } 383 } 384 385 void AudioFlinger::PlaybackThread::Track::destroy() 386 { 387 // NOTE: destroyTrack_l() can remove a strong reference to this Track 388 // by removing it from mTracks vector, so there is a risk that this Tracks's 389 // destructor is called. As the destructor needs to lock mLock, 390 // we must acquire a strong reference on this Track before locking mLock 391 // here so that the destructor is called only when exiting this function. 392 // On the other hand, as long as Track::destroy() is only called by 393 // TrackHandle destructor, the TrackHandle still holds a strong ref on 394 // this Track with its member mTrack. 395 sp<Track> keep(this); 396 { // scope for mLock 397 sp<ThreadBase> thread = mThread.promote(); 398 if (thread != 0) { 399 Mutex::Autolock _l(thread->mLock); 400 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 401 bool wasActive = playbackThread->destroyTrack_l(this); 402 if (!isOutputTrack() && !wasActive) { 403 AudioSystem::releaseOutput(thread->id()); 404 } 405 } 406 } 407 } 408 409 /*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result) 410 { 411 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate " 412 "L dB R dB Server Main buf Aux Buf Flags UndFrmCnt\n"); 413 } 414 415 void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size) 416 { 417 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR(); 418 if (isFastTrack()) { 419 sprintf(buffer, " F %2d", mFastIndex); 420 } else { 421 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0); 422 } 423 track_state state = mState; 424 char stateChar; 425 if (isTerminated()) { 426 stateChar = 'T'; 427 } else { 428 switch (state) { 429 case IDLE: 430 stateChar = 'I'; 431 break; 432 case STOPPING_1: 433 stateChar = 's'; 434 break; 435 case STOPPING_2: 436 stateChar = '5'; 437 break; 438 case STOPPED: 439 stateChar = 'S'; 440 break; 441 case RESUMING: 442 stateChar = 'R'; 443 break; 444 case ACTIVE: 445 stateChar = 'A'; 446 break; 447 case PAUSING: 448 stateChar = 'p'; 449 break; 450 case PAUSED: 451 stateChar = 'P'; 452 break; 453 case FLUSHED: 454 stateChar = 'F'; 455 break; 456 default: 457 stateChar = '?'; 458 break; 459 } 460 } 461 char nowInUnderrun; 462 switch (mObservedUnderruns.mBitFields.mMostRecent) { 463 case UNDERRUN_FULL: 464 nowInUnderrun = ' '; 465 break; 466 case UNDERRUN_PARTIAL: 467 nowInUnderrun = '<'; 468 break; 469 case UNDERRUN_EMPTY: 470 nowInUnderrun = '*'; 471 break; 472 default: 473 nowInUnderrun = '?'; 474 break; 475 } 476 snprintf(&buffer[7], size-7, " %6u %4u %08X %08X %7u %6u %1c %1d %5u %5.2g %5.2g " 477 "%08X %08X %08X 0x%03X %9u%c\n", 478 (mClient == 0) ? getpid_cached : mClient->pid(), 479 mStreamType, 480 mFormat, 481 mChannelMask, 482 mSessionId, 483 mFrameCount, 484 stateChar, 485 mFillingUpStatus, 486 mAudioTrackServerProxy->getSampleRate(), 487 20.0 * log10((vlr & 0xFFFF) / 4096.0), 488 20.0 * log10((vlr >> 16) / 4096.0), 489 mCblk->mServer, 490 (int)mMainBuffer, 491 (int)mAuxBuffer, 492 mCblk->mFlags, 493 mAudioTrackServerProxy->getUnderrunFrames(), 494 nowInUnderrun); 495 } 496 497 uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const { 498 return mAudioTrackServerProxy->getSampleRate(); 499 } 500 501 // AudioBufferProvider interface 502 status_t AudioFlinger::PlaybackThread::Track::getNextBuffer( 503 AudioBufferProvider::Buffer* buffer, int64_t pts) 504 { 505 ServerProxy::Buffer buf; 506 size_t desiredFrames = buffer->frameCount; 507 buf.mFrameCount = desiredFrames; 508 status_t status = mServerProxy->obtainBuffer(&buf); 509 buffer->frameCount = buf.mFrameCount; 510 buffer->raw = buf.mRaw; 511 if (buf.mFrameCount == 0) { 512 mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 513 } 514 return status; 515 } 516 517 // releaseBuffer() is not overridden 518 519 // ExtendedAudioBufferProvider interface 520 521 // Note that framesReady() takes a mutex on the control block using tryLock(). 522 // This could result in priority inversion if framesReady() is called by the normal mixer, 523 // as the normal mixer thread runs at lower 524 // priority than the client's callback thread: there is a short window within framesReady() 525 // during which the normal mixer could be preempted, and the client callback would block. 526 // Another problem can occur if framesReady() is called by the fast mixer: 527 // the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer. 528 // FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue. 529 size_t AudioFlinger::PlaybackThread::Track::framesReady() const { 530 return mAudioTrackServerProxy->framesReady(); 531 } 532 533 size_t AudioFlinger::PlaybackThread::Track::framesReleased() const 534 { 535 return mAudioTrackServerProxy->framesReleased(); 536 } 537 538 // Don't call for fast tracks; the framesReady() could result in priority inversion 539 bool AudioFlinger::PlaybackThread::Track::isReady() const { 540 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) { 541 return true; 542 } 543 544 if (framesReady() >= mFrameCount || 545 (mCblk->mFlags & CBLK_FORCEREADY)) { 546 mFillingUpStatus = FS_FILLED; 547 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags); 548 return true; 549 } 550 return false; 551 } 552 553 status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event, 554 int triggerSession) 555 { 556 status_t status = NO_ERROR; 557 ALOGV("start(%d), calling pid %d session %d", 558 mName, IPCThreadState::self()->getCallingPid(), mSessionId); 559 560 sp<ThreadBase> thread = mThread.promote(); 561 if (thread != 0) { 562 if (isOffloaded()) { 563 Mutex::Autolock _laf(thread->mAudioFlinger->mLock); 564 Mutex::Autolock _lth(thread->mLock); 565 sp<EffectChain> ec = thread->getEffectChain_l(mSessionId); 566 if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() || 567 (ec != 0 && ec->isNonOffloadableEnabled())) { 568 invalidate(); 569 return PERMISSION_DENIED; 570 } 571 } 572 Mutex::Autolock _lth(thread->mLock); 573 track_state state = mState; 574 // here the track could be either new, or restarted 575 // in both cases "unstop" the track 576 577 if (state == PAUSED) { 578 if (mResumeToStopping) { 579 // happened we need to resume to STOPPING_1 580 mState = TrackBase::STOPPING_1; 581 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this); 582 } else { 583 mState = TrackBase::RESUMING; 584 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this); 585 } 586 } else { 587 mState = TrackBase::ACTIVE; 588 ALOGV("? => ACTIVE (%d) on thread %p", mName, this); 589 } 590 591 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 592 status = playbackThread->addTrack_l(this); 593 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) { 594 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 595 // restore previous state if start was rejected by policy manager 596 if (status == PERMISSION_DENIED) { 597 mState = state; 598 } 599 } 600 // track was already in the active list, not a problem 601 if (status == ALREADY_EXISTS) { 602 status = NO_ERROR; 603 } else { 604 // Acknowledge any pending flush(), so that subsequent new data isn't discarded. 605 // It is usually unsafe to access the server proxy from a binder thread. 606 // But in this case we know the mixer thread (whether normal mixer or fast mixer) 607 // isn't looking at this track yet: we still hold the normal mixer thread lock, 608 // and for fast tracks the track is not yet in the fast mixer thread's active set. 609 ServerProxy::Buffer buffer; 610 buffer.mFrameCount = 1; 611 (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/); 612 } 613 } else { 614 status = BAD_VALUE; 615 } 616 return status; 617 } 618 619 void AudioFlinger::PlaybackThread::Track::stop() 620 { 621 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 622 sp<ThreadBase> thread = mThread.promote(); 623 if (thread != 0) { 624 Mutex::Autolock _l(thread->mLock); 625 track_state state = mState; 626 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) { 627 // If the track is not active (PAUSED and buffers full), flush buffers 628 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 629 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 630 reset(); 631 mState = STOPPED; 632 } else if (!isFastTrack() && !isOffloaded()) { 633 mState = STOPPED; 634 } else { 635 // For fast tracks prepareTracks_l() will set state to STOPPING_2 636 // presentation is complete 637 // For an offloaded track this starts a drain and state will 638 // move to STOPPING_2 when drain completes and then STOPPED 639 mState = STOPPING_1; 640 } 641 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, 642 playbackThread); 643 } 644 } 645 } 646 647 void AudioFlinger::PlaybackThread::Track::pause() 648 { 649 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 650 sp<ThreadBase> thread = mThread.promote(); 651 if (thread != 0) { 652 Mutex::Autolock _l(thread->mLock); 653 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 654 switch (mState) { 655 case STOPPING_1: 656 case STOPPING_2: 657 if (!isOffloaded()) { 658 /* nothing to do if track is not offloaded */ 659 break; 660 } 661 662 // Offloaded track was draining, we need to carry on draining when resumed 663 mResumeToStopping = true; 664 // fall through... 665 case ACTIVE: 666 case RESUMING: 667 mState = PAUSING; 668 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get()); 669 playbackThread->broadcast_l(); 670 break; 671 672 default: 673 break; 674 } 675 } 676 } 677 678 void AudioFlinger::PlaybackThread::Track::flush() 679 { 680 ALOGV("flush(%d)", mName); 681 sp<ThreadBase> thread = mThread.promote(); 682 if (thread != 0) { 683 Mutex::Autolock _l(thread->mLock); 684 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 685 686 if (isOffloaded()) { 687 // If offloaded we allow flush during any state except terminated 688 // and keep the track active to avoid problems if user is seeking 689 // rapidly and underlying hardware has a significant delay handling 690 // a pause 691 if (isTerminated()) { 692 return; 693 } 694 695 ALOGV("flush: offload flush"); 696 reset(); 697 698 if (mState == STOPPING_1 || mState == STOPPING_2) { 699 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE"); 700 mState = ACTIVE; 701 } 702 703 if (mState == ACTIVE) { 704 ALOGV("flush called in active state, resetting buffer time out retry count"); 705 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload; 706 } 707 708 mResumeToStopping = false; 709 } else { 710 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && 711 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) { 712 return; 713 } 714 // No point remaining in PAUSED state after a flush => go to 715 // FLUSHED state 716 mState = FLUSHED; 717 // do not reset the track if it is still in the process of being stopped or paused. 718 // this will be done by prepareTracks_l() when the track is stopped. 719 // prepareTracks_l() will see mState == FLUSHED, then 720 // remove from active track list, reset(), and trigger presentation complete 721 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 722 reset(); 723 } 724 } 725 // Prevent flush being lost if the track is flushed and then resumed 726 // before mixer thread can run. This is important when offloading 727 // because the hardware buffer could hold a large amount of audio 728 playbackThread->flushOutput_l(); 729 playbackThread->broadcast_l(); 730 } 731 } 732 733 void AudioFlinger::PlaybackThread::Track::reset() 734 { 735 // Do not reset twice to avoid discarding data written just after a flush and before 736 // the audioflinger thread detects the track is stopped. 737 if (!mResetDone) { 738 // Force underrun condition to avoid false underrun callback until first data is 739 // written to buffer 740 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags); 741 mFillingUpStatus = FS_FILLING; 742 mResetDone = true; 743 if (mState == FLUSHED) { 744 mState = IDLE; 745 } 746 } 747 } 748 749 status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs) 750 { 751 sp<ThreadBase> thread = mThread.promote(); 752 if (thread == 0) { 753 ALOGE("thread is dead"); 754 return FAILED_TRANSACTION; 755 } else if ((thread->type() == ThreadBase::DIRECT) || 756 (thread->type() == ThreadBase::OFFLOAD)) { 757 return thread->setParameters(keyValuePairs); 758 } else { 759 return PERMISSION_DENIED; 760 } 761 } 762 763 status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp) 764 { 765 // Client should implement this using SSQ; the unpresented frame count in latch is irrelevant 766 if (isFastTrack()) { 767 return INVALID_OPERATION; 768 } 769 sp<ThreadBase> thread = mThread.promote(); 770 if (thread == 0) { 771 return INVALID_OPERATION; 772 } 773 Mutex::Autolock _l(thread->mLock); 774 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 775 if (!isOffloaded()) { 776 if (!playbackThread->mLatchQValid) { 777 return INVALID_OPERATION; 778 } 779 uint32_t unpresentedFrames = 780 ((int64_t) playbackThread->mLatchQ.mUnpresentedFrames * mSampleRate) / 781 playbackThread->mSampleRate; 782 uint32_t framesWritten = mAudioTrackServerProxy->framesReleased(); 783 if (framesWritten < unpresentedFrames) { 784 return INVALID_OPERATION; 785 } 786 timestamp.mPosition = framesWritten - unpresentedFrames; 787 timestamp.mTime = playbackThread->mLatchQ.mTimestamp.mTime; 788 return NO_ERROR; 789 } 790 791 return playbackThread->getTimestamp_l(timestamp); 792 } 793 794 status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId) 795 { 796 status_t status = DEAD_OBJECT; 797 sp<ThreadBase> thread = mThread.promote(); 798 if (thread != 0) { 799 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 800 sp<AudioFlinger> af = mClient->audioFlinger(); 801 802 Mutex::Autolock _l(af->mLock); 803 804 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 805 806 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) { 807 Mutex::Autolock _dl(playbackThread->mLock); 808 Mutex::Autolock _sl(srcThread->mLock); 809 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 810 if (chain == 0) { 811 return INVALID_OPERATION; 812 } 813 814 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId); 815 if (effect == 0) { 816 return INVALID_OPERATION; 817 } 818 srcThread->removeEffect_l(effect); 819 status = playbackThread->addEffect_l(effect); 820 if (status != NO_ERROR) { 821 srcThread->addEffect_l(effect); 822 return INVALID_OPERATION; 823 } 824 // removeEffect_l() has stopped the effect if it was active so it must be restarted 825 if (effect->state() == EffectModule::ACTIVE || 826 effect->state() == EffectModule::STOPPING) { 827 effect->start(); 828 } 829 830 sp<EffectChain> dstChain = effect->chain().promote(); 831 if (dstChain == 0) { 832 srcThread->addEffect_l(effect); 833 return INVALID_OPERATION; 834 } 835 AudioSystem::unregisterEffect(effect->id()); 836 AudioSystem::registerEffect(&effect->desc(), 837 srcThread->id(), 838 dstChain->strategy(), 839 AUDIO_SESSION_OUTPUT_MIX, 840 effect->id()); 841 } 842 status = playbackThread->attachAuxEffect(this, EffectId); 843 } 844 return status; 845 } 846 847 void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer) 848 { 849 mAuxEffectId = EffectId; 850 mAuxBuffer = buffer; 851 } 852 853 bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten, 854 size_t audioHalFrames) 855 { 856 // a track is considered presented when the total number of frames written to audio HAL 857 // corresponds to the number of frames written when presentationComplete() is called for the 858 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time. 859 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used 860 // to detect when all frames have been played. In this case framesWritten isn't 861 // useful because it doesn't always reflect whether there is data in the h/w 862 // buffers, particularly if a track has been paused and resumed during draining 863 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d", 864 mPresentationCompleteFrames, framesWritten); 865 if (mPresentationCompleteFrames == 0) { 866 mPresentationCompleteFrames = framesWritten + audioHalFrames; 867 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d", 868 mPresentationCompleteFrames, audioHalFrames); 869 } 870 871 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) { 872 ALOGV("presentationComplete() session %d complete: framesWritten %d", 873 mSessionId, framesWritten); 874 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 875 mAudioTrackServerProxy->setStreamEndDone(); 876 return true; 877 } 878 return false; 879 } 880 881 void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type) 882 { 883 for (int i = 0; i < (int)mSyncEvents.size(); i++) { 884 if (mSyncEvents[i]->type() == type) { 885 mSyncEvents[i]->trigger(); 886 mSyncEvents.removeAt(i); 887 i--; 888 } 889 } 890 } 891 892 // implement VolumeBufferProvider interface 893 894 uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR() 895 { 896 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs 897 ALOG_ASSERT(isFastTrack() && (mCblk != NULL)); 898 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR(); 899 uint32_t vl = vlr & 0xFFFF; 900 uint32_t vr = vlr >> 16; 901 // track volumes come from shared memory, so can't be trusted and must be clamped 902 if (vl > MAX_GAIN_INT) { 903 vl = MAX_GAIN_INT; 904 } 905 if (vr > MAX_GAIN_INT) { 906 vr = MAX_GAIN_INT; 907 } 908 // now apply the cached master volume and stream type volume; 909 // this is trusted but lacks any synchronization or barrier so may be stale 910 float v = mCachedVolume; 911 vl *= v; 912 vr *= v; 913 // re-combine into U4.16 914 vlr = (vr << 16) | (vl & 0xFFFF); 915 // FIXME look at mute, pause, and stop flags 916 return vlr; 917 } 918 919 status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event) 920 { 921 if (isTerminated() || mState == PAUSED || 922 ((framesReady() == 0) && ((mSharedBuffer != 0) || 923 (mState == STOPPED)))) { 924 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ", 925 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady()); 926 event->cancel(); 927 return INVALID_OPERATION; 928 } 929 (void) TrackBase::setSyncEvent(event); 930 return NO_ERROR; 931 } 932 933 void AudioFlinger::PlaybackThread::Track::invalidate() 934 { 935 // FIXME should use proxy, and needs work 936 audio_track_cblk_t* cblk = mCblk; 937 android_atomic_or(CBLK_INVALID, &cblk->mFlags); 938 android_atomic_release_store(0x40000000, &cblk->mFutex); 939 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE 940 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX); 941 mIsInvalid = true; 942 } 943 944 void AudioFlinger::PlaybackThread::Track::signal() 945 { 946 sp<ThreadBase> thread = mThread.promote(); 947 if (thread != 0) { 948 PlaybackThread *t = (PlaybackThread *)thread.get(); 949 Mutex::Autolock _l(t->mLock); 950 t->broadcast_l(); 951 } 952 } 953 954 // ---------------------------------------------------------------------------- 955 956 sp<AudioFlinger::PlaybackThread::TimedTrack> 957 AudioFlinger::PlaybackThread::TimedTrack::create( 958 PlaybackThread *thread, 959 const sp<Client>& client, 960 audio_stream_type_t streamType, 961 uint32_t sampleRate, 962 audio_format_t format, 963 audio_channel_mask_t channelMask, 964 size_t frameCount, 965 const sp<IMemory>& sharedBuffer, 966 int sessionId) { 967 if (!client->reserveTimedTrack()) 968 return 0; 969 970 return new TimedTrack( 971 thread, client, streamType, sampleRate, format, channelMask, frameCount, 972 sharedBuffer, sessionId); 973 } 974 975 AudioFlinger::PlaybackThread::TimedTrack::TimedTrack( 976 PlaybackThread *thread, 977 const sp<Client>& client, 978 audio_stream_type_t streamType, 979 uint32_t sampleRate, 980 audio_format_t format, 981 audio_channel_mask_t channelMask, 982 size_t frameCount, 983 const sp<IMemory>& sharedBuffer, 984 int sessionId) 985 : Track(thread, client, streamType, sampleRate, format, channelMask, 986 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED), 987 mQueueHeadInFlight(false), 988 mTrimQueueHeadOnRelease(false), 989 mFramesPendingInQueue(0), 990 mTimedSilenceBuffer(NULL), 991 mTimedSilenceBufferSize(0), 992 mTimedAudioOutputOnTime(false), 993 mMediaTimeTransformValid(false) 994 { 995 LocalClock lc; 996 mLocalTimeFreq = lc.getLocalFreq(); 997 998 mLocalTimeToSampleTransform.a_zero = 0; 999 mLocalTimeToSampleTransform.b_zero = 0; 1000 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate; 1001 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq; 1002 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer, 1003 &mLocalTimeToSampleTransform.a_to_b_denom); 1004 1005 mMediaTimeToSampleTransform.a_zero = 0; 1006 mMediaTimeToSampleTransform.b_zero = 0; 1007 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate; 1008 mMediaTimeToSampleTransform.a_to_b_denom = 1000000; 1009 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer, 1010 &mMediaTimeToSampleTransform.a_to_b_denom); 1011 } 1012 1013 AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() { 1014 mClient->releaseTimedTrack(); 1015 delete [] mTimedSilenceBuffer; 1016 } 1017 1018 status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer( 1019 size_t size, sp<IMemory>* buffer) { 1020 1021 Mutex::Autolock _l(mTimedBufferQueueLock); 1022 1023 trimTimedBufferQueue_l(); 1024 1025 // lazily initialize the shared memory heap for timed buffers 1026 if (mTimedMemoryDealer == NULL) { 1027 const int kTimedBufferHeapSize = 512 << 10; 1028 1029 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize, 1030 "AudioFlingerTimed"); 1031 if (mTimedMemoryDealer == NULL) 1032 return NO_MEMORY; 1033 } 1034 1035 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size); 1036 if (newBuffer == NULL) { 1037 newBuffer = mTimedMemoryDealer->allocate(size); 1038 if (newBuffer == NULL) 1039 return NO_MEMORY; 1040 } 1041 1042 *buffer = newBuffer; 1043 return NO_ERROR; 1044 } 1045 1046 // caller must hold mTimedBufferQueueLock 1047 void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() { 1048 int64_t mediaTimeNow; 1049 { 1050 Mutex::Autolock mttLock(mMediaTimeTransformLock); 1051 if (!mMediaTimeTransformValid) 1052 return; 1053 1054 int64_t targetTimeNow; 1055 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) 1056 ? mCCHelper.getCommonTime(&targetTimeNow) 1057 : mCCHelper.getLocalTime(&targetTimeNow); 1058 1059 if (OK != res) 1060 return; 1061 1062 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow, 1063 &mediaTimeNow)) { 1064 return; 1065 } 1066 } 1067 1068 size_t trimEnd; 1069 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) { 1070 int64_t bufEnd; 1071 1072 if ((trimEnd + 1) < mTimedBufferQueue.size()) { 1073 // We have a next buffer. Just use its PTS as the PTS of the frame 1074 // following the last frame in this buffer. If the stream is sparse 1075 // (ie, there are deliberate gaps left in the stream which should be 1076 // filled with silence by the TimedAudioTrack), then this can result 1077 // in one extra buffer being left un-trimmed when it could have 1078 // been. In general, this is not typical, and we would rather 1079 // optimized away the TS calculation below for the more common case 1080 // where PTSes are contiguous. 1081 bufEnd = mTimedBufferQueue[trimEnd + 1].pts(); 1082 } else { 1083 // We have no next buffer. Compute the PTS of the frame following 1084 // the last frame in this buffer by computing the duration of of 1085 // this frame in media time units and adding it to the PTS of the 1086 // buffer. 1087 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size() 1088 / mFrameSize; 1089 1090 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount, 1091 &bufEnd)) { 1092 ALOGE("Failed to convert frame count of %lld to media time" 1093 " duration" " (scale factor %d/%u) in %s", 1094 frameCount, 1095 mMediaTimeToSampleTransform.a_to_b_numer, 1096 mMediaTimeToSampleTransform.a_to_b_denom, 1097 __PRETTY_FUNCTION__); 1098 break; 1099 } 1100 bufEnd += mTimedBufferQueue[trimEnd].pts(); 1101 } 1102 1103 if (bufEnd > mediaTimeNow) 1104 break; 1105 1106 // Is the buffer we want to use in the middle of a mix operation right 1107 // now? If so, don't actually trim it. Just wait for the releaseBuffer 1108 // from the mixer which should be coming back shortly. 1109 if (!trimEnd && mQueueHeadInFlight) { 1110 mTrimQueueHeadOnRelease = true; 1111 } 1112 } 1113 1114 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0; 1115 if (trimStart < trimEnd) { 1116 // Update the bookkeeping for framesReady() 1117 for (size_t i = trimStart; i < trimEnd; ++i) { 1118 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim"); 1119 } 1120 1121 // Now actually remove the buffers from the queue. 1122 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd); 1123 } 1124 } 1125 1126 void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l( 1127 const char* logTag) { 1128 ALOG_ASSERT(mTimedBufferQueue.size() > 0, 1129 "%s called (reason \"%s\"), but timed buffer queue has no" 1130 " elements to trim.", __FUNCTION__, logTag); 1131 1132 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag); 1133 mTimedBufferQueue.removeAt(0); 1134 } 1135 1136 void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l( 1137 const TimedBuffer& buf, 1138 const char* logTag) { 1139 uint32_t bufBytes = buf.buffer()->size(); 1140 uint32_t consumedAlready = buf.position(); 1141 1142 ALOG_ASSERT(consumedAlready <= bufBytes, 1143 "Bad bookkeeping while updating frames pending. Timed buffer is" 1144 " only %u bytes long, but claims to have consumed %u" 1145 " bytes. (update reason: \"%s\")", 1146 bufBytes, consumedAlready, logTag); 1147 1148 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize; 1149 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames, 1150 "Bad bookkeeping while updating frames pending. Should have at" 1151 " least %u queued frames, but we think we have only %u. (update" 1152 " reason: \"%s\")", 1153 bufFrames, mFramesPendingInQueue, logTag); 1154 1155 mFramesPendingInQueue -= bufFrames; 1156 } 1157 1158 status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer( 1159 const sp<IMemory>& buffer, int64_t pts) { 1160 1161 { 1162 Mutex::Autolock mttLock(mMediaTimeTransformLock); 1163 if (!mMediaTimeTransformValid) 1164 return INVALID_OPERATION; 1165 } 1166 1167 Mutex::Autolock _l(mTimedBufferQueueLock); 1168 1169 uint32_t bufFrames = buffer->size() / mFrameSize; 1170 mFramesPendingInQueue += bufFrames; 1171 mTimedBufferQueue.add(TimedBuffer(buffer, pts)); 1172 1173 return NO_ERROR; 1174 } 1175 1176 status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform( 1177 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) { 1178 1179 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d", 1180 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom, 1181 target); 1182 1183 if (!(target == TimedAudioTrack::LOCAL_TIME || 1184 target == TimedAudioTrack::COMMON_TIME)) { 1185 return BAD_VALUE; 1186 } 1187 1188 Mutex::Autolock lock(mMediaTimeTransformLock); 1189 mMediaTimeTransform = xform; 1190 mMediaTimeTransformTarget = target; 1191 mMediaTimeTransformValid = true; 1192 1193 return NO_ERROR; 1194 } 1195 1196 #define min(a, b) ((a) < (b) ? (a) : (b)) 1197 1198 // implementation of getNextBuffer for tracks whose buffers have timestamps 1199 status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer( 1200 AudioBufferProvider::Buffer* buffer, int64_t pts) 1201 { 1202 if (pts == AudioBufferProvider::kInvalidPTS) { 1203 buffer->raw = NULL; 1204 buffer->frameCount = 0; 1205 mTimedAudioOutputOnTime = false; 1206 return INVALID_OPERATION; 1207 } 1208 1209 Mutex::Autolock _l(mTimedBufferQueueLock); 1210 1211 ALOG_ASSERT(!mQueueHeadInFlight, 1212 "getNextBuffer called without releaseBuffer!"); 1213 1214 while (true) { 1215 1216 // if we have no timed buffers, then fail 1217 if (mTimedBufferQueue.isEmpty()) { 1218 buffer->raw = NULL; 1219 buffer->frameCount = 0; 1220 return NOT_ENOUGH_DATA; 1221 } 1222 1223 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 1224 1225 // calculate the PTS of the head of the timed buffer queue expressed in 1226 // local time 1227 int64_t headLocalPTS; 1228 { 1229 Mutex::Autolock mttLock(mMediaTimeTransformLock); 1230 1231 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid"); 1232 1233 if (mMediaTimeTransform.a_to_b_denom == 0) { 1234 // the transform represents a pause, so yield silence 1235 timedYieldSilence_l(buffer->frameCount, buffer); 1236 return NO_ERROR; 1237 } 1238 1239 int64_t transformedPTS; 1240 if (!mMediaTimeTransform.doForwardTransform(head.pts(), 1241 &transformedPTS)) { 1242 // the transform failed. this shouldn't happen, but if it does 1243 // then just drop this buffer 1244 ALOGW("timedGetNextBuffer transform failed"); 1245 buffer->raw = NULL; 1246 buffer->frameCount = 0; 1247 trimTimedBufferQueueHead_l("getNextBuffer; no transform"); 1248 return NO_ERROR; 1249 } 1250 1251 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) { 1252 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS, 1253 &headLocalPTS)) { 1254 buffer->raw = NULL; 1255 buffer->frameCount = 0; 1256 return INVALID_OPERATION; 1257 } 1258 } else { 1259 headLocalPTS = transformedPTS; 1260 } 1261 } 1262 1263 uint32_t sr = sampleRate(); 1264 1265 // adjust the head buffer's PTS to reflect the portion of the head buffer 1266 // that has already been consumed 1267 int64_t effectivePTS = headLocalPTS + 1268 ((head.position() / mFrameSize) * mLocalTimeFreq / sr); 1269 1270 // Calculate the delta in samples between the head of the input buffer 1271 // queue and the start of the next output buffer that will be written. 1272 // If the transformation fails because of over or underflow, it means 1273 // that the sample's position in the output stream is so far out of 1274 // whack that it should just be dropped. 1275 int64_t sampleDelta; 1276 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) { 1277 ALOGV("*** head buffer is too far from PTS: dropped buffer"); 1278 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from" 1279 " mix"); 1280 continue; 1281 } 1282 if (!mLocalTimeToSampleTransform.doForwardTransform( 1283 (effectivePTS - pts) << 32, &sampleDelta)) { 1284 ALOGV("*** too late during sample rate transform: dropped buffer"); 1285 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample"); 1286 continue; 1287 } 1288 1289 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld" 1290 " sampleDelta=[%d.%08x]", 1291 head.pts(), head.position(), pts, 1292 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) 1293 + (sampleDelta >> 32)), 1294 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF)); 1295 1296 // if the delta between the ideal placement for the next input sample and 1297 // the current output position is within this threshold, then we will 1298 // concatenate the next input samples to the previous output 1299 const int64_t kSampleContinuityThreshold = 1300 (static_cast<int64_t>(sr) << 32) / 250; 1301 1302 // if this is the first buffer of audio that we're emitting from this track 1303 // then it should be almost exactly on time. 1304 const int64_t kSampleStartupThreshold = 1LL << 32; 1305 1306 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) || 1307 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) { 1308 // the next input is close enough to being on time, so concatenate it 1309 // with the last output 1310 timedYieldSamples_l(buffer); 1311 1312 ALOGVV("*** on time: head.pos=%d frameCount=%u", 1313 head.position(), buffer->frameCount); 1314 return NO_ERROR; 1315 } 1316 1317 // Looks like our output is not on time. Reset our on timed status. 1318 // Next time we mix samples from our input queue, then should be within 1319 // the StartupThreshold. 1320 mTimedAudioOutputOnTime = false; 1321 if (sampleDelta > 0) { 1322 // the gap between the current output position and the proper start of 1323 // the next input sample is too big, so fill it with silence 1324 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32; 1325 1326 timedYieldSilence_l(framesUntilNextInput, buffer); 1327 ALOGV("*** silence: frameCount=%u", buffer->frameCount); 1328 return NO_ERROR; 1329 } else { 1330 // the next input sample is late 1331 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32)); 1332 size_t onTimeSamplePosition = 1333 head.position() + lateFrames * mFrameSize; 1334 1335 if (onTimeSamplePosition > head.buffer()->size()) { 1336 // all the remaining samples in the head are too late, so 1337 // drop it and move on 1338 ALOGV("*** too late: dropped buffer"); 1339 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer"); 1340 continue; 1341 } else { 1342 // skip over the late samples 1343 head.setPosition(onTimeSamplePosition); 1344 1345 // yield the available samples 1346 timedYieldSamples_l(buffer); 1347 1348 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount); 1349 return NO_ERROR; 1350 } 1351 } 1352 } 1353 } 1354 1355 // Yield samples from the timed buffer queue head up to the given output 1356 // buffer's capacity. 1357 // 1358 // Caller must hold mTimedBufferQueueLock 1359 void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l( 1360 AudioBufferProvider::Buffer* buffer) { 1361 1362 const TimedBuffer& head = mTimedBufferQueue[0]; 1363 1364 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) + 1365 head.position()); 1366 1367 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) / 1368 mFrameSize); 1369 size_t framesRequested = buffer->frameCount; 1370 buffer->frameCount = min(framesLeftInHead, framesRequested); 1371 1372 mQueueHeadInFlight = true; 1373 mTimedAudioOutputOnTime = true; 1374 } 1375 1376 // Yield samples of silence up to the given output buffer's capacity 1377 // 1378 // Caller must hold mTimedBufferQueueLock 1379 void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l( 1380 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) { 1381 1382 // lazily allocate a buffer filled with silence 1383 if (mTimedSilenceBufferSize < numFrames * mFrameSize) { 1384 delete [] mTimedSilenceBuffer; 1385 mTimedSilenceBufferSize = numFrames * mFrameSize; 1386 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize]; 1387 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize); 1388 } 1389 1390 buffer->raw = mTimedSilenceBuffer; 1391 size_t framesRequested = buffer->frameCount; 1392 buffer->frameCount = min(numFrames, framesRequested); 1393 1394 mTimedAudioOutputOnTime = false; 1395 } 1396 1397 // AudioBufferProvider interface 1398 void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer( 1399 AudioBufferProvider::Buffer* buffer) { 1400 1401 Mutex::Autolock _l(mTimedBufferQueueLock); 1402 1403 // If the buffer which was just released is part of the buffer at the head 1404 // of the queue, be sure to update the amt of the buffer which has been 1405 // consumed. If the buffer being returned is not part of the head of the 1406 // queue, its either because the buffer is part of the silence buffer, or 1407 // because the head of the timed queue was trimmed after the mixer called 1408 // getNextBuffer but before the mixer called releaseBuffer. 1409 if (buffer->raw == mTimedSilenceBuffer) { 1410 ALOG_ASSERT(!mQueueHeadInFlight, 1411 "Queue head in flight during release of silence buffer!"); 1412 goto done; 1413 } 1414 1415 ALOG_ASSERT(mQueueHeadInFlight, 1416 "TimedTrack::releaseBuffer of non-silence buffer, but no queue" 1417 " head in flight."); 1418 1419 if (mTimedBufferQueue.size()) { 1420 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 1421 1422 void* start = head.buffer()->pointer(); 1423 void* end = reinterpret_cast<void*>( 1424 reinterpret_cast<uint8_t*>(head.buffer()->pointer()) 1425 + head.buffer()->size()); 1426 1427 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end), 1428 "released buffer not within the head of the timed buffer" 1429 " queue; qHead = [%p, %p], released buffer = %p", 1430 start, end, buffer->raw); 1431 1432 head.setPosition(head.position() + 1433 (buffer->frameCount * mFrameSize)); 1434 mQueueHeadInFlight = false; 1435 1436 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount, 1437 "Bad bookkeeping during releaseBuffer! Should have at" 1438 " least %u queued frames, but we think we have only %u", 1439 buffer->frameCount, mFramesPendingInQueue); 1440 1441 mFramesPendingInQueue -= buffer->frameCount; 1442 1443 if ((static_cast<size_t>(head.position()) >= head.buffer()->size()) 1444 || mTrimQueueHeadOnRelease) { 1445 trimTimedBufferQueueHead_l("releaseBuffer"); 1446 mTrimQueueHeadOnRelease = false; 1447 } 1448 } else { 1449 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no" 1450 " buffers in the timed buffer queue"); 1451 } 1452 1453 done: 1454 buffer->raw = 0; 1455 buffer->frameCount = 0; 1456 } 1457 1458 size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const { 1459 Mutex::Autolock _l(mTimedBufferQueueLock); 1460 return mFramesPendingInQueue; 1461 } 1462 1463 AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer() 1464 : mPTS(0), mPosition(0) {} 1465 1466 AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer( 1467 const sp<IMemory>& buffer, int64_t pts) 1468 : mBuffer(buffer), mPTS(pts), mPosition(0) {} 1469 1470 1471 // ---------------------------------------------------------------------------- 1472 1473 AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( 1474 PlaybackThread *playbackThread, 1475 DuplicatingThread *sourceThread, 1476 uint32_t sampleRate, 1477 audio_format_t format, 1478 audio_channel_mask_t channelMask, 1479 size_t frameCount) 1480 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, 1481 NULL, 0, IAudioFlinger::TRACK_DEFAULT), 1482 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL) 1483 { 1484 1485 if (mCblk != NULL) { 1486 mOutBuffer.frameCount = 0; 1487 playbackThread->mTracks.add(this); 1488 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, " 1489 "mCblk->frameCount_ %u, mChannelMask 0x%08x", 1490 mCblk, mBuffer, 1491 mCblk->frameCount_, mChannelMask); 1492 // since client and server are in the same process, 1493 // the buffer has the same virtual address on both sides 1494 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize); 1495 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000)); 1496 mClientProxy->setSendLevel(0.0); 1497 mClientProxy->setSampleRate(sampleRate); 1498 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize, 1499 true /*clientInServer*/); 1500 } else { 1501 ALOGW("Error creating output track on thread %p", playbackThread); 1502 } 1503 } 1504 1505 AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack() 1506 { 1507 clearBufferQueue(); 1508 delete mClientProxy; 1509 // superclass destructor will now delete the server proxy and shared memory both refer to 1510 } 1511 1512 status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event, 1513 int triggerSession) 1514 { 1515 status_t status = Track::start(event, triggerSession); 1516 if (status != NO_ERROR) { 1517 return status; 1518 } 1519 1520 mActive = true; 1521 mRetryCount = 127; 1522 return status; 1523 } 1524 1525 void AudioFlinger::PlaybackThread::OutputTrack::stop() 1526 { 1527 Track::stop(); 1528 clearBufferQueue(); 1529 mOutBuffer.frameCount = 0; 1530 mActive = false; 1531 } 1532 1533 bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames) 1534 { 1535 Buffer *pInBuffer; 1536 Buffer inBuffer; 1537 uint32_t channelCount = mChannelCount; 1538 bool outputBufferFull = false; 1539 inBuffer.frameCount = frames; 1540 inBuffer.i16 = data; 1541 1542 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs(); 1543 1544 if (!mActive && frames != 0) { 1545 start(); 1546 sp<ThreadBase> thread = mThread.promote(); 1547 if (thread != 0) { 1548 MixerThread *mixerThread = (MixerThread *)thread.get(); 1549 if (mFrameCount > frames) { 1550 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 1551 uint32_t startFrames = (mFrameCount - frames); 1552 pInBuffer = new Buffer; 1553 pInBuffer->mBuffer = new int16_t[startFrames * channelCount]; 1554 pInBuffer->frameCount = startFrames; 1555 pInBuffer->i16 = pInBuffer->mBuffer; 1556 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t)); 1557 mBufferQueue.add(pInBuffer); 1558 } else { 1559 ALOGW("OutputTrack::write() %p no more buffers in queue", this); 1560 } 1561 } 1562 } 1563 } 1564 1565 while (waitTimeLeftMs) { 1566 // First write pending buffers, then new data 1567 if (mBufferQueue.size()) { 1568 pInBuffer = mBufferQueue.itemAt(0); 1569 } else { 1570 pInBuffer = &inBuffer; 1571 } 1572 1573 if (pInBuffer->frameCount == 0) { 1574 break; 1575 } 1576 1577 if (mOutBuffer.frameCount == 0) { 1578 mOutBuffer.frameCount = pInBuffer->frameCount; 1579 nsecs_t startTime = systemTime(); 1580 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs); 1581 if (status != NO_ERROR) { 1582 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this, 1583 mThread.unsafe_get(), status); 1584 outputBufferFull = true; 1585 break; 1586 } 1587 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime); 1588 if (waitTimeLeftMs >= waitTimeMs) { 1589 waitTimeLeftMs -= waitTimeMs; 1590 } else { 1591 waitTimeLeftMs = 0; 1592 } 1593 } 1594 1595 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : 1596 pInBuffer->frameCount; 1597 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t)); 1598 Proxy::Buffer buf; 1599 buf.mFrameCount = outFrames; 1600 buf.mRaw = NULL; 1601 mClientProxy->releaseBuffer(&buf); 1602 pInBuffer->frameCount -= outFrames; 1603 pInBuffer->i16 += outFrames * channelCount; 1604 mOutBuffer.frameCount -= outFrames; 1605 mOutBuffer.i16 += outFrames * channelCount; 1606 1607 if (pInBuffer->frameCount == 0) { 1608 if (mBufferQueue.size()) { 1609 mBufferQueue.removeAt(0); 1610 delete [] pInBuffer->mBuffer; 1611 delete pInBuffer; 1612 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, 1613 mThread.unsafe_get(), mBufferQueue.size()); 1614 } else { 1615 break; 1616 } 1617 } 1618 } 1619 1620 // If we could not write all frames, allocate a buffer and queue it for next time. 1621 if (inBuffer.frameCount) { 1622 sp<ThreadBase> thread = mThread.promote(); 1623 if (thread != 0 && !thread->standby()) { 1624 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 1625 pInBuffer = new Buffer; 1626 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount]; 1627 pInBuffer->frameCount = inBuffer.frameCount; 1628 pInBuffer->i16 = pInBuffer->mBuffer; 1629 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * 1630 sizeof(int16_t)); 1631 mBufferQueue.add(pInBuffer); 1632 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, 1633 mThread.unsafe_get(), mBufferQueue.size()); 1634 } else { 1635 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", 1636 mThread.unsafe_get(), this); 1637 } 1638 } 1639 } 1640 1641 // Calling write() with a 0 length buffer, means that no more data will be written: 1642 // If no more buffers are pending, fill output track buffer to make sure it is started 1643 // by output mixer. 1644 if (frames == 0 && mBufferQueue.size() == 0) { 1645 // FIXME borken, replace by getting framesReady() from proxy 1646 size_t user = 0; // was mCblk->user 1647 if (user < mFrameCount) { 1648 frames = mFrameCount - user; 1649 pInBuffer = new Buffer; 1650 pInBuffer->mBuffer = new int16_t[frames * channelCount]; 1651 pInBuffer->frameCount = frames; 1652 pInBuffer->i16 = pInBuffer->mBuffer; 1653 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t)); 1654 mBufferQueue.add(pInBuffer); 1655 } else if (mActive) { 1656 stop(); 1657 } 1658 } 1659 1660 return outputBufferFull; 1661 } 1662 1663 status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer( 1664 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs) 1665 { 1666 ClientProxy::Buffer buf; 1667 buf.mFrameCount = buffer->frameCount; 1668 struct timespec timeout; 1669 timeout.tv_sec = waitTimeMs / 1000; 1670 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000; 1671 status_t status = mClientProxy->obtainBuffer(&buf, &timeout); 1672 buffer->frameCount = buf.mFrameCount; 1673 buffer->raw = buf.mRaw; 1674 return status; 1675 } 1676 1677 void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue() 1678 { 1679 size_t size = mBufferQueue.size(); 1680 1681 for (size_t i = 0; i < size; i++) { 1682 Buffer *pBuffer = mBufferQueue.itemAt(i); 1683 delete [] pBuffer->mBuffer; 1684 delete pBuffer; 1685 } 1686 mBufferQueue.clear(); 1687 } 1688 1689 1690 // ---------------------------------------------------------------------------- 1691 // Record 1692 // ---------------------------------------------------------------------------- 1693 1694 AudioFlinger::RecordHandle::RecordHandle( 1695 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack) 1696 : BnAudioRecord(), 1697 mRecordTrack(recordTrack) 1698 { 1699 } 1700 1701 AudioFlinger::RecordHandle::~RecordHandle() { 1702 stop_nonvirtual(); 1703 mRecordTrack->destroy(); 1704 } 1705 1706 sp<IMemory> AudioFlinger::RecordHandle::getCblk() const { 1707 return mRecordTrack->getCblk(); 1708 } 1709 1710 status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, 1711 int triggerSession) { 1712 ALOGV("RecordHandle::start()"); 1713 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession); 1714 } 1715 1716 void AudioFlinger::RecordHandle::stop() { 1717 stop_nonvirtual(); 1718 } 1719 1720 void AudioFlinger::RecordHandle::stop_nonvirtual() { 1721 ALOGV("RecordHandle::stop()"); 1722 mRecordTrack->stop(); 1723 } 1724 1725 status_t AudioFlinger::RecordHandle::onTransact( 1726 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 1727 { 1728 return BnAudioRecord::onTransact(code, data, reply, flags); 1729 } 1730 1731 // ---------------------------------------------------------------------------- 1732 1733 // RecordTrack constructor must be called with AudioFlinger::mLock held 1734 AudioFlinger::RecordThread::RecordTrack::RecordTrack( 1735 RecordThread *thread, 1736 const sp<Client>& client, 1737 uint32_t sampleRate, 1738 audio_format_t format, 1739 audio_channel_mask_t channelMask, 1740 size_t frameCount, 1741 int sessionId) 1742 : TrackBase(thread, client, sampleRate, format, 1743 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/), 1744 mOverflow(false) 1745 { 1746 ALOGV("RecordTrack constructor"); 1747 if (mCblk != NULL) { 1748 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, 1749 mFrameSize); 1750 mServerProxy = mAudioRecordServerProxy; 1751 } 1752 } 1753 1754 AudioFlinger::RecordThread::RecordTrack::~RecordTrack() 1755 { 1756 ALOGV("%s", __func__); 1757 } 1758 1759 // AudioBufferProvider interface 1760 status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, 1761 int64_t pts) 1762 { 1763 ServerProxy::Buffer buf; 1764 buf.mFrameCount = buffer->frameCount; 1765 status_t status = mServerProxy->obtainBuffer(&buf); 1766 buffer->frameCount = buf.mFrameCount; 1767 buffer->raw = buf.mRaw; 1768 if (buf.mFrameCount == 0) { 1769 // FIXME also wake futex so that overrun is noticed more quickly 1770 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags); 1771 } 1772 return status; 1773 } 1774 1775 status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event, 1776 int triggerSession) 1777 { 1778 sp<ThreadBase> thread = mThread.promote(); 1779 if (thread != 0) { 1780 RecordThread *recordThread = (RecordThread *)thread.get(); 1781 return recordThread->start(this, event, triggerSession); 1782 } else { 1783 return BAD_VALUE; 1784 } 1785 } 1786 1787 void AudioFlinger::RecordThread::RecordTrack::stop() 1788 { 1789 sp<ThreadBase> thread = mThread.promote(); 1790 if (thread != 0) { 1791 RecordThread *recordThread = (RecordThread *)thread.get(); 1792 if (recordThread->stop(this)) { 1793 AudioSystem::stopInput(recordThread->id()); 1794 } 1795 } 1796 } 1797 1798 void AudioFlinger::RecordThread::RecordTrack::destroy() 1799 { 1800 // see comments at AudioFlinger::PlaybackThread::Track::destroy() 1801 sp<RecordTrack> keep(this); 1802 { 1803 sp<ThreadBase> thread = mThread.promote(); 1804 if (thread != 0) { 1805 if (mState == ACTIVE || mState == RESUMING) { 1806 AudioSystem::stopInput(thread->id()); 1807 } 1808 AudioSystem::releaseInput(thread->id()); 1809 Mutex::Autolock _l(thread->mLock); 1810 RecordThread *recordThread = (RecordThread *) thread.get(); 1811 recordThread->destroyTrack_l(this); 1812 } 1813 } 1814 } 1815 1816 void AudioFlinger::RecordThread::RecordTrack::invalidate() 1817 { 1818 // FIXME should use proxy, and needs work 1819 audio_track_cblk_t* cblk = mCblk; 1820 android_atomic_or(CBLK_INVALID, &cblk->mFlags); 1821 android_atomic_release_store(0x40000000, &cblk->mFutex); 1822 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE 1823 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX); 1824 } 1825 1826 1827 /*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result) 1828 { 1829 result.append("Client Fmt Chn mask Session S Server fCount\n"); 1830 } 1831 1832 void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size) 1833 { 1834 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n", 1835 (mClient == 0) ? getpid_cached : mClient->pid(), 1836 mFormat, 1837 mChannelMask, 1838 mSessionId, 1839 mState, 1840 mCblk->mServer, 1841 mFrameCount); 1842 } 1843 1844 }; // namespace android 1845