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