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