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