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 #ifndef INCLUDING_FROM_AUDIOFLINGER_H
     19     #error This header file should only be included from AudioFlinger.h
     20 #endif
     21 
     22 class ThreadBase : public Thread {
     23 public:
     24 
     25 #include "TrackBase.h"
     26 
     27     enum type_t {
     28         MIXER,              // Thread class is MixerThread
     29         DIRECT,             // Thread class is DirectOutputThread
     30         DUPLICATING,        // Thread class is DuplicatingThread
     31         RECORD,             // Thread class is RecordThread
     32         OFFLOAD             // Thread class is OffloadThread
     33     };
     34 
     35     ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
     36                 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
     37     virtual             ~ThreadBase();
     38 
     39     virtual status_t    readyToRun();
     40 
     41     void dumpBase(int fd, const Vector<String16>& args);
     42     void dumpEffectChains(int fd, const Vector<String16>& args);
     43 
     44     void clearPowerManager();
     45 
     46     // base for record and playback
     47     enum {
     48         CFG_EVENT_IO,
     49         CFG_EVENT_PRIO,
     50         CFG_EVENT_SET_PARAMETER,
     51         CFG_EVENT_CREATE_AUDIO_PATCH,
     52         CFG_EVENT_RELEASE_AUDIO_PATCH,
     53     };
     54 
     55     class ConfigEventData: public RefBase {
     56     public:
     57         virtual ~ConfigEventData() {}
     58 
     59         virtual  void dump(char *buffer, size_t size) = 0;
     60     protected:
     61         ConfigEventData() {}
     62     };
     63 
     64     // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
     65     //  1. create SetParameterConfigEvent. This sets mWaitStatus in config event
     66     //  2. Lock mLock
     67     //  3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
     68     //  4. sendConfigEvent_l() reads status from event->mStatus;
     69     //  5. sendConfigEvent_l() returns status
     70     //  6. Unlock
     71     //
     72     // Parameter sequence by server: threadLoop calling processConfigEvents_l():
     73     // 1. Lock mLock
     74     // 2. If there is an entry in mConfigEvents proceed ...
     75     // 3. Read first entry in mConfigEvents
     76     // 4. Remove first entry from mConfigEvents
     77     // 5. Process
     78     // 6. Set event->mStatus
     79     // 7. event->mCond.signal
     80     // 8. Unlock
     81 
     82     class ConfigEvent: public RefBase {
     83     public:
     84         virtual ~ConfigEvent() {}
     85 
     86         void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
     87 
     88         const int mType; // event type e.g. CFG_EVENT_IO
     89         Mutex mLock;     // mutex associated with mCond
     90         Condition mCond; // condition for status return
     91         status_t mStatus; // status communicated to sender
     92         bool mWaitStatus; // true if sender is waiting for status
     93         sp<ConfigEventData> mData;     // event specific parameter data
     94 
     95     protected:
     96         ConfigEvent(int type) : mType(type), mStatus(NO_ERROR), mWaitStatus(false), mData(NULL) {}
     97     };
     98 
     99     class IoConfigEventData : public ConfigEventData {
    100     public:
    101         IoConfigEventData(int event, int param) :
    102             mEvent(event), mParam(param) {}
    103 
    104         virtual  void dump(char *buffer, size_t size) {
    105             snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
    106         }
    107 
    108         const int mEvent;
    109         const int mParam;
    110     };
    111 
    112     class IoConfigEvent : public ConfigEvent {
    113     public:
    114         IoConfigEvent(int event, int param) :
    115             ConfigEvent(CFG_EVENT_IO) {
    116             mData = new IoConfigEventData(event, param);
    117         }
    118         virtual ~IoConfigEvent() {}
    119     };
    120 
    121     class PrioConfigEventData : public ConfigEventData {
    122     public:
    123         PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio) :
    124             mPid(pid), mTid(tid), mPrio(prio) {}
    125 
    126         virtual  void dump(char *buffer, size_t size) {
    127             snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
    128         }
    129 
    130         const pid_t mPid;
    131         const pid_t mTid;
    132         const int32_t mPrio;
    133     };
    134 
    135     class PrioConfigEvent : public ConfigEvent {
    136     public:
    137         PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
    138             ConfigEvent(CFG_EVENT_PRIO) {
    139             mData = new PrioConfigEventData(pid, tid, prio);
    140         }
    141         virtual ~PrioConfigEvent() {}
    142     };
    143 
    144     class SetParameterConfigEventData : public ConfigEventData {
    145     public:
    146         SetParameterConfigEventData(String8 keyValuePairs) :
    147             mKeyValuePairs(keyValuePairs) {}
    148 
    149         virtual  void dump(char *buffer, size_t size) {
    150             snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
    151         }
    152 
    153         const String8 mKeyValuePairs;
    154     };
    155 
    156     class SetParameterConfigEvent : public ConfigEvent {
    157     public:
    158         SetParameterConfigEvent(String8 keyValuePairs) :
    159             ConfigEvent(CFG_EVENT_SET_PARAMETER) {
    160             mData = new SetParameterConfigEventData(keyValuePairs);
    161             mWaitStatus = true;
    162         }
    163         virtual ~SetParameterConfigEvent() {}
    164     };
    165 
    166     class CreateAudioPatchConfigEventData : public ConfigEventData {
    167     public:
    168         CreateAudioPatchConfigEventData(const struct audio_patch patch,
    169                                         audio_patch_handle_t handle) :
    170             mPatch(patch), mHandle(handle) {}
    171 
    172         virtual  void dump(char *buffer, size_t size) {
    173             snprintf(buffer, size, "Patch handle: %u\n", mHandle);
    174         }
    175 
    176         const struct audio_patch mPatch;
    177         audio_patch_handle_t mHandle;
    178     };
    179 
    180     class CreateAudioPatchConfigEvent : public ConfigEvent {
    181     public:
    182         CreateAudioPatchConfigEvent(const struct audio_patch patch,
    183                                     audio_patch_handle_t handle) :
    184             ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
    185             mData = new CreateAudioPatchConfigEventData(patch, handle);
    186             mWaitStatus = true;
    187         }
    188         virtual ~CreateAudioPatchConfigEvent() {}
    189     };
    190 
    191     class ReleaseAudioPatchConfigEventData : public ConfigEventData {
    192     public:
    193         ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
    194             mHandle(handle) {}
    195 
    196         virtual  void dump(char *buffer, size_t size) {
    197             snprintf(buffer, size, "Patch handle: %u\n", mHandle);
    198         }
    199 
    200         audio_patch_handle_t mHandle;
    201     };
    202 
    203     class ReleaseAudioPatchConfigEvent : public ConfigEvent {
    204     public:
    205         ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
    206             ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
    207             mData = new ReleaseAudioPatchConfigEventData(handle);
    208             mWaitStatus = true;
    209         }
    210         virtual ~ReleaseAudioPatchConfigEvent() {}
    211     };
    212 
    213     class PMDeathRecipient : public IBinder::DeathRecipient {
    214     public:
    215                     PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
    216         virtual     ~PMDeathRecipient() {}
    217 
    218         // IBinder::DeathRecipient
    219         virtual     void        binderDied(const wp<IBinder>& who);
    220 
    221     private:
    222                     PMDeathRecipient(const PMDeathRecipient&);
    223                     PMDeathRecipient& operator = (const PMDeathRecipient&);
    224 
    225         wp<ThreadBase> mThread;
    226     };
    227 
    228     virtual     status_t    initCheck() const = 0;
    229 
    230                 // static externally-visible
    231                 type_t      type() const { return mType; }
    232                 audio_io_handle_t id() const { return mId;}
    233 
    234                 // dynamic externally-visible
    235                 uint32_t    sampleRate() const { return mSampleRate; }
    236                 audio_channel_mask_t channelMask() const { return mChannelMask; }
    237                 audio_format_t format() const { return mHALFormat; }
    238                 uint32_t channelCount() const { return mChannelCount; }
    239                 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
    240                 // and returns the [normal mix] buffer's frame count.
    241     virtual     size_t      frameCount() const = 0;
    242                 size_t      frameSize() const { return mFrameSize; }
    243 
    244     // Should be "virtual status_t requestExitAndWait()" and override same
    245     // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
    246                 void        exit();
    247     virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
    248                                                     status_t& status) = 0;
    249     virtual     status_t    setParameters(const String8& keyValuePairs);
    250     virtual     String8     getParameters(const String8& keys) = 0;
    251     virtual     void        audioConfigChanged(int event, int param = 0) = 0;
    252                 // sendConfigEvent_l() must be called with ThreadBase::mLock held
    253                 // Can temporarily release the lock if waiting for a reply from
    254                 // processConfigEvents_l().
    255                 status_t    sendConfigEvent_l(sp<ConfigEvent>& event);
    256                 void        sendIoConfigEvent(int event, int param = 0);
    257                 void        sendIoConfigEvent_l(int event, int param = 0);
    258                 void        sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
    259                 status_t    sendSetParameterConfigEvent_l(const String8& keyValuePair);
    260                 status_t    sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
    261                                                             audio_patch_handle_t *handle);
    262                 status_t    sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
    263                 void        processConfigEvents_l();
    264     virtual     void        cacheParameters_l() = 0;
    265     virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
    266                                                audio_patch_handle_t *handle) = 0;
    267     virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
    268     virtual     void        getAudioPortConfig(struct audio_port_config *config) = 0;
    269 
    270 
    271                 // see note at declaration of mStandby, mOutDevice and mInDevice
    272                 bool        standby() const { return mStandby; }
    273                 audio_devices_t outDevice() const { return mOutDevice; }
    274                 audio_devices_t inDevice() const { return mInDevice; }
    275 
    276     virtual     audio_stream_t* stream() const = 0;
    277 
    278                 sp<EffectHandle> createEffect_l(
    279                                     const sp<AudioFlinger::Client>& client,
    280                                     const sp<IEffectClient>& effectClient,
    281                                     int32_t priority,
    282                                     int sessionId,
    283                                     effect_descriptor_t *desc,
    284                                     int *enabled,
    285                                     status_t *status /*non-NULL*/);
    286 
    287                 // return values for hasAudioSession (bit field)
    288                 enum effect_state {
    289                     EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
    290                                             // effect
    291                     TRACK_SESSION = 0x2     // the audio session corresponds to at least one
    292                                             // track
    293                 };
    294 
    295                 // get effect chain corresponding to session Id.
    296                 sp<EffectChain> getEffectChain(int sessionId);
    297                 // same as getEffectChain() but must be called with ThreadBase mutex locked
    298                 sp<EffectChain> getEffectChain_l(int sessionId) const;
    299                 // add an effect chain to the chain list (mEffectChains)
    300     virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
    301                 // remove an effect chain from the chain list (mEffectChains)
    302     virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
    303                 // lock all effect chains Mutexes. Must be called before releasing the
    304                 // ThreadBase mutex before processing the mixer and effects. This guarantees the
    305                 // integrity of the chains during the process.
    306                 // Also sets the parameter 'effectChains' to current value of mEffectChains.
    307                 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
    308                 // unlock effect chains after process
    309                 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
    310                 // get a copy of mEffectChains vector
    311                 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
    312                 // set audio mode to all effect chains
    313                 void setMode(audio_mode_t mode);
    314                 // get effect module with corresponding ID on specified audio session
    315                 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
    316                 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
    317                 // add and effect module. Also creates the effect chain is none exists for
    318                 // the effects audio session
    319                 status_t addEffect_l(const sp< EffectModule>& effect);
    320                 // remove and effect module. Also removes the effect chain is this was the last
    321                 // effect
    322                 void removeEffect_l(const sp< EffectModule>& effect);
    323                 // detach all tracks connected to an auxiliary effect
    324     virtual     void detachAuxEffect_l(int effectId __unused) {}
    325                 // returns either EFFECT_SESSION if effects on this audio session exist in one
    326                 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
    327                 virtual uint32_t hasAudioSession(int sessionId) const = 0;
    328                 // the value returned by default implementation is not important as the
    329                 // strategy is only meaningful for PlaybackThread which implements this method
    330                 virtual uint32_t getStrategyForSession_l(int sessionId __unused) { return 0; }
    331 
    332                 // suspend or restore effect according to the type of effect passed. a NULL
    333                 // type pointer means suspend all effects in the session
    334                 void setEffectSuspended(const effect_uuid_t *type,
    335                                         bool suspend,
    336                                         int sessionId = AUDIO_SESSION_OUTPUT_MIX);
    337                 // check if some effects must be suspended/restored when an effect is enabled
    338                 // or disabled
    339                 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
    340                                                  bool enabled,
    341                                                  int sessionId = AUDIO_SESSION_OUTPUT_MIX);
    342                 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
    343                                                    bool enabled,
    344                                                    int sessionId = AUDIO_SESSION_OUTPUT_MIX);
    345 
    346                 virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
    347                 virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
    348 
    349                 // Return a reference to a per-thread heap which can be used to allocate IMemory
    350                 // objects that will be read-only to client processes, read/write to mediaserver,
    351                 // and shared by all client processes of the thread.
    352                 // The heap is per-thread rather than common across all threads, because
    353                 // clients can't be trusted not to modify the offset of the IMemory they receive.
    354                 // If a thread does not have such a heap, this method returns 0.
    355                 virtual sp<MemoryDealer>    readOnlyHeap() const { return 0; }
    356 
    357                 virtual sp<IMemory> pipeMemory() const { return 0; }
    358 
    359     mutable     Mutex                   mLock;
    360 
    361 protected:
    362 
    363                 // entry describing an effect being suspended in mSuspendedSessions keyed vector
    364                 class SuspendedSessionDesc : public RefBase {
    365                 public:
    366                     SuspendedSessionDesc() : mRefCount(0) {}
    367 
    368                     int mRefCount;          // number of active suspend requests
    369                     effect_uuid_t mType;    // effect type UUID
    370                 };
    371 
    372                 void        acquireWakeLock(int uid = -1);
    373                 void        acquireWakeLock_l(int uid = -1);
    374                 void        releaseWakeLock();
    375                 void        releaseWakeLock_l();
    376                 void        updateWakeLockUids(const SortedVector<int> &uids);
    377                 void        updateWakeLockUids_l(const SortedVector<int> &uids);
    378                 void        getPowerManager_l();
    379                 void setEffectSuspended_l(const effect_uuid_t *type,
    380                                           bool suspend,
    381                                           int sessionId);
    382                 // updated mSuspendedSessions when an effect suspended or restored
    383                 void        updateSuspendedSessions_l(const effect_uuid_t *type,
    384                                                       bool suspend,
    385                                                       int sessionId);
    386                 // check if some effects must be suspended when an effect chain is added
    387                 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
    388 
    389                 String16 getWakeLockTag();
    390 
    391     virtual     void        preExit() { }
    392 
    393     friend class AudioFlinger;      // for mEffectChains
    394 
    395                 const type_t            mType;
    396 
    397                 // Used by parameters, config events, addTrack_l, exit
    398                 Condition               mWaitWorkCV;
    399 
    400                 const sp<AudioFlinger>  mAudioFlinger;
    401 
    402                 // updated by PlaybackThread::readOutputParameters_l() or
    403                 // RecordThread::readInputParameters_l()
    404                 uint32_t                mSampleRate;
    405                 size_t                  mFrameCount;       // output HAL, direct output, record
    406                 audio_channel_mask_t    mChannelMask;
    407                 uint32_t                mChannelCount;
    408                 size_t                  mFrameSize;
    409                 audio_format_t          mFormat;           // Source format for Recording and
    410                                                            // Sink format for Playback.
    411                                                            // Sink format may be different than
    412                                                            // HAL format if Fastmixer is used.
    413                 audio_format_t          mHALFormat;
    414                 size_t                  mBufferSize;       // HAL buffer size for read() or write()
    415 
    416                 Vector< sp<ConfigEvent> >     mConfigEvents;
    417 
    418                 // These fields are written and read by thread itself without lock or barrier,
    419                 // and read by other threads without lock or barrier via standby(), outDevice()
    420                 // and inDevice().
    421                 // Because of the absence of a lock or barrier, any other thread that reads
    422                 // these fields must use the information in isolation, or be prepared to deal
    423                 // with possibility that it might be inconsistent with other information.
    424                 bool                    mStandby;     // Whether thread is currently in standby.
    425                 audio_devices_t         mOutDevice;   // output device
    426                 audio_devices_t         mInDevice;    // input device
    427                 audio_source_t          mAudioSource; // (see audio.h, audio_source_t)
    428 
    429                 const audio_io_handle_t mId;
    430                 Vector< sp<EffectChain> > mEffectChains;
    431 
    432                 static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
    433                 char                    mName[kNameLength];
    434                 sp<IPowerManager>       mPowerManager;
    435                 sp<IBinder>             mWakeLockToken;
    436                 const sp<PMDeathRecipient> mDeathRecipient;
    437                 // list of suspended effects per session and per type. The first vector is
    438                 // keyed by session ID, the second by type UUID timeLow field
    439                 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
    440                                         mSuspendedSessions;
    441                 static const size_t     kLogSize = 4 * 1024;
    442                 sp<NBLog::Writer>       mNBLogWriter;
    443 };
    444 
    445 // --- PlaybackThread ---
    446 class PlaybackThread : public ThreadBase {
    447 public:
    448 
    449 #include "PlaybackTracks.h"
    450 
    451     enum mixer_state {
    452         MIXER_IDLE,             // no active tracks
    453         MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
    454         MIXER_TRACKS_READY,      // at least one active track, and at least one track has data
    455         MIXER_DRAIN_TRACK,      // drain currently playing track
    456         MIXER_DRAIN_ALL,        // fully drain the hardware
    457         // standby mode does not have an enum value
    458         // suspend by audio policy manager is orthogonal to mixer state
    459     };
    460 
    461     // retry count before removing active track in case of underrun on offloaded thread:
    462     // we need to make sure that AudioTrack client has enough time to send large buffers
    463 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
    464     // for offloaded tracks
    465     static const int8_t kMaxTrackRetriesOffload = 20;
    466 
    467     PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
    468                    audio_io_handle_t id, audio_devices_t device, type_t type);
    469     virtual             ~PlaybackThread();
    470 
    471                 void        dump(int fd, const Vector<String16>& args);
    472 
    473     // Thread virtuals
    474     virtual     bool        threadLoop();
    475 
    476     // RefBase
    477     virtual     void        onFirstRef();
    478 
    479 protected:
    480     // Code snippets that were lifted up out of threadLoop()
    481     virtual     void        threadLoop_mix() = 0;
    482     virtual     void        threadLoop_sleepTime() = 0;
    483     virtual     ssize_t     threadLoop_write();
    484     virtual     void        threadLoop_drain();
    485     virtual     void        threadLoop_standby();
    486     virtual     void        threadLoop_exit();
    487     virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
    488 
    489                 // prepareTracks_l reads and writes mActiveTracks, and returns
    490                 // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
    491                 // is responsible for clearing or destroying this Vector later on, when it
    492                 // is safe to do so. That will drop the final ref count and destroy the tracks.
    493     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
    494                 void        removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
    495 
    496                 void        writeCallback();
    497                 void        resetWriteBlocked(uint32_t sequence);
    498                 void        drainCallback();
    499                 void        resetDraining(uint32_t sequence);
    500 
    501     static      int         asyncCallback(stream_callback_event_t event, void *param, void *cookie);
    502 
    503     virtual     bool        waitingAsyncCallback();
    504     virtual     bool        waitingAsyncCallback_l();
    505     virtual     bool        shouldStandby_l();
    506     virtual     void        onAddNewTrack_l();
    507 
    508     // ThreadBase virtuals
    509     virtual     void        preExit();
    510 
    511 public:
    512 
    513     virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
    514 
    515                 // return estimated latency in milliseconds, as reported by HAL
    516                 uint32_t    latency() const;
    517                 // same, but lock must already be held
    518                 uint32_t    latency_l() const;
    519 
    520                 void        setMasterVolume(float value);
    521                 void        setMasterMute(bool muted);
    522 
    523                 void        setStreamVolume(audio_stream_type_t stream, float value);
    524                 void        setStreamMute(audio_stream_type_t stream, bool muted);
    525 
    526                 float       streamVolume(audio_stream_type_t stream) const;
    527 
    528                 sp<Track>   createTrack_l(
    529                                 const sp<AudioFlinger::Client>& client,
    530                                 audio_stream_type_t streamType,
    531                                 uint32_t sampleRate,
    532                                 audio_format_t format,
    533                                 audio_channel_mask_t channelMask,
    534                                 size_t *pFrameCount,
    535                                 const sp<IMemory>& sharedBuffer,
    536                                 int sessionId,
    537                                 IAudioFlinger::track_flags_t *flags,
    538                                 pid_t tid,
    539                                 int uid,
    540                                 status_t *status /*non-NULL*/);
    541 
    542                 AudioStreamOut* getOutput() const;
    543                 AudioStreamOut* clearOutput();
    544                 virtual audio_stream_t* stream() const;
    545 
    546                 // a very large number of suspend() will eventually wraparound, but unlikely
    547                 void        suspend() { (void) android_atomic_inc(&mSuspended); }
    548                 void        restore()
    549                                 {
    550                                     // if restore() is done without suspend(), get back into
    551                                     // range so that the next suspend() will operate correctly
    552                                     if (android_atomic_dec(&mSuspended) <= 0) {
    553                                         android_atomic_release_store(0, &mSuspended);
    554                                     }
    555                                 }
    556                 bool        isSuspended() const
    557                                 { return android_atomic_acquire_load(&mSuspended) > 0; }
    558 
    559     virtual     String8     getParameters(const String8& keys);
    560     virtual     void        audioConfigChanged(int event, int param = 0);
    561                 status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
    562                 // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency.
    563                 // Consider also removing and passing an explicit mMainBuffer initialization
    564                 // parameter to AF::PlaybackThread::Track::Track().
    565                 int16_t     *mixBuffer() const {
    566                     return reinterpret_cast<int16_t *>(mSinkBuffer); };
    567 
    568     virtual     void detachAuxEffect_l(int effectId);
    569                 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
    570                         int EffectId);
    571                 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
    572                         int EffectId);
    573 
    574                 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
    575                 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
    576                 virtual uint32_t hasAudioSession(int sessionId) const;
    577                 virtual uint32_t getStrategyForSession_l(int sessionId);
    578 
    579 
    580                 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
    581                 virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
    582 
    583                 // called with AudioFlinger lock held
    584                         void     invalidateTracks(audio_stream_type_t streamType);
    585 
    586     virtual     size_t      frameCount() const { return mNormalFrameCount; }
    587 
    588                 // Return's the HAL's frame count i.e. fast mixer buffer size.
    589                 size_t      frameCountHAL() const { return mFrameCount; }
    590 
    591                 status_t    getTimestamp_l(AudioTimestamp& timestamp);
    592 
    593                 void        addPatchTrack(const sp<PatchTrack>& track);
    594                 void        deletePatchTrack(const sp<PatchTrack>& track);
    595 
    596     virtual     void        getAudioPortConfig(struct audio_port_config *config);
    597 
    598 protected:
    599     // updated by readOutputParameters_l()
    600     size_t                          mNormalFrameCount;  // normal mixer and effects
    601 
    602     void*                           mSinkBuffer;         // frame size aligned sink buffer
    603 
    604     // TODO:
    605     // Rearrange the buffer info into a struct/class with
    606     // clear, copy, construction, destruction methods.
    607     //
    608     // mSinkBuffer also has associated with it:
    609     //
    610     // mSinkBufferSize: Sink Buffer Size
    611     // mFormat: Sink Buffer Format
    612 
    613     // Mixer Buffer (mMixerBuffer*)
    614     //
    615     // In the case of floating point or multichannel data, which is not in the
    616     // sink format, it is required to accumulate in a higher precision or greater channel count
    617     // buffer before downmixing or data conversion to the sink buffer.
    618 
    619     // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
    620     bool                            mMixerBufferEnabled;
    621 
    622     // Storage, 32 byte aligned (may make this alignment a requirement later).
    623     // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
    624     void*                           mMixerBuffer;
    625 
    626     // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
    627     size_t                          mMixerBufferSize;
    628 
    629     // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
    630     audio_format_t                  mMixerBufferFormat;
    631 
    632     // An internal flag set to true by MixerThread::prepareTracks_l()
    633     // when mMixerBuffer contains valid data after mixing.
    634     bool                            mMixerBufferValid;
    635 
    636     // Effects Buffer (mEffectsBuffer*)
    637     //
    638     // In the case of effects data, which is not in the sink format,
    639     // it is required to accumulate in a different buffer before data conversion
    640     // to the sink buffer.
    641 
    642     // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
    643     bool                            mEffectBufferEnabled;
    644 
    645     // Storage, 32 byte aligned (may make this alignment a requirement later).
    646     // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
    647     void*                           mEffectBuffer;
    648 
    649     // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
    650     size_t                          mEffectBufferSize;
    651 
    652     // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
    653     audio_format_t                  mEffectBufferFormat;
    654 
    655     // An internal flag set to true by MixerThread::prepareTracks_l()
    656     // when mEffectsBuffer contains valid data after mixing.
    657     //
    658     // When this is set, all mixer data is routed into the effects buffer
    659     // for any processing (including output processing).
    660     bool                            mEffectBufferValid;
    661 
    662     // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
    663     // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
    664     // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
    665     // workaround that restriction.
    666     // 'volatile' means accessed via atomic operations and no lock.
    667     volatile int32_t                mSuspended;
    668 
    669     // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
    670     // mFramesWritten would be better, or 64-bit even better
    671     size_t                          mBytesWritten;
    672 private:
    673     // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
    674     // PlaybackThread needs to find out if master-muted, it checks it's local
    675     // copy rather than the one in AudioFlinger.  This optimization saves a lock.
    676     bool                            mMasterMute;
    677                 void        setMasterMute_l(bool muted) { mMasterMute = muted; }
    678 protected:
    679     SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
    680     SortedVector<int>               mWakeLockUids;
    681     int                             mActiveTracksGeneration;
    682     wp<Track>                       mLatestActiveTrack; // latest track added to mActiveTracks
    683 
    684     // Allocate a track name for a given channel mask.
    685     //   Returns name >= 0 if successful, -1 on failure.
    686     virtual int             getTrackName_l(audio_channel_mask_t channelMask,
    687                                            audio_format_t format, int sessionId) = 0;
    688     virtual void            deleteTrackName_l(int name) = 0;
    689 
    690     // Time to sleep between cycles when:
    691     virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
    692     virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
    693     virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
    694     // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
    695     // No sleep in standby mode; waits on a condition
    696 
    697     // Code snippets that are temporarily lifted up out of threadLoop() until the merge
    698                 void        checkSilentMode_l();
    699 
    700     // Non-trivial for DUPLICATING only
    701     virtual     void        saveOutputTracks() { }
    702     virtual     void        clearOutputTracks() { }
    703 
    704     // Cache various calculated values, at threadLoop() entry and after a parameter change
    705     virtual     void        cacheParameters_l();
    706 
    707     virtual     uint32_t    correctLatency_l(uint32_t latency) const;
    708 
    709     virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
    710                                    audio_patch_handle_t *handle);
    711     virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
    712 
    713 private:
    714 
    715     friend class AudioFlinger;      // for numerous
    716 
    717     PlaybackThread& operator = (const PlaybackThread&);
    718 
    719     status_t    addTrack_l(const sp<Track>& track);
    720     bool        destroyTrack_l(const sp<Track>& track);
    721     void        removeTrack_l(const sp<Track>& track);
    722     void        broadcast_l();
    723 
    724     void        readOutputParameters_l();
    725 
    726     virtual void dumpInternals(int fd, const Vector<String16>& args);
    727     void        dumpTracks(int fd, const Vector<String16>& args);
    728 
    729     SortedVector< sp<Track> >       mTracks;
    730     // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
    731     // DuplicatingThread
    732     stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
    733     AudioStreamOut                  *mOutput;
    734 
    735     float                           mMasterVolume;
    736     nsecs_t                         mLastWriteTime;
    737     int                             mNumWrites;
    738     int                             mNumDelayedWrites;
    739     bool                            mInWrite;
    740 
    741     // FIXME rename these former local variables of threadLoop to standard "m" names
    742     nsecs_t                         standbyTime;
    743     size_t                          mSinkBufferSize;
    744 
    745     // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
    746     uint32_t                        activeSleepTime;
    747     uint32_t                        idleSleepTime;
    748 
    749     uint32_t                        sleepTime;
    750 
    751     // mixer status returned by prepareTracks_l()
    752     mixer_state                     mMixerStatus; // current cycle
    753                                                   // previous cycle when in prepareTracks_l()
    754     mixer_state                     mMixerStatusIgnoringFastTracks;
    755                                                   // FIXME or a separate ready state per track
    756 
    757     // FIXME move these declarations into the specific sub-class that needs them
    758     // MIXER only
    759     uint32_t                        sleepTimeShift;
    760 
    761     // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
    762     nsecs_t                         standbyDelay;
    763 
    764     // MIXER only
    765     nsecs_t                         maxPeriod;
    766 
    767     // DUPLICATING only
    768     uint32_t                        writeFrames;
    769 
    770     size_t                          mBytesRemaining;
    771     size_t                          mCurrentWriteLength;
    772     bool                            mUseAsyncWrite;
    773     // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
    774     // incremented each time a write(), a flush() or a standby() occurs.
    775     // Bit 0 is set when a write blocks and indicates a callback is expected.
    776     // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
    777     // callbacks are ignored.
    778     uint32_t                        mWriteAckSequence;
    779     // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
    780     // incremented each time a drain is requested or a flush() or standby() occurs.
    781     // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
    782     // expected.
    783     // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
    784     // callbacks are ignored.
    785     uint32_t                        mDrainSequence;
    786     // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
    787     // for async write callback in the thread loop before evaluating it
    788     bool                            mSignalPending;
    789     sp<AsyncCallbackThread>         mCallbackThread;
    790 
    791 private:
    792     // The HAL output sink is treated as non-blocking, but current implementation is blocking
    793     sp<NBAIO_Sink>          mOutputSink;
    794     // If a fast mixer is present, the blocking pipe sink, otherwise clear
    795     sp<NBAIO_Sink>          mPipeSink;
    796     // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
    797     sp<NBAIO_Sink>          mNormalSink;
    798 #ifdef TEE_SINK
    799     // For dumpsys
    800     sp<NBAIO_Sink>          mTeeSink;
    801     sp<NBAIO_Source>        mTeeSource;
    802 #endif
    803     uint32_t                mScreenState;   // cached copy of gScreenState
    804     static const size_t     kFastMixerLogSize = 4 * 1024;
    805     sp<NBLog::Writer>       mFastMixerNBLogWriter;
    806 public:
    807     virtual     bool        hasFastMixer() const = 0;
    808     virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
    809                                 { FastTrackUnderruns dummy; return dummy; }
    810 
    811 protected:
    812                 // accessed by both binder threads and within threadLoop(), lock on mutex needed
    813                 unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
    814 
    815 private:
    816     // timestamp latch:
    817     //  D input is written by threadLoop_write while mutex is unlocked, and read while locked
    818     //  Q output is written while locked, and read while locked
    819     struct {
    820         AudioTimestamp  mTimestamp;
    821         uint32_t        mUnpresentedFrames;
    822         KeyedVector<Track *, uint32_t> mFramesReleased;
    823     } mLatchD, mLatchQ;
    824     bool mLatchDValid;  // true means mLatchD is valid
    825                         //     (except for mFramesReleased which is filled in later),
    826                         //     and clock it into latch at next opportunity
    827     bool mLatchQValid;  // true means mLatchQ is valid
    828 };
    829 
    830 class MixerThread : public PlaybackThread {
    831 public:
    832     MixerThread(const sp<AudioFlinger>& audioFlinger,
    833                 AudioStreamOut* output,
    834                 audio_io_handle_t id,
    835                 audio_devices_t device,
    836                 type_t type = MIXER);
    837     virtual             ~MixerThread();
    838 
    839     // Thread virtuals
    840 
    841     virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
    842                                                    status_t& status);
    843     virtual     void        dumpInternals(int fd, const Vector<String16>& args);
    844 
    845 protected:
    846     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
    847     virtual     int         getTrackName_l(audio_channel_mask_t channelMask,
    848                                            audio_format_t format, int sessionId);
    849     virtual     void        deleteTrackName_l(int name);
    850     virtual     uint32_t    idleSleepTimeUs() const;
    851     virtual     uint32_t    suspendSleepTimeUs() const;
    852     virtual     void        cacheParameters_l();
    853 
    854     // threadLoop snippets
    855     virtual     ssize_t     threadLoop_write();
    856     virtual     void        threadLoop_standby();
    857     virtual     void        threadLoop_mix();
    858     virtual     void        threadLoop_sleepTime();
    859     virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
    860     virtual     uint32_t    correctLatency_l(uint32_t latency) const;
    861 
    862                 AudioMixer* mAudioMixer;    // normal mixer
    863 private:
    864                 // one-time initialization, no locks required
    865                 sp<FastMixer>     mFastMixer;     // non-0 if there is also a fast mixer
    866                 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
    867 
    868                 // contents are not guaranteed to be consistent, no locks required
    869                 FastMixerDumpState mFastMixerDumpState;
    870 #ifdef STATE_QUEUE_DUMP
    871                 StateQueueObserverDump mStateQueueObserverDump;
    872                 StateQueueMutatorDump  mStateQueueMutatorDump;
    873 #endif
    874                 AudioWatchdogDump mAudioWatchdogDump;
    875 
    876                 // accessible only within the threadLoop(), no locks required
    877                 //          mFastMixer->sq()    // for mutating and pushing state
    878                 int32_t     mFastMixerFutex;    // for cold idle
    879 
    880 public:
    881     virtual     bool        hasFastMixer() const { return mFastMixer != 0; }
    882     virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
    883                               ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
    884                               return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
    885                             }
    886 
    887 };
    888 
    889 class DirectOutputThread : public PlaybackThread {
    890 public:
    891 
    892     DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
    893                        audio_io_handle_t id, audio_devices_t device);
    894     virtual                 ~DirectOutputThread();
    895 
    896     // Thread virtuals
    897 
    898     virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
    899                                                    status_t& status);
    900     virtual     void        flushHw_l();
    901 
    902 protected:
    903     virtual     int         getTrackName_l(audio_channel_mask_t channelMask,
    904                                            audio_format_t format, int sessionId);
    905     virtual     void        deleteTrackName_l(int name);
    906     virtual     uint32_t    activeSleepTimeUs() const;
    907     virtual     uint32_t    idleSleepTimeUs() const;
    908     virtual     uint32_t    suspendSleepTimeUs() const;
    909     virtual     void        cacheParameters_l();
    910 
    911     // threadLoop snippets
    912     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
    913     virtual     void        threadLoop_mix();
    914     virtual     void        threadLoop_sleepTime();
    915 
    916     // volumes last sent to audio HAL with stream->set_volume()
    917     float mLeftVolFloat;
    918     float mRightVolFloat;
    919 
    920     DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
    921                         audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
    922     void processVolume_l(Track *track, bool lastTrack);
    923 
    924     // prepareTracks_l() tells threadLoop_mix() the name of the single active track
    925     sp<Track>               mActiveTrack;
    926 public:
    927     virtual     bool        hasFastMixer() const { return false; }
    928 };
    929 
    930 class OffloadThread : public DirectOutputThread {
    931 public:
    932 
    933     OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
    934                         audio_io_handle_t id, uint32_t device);
    935     virtual                 ~OffloadThread() {};
    936     virtual     void        flushHw_l();
    937 
    938 protected:
    939     // threadLoop snippets
    940     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
    941     virtual     void        threadLoop_exit();
    942 
    943     virtual     bool        waitingAsyncCallback();
    944     virtual     bool        waitingAsyncCallback_l();
    945     virtual     bool        shouldStandby_l();
    946     virtual     void        onAddNewTrack_l();
    947 
    948 private:
    949     bool        mHwPaused;
    950     bool        mFlushPending;
    951     size_t      mPausedWriteLength;     // length in bytes of write interrupted by pause
    952     size_t      mPausedBytesRemaining;  // bytes still waiting in mixbuffer after resume
    953     wp<Track>   mPreviousTrack;         // used to detect track switch
    954 };
    955 
    956 class AsyncCallbackThread : public Thread {
    957 public:
    958 
    959     AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
    960 
    961     virtual             ~AsyncCallbackThread();
    962 
    963     // Thread virtuals
    964     virtual bool        threadLoop();
    965 
    966     // RefBase
    967     virtual void        onFirstRef();
    968 
    969             void        exit();
    970             void        setWriteBlocked(uint32_t sequence);
    971             void        resetWriteBlocked();
    972             void        setDraining(uint32_t sequence);
    973             void        resetDraining();
    974 
    975 private:
    976     const wp<PlaybackThread>   mPlaybackThread;
    977     // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
    978     // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
    979     // to indicate that the callback has been received via resetWriteBlocked()
    980     uint32_t                   mWriteAckSequence;
    981     // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
    982     // setDraining(). The sequence is shifted one bit to the left and the lsb is used
    983     // to indicate that the callback has been received via resetDraining()
    984     uint32_t                   mDrainSequence;
    985     Condition                  mWaitWorkCV;
    986     Mutex                      mLock;
    987 };
    988 
    989 class DuplicatingThread : public MixerThread {
    990 public:
    991     DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
    992                       audio_io_handle_t id);
    993     virtual                 ~DuplicatingThread();
    994 
    995     // Thread virtuals
    996                 void        addOutputTrack(MixerThread* thread);
    997                 void        removeOutputTrack(MixerThread* thread);
    998                 uint32_t    waitTimeMs() const { return mWaitTimeMs; }
    999 protected:
   1000     virtual     uint32_t    activeSleepTimeUs() const;
   1001 
   1002 private:
   1003                 bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
   1004 protected:
   1005     // threadLoop snippets
   1006     virtual     void        threadLoop_mix();
   1007     virtual     void        threadLoop_sleepTime();
   1008     virtual     ssize_t     threadLoop_write();
   1009     virtual     void        threadLoop_standby();
   1010     virtual     void        cacheParameters_l();
   1011 
   1012 private:
   1013     // called from threadLoop, addOutputTrack, removeOutputTrack
   1014     virtual     void        updateWaitTime_l();
   1015 protected:
   1016     virtual     void        saveOutputTracks();
   1017     virtual     void        clearOutputTracks();
   1018 private:
   1019 
   1020                 uint32_t    mWaitTimeMs;
   1021     SortedVector < sp<OutputTrack> >  outputTracks;
   1022     SortedVector < sp<OutputTrack> >  mOutputTracks;
   1023 public:
   1024     virtual     bool        hasFastMixer() const { return false; }
   1025 };
   1026 
   1027 
   1028 // record thread
   1029 class RecordThread : public ThreadBase
   1030 {
   1031 public:
   1032 
   1033     class RecordTrack;
   1034     class ResamplerBufferProvider : public AudioBufferProvider
   1035                         // derives from AudioBufferProvider interface for use by resampler
   1036     {
   1037     public:
   1038         ResamplerBufferProvider(RecordTrack* recordTrack) : mRecordTrack(recordTrack) { }
   1039         virtual ~ResamplerBufferProvider() { }
   1040         // AudioBufferProvider interface
   1041         virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
   1042         virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
   1043     private:
   1044         RecordTrack * const mRecordTrack;
   1045     };
   1046 
   1047 #include "RecordTracks.h"
   1048 
   1049             RecordThread(const sp<AudioFlinger>& audioFlinger,
   1050                     AudioStreamIn *input,
   1051                     audio_io_handle_t id,
   1052                     audio_devices_t outDevice,
   1053                     audio_devices_t inDevice
   1054 #ifdef TEE_SINK
   1055                     , const sp<NBAIO_Sink>& teeSink
   1056 #endif
   1057                     );
   1058             virtual     ~RecordThread();
   1059 
   1060     // no addTrack_l ?
   1061     void        destroyTrack_l(const sp<RecordTrack>& track);
   1062     void        removeTrack_l(const sp<RecordTrack>& track);
   1063 
   1064     void        dumpInternals(int fd, const Vector<String16>& args);
   1065     void        dumpTracks(int fd, const Vector<String16>& args);
   1066 
   1067     // Thread virtuals
   1068     virtual bool        threadLoop();
   1069 
   1070     // RefBase
   1071     virtual void        onFirstRef();
   1072 
   1073     virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
   1074 
   1075     virtual sp<MemoryDealer>    readOnlyHeap() const { return mReadOnlyHeap; }
   1076 
   1077     virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
   1078 
   1079             sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
   1080                     const sp<AudioFlinger::Client>& client,
   1081                     uint32_t sampleRate,
   1082                     audio_format_t format,
   1083                     audio_channel_mask_t channelMask,
   1084                     size_t *pFrameCount,
   1085                     int sessionId,
   1086                     size_t *notificationFrames,
   1087                     int uid,
   1088                     IAudioFlinger::track_flags_t *flags,
   1089                     pid_t tid,
   1090                     status_t *status /*non-NULL*/);
   1091 
   1092             status_t    start(RecordTrack* recordTrack,
   1093                               AudioSystem::sync_event_t event,
   1094                               int triggerSession);
   1095 
   1096             // ask the thread to stop the specified track, and
   1097             // return true if the caller should then do it's part of the stopping process
   1098             bool        stop(RecordTrack* recordTrack);
   1099 
   1100             void        dump(int fd, const Vector<String16>& args);
   1101             AudioStreamIn* clearInput();
   1102             virtual audio_stream_t* stream() const;
   1103 
   1104 
   1105     virtual bool        checkForNewParameter_l(const String8& keyValuePair,
   1106                                                status_t& status);
   1107     virtual void        cacheParameters_l() {}
   1108     virtual String8     getParameters(const String8& keys);
   1109     virtual void        audioConfigChanged(int event, int param = 0);
   1110     virtual status_t    createAudioPatch_l(const struct audio_patch *patch,
   1111                                            audio_patch_handle_t *handle);
   1112     virtual status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
   1113 
   1114             void        addPatchRecord(const sp<PatchRecord>& record);
   1115             void        deletePatchRecord(const sp<PatchRecord>& record);
   1116 
   1117             void        readInputParameters_l();
   1118     virtual uint32_t    getInputFramesLost();
   1119 
   1120     virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
   1121     virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
   1122     virtual uint32_t hasAudioSession(int sessionId) const;
   1123 
   1124             // Return the set of unique session IDs across all tracks.
   1125             // The keys are the session IDs, and the associated values are meaningless.
   1126             // FIXME replace by Set [and implement Bag/Multiset for other uses].
   1127             KeyedVector<int, bool> sessionIds() const;
   1128 
   1129     virtual status_t setSyncEvent(const sp<SyncEvent>& event);
   1130     virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
   1131 
   1132     static void syncStartEventCallback(const wp<SyncEvent>& event);
   1133 
   1134     virtual size_t      frameCount() const { return mFrameCount; }
   1135             bool        hasFastCapture() const { return mFastCapture != 0; }
   1136     virtual void        getAudioPortConfig(struct audio_port_config *config);
   1137 
   1138 private:
   1139             // Enter standby if not already in standby, and set mStandby flag
   1140             void    standbyIfNotAlreadyInStandby();
   1141 
   1142             // Call the HAL standby method unconditionally, and don't change mStandby flag
   1143             void    inputStandBy();
   1144 
   1145             AudioStreamIn                       *mInput;
   1146             SortedVector < sp<RecordTrack> >    mTracks;
   1147             // mActiveTracks has dual roles:  it indicates the current active track(s), and
   1148             // is used together with mStartStopCond to indicate start()/stop() progress
   1149             SortedVector< sp<RecordTrack> >     mActiveTracks;
   1150             // generation counter for mActiveTracks
   1151             int                                 mActiveTracksGen;
   1152             Condition                           mStartStopCond;
   1153 
   1154             // resampler converts input at HAL Hz to output at AudioRecord client Hz
   1155             int16_t                             *mRsmpInBuffer; // see new[] for details on the size
   1156             size_t                              mRsmpInFrames;  // size of resampler input in frames
   1157             size_t                              mRsmpInFramesP2;// size rounded up to a power-of-2
   1158 
   1159             // rolling index that is never cleared
   1160             int32_t                             mRsmpInRear;    // last filled frame + 1
   1161 
   1162             // For dumpsys
   1163             const sp<NBAIO_Sink>                mTeeSink;
   1164 
   1165             const sp<MemoryDealer>              mReadOnlyHeap;
   1166 
   1167             // one-time initialization, no locks required
   1168             sp<FastCapture>                     mFastCapture;   // non-0 if there is also a fast capture
   1169             // FIXME audio watchdog thread
   1170 
   1171             // contents are not guaranteed to be consistent, no locks required
   1172             FastCaptureDumpState                mFastCaptureDumpState;
   1173 #ifdef STATE_QUEUE_DUMP
   1174             // FIXME StateQueue observer and mutator dump fields
   1175 #endif
   1176             // FIXME audio watchdog dump
   1177 
   1178             // accessible only within the threadLoop(), no locks required
   1179             //          mFastCapture->sq()      // for mutating and pushing state
   1180             int32_t     mFastCaptureFutex;      // for cold idle
   1181 
   1182             // The HAL input source is treated as non-blocking,
   1183             // but current implementation is blocking
   1184             sp<NBAIO_Source>                    mInputSource;
   1185             // The source for the normal capture thread to read from: mInputSource or mPipeSource
   1186             sp<NBAIO_Source>                    mNormalSource;
   1187             // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
   1188             // otherwise clear
   1189             sp<NBAIO_Sink>                      mPipeSink;
   1190             // If a fast capture is present, the non-blocking pipe source read by normal thread,
   1191             // otherwise clear
   1192             sp<NBAIO_Source>                    mPipeSource;
   1193             // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
   1194             size_t                              mPipeFramesP2;
   1195             // If a fast capture is present, the Pipe as IMemory, otherwise clear
   1196             sp<IMemory>                         mPipeMemory;
   1197 
   1198             static const size_t                 kFastCaptureLogSize = 4 * 1024;
   1199             sp<NBLog::Writer>                   mFastCaptureNBLogWriter;
   1200 
   1201             bool                                mFastTrackAvail;    // true if fast track available
   1202 };
   1203