Threads.h revision 1bfe09a0b1755a79abd32b41c0dd433b88fc260c
1bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai/*
2bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai**
3bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai** Copyright 2012, The Android Open Source Project
4bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai**
5bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai** Licensed under the Apache License, Version 2.0 (the "License");
6bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai** you may not use this file except in compliance with the License.
70a8380313528574c0a08babc56bc5db45775147eFumitoshi Ukai** You may obtain a copy of the License at
80a8380313528574c0a08babc56bc5db45775147eFumitoshi Ukai**
937626b6a9f1326cd7712b8c902416e36ac5c2ba9Shinichiro Hamaji**     http://www.apache.org/licenses/LICENSE-2.0
1055906852d451c0b11bb6fba7e674ad44568e951fShinichiro Hamaji**
11bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai** Unless required by applicable law or agreed to in writing, software
12bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai** distributed under the License is distributed on an "AS IS" BASIS,
13bb79a9daceea93a8a9c4eaf54a5dac37a3420033Fumitoshi Ukai** 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
22class ThreadBase : public Thread {
23public:
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        MMAP                // control thread for MMAP stream
34        // If you add any values here, also update ThreadBase::threadTypeToString()
35    };
36
37    static const char *threadTypeToString(type_t type);
38
39    ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
40                audio_devices_t outDevice, audio_devices_t inDevice, type_t type,
41                bool systemReady);
42    virtual             ~ThreadBase();
43
44    virtual status_t    readyToRun();
45
46    void dumpBase(int fd, const Vector<String16>& args);
47    void dumpEffectChains(int fd, const Vector<String16>& args);
48
49    void clearPowerManager();
50
51    // base for record and playback
52    enum {
53        CFG_EVENT_IO,
54        CFG_EVENT_PRIO,
55        CFG_EVENT_SET_PARAMETER,
56        CFG_EVENT_CREATE_AUDIO_PATCH,
57        CFG_EVENT_RELEASE_AUDIO_PATCH,
58    };
59
60    class ConfigEventData: public RefBase {
61    public:
62        virtual ~ConfigEventData() {}
63
64        virtual  void dump(char *buffer, size_t size) = 0;
65    protected:
66        ConfigEventData() {}
67    };
68
69    // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
70    //  1. create SetParameterConfigEvent. This sets mWaitStatus in config event
71    //  2. Lock mLock
72    //  3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
73    //  4. sendConfigEvent_l() reads status from event->mStatus;
74    //  5. sendConfigEvent_l() returns status
75    //  6. Unlock
76    //
77    // Parameter sequence by server: threadLoop calling processConfigEvents_l():
78    // 1. Lock mLock
79    // 2. If there is an entry in mConfigEvents proceed ...
80    // 3. Read first entry in mConfigEvents
81    // 4. Remove first entry from mConfigEvents
82    // 5. Process
83    // 6. Set event->mStatus
84    // 7. event->mCond.signal
85    // 8. Unlock
86
87    class ConfigEvent: public RefBase {
88    public:
89        virtual ~ConfigEvent() {}
90
91        void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
92
93        const int mType; // event type e.g. CFG_EVENT_IO
94        Mutex mLock;     // mutex associated with mCond
95        Condition mCond; // condition for status return
96        status_t mStatus; // status communicated to sender
97        bool mWaitStatus; // true if sender is waiting for status
98        bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
99        sp<ConfigEventData> mData;     // event specific parameter data
100
101    protected:
102        explicit ConfigEvent(int type, bool requiresSystemReady = false) :
103            mType(type), mStatus(NO_ERROR), mWaitStatus(false),
104            mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
105    };
106
107    class IoConfigEventData : public ConfigEventData {
108    public:
109        IoConfigEventData(audio_io_config_event event, pid_t pid) :
110            mEvent(event), mPid(pid) {}
111
112        virtual  void dump(char *buffer, size_t size) {
113            snprintf(buffer, size, "IO event: event %d\n", mEvent);
114        }
115
116        const audio_io_config_event mEvent;
117        const pid_t                 mPid;
118    };
119
120    class IoConfigEvent : public ConfigEvent {
121    public:
122        IoConfigEvent(audio_io_config_event event, pid_t pid) :
123            ConfigEvent(CFG_EVENT_IO) {
124            mData = new IoConfigEventData(event, pid);
125        }
126        virtual ~IoConfigEvent() {}
127    };
128
129    class PrioConfigEventData : public ConfigEventData {
130    public:
131        PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
132            mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
133
134        virtual  void dump(char *buffer, size_t size) {
135            snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d, for app? %d\n",
136                    mPid, mTid, mPrio, mForApp);
137        }
138
139        const pid_t mPid;
140        const pid_t mTid;
141        const int32_t mPrio;
142        const bool mForApp;
143    };
144
145    class PrioConfigEvent : public ConfigEvent {
146    public:
147        PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
148            ConfigEvent(CFG_EVENT_PRIO, true) {
149            mData = new PrioConfigEventData(pid, tid, prio, forApp);
150        }
151        virtual ~PrioConfigEvent() {}
152    };
153
154    class SetParameterConfigEventData : public ConfigEventData {
155    public:
156        explicit SetParameterConfigEventData(String8 keyValuePairs) :
157            mKeyValuePairs(keyValuePairs) {}
158
159        virtual  void dump(char *buffer, size_t size) {
160            snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
161        }
162
163        const String8 mKeyValuePairs;
164    };
165
166    class SetParameterConfigEvent : public ConfigEvent {
167    public:
168        explicit SetParameterConfigEvent(String8 keyValuePairs) :
169            ConfigEvent(CFG_EVENT_SET_PARAMETER) {
170            mData = new SetParameterConfigEventData(keyValuePairs);
171            mWaitStatus = true;
172        }
173        virtual ~SetParameterConfigEvent() {}
174    };
175
176    class CreateAudioPatchConfigEventData : public ConfigEventData {
177    public:
178        CreateAudioPatchConfigEventData(const struct audio_patch patch,
179                                        audio_patch_handle_t handle) :
180            mPatch(patch), mHandle(handle) {}
181
182        virtual  void dump(char *buffer, size_t size) {
183            snprintf(buffer, size, "Patch handle: %u\n", mHandle);
184        }
185
186        const struct audio_patch mPatch;
187        audio_patch_handle_t mHandle;
188    };
189
190    class CreateAudioPatchConfigEvent : public ConfigEvent {
191    public:
192        CreateAudioPatchConfigEvent(const struct audio_patch patch,
193                                    audio_patch_handle_t handle) :
194            ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
195            mData = new CreateAudioPatchConfigEventData(patch, handle);
196            mWaitStatus = true;
197        }
198        virtual ~CreateAudioPatchConfigEvent() {}
199    };
200
201    class ReleaseAudioPatchConfigEventData : public ConfigEventData {
202    public:
203        explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
204            mHandle(handle) {}
205
206        virtual  void dump(char *buffer, size_t size) {
207            snprintf(buffer, size, "Patch handle: %u\n", mHandle);
208        }
209
210        audio_patch_handle_t mHandle;
211    };
212
213    class ReleaseAudioPatchConfigEvent : public ConfigEvent {
214    public:
215        explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
216            ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
217            mData = new ReleaseAudioPatchConfigEventData(handle);
218            mWaitStatus = true;
219        }
220        virtual ~ReleaseAudioPatchConfigEvent() {}
221    };
222
223    class PMDeathRecipient : public IBinder::DeathRecipient {
224    public:
225        explicit    PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
226        virtual     ~PMDeathRecipient() {}
227
228        // IBinder::DeathRecipient
229        virtual     void        binderDied(const wp<IBinder>& who);
230
231    private:
232                    PMDeathRecipient(const PMDeathRecipient&);
233                    PMDeathRecipient& operator = (const PMDeathRecipient&);
234
235        wp<ThreadBase> mThread;
236    };
237
238    virtual     status_t    initCheck() const = 0;
239
240                // static externally-visible
241                type_t      type() const { return mType; }
242                bool isDuplicating() const { return (mType == DUPLICATING); }
243
244                audio_io_handle_t id() const { return mId;}
245
246                // dynamic externally-visible
247                uint32_t    sampleRate() const { return mSampleRate; }
248                audio_channel_mask_t channelMask() const { return mChannelMask; }
249                audio_format_t format() const { return mHALFormat; }
250                uint32_t channelCount() const { return mChannelCount; }
251                // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
252                // and returns the [normal mix] buffer's frame count.
253    virtual     size_t      frameCount() const = 0;
254
255                // Return's the HAL's frame count i.e. fast mixer buffer size.
256                size_t      frameCountHAL() const { return mFrameCount; }
257
258                size_t      frameSize() const { return mFrameSize; }
259
260    // Should be "virtual status_t requestExitAndWait()" and override same
261    // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
262                void        exit();
263    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
264                                                    status_t& status) = 0;
265    virtual     status_t    setParameters(const String8& keyValuePairs);
266    virtual     String8     getParameters(const String8& keys) = 0;
267    virtual     void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0) = 0;
268                // sendConfigEvent_l() must be called with ThreadBase::mLock held
269                // Can temporarily release the lock if waiting for a reply from
270                // processConfigEvents_l().
271                status_t    sendConfigEvent_l(sp<ConfigEvent>& event);
272                void        sendIoConfigEvent(audio_io_config_event event, pid_t pid = 0);
273                void        sendIoConfigEvent_l(audio_io_config_event event, pid_t pid = 0);
274                void        sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp);
275                void        sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp);
276                status_t    sendSetParameterConfigEvent_l(const String8& keyValuePair);
277                status_t    sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
278                                                            audio_patch_handle_t *handle);
279                status_t    sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
280                void        processConfigEvents_l();
281    virtual     void        cacheParameters_l() = 0;
282    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
283                                               audio_patch_handle_t *handle) = 0;
284    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
285    virtual     void        getAudioPortConfig(struct audio_port_config *config) = 0;
286
287
288                // see note at declaration of mStandby, mOutDevice and mInDevice
289                bool        standby() const { return mStandby; }
290                audio_devices_t outDevice() const { return mOutDevice; }
291                audio_devices_t inDevice() const { return mInDevice; }
292                audio_devices_t getDevice() const { return isOutput() ? mOutDevice : mInDevice; }
293
294    virtual     bool        isOutput() const = 0;
295
296    virtual     sp<StreamHalInterface> stream() const = 0;
297
298                sp<EffectHandle> createEffect_l(
299                                    const sp<AudioFlinger::Client>& client,
300                                    const sp<IEffectClient>& effectClient,
301                                    int32_t priority,
302                                    audio_session_t sessionId,
303                                    effect_descriptor_t *desc,
304                                    int *enabled,
305                                    status_t *status /*non-NULL*/,
306                                    bool pinned);
307
308                // return values for hasAudioSession (bit field)
309                enum effect_state {
310                    EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
311                                            // effect
312                    TRACK_SESSION = 0x2,    // the audio session corresponds to at least one
313                                            // track
314                    FAST_SESSION = 0x4      // the audio session corresponds to at least one
315                                            // fast track
316                };
317
318                // get effect chain corresponding to session Id.
319                sp<EffectChain> getEffectChain(audio_session_t sessionId);
320                // same as getEffectChain() but must be called with ThreadBase mutex locked
321                sp<EffectChain> getEffectChain_l(audio_session_t sessionId) const;
322                // add an effect chain to the chain list (mEffectChains)
323    virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
324                // remove an effect chain from the chain list (mEffectChains)
325    virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
326                // lock all effect chains Mutexes. Must be called before releasing the
327                // ThreadBase mutex before processing the mixer and effects. This guarantees the
328                // integrity of the chains during the process.
329                // Also sets the parameter 'effectChains' to current value of mEffectChains.
330                void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
331                // unlock effect chains after process
332                void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
333                // get a copy of mEffectChains vector
334                Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
335                // set audio mode to all effect chains
336                void setMode(audio_mode_t mode);
337                // get effect module with corresponding ID on specified audio session
338                sp<AudioFlinger::EffectModule> getEffect(audio_session_t sessionId, int effectId);
339                sp<AudioFlinger::EffectModule> getEffect_l(audio_session_t sessionId, int effectId);
340                // add and effect module. Also creates the effect chain is none exists for
341                // the effects audio session
342                status_t addEffect_l(const sp< EffectModule>& effect);
343                // remove and effect module. Also removes the effect chain is this was the last
344                // effect
345                void removeEffect_l(const sp< EffectModule>& effect, bool release = false);
346                // disconnect an effect handle from module and destroy module if last handle
347                void disconnectEffectHandle(EffectHandle *handle, bool unpinIfLast);
348                // detach all tracks connected to an auxiliary effect
349    virtual     void detachAuxEffect_l(int effectId __unused) {}
350                // returns a combination of:
351                // - EFFECT_SESSION if effects on this audio session exist in one chain
352                // - TRACK_SESSION if tracks on this audio session exist
353                // - FAST_SESSION if fast tracks on this audio session exist
354    virtual     uint32_t hasAudioSession_l(audio_session_t sessionId) const = 0;
355                uint32_t hasAudioSession(audio_session_t sessionId) const {
356                    Mutex::Autolock _l(mLock);
357                    return hasAudioSession_l(sessionId);
358                }
359
360                // the value returned by default implementation is not important as the
361                // strategy is only meaningful for PlaybackThread which implements this method
362                virtual uint32_t getStrategyForSession_l(audio_session_t sessionId __unused)
363                        { return 0; }
364
365                // suspend or restore effect according to the type of effect passed. a NULL
366                // type pointer means suspend all effects in the session
367                void setEffectSuspended(const effect_uuid_t *type,
368                                        bool suspend,
369                                        audio_session_t sessionId = AUDIO_SESSION_OUTPUT_MIX);
370                // check if some effects must be suspended/restored when an effect is enabled
371                // or disabled
372                void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
373                                                 bool enabled,
374                                                 audio_session_t sessionId =
375                                                        AUDIO_SESSION_OUTPUT_MIX);
376                void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
377                                                   bool enabled,
378                                                   audio_session_t sessionId =
379                                                        AUDIO_SESSION_OUTPUT_MIX);
380
381                virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
382                virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
383
384                // Return a reference to a per-thread heap which can be used to allocate IMemory
385                // objects that will be read-only to client processes, read/write to mediaserver,
386                // and shared by all client processes of the thread.
387                // The heap is per-thread rather than common across all threads, because
388                // clients can't be trusted not to modify the offset of the IMemory they receive.
389                // If a thread does not have such a heap, this method returns 0.
390                virtual sp<MemoryDealer>    readOnlyHeap() const { return 0; }
391
392                virtual sp<IMemory> pipeMemory() const { return 0; }
393
394                        void systemReady();
395
396                // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
397                virtual status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
398                                                               audio_session_t sessionId) = 0;
399
400                        void        broadcast_l();
401
402    mutable     Mutex                   mLock;
403
404protected:
405
406                // entry describing an effect being suspended in mSuspendedSessions keyed vector
407                class SuspendedSessionDesc : public RefBase {
408                public:
409                    SuspendedSessionDesc() : mRefCount(0) {}
410
411                    int mRefCount;          // number of active suspend requests
412                    effect_uuid_t mType;    // effect type UUID
413                };
414
415                void        acquireWakeLock();
416                virtual void acquireWakeLock_l();
417                void        releaseWakeLock();
418                void        releaseWakeLock_l();
419                void        updateWakeLockUids_l(const SortedVector<uid_t> &uids);
420                void        getPowerManager_l();
421                void setEffectSuspended_l(const effect_uuid_t *type,
422                                          bool suspend,
423                                          audio_session_t sessionId);
424                // updated mSuspendedSessions when an effect suspended or restored
425                void        updateSuspendedSessions_l(const effect_uuid_t *type,
426                                                      bool suspend,
427                                                      audio_session_t sessionId);
428                // check if some effects must be suspended when an effect chain is added
429                void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
430
431                String16 getWakeLockTag();
432
433    virtual     void        preExit() { }
434    virtual     void        setMasterMono_l(bool mono __unused) { }
435    virtual     bool        requireMonoBlend() { return false; }
436
437    friend class AudioFlinger;      // for mEffectChains
438
439                const type_t            mType;
440
441                // Used by parameters, config events, addTrack_l, exit
442                Condition               mWaitWorkCV;
443
444                const sp<AudioFlinger>  mAudioFlinger;
445
446                // updated by PlaybackThread::readOutputParameters_l() or
447                // RecordThread::readInputParameters_l()
448                uint32_t                mSampleRate;
449                size_t                  mFrameCount;       // output HAL, direct output, record
450                audio_channel_mask_t    mChannelMask;
451                uint32_t                mChannelCount;
452                size_t                  mFrameSize;
453                // not HAL frame size, this is for output sink (to pipe to fast mixer)
454                audio_format_t          mFormat;           // Source format for Recording and
455                                                           // Sink format for Playback.
456                                                           // Sink format may be different than
457                                                           // HAL format if Fastmixer is used.
458                audio_format_t          mHALFormat;
459                size_t                  mBufferSize;       // HAL buffer size for read() or write()
460
461                Vector< sp<ConfigEvent> >     mConfigEvents;
462                Vector< sp<ConfigEvent> >     mPendingConfigEvents; // events awaiting system ready
463
464                // These fields are written and read by thread itself without lock or barrier,
465                // and read by other threads without lock or barrier via standby(), outDevice()
466                // and inDevice().
467                // Because of the absence of a lock or barrier, any other thread that reads
468                // these fields must use the information in isolation, or be prepared to deal
469                // with possibility that it might be inconsistent with other information.
470                bool                    mStandby;     // Whether thread is currently in standby.
471                audio_devices_t         mOutDevice;   // output device
472                audio_devices_t         mInDevice;    // input device
473                audio_devices_t         mPrevOutDevice;   // previous output device
474                audio_devices_t         mPrevInDevice;    // previous input device
475                struct audio_patch      mPatch;
476                audio_source_t          mAudioSource;
477
478                const audio_io_handle_t mId;
479                Vector< sp<EffectChain> > mEffectChains;
480
481                static const int        kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
482                char                    mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
483                sp<IPowerManager>       mPowerManager;
484                sp<IBinder>             mWakeLockToken;
485                const sp<PMDeathRecipient> mDeathRecipient;
486                // list of suspended effects per session and per type. The first (outer) vector is
487                // keyed by session ID, the second (inner) by type UUID timeLow field
488                KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
489                                        mSuspendedSessions;
490                static const size_t     kLogSize = 4 * 1024;
491                sp<NBLog::Writer>       mNBLogWriter;
492                bool                    mSystemReady;
493                ExtendedTimestamp       mTimestamp;
494                // A condition that must be evaluated by the thread loop has changed and
495                // we must not wait for async write callback in the thread loop before evaluating it
496                bool                    mSignalPending;
497
498                // ActiveTracks is a sorted vector of track type T representing the
499                // active tracks of threadLoop() to be considered by the locked prepare portion.
500                // ActiveTracks should be accessed with the ThreadBase lock held.
501                //
502                // During processing and I/O, the threadLoop does not hold the lock;
503                // hence it does not directly use ActiveTracks.  Care should be taken
504                // to hold local strong references or defer removal of tracks
505                // if the threadLoop may still be accessing those tracks due to mix, etc.
506                //
507                // This class updates power information appropriately.
508                //
509
510                template <typename T>
511                class ActiveTracks {
512                public:
513                    ActiveTracks()
514                        : mActiveTracksGeneration(0)
515                        , mLastActiveTracksGeneration(0)
516                    { }
517
518                    ~ActiveTracks() {
519                        ALOGW_IF(!mActiveTracks.isEmpty(),
520                                "ActiveTracks should be empty in destructor");
521                    }
522                    // returns the last track added (even though it may have been
523                    // subsequently removed from ActiveTracks).
524                    //
525                    // Used for DirectOutputThread to ensure a flush is called when transitioning
526                    // to a new track (even though it may be on the same session).
527                    // Used for OffloadThread to ensure that volume and mixer state is
528                    // taken from the latest track added.
529                    //
530                    // The latest track is saved with a weak pointer to prevent keeping an
531                    // otherwise useless track alive. Thus the function will return nullptr
532                    // if the latest track has subsequently been removed and destroyed.
533                    sp<T> getLatest() {
534                        return mLatestActiveTrack.promote();
535                    }
536
537                    // SortedVector methods
538                    ssize_t         add(const sp<T> &track);
539                    ssize_t         remove(const sp<T> &track);
540                    size_t          size() const {
541                        return mActiveTracks.size();
542                    }
543                    ssize_t         indexOf(const sp<T>& item) {
544                        return mActiveTracks.indexOf(item);
545                    }
546                    sp<T>           operator[](size_t index) const {
547                        return mActiveTracks[index];
548                    }
549                    typename SortedVector<sp<T>>::iterator begin() {
550                        return mActiveTracks.begin();
551                    }
552                    typename SortedVector<sp<T>>::iterator end() {
553                        return mActiveTracks.end();
554                    }
555
556                    // Due to Binder recursion optimization, clear() and updatePowerState()
557                    // cannot be called from a Binder thread because they may call back into
558                    // the original calling process (system server) for BatteryNotifier
559                    // (which requires a Java environment that may not be present).
560                    // Hence, call clear() and updatePowerState() only from the
561                    // ThreadBase thread.
562                    void            clear();
563                    // periodically called in the threadLoop() to update power state uids.
564                    void            updatePowerState(sp<ThreadBase> thread, bool force = false);
565
566                private:
567                    SortedVector<uid_t> getWakeLockUids() {
568                        SortedVector<uid_t> wakeLockUids;
569                        for (const sp<T> &track : mActiveTracks) {
570                            wakeLockUids.add(track->uid());
571                        }
572                        return wakeLockUids; // moved by underlying SharedBuffer
573                    }
574
575                    std::map<uid_t, std::pair<ssize_t /* previous */, ssize_t /* current */>>
576                                        mBatteryCounter;
577                    SortedVector<sp<T>> mActiveTracks;
578                    int                 mActiveTracksGeneration;
579                    int                 mLastActiveTracksGeneration;
580                    wp<T>               mLatestActiveTrack; // latest track added to ActiveTracks
581                };
582
583                SimpleLog mLocalLog;
584};
585
586class VolumeInterface {
587 public:
588
589    virtual ~VolumeInterface() {}
590
591    virtual void        setMasterVolume(float value) = 0;
592    virtual void        setMasterMute(bool muted) = 0;
593    virtual void        setStreamVolume(audio_stream_type_t stream, float value) = 0;
594    virtual void        setStreamMute(audio_stream_type_t stream, bool muted) = 0;
595    virtual float       streamVolume(audio_stream_type_t stream) const = 0;
596
597};
598
599// --- PlaybackThread ---
600class PlaybackThread : public ThreadBase, public StreamOutHalInterfaceCallback,
601    public VolumeInterface {
602public:
603
604#include "PlaybackTracks.h"
605
606    enum mixer_state {
607        MIXER_IDLE,             // no active tracks
608        MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
609        MIXER_TRACKS_READY,      // at least one active track, and at least one track has data
610        MIXER_DRAIN_TRACK,      // drain currently playing track
611        MIXER_DRAIN_ALL,        // fully drain the hardware
612        // standby mode does not have an enum value
613        // suspend by audio policy manager is orthogonal to mixer state
614    };
615
616    // retry count before removing active track in case of underrun on offloaded thread:
617    // we need to make sure that AudioTrack client has enough time to send large buffers
618    //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
619    // handled for offloaded tracks
620    static const int8_t kMaxTrackRetriesOffload = 20;
621    static const int8_t kMaxTrackStartupRetriesOffload = 100;
622    static const int8_t kMaxTrackStopRetriesOffload = 2;
623    // 14 tracks max per client allows for 2 misbehaving application leaving 4 available tracks.
624    static const uint32_t kMaxTracksPerUid = 14;
625
626    PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
627                   audio_io_handle_t id, audio_devices_t device, type_t type, bool systemReady);
628    virtual             ~PlaybackThread();
629
630                void        dump(int fd, const Vector<String16>& args);
631
632    // Thread virtuals
633    virtual     bool        threadLoop();
634
635    // RefBase
636    virtual     void        onFirstRef();
637
638    virtual     status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
639                                                       audio_session_t sessionId);
640
641protected:
642    // Code snippets that were lifted up out of threadLoop()
643    virtual     void        threadLoop_mix() = 0;
644    virtual     void        threadLoop_sleepTime() = 0;
645    virtual     ssize_t     threadLoop_write();
646    virtual     void        threadLoop_drain();
647    virtual     void        threadLoop_standby();
648    virtual     void        threadLoop_exit();
649    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
650
651                // prepareTracks_l reads and writes mActiveTracks, and returns
652                // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
653                // is responsible for clearing or destroying this Vector later on, when it
654                // is safe to do so. That will drop the final ref count and destroy the tracks.
655    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
656                void        removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
657
658    // StreamOutHalInterfaceCallback implementation
659    virtual     void        onWriteReady();
660    virtual     void        onDrainReady();
661    virtual     void        onError();
662
663                void        resetWriteBlocked(uint32_t sequence);
664                void        resetDraining(uint32_t sequence);
665
666    virtual     bool        waitingAsyncCallback();
667    virtual     bool        waitingAsyncCallback_l();
668    virtual     bool        shouldStandby_l();
669    virtual     void        onAddNewTrack_l();
670                void        onAsyncError(); // error reported by AsyncCallbackThread
671
672    // ThreadBase virtuals
673    virtual     void        preExit();
674
675    virtual     bool        keepWakeLock() const { return true; }
676    virtual     void        acquireWakeLock_l() {
677                                ThreadBase::acquireWakeLock_l();
678                                mActiveTracks.updatePowerState(this, true /* force */);
679                            }
680
681public:
682
683    virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
684
685                // return estimated latency in milliseconds, as reported by HAL
686                uint32_t    latency() const;
687                // same, but lock must already be held
688                uint32_t    latency_l() const;
689
690                // VolumeInterface
691    virtual     void        setMasterVolume(float value);
692    virtual     void        setMasterMute(bool muted);
693    virtual     void        setStreamVolume(audio_stream_type_t stream, float value);
694    virtual     void        setStreamMute(audio_stream_type_t stream, bool muted);
695    virtual     float       streamVolume(audio_stream_type_t stream) const;
696
697                sp<Track>   createTrack_l(
698                                const sp<AudioFlinger::Client>& client,
699                                audio_stream_type_t streamType,
700                                uint32_t sampleRate,
701                                audio_format_t format,
702                                audio_channel_mask_t channelMask,
703                                size_t *pFrameCount,
704                                const sp<IMemory>& sharedBuffer,
705                                audio_session_t sessionId,
706                                audio_output_flags_t *flags,
707                                pid_t tid,
708                                uid_t uid,
709                                status_t *status /*non-NULL*/,
710                                audio_port_handle_t portId);
711
712                AudioStreamOut* getOutput() const;
713                AudioStreamOut* clearOutput();
714                virtual sp<StreamHalInterface> stream() const;
715
716                // a very large number of suspend() will eventually wraparound, but unlikely
717                void        suspend() { (void) android_atomic_inc(&mSuspended); }
718                void        restore()
719                                {
720                                    // if restore() is done without suspend(), get back into
721                                    // range so that the next suspend() will operate correctly
722                                    if (android_atomic_dec(&mSuspended) <= 0) {
723                                        android_atomic_release_store(0, &mSuspended);
724                                    }
725                                }
726                bool        isSuspended() const
727                                { return android_atomic_acquire_load(&mSuspended) > 0; }
728
729    virtual     String8     getParameters(const String8& keys);
730    virtual     void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
731                status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
732                // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency.
733                // Consider also removing and passing an explicit mMainBuffer initialization
734                // parameter to AF::PlaybackThread::Track::Track().
735                int16_t     *mixBuffer() const {
736                    return reinterpret_cast<int16_t *>(mSinkBuffer); };
737
738    virtual     void detachAuxEffect_l(int effectId);
739                status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track>& track,
740                        int EffectId);
741                status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track>& track,
742                        int EffectId);
743
744                virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
745                virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
746                virtual uint32_t hasAudioSession_l(audio_session_t sessionId) const;
747                virtual uint32_t getStrategyForSession_l(audio_session_t sessionId);
748
749
750                virtual status_t setSyncEvent(const sp<SyncEvent>& event);
751                virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
752
753                // called with AudioFlinger lock held
754                        bool     invalidateTracks_l(audio_stream_type_t streamType);
755                virtual void     invalidateTracks(audio_stream_type_t streamType);
756
757    virtual     size_t      frameCount() const { return mNormalFrameCount; }
758
759                status_t    getTimestamp_l(AudioTimestamp& timestamp);
760
761                void        addPatchTrack(const sp<PatchTrack>& track);
762                void        deletePatchTrack(const sp<PatchTrack>& track);
763
764    virtual     void        getAudioPortConfig(struct audio_port_config *config);
765
766                // Return the asynchronous signal wait time.
767    virtual     int64_t     computeWaitTimeNs_l() const { return INT64_MAX; }
768
769    virtual     bool        isOutput() const override { return true; }
770
771protected:
772    // updated by readOutputParameters_l()
773    size_t                          mNormalFrameCount;  // normal mixer and effects
774
775    bool                            mThreadThrottle;     // throttle the thread processing
776    uint32_t                        mThreadThrottleTimeMs; // throttle time for MIXER threads
777    uint32_t                        mThreadThrottleEndMs;  // notify once per throttling
778    uint32_t                        mHalfBufferMs;       // half the buffer size in milliseconds
779
780    void*                           mSinkBuffer;         // frame size aligned sink buffer
781
782    // TODO:
783    // Rearrange the buffer info into a struct/class with
784    // clear, copy, construction, destruction methods.
785    //
786    // mSinkBuffer also has associated with it:
787    //
788    // mSinkBufferSize: Sink Buffer Size
789    // mFormat: Sink Buffer Format
790
791    // Mixer Buffer (mMixerBuffer*)
792    //
793    // In the case of floating point or multichannel data, which is not in the
794    // sink format, it is required to accumulate in a higher precision or greater channel count
795    // buffer before downmixing or data conversion to the sink buffer.
796
797    // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
798    bool                            mMixerBufferEnabled;
799
800    // Storage, 32 byte aligned (may make this alignment a requirement later).
801    // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
802    void*                           mMixerBuffer;
803
804    // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
805    size_t                          mMixerBufferSize;
806
807    // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
808    audio_format_t                  mMixerBufferFormat;
809
810    // An internal flag set to true by MixerThread::prepareTracks_l()
811    // when mMixerBuffer contains valid data after mixing.
812    bool                            mMixerBufferValid;
813
814    // Effects Buffer (mEffectsBuffer*)
815    //
816    // In the case of effects data, which is not in the sink format,
817    // it is required to accumulate in a different buffer before data conversion
818    // to the sink buffer.
819
820    // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
821    bool                            mEffectBufferEnabled;
822
823    // Storage, 32 byte aligned (may make this alignment a requirement later).
824    // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
825    void*                           mEffectBuffer;
826
827    // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
828    size_t                          mEffectBufferSize;
829
830    // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
831    audio_format_t                  mEffectBufferFormat;
832
833    // An internal flag set to true by MixerThread::prepareTracks_l()
834    // when mEffectsBuffer contains valid data after mixing.
835    //
836    // When this is set, all mixer data is routed into the effects buffer
837    // for any processing (including output processing).
838    bool                            mEffectBufferValid;
839
840    // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
841    // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
842    // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
843    // workaround that restriction.
844    // 'volatile' means accessed via atomic operations and no lock.
845    volatile int32_t                mSuspended;
846
847    int64_t                         mBytesWritten;
848    int64_t                         mFramesWritten; // not reset on standby
849    int64_t                         mSuspendedFrames; // not reset on standby
850private:
851    // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
852    // PlaybackThread needs to find out if master-muted, it checks it's local
853    // copy rather than the one in AudioFlinger.  This optimization saves a lock.
854    bool                            mMasterMute;
855                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
856protected:
857    ActiveTracks<Track>     mActiveTracks;
858
859    // Allocate a track name for a given channel mask.
860    //   Returns name >= 0 if successful, -1 on failure.
861    virtual int             getTrackName_l(audio_channel_mask_t channelMask, audio_format_t format,
862                                           audio_session_t sessionId, uid_t uid) = 0;
863    virtual void            deleteTrackName_l(int name) = 0;
864
865    // Time to sleep between cycles when:
866    virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
867    virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
868    virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
869    // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
870    // No sleep in standby mode; waits on a condition
871
872    // Code snippets that are temporarily lifted up out of threadLoop() until the merge
873                void        checkSilentMode_l();
874
875    // Non-trivial for DUPLICATING only
876    virtual     void        saveOutputTracks() { }
877    virtual     void        clearOutputTracks() { }
878
879    // Cache various calculated values, at threadLoop() entry and after a parameter change
880    virtual     void        cacheParameters_l();
881
882    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
883
884    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
885                                   audio_patch_handle_t *handle);
886    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
887
888                bool        usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL)
889                                    && mHwSupportsPause
890                                    && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
891
892                uint32_t    trackCountForUid_l(uid_t uid);
893
894private:
895
896    friend class AudioFlinger;      // for numerous
897
898    PlaybackThread& operator = (const PlaybackThread&);
899
900    status_t    addTrack_l(const sp<Track>& track);
901    bool        destroyTrack_l(const sp<Track>& track);
902    void        removeTrack_l(const sp<Track>& track);
903
904    void        readOutputParameters_l();
905
906    virtual void dumpInternals(int fd, const Vector<String16>& args);
907    void        dumpTracks(int fd, const Vector<String16>& args);
908
909    SortedVector< sp<Track> >       mTracks;
910    stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT];
911    AudioStreamOut                  *mOutput;
912
913    float                           mMasterVolume;
914    nsecs_t                         mLastWriteTime;
915    int                             mNumWrites;
916    int                             mNumDelayedWrites;
917    bool                            mInWrite;
918
919    // FIXME rename these former local variables of threadLoop to standard "m" names
920    nsecs_t                         mStandbyTimeNs;
921    size_t                          mSinkBufferSize;
922
923    // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
924    uint32_t                        mActiveSleepTimeUs;
925    uint32_t                        mIdleSleepTimeUs;
926
927    uint32_t                        mSleepTimeUs;
928
929    // mixer status returned by prepareTracks_l()
930    mixer_state                     mMixerStatus; // current cycle
931                                                  // previous cycle when in prepareTracks_l()
932    mixer_state                     mMixerStatusIgnoringFastTracks;
933                                                  // FIXME or a separate ready state per track
934
935    // FIXME move these declarations into the specific sub-class that needs them
936    // MIXER only
937    uint32_t                        sleepTimeShift;
938
939    // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
940    nsecs_t                         mStandbyDelayNs;
941
942    // MIXER only
943    nsecs_t                         maxPeriod;
944
945    // DUPLICATING only
946    uint32_t                        writeFrames;
947
948    size_t                          mBytesRemaining;
949    size_t                          mCurrentWriteLength;
950    bool                            mUseAsyncWrite;
951    // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
952    // incremented each time a write(), a flush() or a standby() occurs.
953    // Bit 0 is set when a write blocks and indicates a callback is expected.
954    // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
955    // callbacks are ignored.
956    uint32_t                        mWriteAckSequence;
957    // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
958    // incremented each time a drain is requested or a flush() or standby() occurs.
959    // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
960    // expected.
961    // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
962    // callbacks are ignored.
963    uint32_t                        mDrainSequence;
964    sp<AsyncCallbackThread>         mCallbackThread;
965
966private:
967    // The HAL output sink is treated as non-blocking, but current implementation is blocking
968    sp<NBAIO_Sink>          mOutputSink;
969    // If a fast mixer is present, the blocking pipe sink, otherwise clear
970    sp<NBAIO_Sink>          mPipeSink;
971    // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
972    sp<NBAIO_Sink>          mNormalSink;
973#ifdef TEE_SINK
974    // For dumpsys
975    sp<NBAIO_Sink>          mTeeSink;
976    sp<NBAIO_Source>        mTeeSource;
977#endif
978    uint32_t                mScreenState;   // cached copy of gScreenState
979    static const size_t     kFastMixerLogSize = 4 * 1024;
980    sp<NBLog::Writer>       mFastMixerNBLogWriter;
981
982
983public:
984    virtual     bool        hasFastMixer() const = 0;
985    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
986                                { FastTrackUnderruns dummy; return dummy; }
987
988protected:
989                // accessed by both binder threads and within threadLoop(), lock on mutex needed
990                unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
991                bool        mHwSupportsPause;
992                bool        mHwPaused;
993                bool        mFlushPending;
994};
995
996class MixerThread : public PlaybackThread {
997public:
998    MixerThread(const sp<AudioFlinger>& audioFlinger,
999                AudioStreamOut* output,
1000                audio_io_handle_t id,
1001                audio_devices_t device,
1002                bool systemReady,
1003                type_t type = MIXER);
1004    virtual             ~MixerThread();
1005
1006    // Thread virtuals
1007
1008    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
1009                                                   status_t& status);
1010    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
1011
1012protected:
1013    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1014    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, audio_format_t format,
1015                                           audio_session_t sessionId, uid_t uid);
1016    virtual     void        deleteTrackName_l(int name);
1017    virtual     uint32_t    idleSleepTimeUs() const;
1018    virtual     uint32_t    suspendSleepTimeUs() const;
1019    virtual     void        cacheParameters_l();
1020
1021    virtual void acquireWakeLock_l() {
1022        PlaybackThread::acquireWakeLock_l();
1023        if (hasFastMixer()) {
1024            mFastMixer->setBoottimeOffset(
1025                    mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1026        }
1027    }
1028
1029    // threadLoop snippets
1030    virtual     ssize_t     threadLoop_write();
1031    virtual     void        threadLoop_standby();
1032    virtual     void        threadLoop_mix();
1033    virtual     void        threadLoop_sleepTime();
1034    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
1035    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
1036
1037    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
1038                                   audio_patch_handle_t *handle);
1039    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1040
1041                AudioMixer* mAudioMixer;    // normal mixer
1042private:
1043                // one-time initialization, no locks required
1044                sp<FastMixer>     mFastMixer;     // non-0 if there is also a fast mixer
1045                sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1046
1047                // contents are not guaranteed to be consistent, no locks required
1048                FastMixerDumpState mFastMixerDumpState;
1049#ifdef STATE_QUEUE_DUMP
1050                StateQueueObserverDump mStateQueueObserverDump;
1051                StateQueueMutatorDump  mStateQueueMutatorDump;
1052#endif
1053                AudioWatchdogDump mAudioWatchdogDump;
1054
1055                // accessible only within the threadLoop(), no locks required
1056                //          mFastMixer->sq()    // for mutating and pushing state
1057                int32_t     mFastMixerFutex;    // for cold idle
1058
1059                std::atomic_bool mMasterMono;
1060public:
1061    virtual     bool        hasFastMixer() const { return mFastMixer != 0; }
1062    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
1063                              ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
1064                              return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1065                            }
1066
1067protected:
1068    virtual     void       setMasterMono_l(bool mono) {
1069                               mMasterMono.store(mono);
1070                               if (mFastMixer != nullptr) { /* hasFastMixer() */
1071                                   mFastMixer->setMasterMono(mMasterMono);
1072                               }
1073                           }
1074                // the FastMixer performs mono blend if it exists.
1075                // Blending with limiter is not idempotent,
1076                // and blending without limiter is idempotent but inefficient to do twice.
1077    virtual     bool       requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
1078};
1079
1080class DirectOutputThread : public PlaybackThread {
1081public:
1082
1083    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1084                       audio_io_handle_t id, audio_devices_t device, bool systemReady);
1085    virtual                 ~DirectOutputThread();
1086
1087    // Thread virtuals
1088
1089    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
1090                                                   status_t& status);
1091    virtual     void        flushHw_l();
1092
1093protected:
1094    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, audio_format_t format,
1095                                           audio_session_t sessionId, uid_t uid);
1096    virtual     void        deleteTrackName_l(int name);
1097    virtual     uint32_t    activeSleepTimeUs() const;
1098    virtual     uint32_t    idleSleepTimeUs() const;
1099    virtual     uint32_t    suspendSleepTimeUs() const;
1100    virtual     void        cacheParameters_l();
1101
1102    // threadLoop snippets
1103    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1104    virtual     void        threadLoop_mix();
1105    virtual     void        threadLoop_sleepTime();
1106    virtual     void        threadLoop_exit();
1107    virtual     bool        shouldStandby_l();
1108
1109    virtual     void        onAddNewTrack_l();
1110
1111    // volumes last sent to audio HAL with stream->set_volume()
1112    float mLeftVolFloat;
1113    float mRightVolFloat;
1114    bool mVolumeShaperActive;
1115
1116    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1117                        audio_io_handle_t id, uint32_t device, ThreadBase::type_t type,
1118                        bool systemReady);
1119    void processVolume_l(Track *track, bool lastTrack);
1120
1121    // prepareTracks_l() tells threadLoop_mix() the name of the single active track
1122    sp<Track>               mActiveTrack;
1123
1124    wp<Track>               mPreviousTrack;         // used to detect track switch
1125
1126public:
1127    virtual     bool        hasFastMixer() const { return false; }
1128
1129    virtual     int64_t     computeWaitTimeNs_l() const override;
1130};
1131
1132class OffloadThread : public DirectOutputThread {
1133public:
1134
1135    OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1136                        audio_io_handle_t id, uint32_t device, bool systemReady);
1137    virtual                 ~OffloadThread() {};
1138    virtual     void        flushHw_l();
1139
1140protected:
1141    // threadLoop snippets
1142    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1143    virtual     void        threadLoop_exit();
1144
1145    virtual     bool        waitingAsyncCallback();
1146    virtual     bool        waitingAsyncCallback_l();
1147    virtual     void        invalidateTracks(audio_stream_type_t streamType);
1148
1149    virtual     bool        keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
1150
1151private:
1152    size_t      mPausedWriteLength;     // length in bytes of write interrupted by pause
1153    size_t      mPausedBytesRemaining;  // bytes still waiting in mixbuffer after resume
1154    bool        mKeepWakeLock;          // keep wake lock while waiting for write callback
1155    uint64_t    mOffloadUnderrunPosition; // Current frame position for offloaded playback
1156                                          // used and valid only during underrun.  ~0 if
1157                                          // no underrun has occurred during playback and
1158                                          // is not reset on standby.
1159};
1160
1161class AsyncCallbackThread : public Thread {
1162public:
1163
1164    explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
1165
1166    virtual             ~AsyncCallbackThread();
1167
1168    // Thread virtuals
1169    virtual bool        threadLoop();
1170
1171    // RefBase
1172    virtual void        onFirstRef();
1173
1174            void        exit();
1175            void        setWriteBlocked(uint32_t sequence);
1176            void        resetWriteBlocked();
1177            void        setDraining(uint32_t sequence);
1178            void        resetDraining();
1179            void        setAsyncError();
1180
1181private:
1182    const wp<PlaybackThread>   mPlaybackThread;
1183    // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1184    // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1185    // to indicate that the callback has been received via resetWriteBlocked()
1186    uint32_t                   mWriteAckSequence;
1187    // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1188    // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1189    // to indicate that the callback has been received via resetDraining()
1190    uint32_t                   mDrainSequence;
1191    Condition                  mWaitWorkCV;
1192    Mutex                      mLock;
1193    bool                       mAsyncError;
1194};
1195
1196class DuplicatingThread : public MixerThread {
1197public:
1198    DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
1199                      audio_io_handle_t id, bool systemReady);
1200    virtual                 ~DuplicatingThread();
1201
1202    // Thread virtuals
1203                void        addOutputTrack(MixerThread* thread);
1204                void        removeOutputTrack(MixerThread* thread);
1205                uint32_t    waitTimeMs() const { return mWaitTimeMs; }
1206protected:
1207    virtual     uint32_t    activeSleepTimeUs() const;
1208
1209private:
1210                bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1211protected:
1212    // threadLoop snippets
1213    virtual     void        threadLoop_mix();
1214    virtual     void        threadLoop_sleepTime();
1215    virtual     ssize_t     threadLoop_write();
1216    virtual     void        threadLoop_standby();
1217    virtual     void        cacheParameters_l();
1218
1219private:
1220    // called from threadLoop, addOutputTrack, removeOutputTrack
1221    virtual     void        updateWaitTime_l();
1222protected:
1223    virtual     void        saveOutputTracks();
1224    virtual     void        clearOutputTracks();
1225private:
1226
1227                uint32_t    mWaitTimeMs;
1228    SortedVector < sp<OutputTrack> >  outputTracks;
1229    SortedVector < sp<OutputTrack> >  mOutputTracks;
1230public:
1231    virtual     bool        hasFastMixer() const { return false; }
1232};
1233
1234// record thread
1235class RecordThread : public ThreadBase
1236{
1237public:
1238
1239    class RecordTrack;
1240
1241    /* The ResamplerBufferProvider is used to retrieve recorded input data from the
1242     * RecordThread.  It maintains local state on the relative position of the read
1243     * position of the RecordTrack compared with the RecordThread.
1244     */
1245    class ResamplerBufferProvider : public AudioBufferProvider
1246    {
1247    public:
1248        explicit ResamplerBufferProvider(RecordTrack* recordTrack) :
1249            mRecordTrack(recordTrack),
1250            mRsmpInUnrel(0), mRsmpInFront(0) { }
1251        virtual ~ResamplerBufferProvider() { }
1252
1253        // called to set the ResamplerBufferProvider to head of the RecordThread data buffer,
1254        // skipping any previous data read from the hal.
1255        virtual void reset();
1256
1257        /* Synchronizes RecordTrack position with the RecordThread.
1258         * Calculates available frames and handle overruns if the RecordThread
1259         * has advanced faster than the ResamplerBufferProvider has retrieved data.
1260         * TODO: why not do this for every getNextBuffer?
1261         *
1262         * Parameters
1263         * framesAvailable:  pointer to optional output size_t to store record track
1264         *                   frames available.
1265         *      hasOverrun:  pointer to optional boolean, returns true if track has overrun.
1266         */
1267
1268        virtual void sync(size_t *framesAvailable = NULL, bool *hasOverrun = NULL);
1269
1270        // AudioBufferProvider interface
1271        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer);
1272        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1273    private:
1274        RecordTrack * const mRecordTrack;
1275        size_t              mRsmpInUnrel;   // unreleased frames remaining from
1276                                            // most recent getNextBuffer
1277                                            // for debug only
1278        int32_t             mRsmpInFront;   // next available frame
1279                                            // rolling counter that is never cleared
1280    };
1281
1282#include "RecordTracks.h"
1283
1284            RecordThread(const sp<AudioFlinger>& audioFlinger,
1285                    AudioStreamIn *input,
1286                    audio_io_handle_t id,
1287                    audio_devices_t outDevice,
1288                    audio_devices_t inDevice,
1289                    bool systemReady
1290#ifdef TEE_SINK
1291                    , const sp<NBAIO_Sink>& teeSink
1292#endif
1293                    );
1294            virtual     ~RecordThread();
1295
1296    // no addTrack_l ?
1297    void        destroyTrack_l(const sp<RecordTrack>& track);
1298    void        removeTrack_l(const sp<RecordTrack>& track);
1299
1300    void        dumpInternals(int fd, const Vector<String16>& args);
1301    void        dumpTracks(int fd, const Vector<String16>& args);
1302
1303    // Thread virtuals
1304    virtual bool        threadLoop();
1305    virtual void        preExit();
1306
1307    // RefBase
1308    virtual void        onFirstRef();
1309
1310    virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1311
1312    virtual sp<MemoryDealer>    readOnlyHeap() const { return mReadOnlyHeap; }
1313
1314    virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1315
1316            sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1317                    const sp<AudioFlinger::Client>& client,
1318                    uint32_t sampleRate,
1319                    audio_format_t format,
1320                    audio_channel_mask_t channelMask,
1321                    size_t *pFrameCount,
1322                    audio_session_t sessionId,
1323                    size_t *notificationFrames,
1324                    uid_t uid,
1325                    audio_input_flags_t *flags,
1326                    pid_t tid,
1327                    status_t *status /*non-NULL*/,
1328                    audio_port_handle_t portId);
1329
1330            status_t    start(RecordTrack* recordTrack,
1331                              AudioSystem::sync_event_t event,
1332                              audio_session_t triggerSession);
1333
1334            // ask the thread to stop the specified track, and
1335            // return true if the caller should then do it's part of the stopping process
1336            bool        stop(RecordTrack* recordTrack);
1337
1338            void        dump(int fd, const Vector<String16>& args);
1339            AudioStreamIn* clearInput();
1340            virtual sp<StreamHalInterface> stream() const;
1341
1342
1343    virtual bool        checkForNewParameter_l(const String8& keyValuePair,
1344                                               status_t& status);
1345    virtual void        cacheParameters_l() {}
1346    virtual String8     getParameters(const String8& keys);
1347    virtual void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
1348    virtual status_t    createAudioPatch_l(const struct audio_patch *patch,
1349                                           audio_patch_handle_t *handle);
1350    virtual status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1351
1352            void        addPatchRecord(const sp<PatchRecord>& record);
1353            void        deletePatchRecord(const sp<PatchRecord>& record);
1354
1355            void        readInputParameters_l();
1356    virtual uint32_t    getInputFramesLost();
1357
1358    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1359    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1360    virtual uint32_t hasAudioSession_l(audio_session_t sessionId) const;
1361
1362            // Return the set of unique session IDs across all tracks.
1363            // The keys are the session IDs, and the associated values are meaningless.
1364            // FIXME replace by Set [and implement Bag/Multiset for other uses].
1365            KeyedVector<audio_session_t, bool> sessionIds() const;
1366
1367    virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1368    virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
1369
1370    static void syncStartEventCallback(const wp<SyncEvent>& event);
1371
1372    virtual size_t      frameCount() const { return mFrameCount; }
1373            bool        hasFastCapture() const { return mFastCapture != 0; }
1374    virtual void        getAudioPortConfig(struct audio_port_config *config);
1375
1376    virtual status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
1377                                                   audio_session_t sessionId);
1378
1379    virtual void        acquireWakeLock_l() {
1380                            ThreadBase::acquireWakeLock_l();
1381                            mActiveTracks.updatePowerState(this, true /* force */);
1382                        }
1383    virtual bool        isOutput() const override { return false; }
1384
1385private:
1386            // Enter standby if not already in standby, and set mStandby flag
1387            void    standbyIfNotAlreadyInStandby();
1388
1389            // Call the HAL standby method unconditionally, and don't change mStandby flag
1390            void    inputStandBy();
1391
1392            AudioStreamIn                       *mInput;
1393            SortedVector < sp<RecordTrack> >    mTracks;
1394            // mActiveTracks has dual roles:  it indicates the current active track(s), and
1395            // is used together with mStartStopCond to indicate start()/stop() progress
1396            ActiveTracks<RecordTrack>           mActiveTracks;
1397
1398            Condition                           mStartStopCond;
1399
1400            // resampler converts input at HAL Hz to output at AudioRecord client Hz
1401            void                               *mRsmpInBuffer;  // size = mRsmpInFramesOA
1402            size_t                              mRsmpInFrames;  // size of resampler input in frames
1403            size_t                              mRsmpInFramesP2;// size rounded up to a power-of-2
1404            size_t                              mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
1405
1406            // rolling index that is never cleared
1407            int32_t                             mRsmpInRear;    // last filled frame + 1
1408
1409            // For dumpsys
1410            const sp<NBAIO_Sink>                mTeeSink;
1411
1412            const sp<MemoryDealer>              mReadOnlyHeap;
1413
1414            // one-time initialization, no locks required
1415            sp<FastCapture>                     mFastCapture;   // non-0 if there is also
1416                                                                // a fast capture
1417
1418            // FIXME audio watchdog thread
1419
1420            // contents are not guaranteed to be consistent, no locks required
1421            FastCaptureDumpState                mFastCaptureDumpState;
1422#ifdef STATE_QUEUE_DUMP
1423            // FIXME StateQueue observer and mutator dump fields
1424#endif
1425            // FIXME audio watchdog dump
1426
1427            // accessible only within the threadLoop(), no locks required
1428            //          mFastCapture->sq()      // for mutating and pushing state
1429            int32_t     mFastCaptureFutex;      // for cold idle
1430
1431            // The HAL input source is treated as non-blocking,
1432            // but current implementation is blocking
1433            sp<NBAIO_Source>                    mInputSource;
1434            // The source for the normal capture thread to read from: mInputSource or mPipeSource
1435            sp<NBAIO_Source>                    mNormalSource;
1436            // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1437            // otherwise clear
1438            sp<NBAIO_Sink>                      mPipeSink;
1439            // If a fast capture is present, the non-blocking pipe source read by normal thread,
1440            // otherwise clear
1441            sp<NBAIO_Source>                    mPipeSource;
1442            // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1443            size_t                              mPipeFramesP2;
1444            // If a fast capture is present, the Pipe as IMemory, otherwise clear
1445            sp<IMemory>                         mPipeMemory;
1446
1447            static const size_t                 kFastCaptureLogSize = 4 * 1024;
1448            sp<NBLog::Writer>                   mFastCaptureNBLogWriter;
1449
1450            bool                                mFastTrackAvail;    // true if fast track available
1451};
1452
1453class MmapThread : public ThreadBase
1454{
1455 public:
1456
1457#include "MmapTracks.h"
1458
1459    MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1460                      AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
1461                      audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1462    virtual     ~MmapThread();
1463
1464    virtual     void        configure(const audio_attributes_t *attr,
1465                                      audio_stream_type_t streamType,
1466                                      audio_session_t sessionId,
1467                                      const sp<MmapStreamCallback>& callback,
1468                                      audio_port_handle_t portId);
1469
1470                void        disconnect();
1471
1472    // MmapStreamInterface
1473    status_t createMmapBuffer(int32_t minSizeFrames,
1474                                      struct audio_mmap_buffer_info *info);
1475    status_t getMmapPosition(struct audio_mmap_position *position);
1476    status_t start(const MmapStreamInterface::Client& client, audio_port_handle_t *handle);
1477    status_t stop(audio_port_handle_t handle);
1478    status_t standby();
1479
1480    // RefBase
1481    virtual     void        onFirstRef();
1482
1483    // Thread virtuals
1484    virtual     bool        threadLoop();
1485
1486    virtual     void        threadLoop_exit();
1487    virtual     void        threadLoop_standby();
1488    virtual     bool        shouldStandby_l() { return false; }
1489
1490    virtual     status_t    initCheck() const { return (mHalStream == 0) ? NO_INIT : NO_ERROR; }
1491    virtual     size_t      frameCount() const { return mFrameCount; }
1492    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
1493                                                    status_t& status);
1494    virtual     String8     getParameters(const String8& keys);
1495    virtual     void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
1496                void        readHalParameters_l();
1497    virtual     void        cacheParameters_l() {}
1498    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
1499                                               audio_patch_handle_t *handle);
1500    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1501    virtual     void        getAudioPortConfig(struct audio_port_config *config);
1502
1503    virtual     sp<StreamHalInterface> stream() const { return mHalStream; }
1504    virtual     status_t    addEffectChain_l(const sp<EffectChain>& chain);
1505    virtual     size_t      removeEffectChain_l(const sp<EffectChain>& chain);
1506    virtual     status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
1507                                                               audio_session_t sessionId);
1508
1509    virtual     uint32_t    hasAudioSession_l(audio_session_t sessionId) const;
1510    virtual     status_t    setSyncEvent(const sp<SyncEvent>& event);
1511    virtual     bool        isValidSyncEvent(const sp<SyncEvent>& event) const;
1512
1513    virtual     void        checkSilentMode_l() {}
1514    virtual     void        processVolume_l() {}
1515                void        checkInvalidTracks_l();
1516
1517    virtual     audio_stream_type_t streamType() { return AUDIO_STREAM_DEFAULT; }
1518
1519    virtual     void        invalidateTracks(audio_stream_type_t streamType __unused) {}
1520
1521                void        dump(int fd, const Vector<String16>& args);
1522    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
1523                void        dumpTracks(int fd, const Vector<String16>& args);
1524
1525 protected:
1526
1527                audio_attributes_t      mAttr;
1528                audio_session_t         mSessionId;
1529                audio_port_handle_t     mPortId;
1530
1531                sp<MmapStreamCallback>  mCallback;
1532                sp<StreamHalInterface>  mHalStream;
1533                sp<DeviceHalInterface>  mHalDevice;
1534                AudioHwDevice* const    mAudioHwDev;
1535                ActiveTracks<MmapTrack> mActiveTracks;
1536};
1537
1538class MmapPlaybackThread : public MmapThread, public VolumeInterface
1539{
1540
1541public:
1542    MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1543                      AudioHwDevice *hwDev, AudioStreamOut *output,
1544                      audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1545    virtual     ~MmapPlaybackThread() {}
1546
1547    virtual     void        configure(const audio_attributes_t *attr,
1548                                      audio_stream_type_t streamType,
1549                                      audio_session_t sessionId,
1550                                      const sp<MmapStreamCallback>& callback,
1551                                      audio_port_handle_t portId);
1552
1553                AudioStreamOut* clearOutput();
1554
1555                // VolumeInterface
1556    virtual     void        setMasterVolume(float value);
1557    virtual     void        setMasterMute(bool muted);
1558    virtual     void        setStreamVolume(audio_stream_type_t stream, float value);
1559    virtual     void        setStreamMute(audio_stream_type_t stream, bool muted);
1560    virtual     float       streamVolume(audio_stream_type_t stream) const;
1561
1562                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
1563
1564    virtual     void        invalidateTracks(audio_stream_type_t streamType);
1565
1566    virtual     audio_stream_type_t streamType() { return mStreamType; }
1567    virtual     void        checkSilentMode_l();
1568    virtual     void        processVolume_l();
1569
1570    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
1571
1572    virtual     bool        isOutput() const override { return true; }
1573
1574protected:
1575
1576                audio_stream_type_t         mStreamType;
1577                float                       mMasterVolume;
1578                float                       mStreamVolume;
1579                bool                        mMasterMute;
1580                bool                        mStreamMute;
1581                float                       mHalVolFloat;
1582                AudioStreamOut*             mOutput;
1583};
1584
1585class MmapCaptureThread : public MmapThread
1586{
1587
1588public:
1589    MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1590                      AudioHwDevice *hwDev, AudioStreamIn *input,
1591                      audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1592    virtual     ~MmapCaptureThread() {}
1593
1594                AudioStreamIn* clearInput();
1595
1596    virtual     bool           isOutput() const override { return false; }
1597
1598protected:
1599
1600                AudioStreamIn*  mInput;
1601};
1602