• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 **
3 ** Copyright 2012, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 #ifndef INCLUDING_FROM_AUDIOFLINGER_H
19     #error This header file should only be included from AudioFlinger.h
20 #endif
21 
22 class ThreadBase : public Thread {
23 public:
24 
25 #include "TrackBase.h"
26 
27     enum type_t {
28         MIXER,              // Thread class is MixerThread
29         DIRECT,             // Thread class is DirectOutputThread
30         DUPLICATING,        // Thread class is DuplicatingThread
31         RECORD,             // Thread class is RecordThread
32         OFFLOAD             // Thread class is OffloadThread
33     };
34 
35     ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
36                 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
37     virtual             ~ThreadBase();
38 
39     virtual status_t    readyToRun();
40 
41     void dumpBase(int fd, const Vector<String16>& args);
42     void dumpEffectChains(int fd, const Vector<String16>& args);
43 
44     void clearPowerManager();
45 
46     // base for record and playback
47     enum {
48         CFG_EVENT_IO,
49         CFG_EVENT_PRIO,
50         CFG_EVENT_SET_PARAMETER,
51         CFG_EVENT_CREATE_AUDIO_PATCH,
52         CFG_EVENT_RELEASE_AUDIO_PATCH,
53     };
54 
55     class ConfigEventData: public RefBase {
56     public:
~ConfigEventData()57         virtual ~ConfigEventData() {}
58 
59         virtual  void dump(char *buffer, size_t size) = 0;
60     protected:
ConfigEventData()61         ConfigEventData() {}
62     };
63 
64     // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
65     //  1. create SetParameterConfigEvent. This sets mWaitStatus in config event
66     //  2. Lock mLock
67     //  3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
68     //  4. sendConfigEvent_l() reads status from event->mStatus;
69     //  5. sendConfigEvent_l() returns status
70     //  6. Unlock
71     //
72     // Parameter sequence by server: threadLoop calling processConfigEvents_l():
73     // 1. Lock mLock
74     // 2. If there is an entry in mConfigEvents proceed ...
75     // 3. Read first entry in mConfigEvents
76     // 4. Remove first entry from mConfigEvents
77     // 5. Process
78     // 6. Set event->mStatus
79     // 7. event->mCond.signal
80     // 8. Unlock
81 
82     class ConfigEvent: public RefBase {
83     public:
~ConfigEvent()84         virtual ~ConfigEvent() {}
85 
dump(char * buffer,size_t size)86         void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
87 
88         const int mType; // event type e.g. CFG_EVENT_IO
89         Mutex mLock;     // mutex associated with mCond
90         Condition mCond; // condition for status return
91         status_t mStatus; // status communicated to sender
92         bool mWaitStatus; // true if sender is waiting for status
93         sp<ConfigEventData> mData;     // event specific parameter data
94 
95     protected:
ConfigEvent(int type)96         ConfigEvent(int type) : mType(type), mStatus(NO_ERROR), mWaitStatus(false), mData(NULL) {}
97     };
98 
99     class IoConfigEventData : public ConfigEventData {
100     public:
IoConfigEventData(int event,int param)101         IoConfigEventData(int event, int param) :
102             mEvent(event), mParam(param) {}
103 
dump(char * buffer,size_t size)104         virtual  void dump(char *buffer, size_t size) {
105             snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
106         }
107 
108         const int mEvent;
109         const int mParam;
110     };
111 
112     class IoConfigEvent : public ConfigEvent {
113     public:
IoConfigEvent(int event,int param)114         IoConfigEvent(int event, int param) :
115             ConfigEvent(CFG_EVENT_IO) {
116             mData = new IoConfigEventData(event, param);
117         }
~IoConfigEvent()118         virtual ~IoConfigEvent() {}
119     };
120 
121     class PrioConfigEventData : public ConfigEventData {
122     public:
PrioConfigEventData(pid_t pid,pid_t tid,int32_t prio)123         PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio) :
124             mPid(pid), mTid(tid), mPrio(prio) {}
125 
dump(char * buffer,size_t size)126         virtual  void dump(char *buffer, size_t size) {
127             snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
128         }
129 
130         const pid_t mPid;
131         const pid_t mTid;
132         const int32_t mPrio;
133     };
134 
135     class PrioConfigEvent : public ConfigEvent {
136     public:
PrioConfigEvent(pid_t pid,pid_t tid,int32_t prio)137         PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
138             ConfigEvent(CFG_EVENT_PRIO) {
139             mData = new PrioConfigEventData(pid, tid, prio);
140         }
~PrioConfigEvent()141         virtual ~PrioConfigEvent() {}
142     };
143 
144     class SetParameterConfigEventData : public ConfigEventData {
145     public:
SetParameterConfigEventData(String8 keyValuePairs)146         SetParameterConfigEventData(String8 keyValuePairs) :
147             mKeyValuePairs(keyValuePairs) {}
148 
dump(char * buffer,size_t size)149         virtual  void dump(char *buffer, size_t size) {
150             snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
151         }
152 
153         const String8 mKeyValuePairs;
154     };
155 
156     class SetParameterConfigEvent : public ConfigEvent {
157     public:
SetParameterConfigEvent(String8 keyValuePairs)158         SetParameterConfigEvent(String8 keyValuePairs) :
159             ConfigEvent(CFG_EVENT_SET_PARAMETER) {
160             mData = new SetParameterConfigEventData(keyValuePairs);
161             mWaitStatus = true;
162         }
~SetParameterConfigEvent()163         virtual ~SetParameterConfigEvent() {}
164     };
165 
166     class CreateAudioPatchConfigEventData : public ConfigEventData {
167     public:
CreateAudioPatchConfigEventData(const struct audio_patch patch,audio_patch_handle_t handle)168         CreateAudioPatchConfigEventData(const struct audio_patch patch,
169                                         audio_patch_handle_t handle) :
170             mPatch(patch), mHandle(handle) {}
171 
dump(char * buffer,size_t size)172         virtual  void dump(char *buffer, size_t size) {
173             snprintf(buffer, size, "Patch handle: %u\n", mHandle);
174         }
175 
176         const struct audio_patch mPatch;
177         audio_patch_handle_t mHandle;
178     };
179 
180     class CreateAudioPatchConfigEvent : public ConfigEvent {
181     public:
CreateAudioPatchConfigEvent(const struct audio_patch patch,audio_patch_handle_t handle)182         CreateAudioPatchConfigEvent(const struct audio_patch patch,
183                                     audio_patch_handle_t handle) :
184             ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
185             mData = new CreateAudioPatchConfigEventData(patch, handle);
186             mWaitStatus = true;
187         }
~CreateAudioPatchConfigEvent()188         virtual ~CreateAudioPatchConfigEvent() {}
189     };
190 
191     class ReleaseAudioPatchConfigEventData : public ConfigEventData {
192     public:
ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle)193         ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
194             mHandle(handle) {}
195 
dump(char * buffer,size_t size)196         virtual  void dump(char *buffer, size_t size) {
197             snprintf(buffer, size, "Patch handle: %u\n", mHandle);
198         }
199 
200         audio_patch_handle_t mHandle;
201     };
202 
203     class ReleaseAudioPatchConfigEvent : public ConfigEvent {
204     public:
ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle)205         ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
206             ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
207             mData = new ReleaseAudioPatchConfigEventData(handle);
208             mWaitStatus = true;
209         }
~ReleaseAudioPatchConfigEvent()210         virtual ~ReleaseAudioPatchConfigEvent() {}
211     };
212 
213     class PMDeathRecipient : public IBinder::DeathRecipient {
214     public:
PMDeathRecipient(const wp<ThreadBase> & thread)215                     PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
~PMDeathRecipient()216         virtual     ~PMDeathRecipient() {}
217 
218         // IBinder::DeathRecipient
219         virtual     void        binderDied(const wp<IBinder>& who);
220 
221     private:
222                     PMDeathRecipient(const PMDeathRecipient&);
223                     PMDeathRecipient& operator = (const PMDeathRecipient&);
224 
225         wp<ThreadBase> mThread;
226     };
227 
228     virtual     status_t    initCheck() const = 0;
229 
230                 // static externally-visible
type()231                 type_t      type() const { return mType; }
isDuplicating()232                 bool isDuplicating() const { return (mType == DUPLICATING); }
233 
id()234                 audio_io_handle_t id() const { return mId;}
235 
236                 // dynamic externally-visible
sampleRate()237                 uint32_t    sampleRate() const { return mSampleRate; }
channelMask()238                 audio_channel_mask_t channelMask() const { return mChannelMask; }
format()239                 audio_format_t format() const { return mHALFormat; }
channelCount()240                 uint32_t channelCount() const { return mChannelCount; }
241                 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
242                 // and returns the [normal mix] buffer's frame count.
243     virtual     size_t      frameCount() const = 0;
frameSize()244                 size_t      frameSize() const { return mFrameSize; }
245 
246     // Should be "virtual status_t requestExitAndWait()" and override same
247     // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
248                 void        exit();
249     virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
250                                                     status_t& status) = 0;
251     virtual     status_t    setParameters(const String8& keyValuePairs);
252     virtual     String8     getParameters(const String8& keys) = 0;
253     virtual     void        audioConfigChanged(int event, int param = 0) = 0;
254                 // sendConfigEvent_l() must be called with ThreadBase::mLock held
255                 // Can temporarily release the lock if waiting for a reply from
256                 // processConfigEvents_l().
257                 status_t    sendConfigEvent_l(sp<ConfigEvent>& event);
258                 void        sendIoConfigEvent(int event, int param = 0);
259                 void        sendIoConfigEvent_l(int event, int param = 0);
260                 void        sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
261                 status_t    sendSetParameterConfigEvent_l(const String8& keyValuePair);
262                 status_t    sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
263                                                             audio_patch_handle_t *handle);
264                 status_t    sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
265                 void        processConfigEvents_l();
266     virtual     void        cacheParameters_l() = 0;
267     virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
268                                                audio_patch_handle_t *handle) = 0;
269     virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
270     virtual     void        getAudioPortConfig(struct audio_port_config *config) = 0;
271 
272 
273                 // see note at declaration of mStandby, mOutDevice and mInDevice
standby()274                 bool        standby() const { return mStandby; }
outDevice()275                 audio_devices_t outDevice() const { return mOutDevice; }
inDevice()276                 audio_devices_t inDevice() const { return mInDevice; }
277 
278     virtual     audio_stream_t* stream() const = 0;
279 
280                 sp<EffectHandle> createEffect_l(
281                                     const sp<AudioFlinger::Client>& client,
282                                     const sp<IEffectClient>& effectClient,
283                                     int32_t priority,
284                                     int sessionId,
285                                     effect_descriptor_t *desc,
286                                     int *enabled,
287                                     status_t *status /*non-NULL*/);
288 
289                 // return values for hasAudioSession (bit field)
290                 enum effect_state {
291                     EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
292                                             // effect
293                     TRACK_SESSION = 0x2     // the audio session corresponds to at least one
294                                             // track
295                 };
296 
297                 // get effect chain corresponding to session Id.
298                 sp<EffectChain> getEffectChain(int sessionId);
299                 // same as getEffectChain() but must be called with ThreadBase mutex locked
300                 sp<EffectChain> getEffectChain_l(int sessionId) const;
301                 // add an effect chain to the chain list (mEffectChains)
302     virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
303                 // remove an effect chain from the chain list (mEffectChains)
304     virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
305                 // lock all effect chains Mutexes. Must be called before releasing the
306                 // ThreadBase mutex before processing the mixer and effects. This guarantees the
307                 // integrity of the chains during the process.
308                 // Also sets the parameter 'effectChains' to current value of mEffectChains.
309                 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
310                 // unlock effect chains after process
311                 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
312                 // get a copy of mEffectChains vector
getEffectChains_l()313                 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
314                 // set audio mode to all effect chains
315                 void setMode(audio_mode_t mode);
316                 // get effect module with corresponding ID on specified audio session
317                 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
318                 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
319                 // add and effect module. Also creates the effect chain is none exists for
320                 // the effects audio session
321                 status_t addEffect_l(const sp< EffectModule>& effect);
322                 // remove and effect module. Also removes the effect chain is this was the last
323                 // effect
324                 void removeEffect_l(const sp< EffectModule>& effect);
325                 // detach all tracks connected to an auxiliary effect
detachAuxEffect_l(int effectId __unused)326     virtual     void detachAuxEffect_l(int effectId __unused) {}
327                 // returns either EFFECT_SESSION if effects on this audio session exist in one
328                 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
329                 virtual uint32_t hasAudioSession(int sessionId) const = 0;
330                 // the value returned by default implementation is not important as the
331                 // strategy is only meaningful for PlaybackThread which implements this method
getStrategyForSession_l(int sessionId __unused)332                 virtual uint32_t getStrategyForSession_l(int sessionId __unused) { return 0; }
333 
334                 // suspend or restore effect according to the type of effect passed. a NULL
335                 // type pointer means suspend all effects in the session
336                 void setEffectSuspended(const effect_uuid_t *type,
337                                         bool suspend,
338                                         int sessionId = AUDIO_SESSION_OUTPUT_MIX);
339                 // check if some effects must be suspended/restored when an effect is enabled
340                 // or disabled
341                 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
342                                                  bool enabled,
343                                                  int sessionId = AUDIO_SESSION_OUTPUT_MIX);
344                 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
345                                                    bool enabled,
346                                                    int sessionId = AUDIO_SESSION_OUTPUT_MIX);
347 
348                 virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
349                 virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
350 
351                 // Return a reference to a per-thread heap which can be used to allocate IMemory
352                 // objects that will be read-only to client processes, read/write to mediaserver,
353                 // and shared by all client processes of the thread.
354                 // The heap is per-thread rather than common across all threads, because
355                 // clients can't be trusted not to modify the offset of the IMemory they receive.
356                 // If a thread does not have such a heap, this method returns 0.
readOnlyHeap()357                 virtual sp<MemoryDealer>    readOnlyHeap() const { return 0; }
358 
pipeMemory()359                 virtual sp<IMemory> pipeMemory() const { return 0; }
360 
361     mutable     Mutex                   mLock;
362 
363 protected:
364 
365                 // entry describing an effect being suspended in mSuspendedSessions keyed vector
366                 class SuspendedSessionDesc : public RefBase {
367                 public:
SuspendedSessionDesc()368                     SuspendedSessionDesc() : mRefCount(0) {}
369 
370                     int mRefCount;          // number of active suspend requests
371                     effect_uuid_t mType;    // effect type UUID
372                 };
373 
374                 void        acquireWakeLock(int uid = -1);
375                 void        acquireWakeLock_l(int uid = -1);
376                 void        releaseWakeLock();
377                 void        releaseWakeLock_l();
378                 void        updateWakeLockUids(const SortedVector<int> &uids);
379                 void        updateWakeLockUids_l(const SortedVector<int> &uids);
380                 void        getPowerManager_l();
381                 void setEffectSuspended_l(const effect_uuid_t *type,
382                                           bool suspend,
383                                           int sessionId);
384                 // updated mSuspendedSessions when an effect suspended or restored
385                 void        updateSuspendedSessions_l(const effect_uuid_t *type,
386                                                       bool suspend,
387                                                       int sessionId);
388                 // check if some effects must be suspended when an effect chain is added
389                 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
390 
391                 String16 getWakeLockTag();
392 
preExit()393     virtual     void        preExit() { }
394 
395     friend class AudioFlinger;      // for mEffectChains
396 
397                 const type_t            mType;
398 
399                 // Used by parameters, config events, addTrack_l, exit
400                 Condition               mWaitWorkCV;
401 
402                 const sp<AudioFlinger>  mAudioFlinger;
403 
404                 // updated by PlaybackThread::readOutputParameters_l() or
405                 // RecordThread::readInputParameters_l()
406                 uint32_t                mSampleRate;
407                 size_t                  mFrameCount;       // output HAL, direct output, record
408                 audio_channel_mask_t    mChannelMask;
409                 uint32_t                mChannelCount;
410                 size_t                  mFrameSize;
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; // (see audio.h, audio_source_t)
430 
431                 const audio_io_handle_t mId;
432                 Vector< sp<EffectChain> > mEffectChains;
433 
434                 static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
435                 char                    mName[kNameLength];
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 ---
448 class PlaybackThread : public ThreadBase {
449 public:
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 
481 protected:
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 
513 public:
514 
initCheck()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
suspend()549                 void        suspend() { (void) android_atomic_inc(&mSuspended); }
restore()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                                 }
isSuspended()558                 bool        isSuspended() const
559                                 { return android_atomic_acquire_load(&mSuspended) > 0; }
560 
561     virtual     String8     getParameters(const String8& keys);
562     virtual     void        audioConfigChanged(int event, int param = 0);
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().
mixBuffer()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 
frameCount()588     virtual     size_t      frameCount() const { return mNormalFrameCount; }
589 
590                 // Return's the HAL's frame count i.e. fast mixer buffer size.
frameCountHAL()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 
600 protected:
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;
674 private:
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;
setMasterMute_l(bool muted)679                 void        setMasterMute_l(bool muted) { mMasterMute = muted; }
680 protected:
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
saveOutputTracks()703     virtual     void        saveOutputTracks() { }
clearOutputTracks()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 
usesHwAvSync()715                 bool        usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL) &&
716                                                 (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
717 
718 private:
719 
720     friend class AudioFlinger;      // for numerous
721 
722     PlaybackThread& operator = (const PlaybackThread&);
723 
724     status_t    addTrack_l(const sp<Track>& track);
725     bool        destroyTrack_l(const sp<Track>& track);
726     void        removeTrack_l(const sp<Track>& track);
727     void        broadcast_l();
728 
729     void        readOutputParameters_l();
730 
731     virtual void dumpInternals(int fd, const Vector<String16>& args);
732     void        dumpTracks(int fd, const Vector<String16>& args);
733 
734     SortedVector< sp<Track> >       mTracks;
735     stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT];
736     AudioStreamOut                  *mOutput;
737 
738     float                           mMasterVolume;
739     nsecs_t                         mLastWriteTime;
740     int                             mNumWrites;
741     int                             mNumDelayedWrites;
742     bool                            mInWrite;
743 
744     // FIXME rename these former local variables of threadLoop to standard "m" names
745     nsecs_t                         standbyTime;
746     size_t                          mSinkBufferSize;
747 
748     // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
749     uint32_t                        activeSleepTime;
750     uint32_t                        idleSleepTime;
751 
752     uint32_t                        sleepTime;
753 
754     // mixer status returned by prepareTracks_l()
755     mixer_state                     mMixerStatus; // current cycle
756                                                   // previous cycle when in prepareTracks_l()
757     mixer_state                     mMixerStatusIgnoringFastTracks;
758                                                   // FIXME or a separate ready state per track
759 
760     // FIXME move these declarations into the specific sub-class that needs them
761     // MIXER only
762     uint32_t                        sleepTimeShift;
763 
764     // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
765     nsecs_t                         standbyDelay;
766 
767     // MIXER only
768     nsecs_t                         maxPeriod;
769 
770     // DUPLICATING only
771     uint32_t                        writeFrames;
772 
773     size_t                          mBytesRemaining;
774     size_t                          mCurrentWriteLength;
775     bool                            mUseAsyncWrite;
776     // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
777     // incremented each time a write(), a flush() or a standby() occurs.
778     // Bit 0 is set when a write blocks and indicates a callback is expected.
779     // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
780     // callbacks are ignored.
781     uint32_t                        mWriteAckSequence;
782     // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
783     // incremented each time a drain is requested or a flush() or standby() occurs.
784     // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
785     // expected.
786     // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
787     // callbacks are ignored.
788     uint32_t                        mDrainSequence;
789     // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
790     // for async write callback in the thread loop before evaluating it
791     bool                            mSignalPending;
792     sp<AsyncCallbackThread>         mCallbackThread;
793 
794 private:
795     // The HAL output sink is treated as non-blocking, but current implementation is blocking
796     sp<NBAIO_Sink>          mOutputSink;
797     // If a fast mixer is present, the blocking pipe sink, otherwise clear
798     sp<NBAIO_Sink>          mPipeSink;
799     // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
800     sp<NBAIO_Sink>          mNormalSink;
801 #ifdef TEE_SINK
802     // For dumpsys
803     sp<NBAIO_Sink>          mTeeSink;
804     sp<NBAIO_Source>        mTeeSource;
805 #endif
806     uint32_t                mScreenState;   // cached copy of gScreenState
807     static const size_t     kFastMixerLogSize = 4 * 1024;
808     sp<NBLog::Writer>       mFastMixerNBLogWriter;
809 public:
810     virtual     bool        hasFastMixer() const = 0;
getFastTrackUnderruns(size_t fastIndex __unused)811     virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
812                                 { FastTrackUnderruns dummy; return dummy; }
813 
814 protected:
815                 // accessed by both binder threads and within threadLoop(), lock on mutex needed
816                 unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
817                 bool        mHwSupportsPause;
818                 bool        mHwPaused;
819                 bool        mFlushPending;
820 private:
821     // timestamp latch:
822     //  D input is written by threadLoop_write while mutex is unlocked, and read while locked
823     //  Q output is written while locked, and read while locked
824     struct {
825         AudioTimestamp  mTimestamp;
826         uint32_t        mUnpresentedFrames;
827         KeyedVector<Track *, uint32_t> mFramesReleased;
828     } mLatchD, mLatchQ;
829     bool mLatchDValid;  // true means mLatchD is valid
830                         //     (except for mFramesReleased which is filled in later),
831                         //     and clock it into latch at next opportunity
832     bool mLatchQValid;  // true means mLatchQ is valid
833 };
834 
835 class MixerThread : public PlaybackThread {
836 public:
837     MixerThread(const sp<AudioFlinger>& audioFlinger,
838                 AudioStreamOut* output,
839                 audio_io_handle_t id,
840                 audio_devices_t device,
841                 type_t type = MIXER);
842     virtual             ~MixerThread();
843 
844     // Thread virtuals
845 
846     virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
847                                                    status_t& status);
848     virtual     void        dumpInternals(int fd, const Vector<String16>& args);
849 
850 protected:
851     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
852     virtual     int         getTrackName_l(audio_channel_mask_t channelMask,
853                                            audio_format_t format, int sessionId);
854     virtual     void        deleteTrackName_l(int name);
855     virtual     uint32_t    idleSleepTimeUs() const;
856     virtual     uint32_t    suspendSleepTimeUs() const;
857     virtual     void        cacheParameters_l();
858 
859     // threadLoop snippets
860     virtual     ssize_t     threadLoop_write();
861     virtual     void        threadLoop_standby();
862     virtual     void        threadLoop_mix();
863     virtual     void        threadLoop_sleepTime();
864     virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
865     virtual     uint32_t    correctLatency_l(uint32_t latency) const;
866 
867                 AudioMixer* mAudioMixer;    // normal mixer
868 private:
869                 // one-time initialization, no locks required
870                 sp<FastMixer>     mFastMixer;     // non-0 if there is also a fast mixer
871                 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
872 
873                 // contents are not guaranteed to be consistent, no locks required
874                 FastMixerDumpState mFastMixerDumpState;
875 #ifdef STATE_QUEUE_DUMP
876                 StateQueueObserverDump mStateQueueObserverDump;
877                 StateQueueMutatorDump  mStateQueueMutatorDump;
878 #endif
879                 AudioWatchdogDump mAudioWatchdogDump;
880 
881                 // accessible only within the threadLoop(), no locks required
882                 //          mFastMixer->sq()    // for mutating and pushing state
883                 int32_t     mFastMixerFutex;    // for cold idle
884 
885 public:
hasFastMixer()886     virtual     bool        hasFastMixer() const { return mFastMixer != 0; }
getFastTrackUnderruns(size_t fastIndex)887     virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
888                               ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
889                               return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
890                             }
891 
892 };
893 
894 class DirectOutputThread : public PlaybackThread {
895 public:
896 
897     DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
898                        audio_io_handle_t id, audio_devices_t device);
899     virtual                 ~DirectOutputThread();
900 
901     // Thread virtuals
902 
903     virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
904                                                    status_t& status);
905     virtual     void        flushHw_l();
906 
907 protected:
908     virtual     int         getTrackName_l(audio_channel_mask_t channelMask,
909                                            audio_format_t format, int sessionId);
910     virtual     void        deleteTrackName_l(int name);
911     virtual     uint32_t    activeSleepTimeUs() const;
912     virtual     uint32_t    idleSleepTimeUs() const;
913     virtual     uint32_t    suspendSleepTimeUs() const;
914     virtual     void        cacheParameters_l();
915 
916     // threadLoop snippets
917     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
918     virtual     void        threadLoop_mix();
919     virtual     void        threadLoop_sleepTime();
920     virtual     void        threadLoop_exit();
921     virtual     bool        shouldStandby_l();
922 
923     // volumes last sent to audio HAL with stream->set_volume()
924     float mLeftVolFloat;
925     float mRightVolFloat;
926 
927     DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
928                         audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
929     void processVolume_l(Track *track, bool lastTrack);
930 
931     // prepareTracks_l() tells threadLoop_mix() the name of the single active track
932     sp<Track>               mActiveTrack;
933 public:
hasFastMixer()934     virtual     bool        hasFastMixer() const { return false; }
935 };
936 
937 class OffloadThread : public DirectOutputThread {
938 public:
939 
940     OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
941                         audio_io_handle_t id, uint32_t device);
~OffloadThread()942     virtual                 ~OffloadThread() {};
943     virtual     void        flushHw_l();
944 
945 protected:
946     // threadLoop snippets
947     virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
948     virtual     void        threadLoop_exit();
949 
950     virtual     bool        waitingAsyncCallback();
951     virtual     bool        waitingAsyncCallback_l();
952     virtual     void        onAddNewTrack_l();
953 
954 private:
955     size_t      mPausedWriteLength;     // length in bytes of write interrupted by pause
956     size_t      mPausedBytesRemaining;  // bytes still waiting in mixbuffer after resume
957     wp<Track>   mPreviousTrack;         // used to detect track switch
958 };
959 
960 class AsyncCallbackThread : public Thread {
961 public:
962 
963     AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
964 
965     virtual             ~AsyncCallbackThread();
966 
967     // Thread virtuals
968     virtual bool        threadLoop();
969 
970     // RefBase
971     virtual void        onFirstRef();
972 
973             void        exit();
974             void        setWriteBlocked(uint32_t sequence);
975             void        resetWriteBlocked();
976             void        setDraining(uint32_t sequence);
977             void        resetDraining();
978 
979 private:
980     const wp<PlaybackThread>   mPlaybackThread;
981     // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
982     // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
983     // to indicate that the callback has been received via resetWriteBlocked()
984     uint32_t                   mWriteAckSequence;
985     // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
986     // setDraining(). The sequence is shifted one bit to the left and the lsb is used
987     // to indicate that the callback has been received via resetDraining()
988     uint32_t                   mDrainSequence;
989     Condition                  mWaitWorkCV;
990     Mutex                      mLock;
991 };
992 
993 class DuplicatingThread : public MixerThread {
994 public:
995     DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
996                       audio_io_handle_t id);
997     virtual                 ~DuplicatingThread();
998 
999     // Thread virtuals
1000                 void        addOutputTrack(MixerThread* thread);
1001                 void        removeOutputTrack(MixerThread* thread);
waitTimeMs()1002                 uint32_t    waitTimeMs() const { return mWaitTimeMs; }
1003 protected:
1004     virtual     uint32_t    activeSleepTimeUs() const;
1005 
1006 private:
1007                 bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1008 protected:
1009     // threadLoop snippets
1010     virtual     void        threadLoop_mix();
1011     virtual     void        threadLoop_sleepTime();
1012     virtual     ssize_t     threadLoop_write();
1013     virtual     void        threadLoop_standby();
1014     virtual     void        cacheParameters_l();
1015 
1016 private:
1017     // called from threadLoop, addOutputTrack, removeOutputTrack
1018     virtual     void        updateWaitTime_l();
1019 protected:
1020     virtual     void        saveOutputTracks();
1021     virtual     void        clearOutputTracks();
1022 private:
1023 
1024                 uint32_t    mWaitTimeMs;
1025     SortedVector < sp<OutputTrack> >  outputTracks;
1026     SortedVector < sp<OutputTrack> >  mOutputTracks;
1027 public:
hasFastMixer()1028     virtual     bool        hasFastMixer() const { return false; }
1029 };
1030 
1031 
1032 // record thread
1033 class RecordThread : public ThreadBase
1034 {
1035 public:
1036 
1037     class RecordTrack;
1038     class ResamplerBufferProvider : public AudioBufferProvider
1039                         // derives from AudioBufferProvider interface for use by resampler
1040     {
1041     public:
ResamplerBufferProvider(RecordTrack * recordTrack)1042         ResamplerBufferProvider(RecordTrack* recordTrack) : mRecordTrack(recordTrack) { }
~ResamplerBufferProvider()1043         virtual ~ResamplerBufferProvider() { }
1044         // AudioBufferProvider interface
1045         virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1046         virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1047     private:
1048         RecordTrack * const mRecordTrack;
1049     };
1050 
1051 #include "RecordTracks.h"
1052 
1053             RecordThread(const sp<AudioFlinger>& audioFlinger,
1054                     AudioStreamIn *input,
1055                     audio_io_handle_t id,
1056                     audio_devices_t outDevice,
1057                     audio_devices_t inDevice
1058 #ifdef TEE_SINK
1059                     , const sp<NBAIO_Sink>& teeSink
1060 #endif
1061                     );
1062             virtual     ~RecordThread();
1063 
1064     // no addTrack_l ?
1065     void        destroyTrack_l(const sp<RecordTrack>& track);
1066     void        removeTrack_l(const sp<RecordTrack>& track);
1067 
1068     void        dumpInternals(int fd, const Vector<String16>& args);
1069     void        dumpTracks(int fd, const Vector<String16>& args);
1070 
1071     // Thread virtuals
1072     virtual bool        threadLoop();
1073 
1074     // RefBase
1075     virtual void        onFirstRef();
1076 
initCheck()1077     virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1078 
readOnlyHeap()1079     virtual sp<MemoryDealer>    readOnlyHeap() const { return mReadOnlyHeap; }
1080 
pipeMemory()1081     virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1082 
1083             sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1084                     const sp<AudioFlinger::Client>& client,
1085                     uint32_t sampleRate,
1086                     audio_format_t format,
1087                     audio_channel_mask_t channelMask,
1088                     size_t *pFrameCount,
1089                     int sessionId,
1090                     size_t *notificationFrames,
1091                     int uid,
1092                     IAudioFlinger::track_flags_t *flags,
1093                     pid_t tid,
1094                     status_t *status /*non-NULL*/);
1095 
1096             status_t    start(RecordTrack* recordTrack,
1097                               AudioSystem::sync_event_t event,
1098                               int triggerSession);
1099 
1100             // ask the thread to stop the specified track, and
1101             // return true if the caller should then do it's part of the stopping process
1102             bool        stop(RecordTrack* recordTrack);
1103 
1104             void        dump(int fd, const Vector<String16>& args);
1105             AudioStreamIn* clearInput();
1106             virtual audio_stream_t* stream() const;
1107 
1108 
1109     virtual bool        checkForNewParameter_l(const String8& keyValuePair,
1110                                                status_t& status);
cacheParameters_l()1111     virtual void        cacheParameters_l() {}
1112     virtual String8     getParameters(const String8& keys);
1113     virtual void        audioConfigChanged(int event, int param = 0);
1114     virtual status_t    createAudioPatch_l(const struct audio_patch *patch,
1115                                            audio_patch_handle_t *handle);
1116     virtual status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1117 
1118             void        addPatchRecord(const sp<PatchRecord>& record);
1119             void        deletePatchRecord(const sp<PatchRecord>& record);
1120 
1121             void        readInputParameters_l();
1122     virtual uint32_t    getInputFramesLost();
1123 
1124     virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1125     virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1126     virtual uint32_t hasAudioSession(int sessionId) const;
1127 
1128             // Return the set of unique session IDs across all tracks.
1129             // The keys are the session IDs, and the associated values are meaningless.
1130             // FIXME replace by Set [and implement Bag/Multiset for other uses].
1131             KeyedVector<int, bool> sessionIds() const;
1132 
1133     virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1134     virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
1135 
1136     static void syncStartEventCallback(const wp<SyncEvent>& event);
1137 
frameCount()1138     virtual size_t      frameCount() const { return mFrameCount; }
hasFastCapture()1139             bool        hasFastCapture() const { return mFastCapture != 0; }
1140     virtual void        getAudioPortConfig(struct audio_port_config *config);
1141 
1142 private:
1143             // Enter standby if not already in standby, and set mStandby flag
1144             void    standbyIfNotAlreadyInStandby();
1145 
1146             // Call the HAL standby method unconditionally, and don't change mStandby flag
1147             void    inputStandBy();
1148 
1149             AudioStreamIn                       *mInput;
1150             SortedVector < sp<RecordTrack> >    mTracks;
1151             // mActiveTracks has dual roles:  it indicates the current active track(s), and
1152             // is used together with mStartStopCond to indicate start()/stop() progress
1153             SortedVector< sp<RecordTrack> >     mActiveTracks;
1154             // generation counter for mActiveTracks
1155             int                                 mActiveTracksGen;
1156             Condition                           mStartStopCond;
1157 
1158             // resampler converts input at HAL Hz to output at AudioRecord client Hz
1159             int16_t                             *mRsmpInBuffer; // see new[] for details on the size
1160             size_t                              mRsmpInFrames;  // size of resampler input in frames
1161             size_t                              mRsmpInFramesP2;// size rounded up to a power-of-2
1162 
1163             // rolling index that is never cleared
1164             int32_t                             mRsmpInRear;    // last filled frame + 1
1165 
1166             // For dumpsys
1167             const sp<NBAIO_Sink>                mTeeSink;
1168 
1169             const sp<MemoryDealer>              mReadOnlyHeap;
1170 
1171             // one-time initialization, no locks required
1172             sp<FastCapture>                     mFastCapture;   // non-0 if there is also a fast capture
1173             // FIXME audio watchdog thread
1174 
1175             // contents are not guaranteed to be consistent, no locks required
1176             FastCaptureDumpState                mFastCaptureDumpState;
1177 #ifdef STATE_QUEUE_DUMP
1178             // FIXME StateQueue observer and mutator dump fields
1179 #endif
1180             // FIXME audio watchdog dump
1181 
1182             // accessible only within the threadLoop(), no locks required
1183             //          mFastCapture->sq()      // for mutating and pushing state
1184             int32_t     mFastCaptureFutex;      // for cold idle
1185 
1186             // The HAL input source is treated as non-blocking,
1187             // but current implementation is blocking
1188             sp<NBAIO_Source>                    mInputSource;
1189             // The source for the normal capture thread to read from: mInputSource or mPipeSource
1190             sp<NBAIO_Source>                    mNormalSource;
1191             // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1192             // otherwise clear
1193             sp<NBAIO_Sink>                      mPipeSink;
1194             // If a fast capture is present, the non-blocking pipe source read by normal thread,
1195             // otherwise clear
1196             sp<NBAIO_Source>                    mPipeSource;
1197             // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1198             size_t                              mPipeFramesP2;
1199             // If a fast capture is present, the Pipe as IMemory, otherwise clear
1200             sp<IMemory>                         mPipeMemory;
1201 
1202             static const size_t                 kFastCaptureLogSize = 4 * 1024;
1203             sp<NBLog::Writer>                   mFastCaptureNBLogWriter;
1204 
1205             bool                                mFastTrackAvail;    // true if fast track available
1206 };
1207