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