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