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