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