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