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