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