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