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