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