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     };
     33 
     34     ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
     35                 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
     36     virtual             ~ThreadBase();
     37 
     38     void dumpBase(int fd, const Vector<String16>& args);
     39     void dumpEffectChains(int fd, const Vector<String16>& args);
     40 
     41     void clearPowerManager();
     42 
     43     // base for record and playback
     44     enum {
     45         CFG_EVENT_IO,
     46         CFG_EVENT_PRIO
     47     };
     48 
     49     class ConfigEvent {
     50     public:
     51         ConfigEvent(int type) : mType(type) {}
     52         virtual ~ConfigEvent() {}
     53 
     54                  int type() const { return mType; }
     55 
     56         virtual  void dump(char *buffer, size_t size) = 0;
     57 
     58     private:
     59         const int mType;
     60     };
     61 
     62     class IoConfigEvent : public ConfigEvent {
     63     public:
     64         IoConfigEvent(int event, int param) :
     65             ConfigEvent(CFG_EVENT_IO), mEvent(event), mParam(event) {}
     66         virtual ~IoConfigEvent() {}
     67 
     68                 int event() const { return mEvent; }
     69                 int param() const { return mParam; }
     70 
     71         virtual  void dump(char *buffer, size_t size) {
     72             snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
     73         }
     74 
     75     private:
     76         const int mEvent;
     77         const int mParam;
     78     };
     79 
     80     class PrioConfigEvent : public ConfigEvent {
     81     public:
     82         PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
     83             ConfigEvent(CFG_EVENT_PRIO), mPid(pid), mTid(tid), mPrio(prio) {}
     84         virtual ~PrioConfigEvent() {}
     85 
     86                 pid_t pid() const { return mPid; }
     87                 pid_t tid() const { return mTid; }
     88                 int32_t prio() const { return mPrio; }
     89 
     90         virtual  void dump(char *buffer, size_t size) {
     91             snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
     92         }
     93 
     94     private:
     95         const pid_t mPid;
     96         const pid_t mTid;
     97         const int32_t mPrio;
     98     };
     99 
    100 
    101     class PMDeathRecipient : public IBinder::DeathRecipient {
    102     public:
    103                     PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
    104         virtual     ~PMDeathRecipient() {}
    105 
    106         // IBinder::DeathRecipient
    107         virtual     void        binderDied(const wp<IBinder>& who);
    108 
    109     private:
    110                     PMDeathRecipient(const PMDeathRecipient&);
    111                     PMDeathRecipient& operator = (const PMDeathRecipient&);
    112 
    113         wp<ThreadBase> mThread;
    114     };
    115 
    116     virtual     status_t    initCheck() const = 0;
    117 
    118                 // static externally-visible
    119                 type_t      type() const { return mType; }
    120                 audio_io_handle_t id() const { return mId;}
    121 
    122                 // dynamic externally-visible
    123                 uint32_t    sampleRate() const { return mSampleRate; }
    124                 uint32_t    channelCount() const { return mChannelCount; }
    125                 audio_channel_mask_t channelMask() const { return mChannelMask; }
    126                 audio_format_t format() const { return mFormat; }
    127                 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
    128                 // and returns the normal mix buffer's frame count.
    129                 size_t      frameCount() const { return mNormalFrameCount; }
    130                 // Return's the HAL's frame count i.e. fast mixer buffer size.
    131                 size_t      frameCountHAL() const { return mFrameCount; }
    132 
    133     // Should be "virtual status_t requestExitAndWait()" and override same
    134     // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
    135                 void        exit();
    136     virtual     bool        checkForNewParameters_l() = 0;
    137     virtual     status_t    setParameters(const String8& keyValuePairs);
    138     virtual     String8     getParameters(const String8& keys) = 0;
    139     virtual     void        audioConfigChanged_l(int event, int param = 0) = 0;
    140                 void        sendIoConfigEvent(int event, int param = 0);
    141                 void        sendIoConfigEvent_l(int event, int param = 0);
    142                 void        sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
    143                 void        processConfigEvents();
    144 
    145                 // see note at declaration of mStandby, mOutDevice and mInDevice
    146                 bool        standby() const { return mStandby; }
    147                 audio_devices_t outDevice() const { return mOutDevice; }
    148                 audio_devices_t inDevice() const { return mInDevice; }
    149 
    150     virtual     audio_stream_t* stream() const = 0;
    151 
    152                 sp<EffectHandle> createEffect_l(
    153                                     const sp<AudioFlinger::Client>& client,
    154                                     const sp<IEffectClient>& effectClient,
    155                                     int32_t priority,
    156                                     int sessionId,
    157                                     effect_descriptor_t *desc,
    158                                     int *enabled,
    159                                     status_t *status);
    160                 void disconnectEffect(const sp< EffectModule>& effect,
    161                                       EffectHandle *handle,
    162                                       bool unpinIfLast);
    163 
    164                 // return values for hasAudioSession (bit field)
    165                 enum effect_state {
    166                     EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
    167                                             // effect
    168                     TRACK_SESSION = 0x2     // the audio session corresponds to at least one
    169                                             // track
    170                 };
    171 
    172                 // get effect chain corresponding to session Id.
    173                 sp<EffectChain> getEffectChain(int sessionId);
    174                 // same as getEffectChain() but must be called with ThreadBase mutex locked
    175                 sp<EffectChain> getEffectChain_l(int sessionId) const;
    176                 // add an effect chain to the chain list (mEffectChains)
    177     virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
    178                 // remove an effect chain from the chain list (mEffectChains)
    179     virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
    180                 // lock all effect chains Mutexes. Must be called before releasing the
    181                 // ThreadBase mutex before processing the mixer and effects. This guarantees the
    182                 // integrity of the chains during the process.
    183                 // Also sets the parameter 'effectChains' to current value of mEffectChains.
    184                 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
    185                 // unlock effect chains after process
    186                 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
    187                 // set audio mode to all effect chains
    188                 void setMode(audio_mode_t mode);
    189                 // get effect module with corresponding ID on specified audio session
    190                 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
    191                 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
    192                 // add and effect module. Also creates the effect chain is none exists for
    193                 // the effects audio session
    194                 status_t addEffect_l(const sp< EffectModule>& effect);
    195                 // remove and effect module. Also removes the effect chain is this was the last
    196                 // effect
    197                 void removeEffect_l(const sp< EffectModule>& effect);
    198                 // detach all tracks connected to an auxiliary effect
    199     virtual     void detachAuxEffect_l(int effectId) {}
    200                 // returns either EFFECT_SESSION if effects on this audio session exist in one
    201                 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
    202                 virtual uint32_t hasAudioSession(int sessionId) const = 0;
    203                 // the value returned by default implementation is not important as the
    204                 // strategy is only meaningful for PlaybackThread which implements this method
    205                 virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; }
    206 
    207                 // suspend or restore effect according to the type of effect passed. a NULL
    208                 // type pointer means suspend all effects in the session
    209                 void setEffectSuspended(const effect_uuid_t *type,
    210                                         bool suspend,
    211                                         int sessionId = AUDIO_SESSION_OUTPUT_MIX);
    212                 // check if some effects must be suspended/restored when an effect is enabled
    213                 // or disabled
    214                 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
    215                                                  bool enabled,
    216                                                  int sessionId = AUDIO_SESSION_OUTPUT_MIX);
    217                 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
    218                                                    bool enabled,
    219                                                    int sessionId = AUDIO_SESSION_OUTPUT_MIX);
    220 
    221                 virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
    222                 virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
    223 
    224 
    225     mutable     Mutex                   mLock;
    226 
    227 protected:
    228 
    229                 // entry describing an effect being suspended in mSuspendedSessions keyed vector
    230                 class SuspendedSessionDesc : public RefBase {
    231                 public:
    232                     SuspendedSessionDesc() : mRefCount(0) {}
    233 
    234                     int mRefCount;          // number of active suspend requests
    235                     effect_uuid_t mType;    // effect type UUID
    236                 };
    237 
    238                 void        acquireWakeLock();
    239                 void        acquireWakeLock_l();
    240                 void        releaseWakeLock();
    241                 void        releaseWakeLock_l();
    242                 void setEffectSuspended_l(const effect_uuid_t *type,
    243                                           bool suspend,
    244                                           int sessionId);
    245                 // updated mSuspendedSessions when an effect suspended or restored
    246                 void        updateSuspendedSessions_l(const effect_uuid_t *type,
    247                                                       bool suspend,
    248                                                       int sessionId);
    249                 // check if some effects must be suspended when an effect chain is added
    250                 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
    251 
    252     virtual     void        preExit() { }
    253 
    254     friend class AudioFlinger;      // for mEffectChains
    255 
    256                 const type_t            mType;
    257 
    258                 // Used by parameters, config events, addTrack_l, exit
    259                 Condition               mWaitWorkCV;
    260 
    261                 const sp<AudioFlinger>  mAudioFlinger;
    262                 uint32_t                mSampleRate;
    263                 size_t                  mFrameCount;       // output HAL, direct output, record
    264                 size_t                  mNormalFrameCount; // normal mixer and effects
    265                 audio_channel_mask_t    mChannelMask;
    266                 uint16_t                mChannelCount;
    267                 size_t                  mFrameSize;
    268                 audio_format_t          mFormat;
    269 
    270                 // Parameter sequence by client: binder thread calling setParameters():
    271                 //  1. Lock mLock
    272                 //  2. Append to mNewParameters
    273                 //  3. mWaitWorkCV.signal
    274                 //  4. mParamCond.waitRelative with timeout
    275                 //  5. read mParamStatus
    276                 //  6. mWaitWorkCV.signal
    277                 //  7. Unlock
    278                 //
    279                 // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
    280                 // 1. Lock mLock
    281                 // 2. If there is an entry in mNewParameters proceed ...
    282                 // 2. Read first entry in mNewParameters
    283                 // 3. Process
    284                 // 4. Remove first entry from mNewParameters
    285                 // 5. Set mParamStatus
    286                 // 6. mParamCond.signal
    287                 // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
    288                 // 8. Unlock
    289                 Condition               mParamCond;
    290                 Vector<String8>         mNewParameters;
    291                 status_t                mParamStatus;
    292 
    293                 Vector<ConfigEvent *>     mConfigEvents;
    294 
    295                 // These fields are written and read by thread itself without lock or barrier,
    296                 // and read by other threads without lock or barrier via standby() , outDevice()
    297                 // and inDevice().
    298                 // Because of the absence of a lock or barrier, any other thread that reads
    299                 // these fields must use the information in isolation, or be prepared to deal
    300                 // with possibility that it might be inconsistent with other information.
    301                 bool                    mStandby;   // Whether thread is currently in standby.
    302                 audio_devices_t         mOutDevice;   // output device
    303                 audio_devices_t         mInDevice;    // input device
    304                 audio_source_t          mAudioSource; // (see audio.h, audio_source_t)
    305 
    306                 const audio_io_handle_t mId;
    307                 Vector< sp<EffectChain> > mEffectChains;
    308 
    309                 static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
    310                 char                    mName[kNameLength];
    311                 sp<IPowerManager>       mPowerManager;
    312                 sp<IBinder>             mWakeLockToken;
    313                 const sp<PMDeathRecipient> mDeathRecipient;
    314                 // list of suspended effects per session and per type. The first vector is
    315                 // keyed by session ID, the second by type UUID timeLow field
    316                 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
    317                                         mSuspendedSessions;
    318                 static const size_t     kLogSize = 4 * 1024;
    319                 sp<NBLog::Writer>       mNBLogWriter;
    320 };
    321 
    322 // --- PlaybackThread ---
    323 class PlaybackThread : public ThreadBase {
    324 public:
    325 
    326 #include "PlaybackTracks.h"
    327 
    328     enum mixer_state {
    329         MIXER_IDLE,             // no active tracks
    330         MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
    331         MIXER_TRACKS_READY      // at least one active track, and at least one track has data
    332         // standby mode does not have an enum value
    333         // suspend by audio policy manager is orthogonal to mixer state
    334     };
    335 
    336     PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
    337                    audio_io_handle_t id, audio_devices_t device, type_t type);
    338     virtual             ~PlaybackThread();
    339 
    340                 void        dump(int fd, const Vector<String16>& args);
    341 
    342     // Thread virtuals
    343     virtual     status_t    readyToRun();
    344     virtual     bool        threadLoop();
    345 
    346     // RefBase
    347     virtual     void        onFirstRef();
    348 
    349 protected:
    350     // Code snippets that were lifted up out of threadLoop()
    351     virtual     void        threadLoop_mix() = 0;
    352     virtual     void        threadLoop_sleepTime() = 0;
    353     virtual     void        threadLoop_write();
    354     virtual     void        threadLoop_standby();
    355     virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
    356 
    357                 // prepareTracks_l reads and writes mActiveTracks, and returns
    358                 // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
    359                 // is responsible for clearing or destroying this Vector later on, when it
    360                 // is safe to do so. That will drop the final ref count and destroy the tracks.
    361     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
    362 
    363     // ThreadBase virtuals
    364     virtual     void        preExit();
    365 
    366 public:
    367 
    368     virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
    369 
    370                 // return estimated latency in milliseconds, as reported by HAL
    371                 uint32_t    latency() const;
    372                 // same, but lock must already be held
    373                 uint32_t    latency_l() const;
    374 
    375                 void        setMasterVolume(float value);
    376                 void        setMasterMute(bool muted);
    377 
    378                 void        setStreamVolume(audio_stream_type_t stream, float value);
    379                 void        setStreamMute(audio_stream_type_t stream, bool muted);
    380 
    381                 float       streamVolume(audio_stream_type_t stream) const;
    382 
    383                 sp<Track>   createTrack_l(
    384                                 const sp<AudioFlinger::Client>& client,
    385                                 audio_stream_type_t streamType,
    386                                 uint32_t sampleRate,
    387                                 audio_format_t format,
    388                                 audio_channel_mask_t channelMask,
    389                                 size_t frameCount,
    390                                 const sp<IMemory>& sharedBuffer,
    391                                 int sessionId,
    392                                 IAudioFlinger::track_flags_t *flags,
    393                                 pid_t tid,
    394                                 status_t *status);
    395 
    396                 AudioStreamOut* getOutput() const;
    397                 AudioStreamOut* clearOutput();
    398                 virtual audio_stream_t* stream() const;
    399 
    400                 // a very large number of suspend() will eventually wraparound, but unlikely
    401                 void        suspend() { (void) android_atomic_inc(&mSuspended); }
    402                 void        restore()
    403                                 {
    404                                     // if restore() is done without suspend(), get back into
    405                                     // range so that the next suspend() will operate correctly
    406                                     if (android_atomic_dec(&mSuspended) <= 0) {
    407                                         android_atomic_release_store(0, &mSuspended);
    408                                     }
    409                                 }
    410                 bool        isSuspended() const
    411                                 { return android_atomic_acquire_load(&mSuspended) > 0; }
    412 
    413     virtual     String8     getParameters(const String8& keys);
    414     virtual     void        audioConfigChanged_l(int event, int param = 0);
    415                 status_t    getRenderPosition(size_t *halFrames, size_t *dspFrames);
    416                 int16_t     *mixBuffer() const { return mMixBuffer; };
    417 
    418     virtual     void detachAuxEffect_l(int effectId);
    419                 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
    420                         int EffectId);
    421                 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
    422                         int EffectId);
    423 
    424                 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
    425                 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
    426                 virtual uint32_t hasAudioSession(int sessionId) const;
    427                 virtual uint32_t getStrategyForSession_l(int sessionId);
    428 
    429 
    430                 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
    431                 virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
    432                         void     invalidateTracks(audio_stream_type_t streamType);
    433 
    434 
    435 protected:
    436     int16_t*                        mMixBuffer;
    437 
    438     // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
    439     // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
    440     // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
    441     // workaround that restriction.
    442     // 'volatile' means accessed via atomic operations and no lock.
    443     volatile int32_t                mSuspended;
    444 
    445     // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
    446     // mFramesWritten would be better, or 64-bit even better
    447     size_t                          mBytesWritten;
    448 private:
    449     // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
    450     // PlaybackThread needs to find out if master-muted, it checks it's local
    451     // copy rather than the one in AudioFlinger.  This optimization saves a lock.
    452     bool                            mMasterMute;
    453                 void        setMasterMute_l(bool muted) { mMasterMute = muted; }
    454 protected:
    455     SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
    456 
    457     // Allocate a track name for a given channel mask.
    458     //   Returns name >= 0 if successful, -1 on failure.
    459     virtual int             getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0;
    460     virtual void            deleteTrackName_l(int name) = 0;
    461 
    462     // Time to sleep between cycles when:
    463     virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
    464     virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
    465     virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
    466     // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
    467     // No sleep in standby mode; waits on a condition
    468 
    469     // Code snippets that are temporarily lifted up out of threadLoop() until the merge
    470                 void        checkSilentMode_l();
    471 
    472     // Non-trivial for DUPLICATING only
    473     virtual     void        saveOutputTracks() { }
    474     virtual     void        clearOutputTracks() { }
    475 
    476     // Cache various calculated values, at threadLoop() entry and after a parameter change
    477     virtual     void        cacheParameters_l();
    478 
    479     virtual     uint32_t    correctLatency_l(uint32_t latency) const;
    480 
    481 private:
    482 
    483     friend class AudioFlinger;      // for numerous
    484 
    485     PlaybackThread(const Client&);
    486     PlaybackThread& operator = (const PlaybackThread&);
    487 
    488     status_t    addTrack_l(const sp<Track>& track);
    489     void        destroyTrack_l(const sp<Track>& track);
    490     void        removeTrack_l(const sp<Track>& track);
    491 
    492     void        readOutputParameters();
    493 
    494     virtual void dumpInternals(int fd, const Vector<String16>& args);
    495     void        dumpTracks(int fd, const Vector<String16>& args);
    496 
    497     SortedVector< sp<Track> >       mTracks;
    498     // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
    499     // DuplicatingThread
    500     stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
    501     AudioStreamOut                  *mOutput;
    502 
    503     float                           mMasterVolume;
    504     nsecs_t                         mLastWriteTime;
    505     int                             mNumWrites;
    506     int                             mNumDelayedWrites;
    507     bool                            mInWrite;
    508 
    509     // FIXME rename these former local variables of threadLoop to standard "m" names
    510     nsecs_t                         standbyTime;
    511     size_t                          mixBufferSize;
    512 
    513     // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
    514     uint32_t                        activeSleepTime;
    515     uint32_t                        idleSleepTime;
    516 
    517     uint32_t                        sleepTime;
    518 
    519     // mixer status returned by prepareTracks_l()
    520     mixer_state                     mMixerStatus; // current cycle
    521                                                   // previous cycle when in prepareTracks_l()
    522     mixer_state                     mMixerStatusIgnoringFastTracks;
    523                                                   // FIXME or a separate ready state per track
    524 
    525     // FIXME move these declarations into the specific sub-class that needs them
    526     // MIXER only
    527     uint32_t                        sleepTimeShift;
    528 
    529     // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
    530     nsecs_t                         standbyDelay;
    531 
    532     // MIXER only
    533     nsecs_t                         maxPeriod;
    534 
    535     // DUPLICATING only
    536     uint32_t                        writeFrames;
    537 
    538 private:
    539     // The HAL output sink is treated as non-blocking, but current implementation is blocking
    540     sp<NBAIO_Sink>          mOutputSink;
    541     // If a fast mixer is present, the blocking pipe sink, otherwise clear
    542     sp<NBAIO_Sink>          mPipeSink;
    543     // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
    544     sp<NBAIO_Sink>          mNormalSink;
    545 #ifdef TEE_SINK
    546     // For dumpsys
    547     sp<NBAIO_Sink>          mTeeSink;
    548     sp<NBAIO_Source>        mTeeSource;
    549 #endif
    550     uint32_t                mScreenState;   // cached copy of gScreenState
    551     static const size_t     kFastMixerLogSize = 4 * 1024;
    552     sp<NBLog::Writer>       mFastMixerNBLogWriter;
    553 public:
    554     virtual     bool        hasFastMixer() const = 0;
    555     virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
    556                                 { FastTrackUnderruns dummy; return dummy; }
    557 
    558 protected:
    559                 // accessed by both binder threads and within threadLoop(), lock on mutex needed
    560                 unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
    561 
    562 };
    563 
    564 class MixerThread : public PlaybackThread {
    565 public:
    566     MixerThread(const sp<AudioFlinger>& audioFlinger,
    567                 AudioStreamOut* output,
    568                 audio_io_handle_t id,
    569                 audio_devices_t device,
    570                 type_t type = MIXER);
    571     virtual             ~MixerThread();
    572 
    573     // Thread virtuals
    574 
    575     virtual     bool        checkForNewParameters_l();
    576     virtual     void        dumpInternals(int fd, const Vector<String16>& args);
    577 
    578 protected:
    579     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
    580     virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
    581     virtual     void        deleteTrackName_l(int name);
    582     virtual     uint32_t    idleSleepTimeUs() const;
    583     virtual     uint32_t    suspendSleepTimeUs() const;
    584     virtual     void        cacheParameters_l();
    585 
    586     // threadLoop snippets
    587     virtual     void        threadLoop_write();
    588     virtual     void        threadLoop_standby();
    589     virtual     void        threadLoop_mix();
    590     virtual     void        threadLoop_sleepTime();
    591     virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
    592     virtual     uint32_t    correctLatency_l(uint32_t latency) const;
    593 
    594                 AudioMixer* mAudioMixer;    // normal mixer
    595 private:
    596                 // one-time initialization, no locks required
    597                 FastMixer*  mFastMixer;         // non-NULL if there is also a fast mixer
    598                 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
    599 
    600                 // contents are not guaranteed to be consistent, no locks required
    601                 FastMixerDumpState mFastMixerDumpState;
    602 #ifdef STATE_QUEUE_DUMP
    603                 StateQueueObserverDump mStateQueueObserverDump;
    604                 StateQueueMutatorDump  mStateQueueMutatorDump;
    605 #endif
    606                 AudioWatchdogDump mAudioWatchdogDump;
    607 
    608                 // accessible only within the threadLoop(), no locks required
    609                 //          mFastMixer->sq()    // for mutating and pushing state
    610                 int32_t     mFastMixerFutex;    // for cold idle
    611 
    612 public:
    613     virtual     bool        hasFastMixer() const { return mFastMixer != NULL; }
    614     virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
    615                               ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
    616                               return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
    617                             }
    618 };
    619 
    620 class DirectOutputThread : public PlaybackThread {
    621 public:
    622 
    623     DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
    624                        audio_io_handle_t id, audio_devices_t device);
    625     virtual                 ~DirectOutputThread();
    626 
    627     // Thread virtuals
    628 
    629     virtual     bool        checkForNewParameters_l();
    630 
    631 protected:
    632     virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
    633     virtual     void        deleteTrackName_l(int name);
    634     virtual     uint32_t    activeSleepTimeUs() const;
    635     virtual     uint32_t    idleSleepTimeUs() const;
    636     virtual     uint32_t    suspendSleepTimeUs() const;
    637     virtual     void        cacheParameters_l();
    638 
    639     // threadLoop snippets
    640     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
    641     virtual     void        threadLoop_mix();
    642     virtual     void        threadLoop_sleepTime();
    643 
    644 private:
    645     // volumes last sent to audio HAL with stream->set_volume()
    646     float mLeftVolFloat;
    647     float mRightVolFloat;
    648 
    649     // prepareTracks_l() tells threadLoop_mix() the name of the single active track
    650     sp<Track>               mActiveTrack;
    651 public:
    652     virtual     bool        hasFastMixer() const { return false; }
    653 };
    654 
    655 class DuplicatingThread : public MixerThread {
    656 public:
    657     DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
    658                       audio_io_handle_t id);
    659     virtual                 ~DuplicatingThread();
    660 
    661     // Thread virtuals
    662                 void        addOutputTrack(MixerThread* thread);
    663                 void        removeOutputTrack(MixerThread* thread);
    664                 uint32_t    waitTimeMs() const { return mWaitTimeMs; }
    665 protected:
    666     virtual     uint32_t    activeSleepTimeUs() const;
    667 
    668 private:
    669                 bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
    670 protected:
    671     // threadLoop snippets
    672     virtual     void        threadLoop_mix();
    673     virtual     void        threadLoop_sleepTime();
    674     virtual     void        threadLoop_write();
    675     virtual     void        threadLoop_standby();
    676     virtual     void        cacheParameters_l();
    677 
    678 private:
    679     // called from threadLoop, addOutputTrack, removeOutputTrack
    680     virtual     void        updateWaitTime_l();
    681 protected:
    682     virtual     void        saveOutputTracks();
    683     virtual     void        clearOutputTracks();
    684 private:
    685 
    686                 uint32_t    mWaitTimeMs;
    687     SortedVector < sp<OutputTrack> >  outputTracks;
    688     SortedVector < sp<OutputTrack> >  mOutputTracks;
    689 public:
    690     virtual     bool        hasFastMixer() const { return false; }
    691 };
    692 
    693 
    694 // record thread
    695 class RecordThread : public ThreadBase, public AudioBufferProvider
    696                         // derives from AudioBufferProvider interface for use by resampler
    697 {
    698 public:
    699 
    700 #include "RecordTracks.h"
    701 
    702             RecordThread(const sp<AudioFlinger>& audioFlinger,
    703                     AudioStreamIn *input,
    704                     uint32_t sampleRate,
    705                     audio_channel_mask_t channelMask,
    706                     audio_io_handle_t id,
    707                     audio_devices_t outDevice,
    708                     audio_devices_t inDevice
    709 #ifdef TEE_SINK
    710                     , const sp<NBAIO_Sink>& teeSink
    711 #endif
    712                     );
    713             virtual     ~RecordThread();
    714 
    715     // no addTrack_l ?
    716     void        destroyTrack_l(const sp<RecordTrack>& track);
    717     void        removeTrack_l(const sp<RecordTrack>& track);
    718 
    719     void        dumpInternals(int fd, const Vector<String16>& args);
    720     void        dumpTracks(int fd, const Vector<String16>& args);
    721 
    722     // Thread virtuals
    723     virtual bool        threadLoop();
    724     virtual status_t    readyToRun();
    725 
    726     // RefBase
    727     virtual void        onFirstRef();
    728 
    729     virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
    730             sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
    731                     const sp<AudioFlinger::Client>& client,
    732                     uint32_t sampleRate,
    733                     audio_format_t format,
    734                     audio_channel_mask_t channelMask,
    735                     size_t frameCount,
    736                     int sessionId,
    737                     IAudioFlinger::track_flags_t flags,
    738                     pid_t tid,
    739                     status_t *status);
    740 
    741             status_t    start(RecordTrack* recordTrack,
    742                               AudioSystem::sync_event_t event,
    743                               int triggerSession);
    744 
    745             // ask the thread to stop the specified track, and
    746             // return true if the caller should then do it's part of the stopping process
    747             bool        stop_l(RecordTrack* recordTrack);
    748 
    749             void        dump(int fd, const Vector<String16>& args);
    750             AudioStreamIn* clearInput();
    751             virtual audio_stream_t* stream() const;
    752 
    753     // AudioBufferProvider interface
    754     virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
    755     virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
    756 
    757     virtual bool        checkForNewParameters_l();
    758     virtual String8     getParameters(const String8& keys);
    759     virtual void        audioConfigChanged_l(int event, int param = 0);
    760             void        readInputParameters();
    761     virtual unsigned int  getInputFramesLost();
    762 
    763     virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
    764     virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
    765     virtual uint32_t hasAudioSession(int sessionId) const;
    766 
    767             // Return the set of unique session IDs across all tracks.
    768             // The keys are the session IDs, and the associated values are meaningless.
    769             // FIXME replace by Set [and implement Bag/Multiset for other uses].
    770             KeyedVector<int, bool> sessionIds() const;
    771 
    772     virtual status_t setSyncEvent(const sp<SyncEvent>& event);
    773     virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
    774 
    775     static void syncStartEventCallback(const wp<SyncEvent>& event);
    776            void handleSyncStartEvent(const sp<SyncEvent>& event);
    777 
    778 private:
    779             void clearSyncStartEvent();
    780 
    781             // Enter standby if not already in standby, and set mStandby flag
    782             void standby();
    783 
    784             // Call the HAL standby method unconditionally, and don't change mStandby flag
    785             void inputStandBy();
    786 
    787             AudioStreamIn                       *mInput;
    788             SortedVector < sp<RecordTrack> >    mTracks;
    789             // mActiveTrack has dual roles:  it indicates the current active track, and
    790             // is used together with mStartStopCond to indicate start()/stop() progress
    791             sp<RecordTrack>                     mActiveTrack;
    792             Condition                           mStartStopCond;
    793             AudioResampler                      *mResampler;
    794             int32_t                             *mRsmpOutBuffer;
    795             int16_t                             *mRsmpInBuffer;
    796             size_t                              mRsmpInIndex;
    797             size_t                              mInputBytes;
    798             const uint32_t                      mReqChannelCount;
    799             const uint32_t                      mReqSampleRate;
    800             ssize_t                             mBytesRead;
    801             // sync event triggering actual audio capture. Frames read before this event will
    802             // be dropped and therefore not read by the application.
    803             sp<SyncEvent>                       mSyncStartEvent;
    804             // number of captured frames to drop after the start sync event has been received.
    805             // when < 0, maximum frames to drop before starting capture even if sync event is
    806             // not received
    807             ssize_t                             mFramestoDrop;
    808 
    809             // For dumpsys
    810             const sp<NBAIO_Sink>                mTeeSink;
    811 };
    812