• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 **
3 ** Copyright 2007, 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 ANDROID_AUDIO_FLINGER_H
19 #define ANDROID_AUDIO_FLINGER_H
20 
21 #include "Configuration.h"
22 #include <stdint.h>
23 #include <sys/types.h>
24 #include <limits.h>
25 
26 #include <common_time/cc_helper.h>
27 
28 #include <cutils/compiler.h>
29 
30 #include <media/IAudioFlinger.h>
31 #include <media/IAudioFlingerClient.h>
32 #include <media/IAudioTrack.h>
33 #include <media/IAudioRecord.h>
34 #include <media/AudioSystem.h>
35 #include <media/AudioTrack.h>
36 
37 #include <utils/Atomic.h>
38 #include <utils/Errors.h>
39 #include <utils/threads.h>
40 #include <utils/SortedVector.h>
41 #include <utils/TypeHelpers.h>
42 #include <utils/Vector.h>
43 
44 #include <binder/BinderService.h>
45 #include <binder/MemoryDealer.h>
46 
47 #include <system/audio.h>
48 #include <hardware/audio.h>
49 #include <hardware/audio_policy.h>
50 
51 #include <media/AudioBufferProvider.h>
52 #include <media/ExtendedAudioBufferProvider.h>
53 
54 #include "FastCapture.h"
55 #include "FastMixer.h"
56 #include <media/nbaio/NBAIO.h>
57 #include "AudioWatchdog.h"
58 #include "AudioMixer.h"
59 #include "AudioStreamOut.h"
60 #include "SpdifStreamOut.h"
61 #include "AudioHwDevice.h"
62 
63 #include <powermanager/IPowerManager.h>
64 
65 #include <media/nbaio/NBLog.h>
66 #include <private/media/AudioTrackShared.h>
67 
68 namespace android {
69 
70 struct audio_track_cblk_t;
71 struct effect_param_cblk_t;
72 class AudioMixer;
73 class AudioBuffer;
74 class AudioResampler;
75 class FastMixer;
76 class PassthruBufferProvider;
77 class ServerProxy;
78 
79 // ----------------------------------------------------------------------------
80 
81 // The macro FCC_2 highlights some (but not all) places where there are are 2-channel assumptions.
82 // This is typically due to legacy implementation of stereo input or output.
83 // Search also for "2", "left", "right", "[0]", "[1]", ">> 16", "<< 16", etc.
84 #define FCC_2 2     // FCC_2 = Fixed Channel Count 2
85 // The macro FCC_8 highlights places where there are 8-channel assumptions.
86 // This is typically due to audio mixer and resampler limitations.
87 #define FCC_8 8     // FCC_8 = Fixed Channel Count 8
88 
89 static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
90 
91 
92 // Max shared memory size for audio tracks and audio records per client process
93 static const size_t kClientSharedHeapSizeBytes = 1024*1024;
94 // Shared memory size multiplier for non low ram devices
95 static const size_t kClientSharedHeapSizeMultiplier = 4;
96 
97 #define INCLUDING_FROM_AUDIOFLINGER_H
98 
99 class AudioFlinger :
100     public BinderService<AudioFlinger>,
101     public BnAudioFlinger
102 {
103     friend class BinderService<AudioFlinger>;   // for AudioFlinger()
104 public:
getServiceName()105     static const char* getServiceName() ANDROID_API { return "media.audio_flinger"; }
106 
107     virtual     status_t    dump(int fd, const Vector<String16>& args);
108 
109     // IAudioFlinger interface, in binder opcode order
110     virtual sp<IAudioTrack> createTrack(
111                                 audio_stream_type_t streamType,
112                                 uint32_t sampleRate,
113                                 audio_format_t format,
114                                 audio_channel_mask_t channelMask,
115                                 size_t *pFrameCount,
116                                 IAudioFlinger::track_flags_t *flags,
117                                 const sp<IMemory>& sharedBuffer,
118                                 audio_io_handle_t output,
119                                 pid_t tid,
120                                 int *sessionId,
121                                 int clientUid,
122                                 status_t *status /*non-NULL*/);
123 
124     virtual sp<IAudioRecord> openRecord(
125                                 audio_io_handle_t input,
126                                 uint32_t sampleRate,
127                                 audio_format_t format,
128                                 audio_channel_mask_t channelMask,
129                                 const String16& opPackageName,
130                                 size_t *pFrameCount,
131                                 IAudioFlinger::track_flags_t *flags,
132                                 pid_t tid,
133                                 int clientUid,
134                                 int *sessionId,
135                                 size_t *notificationFrames,
136                                 sp<IMemory>& cblk,
137                                 sp<IMemory>& buffers,
138                                 status_t *status /*non-NULL*/);
139 
140     virtual     uint32_t    sampleRate(audio_io_handle_t output) const;
141     virtual     audio_format_t format(audio_io_handle_t output) const;
142     virtual     size_t      frameCount(audio_io_handle_t output) const;
143     virtual     uint32_t    latency(audio_io_handle_t output) const;
144 
145     virtual     status_t    setMasterVolume(float value);
146     virtual     status_t    setMasterMute(bool muted);
147 
148     virtual     float       masterVolume() const;
149     virtual     bool        masterMute() const;
150 
151     virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value,
152                                             audio_io_handle_t output);
153     virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
154 
155     virtual     float       streamVolume(audio_stream_type_t stream,
156                                          audio_io_handle_t output) const;
157     virtual     bool        streamMute(audio_stream_type_t stream) const;
158 
159     virtual     status_t    setMode(audio_mode_t mode);
160 
161     virtual     status_t    setMicMute(bool state);
162     virtual     bool        getMicMute() const;
163 
164     virtual     status_t    setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
165     virtual     String8     getParameters(audio_io_handle_t ioHandle, const String8& keys) const;
166 
167     virtual     void        registerClient(const sp<IAudioFlingerClient>& client);
168 
169     virtual     size_t      getInputBufferSize(uint32_t sampleRate, audio_format_t format,
170                                                audio_channel_mask_t channelMask) const;
171 
172     virtual status_t openOutput(audio_module_handle_t module,
173                                 audio_io_handle_t *output,
174                                 audio_config_t *config,
175                                 audio_devices_t *devices,
176                                 const String8& address,
177                                 uint32_t *latencyMs,
178                                 audio_output_flags_t flags);
179 
180     virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1,
181                                                   audio_io_handle_t output2);
182 
183     virtual status_t closeOutput(audio_io_handle_t output);
184 
185     virtual status_t suspendOutput(audio_io_handle_t output);
186 
187     virtual status_t restoreOutput(audio_io_handle_t output);
188 
189     virtual status_t openInput(audio_module_handle_t module,
190                                audio_io_handle_t *input,
191                                audio_config_t *config,
192                                audio_devices_t *device,
193                                const String8& address,
194                                audio_source_t source,
195                                audio_input_flags_t flags);
196 
197     virtual status_t closeInput(audio_io_handle_t input);
198 
199     virtual status_t invalidateStream(audio_stream_type_t stream);
200 
201     virtual status_t setVoiceVolume(float volume);
202 
203     virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
204                                        audio_io_handle_t output) const;
205 
206     virtual uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const;
207 
208     virtual audio_unique_id_t newAudioUniqueId();
209 
210     virtual void acquireAudioSessionId(int audioSession, pid_t pid);
211 
212     virtual void releaseAudioSessionId(int audioSession, pid_t pid);
213 
214     virtual status_t queryNumberEffects(uint32_t *numEffects) const;
215 
216     virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor) const;
217 
218     virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid,
219                                          effect_descriptor_t *descriptor) const;
220 
221     virtual sp<IEffect> createEffect(
222                         effect_descriptor_t *pDesc,
223                         const sp<IEffectClient>& effectClient,
224                         int32_t priority,
225                         audio_io_handle_t io,
226                         int sessionId,
227                         const String16& opPackageName,
228                         status_t *status /*non-NULL*/,
229                         int *id,
230                         int *enabled);
231 
232     virtual status_t moveEffects(int sessionId, audio_io_handle_t srcOutput,
233                         audio_io_handle_t dstOutput);
234 
235     virtual audio_module_handle_t loadHwModule(const char *name);
236 
237     virtual uint32_t getPrimaryOutputSamplingRate();
238     virtual size_t getPrimaryOutputFrameCount();
239 
240     virtual status_t setLowRamDevice(bool isLowRamDevice);
241 
242     /* List available audio ports and their attributes */
243     virtual status_t listAudioPorts(unsigned int *num_ports,
244                                     struct audio_port *ports);
245 
246     /* Get attributes for a given audio port */
247     virtual status_t getAudioPort(struct audio_port *port);
248 
249     /* Create an audio patch between several source and sink ports */
250     virtual status_t createAudioPatch(const struct audio_patch *patch,
251                                        audio_patch_handle_t *handle);
252 
253     /* Release an audio patch */
254     virtual status_t releaseAudioPatch(audio_patch_handle_t handle);
255 
256     /* List existing audio patches */
257     virtual status_t listAudioPatches(unsigned int *num_patches,
258                                       struct audio_patch *patches);
259 
260     /* Set audio port configuration */
261     virtual status_t setAudioPortConfig(const struct audio_port_config *config);
262 
263     /* Get the HW synchronization source used for an audio session */
264     virtual audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId);
265 
266     /* Indicate JAVA services are ready (scheduling, power management ...) */
267     virtual status_t systemReady();
268 
269     virtual     status_t    onTransact(
270                                 uint32_t code,
271                                 const Parcel& data,
272                                 Parcel* reply,
273                                 uint32_t flags);
274 
275     // end of IAudioFlinger interface
276 
277     sp<NBLog::Writer>   newWriter_l(size_t size, const char *name);
278     void                unregisterWriter(const sp<NBLog::Writer>& writer);
279 private:
280     static const size_t kLogMemorySize = 40 * 1024;
281     sp<MemoryDealer>    mLogMemoryDealer;   // == 0 when NBLog is disabled
282     // When a log writer is unregistered, it is done lazily so that media.log can continue to see it
283     // for as long as possible.  The memory is only freed when it is needed for another log writer.
284     Vector< sp<NBLog::Writer> > mUnregisteredWriters;
285     Mutex               mUnregisteredWritersLock;
286 public:
287 
288     class SyncEvent;
289 
290     typedef void (*sync_event_callback_t)(const wp<SyncEvent>& event) ;
291 
292     class SyncEvent : public RefBase {
293     public:
SyncEvent(AudioSystem::sync_event_t type,int triggerSession,int listenerSession,sync_event_callback_t callBack,wp<RefBase> cookie)294         SyncEvent(AudioSystem::sync_event_t type,
295                   int triggerSession,
296                   int listenerSession,
297                   sync_event_callback_t callBack,
298                   wp<RefBase> cookie)
299         : mType(type), mTriggerSession(triggerSession), mListenerSession(listenerSession),
300           mCallback(callBack), mCookie(cookie)
301         {}
302 
~SyncEvent()303         virtual ~SyncEvent() {}
304 
trigger()305         void trigger() { Mutex::Autolock _l(mLock); if (mCallback) mCallback(this); }
isCancelled()306         bool isCancelled() const { Mutex::Autolock _l(mLock); return (mCallback == NULL); }
cancel()307         void cancel() { Mutex::Autolock _l(mLock); mCallback = NULL; }
type()308         AudioSystem::sync_event_t type() const { return mType; }
triggerSession()309         int triggerSession() const { return mTriggerSession; }
listenerSession()310         int listenerSession() const { return mListenerSession; }
cookie()311         wp<RefBase> cookie() const { return mCookie; }
312 
313     private:
314           const AudioSystem::sync_event_t mType;
315           const int mTriggerSession;
316           const int mListenerSession;
317           sync_event_callback_t mCallback;
318           const wp<RefBase> mCookie;
319           mutable Mutex mLock;
320     };
321 
322     sp<SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
323                                         int triggerSession,
324                                         int listenerSession,
325                                         sync_event_callback_t callBack,
326                                         wp<RefBase> cookie);
327 
328 private:
329 
getMode()330                audio_mode_t getMode() const { return mMode; }
331 
btNrecIsOff()332                 bool        btNrecIsOff() const { return mBtNrecIsOff; }
333 
334                             AudioFlinger() ANDROID_API;
335     virtual                 ~AudioFlinger();
336 
337     // call in any IAudioFlinger method that accesses mPrimaryHardwareDev
initCheck()338     status_t                initCheck() const { return mPrimaryHardwareDev == NULL ?
339                                                         NO_INIT : NO_ERROR; }
340 
341     // RefBase
342     virtual     void        onFirstRef();
343 
344     AudioHwDevice*          findSuitableHwDev_l(audio_module_handle_t module,
345                                                 audio_devices_t devices);
346     void                    purgeStaleEffects_l();
347 
348     // Set kEnableExtendedChannels to true to enable greater than stereo output
349     // for the MixerThread and device sink.  Number of channels allowed is
350     // FCC_2 <= channels <= AudioMixer::MAX_NUM_CHANNELS.
351     static const bool kEnableExtendedChannels = true;
352 
353     // Returns true if channel mask is permitted for the PCM sink in the MixerThread
isValidPcmSinkChannelMask(audio_channel_mask_t channelMask)354     static inline bool isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
355         switch (audio_channel_mask_get_representation(channelMask)) {
356         case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
357             uint32_t channelCount = FCC_2; // stereo is default
358             if (kEnableExtendedChannels) {
359                 channelCount = audio_channel_count_from_out_mask(channelMask);
360                 if (channelCount < FCC_2 // mono is not supported at this time
361                         || channelCount > AudioMixer::MAX_NUM_CHANNELS) {
362                     return false;
363                 }
364             }
365             // check that channelMask is the "canonical" one we expect for the channelCount.
366             return channelMask == audio_channel_out_mask_from_count(channelCount);
367             }
368         case AUDIO_CHANNEL_REPRESENTATION_INDEX:
369             if (kEnableExtendedChannels) {
370                 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
371                 if (channelCount >= FCC_2 // mono is not supported at this time
372                         && channelCount <= AudioMixer::MAX_NUM_CHANNELS) {
373                     return true;
374                 }
375             }
376             return false;
377         default:
378             return false;
379         }
380     }
381 
382     // Set kEnableExtendedPrecision to true to use extended precision in MixerThread
383     static const bool kEnableExtendedPrecision = true;
384 
385     // Returns true if format is permitted for the PCM sink in the MixerThread
isValidPcmSinkFormat(audio_format_t format)386     static inline bool isValidPcmSinkFormat(audio_format_t format) {
387         switch (format) {
388         case AUDIO_FORMAT_PCM_16_BIT:
389             return true;
390         case AUDIO_FORMAT_PCM_FLOAT:
391         case AUDIO_FORMAT_PCM_24_BIT_PACKED:
392         case AUDIO_FORMAT_PCM_32_BIT:
393         case AUDIO_FORMAT_PCM_8_24_BIT:
394             return kEnableExtendedPrecision;
395         default:
396             return false;
397         }
398     }
399 
400     // standby delay for MIXER and DUPLICATING playback threads is read from property
401     // ro.audio.flinger_standbytime_ms or defaults to kDefaultStandbyTimeInNsecs
402     static nsecs_t          mStandbyTimeInNsecs;
403 
404     // incremented by 2 when screen state changes, bit 0 == 1 means "off"
405     // AudioFlinger::setParameters() updates, other threads read w/o lock
406     static uint32_t         mScreenState;
407 
408     // Internal dump utilities.
409     static const int kDumpLockRetries = 50;
410     static const int kDumpLockSleepUs = 20000;
411     static bool dumpTryLock(Mutex& mutex);
412     void dumpPermissionDenial(int fd, const Vector<String16>& args);
413     void dumpClients(int fd, const Vector<String16>& args);
414     void dumpInternals(int fd, const Vector<String16>& args);
415 
416     // --- Client ---
417     class Client : public RefBase {
418     public:
419                             Client(const sp<AudioFlinger>& audioFlinger, pid_t pid);
420         virtual             ~Client();
421         sp<MemoryDealer>    heap() const;
pid()422         pid_t               pid() const { return mPid; }
audioFlinger()423         sp<AudioFlinger>    audioFlinger() const { return mAudioFlinger; }
424 
425         bool reserveTimedTrack();
426         void releaseTimedTrack();
427 
428     private:
429                             Client(const Client&);
430                             Client& operator = (const Client&);
431         const sp<AudioFlinger> mAudioFlinger;
432               sp<MemoryDealer> mMemoryDealer;
433         const pid_t         mPid;
434 
435         Mutex               mTimedTrackLock;
436         int                 mTimedTrackCount;
437     };
438 
439     // --- Notification Client ---
440     class NotificationClient : public IBinder::DeathRecipient {
441     public:
442                             NotificationClient(const sp<AudioFlinger>& audioFlinger,
443                                                 const sp<IAudioFlingerClient>& client,
444                                                 pid_t pid);
445         virtual             ~NotificationClient();
446 
audioFlingerClient()447                 sp<IAudioFlingerClient> audioFlingerClient() const { return mAudioFlingerClient; }
448 
449                 // IBinder::DeathRecipient
450                 virtual     void        binderDied(const wp<IBinder>& who);
451 
452     private:
453                             NotificationClient(const NotificationClient&);
454                             NotificationClient& operator = (const NotificationClient&);
455 
456         const sp<AudioFlinger>  mAudioFlinger;
457         const pid_t             mPid;
458         const sp<IAudioFlingerClient> mAudioFlingerClient;
459     };
460 
461     class TrackHandle;
462     class RecordHandle;
463     class RecordThread;
464     class PlaybackThread;
465     class MixerThread;
466     class DirectOutputThread;
467     class OffloadThread;
468     class DuplicatingThread;
469     class AsyncCallbackThread;
470     class Track;
471     class RecordTrack;
472     class EffectModule;
473     class EffectHandle;
474     class EffectChain;
475 
476     struct AudioStreamIn;
477 
478     struct  stream_type_t {
stream_type_tstream_type_t479         stream_type_t()
480             :   volume(1.0f),
481                 mute(false)
482         {
483         }
484         float       volume;
485         bool        mute;
486     };
487 
488     // --- PlaybackThread ---
489 
490 #include "Threads.h"
491 
492 #include "Effects.h"
493 
494 #include "PatchPanel.h"
495 
496     // server side of the client's IAudioTrack
497     class TrackHandle : public android::BnAudioTrack {
498     public:
499                             TrackHandle(const sp<PlaybackThread::Track>& track);
500         virtual             ~TrackHandle();
501         virtual sp<IMemory> getCblk() const;
502         virtual status_t    start();
503         virtual void        stop();
504         virtual void        flush();
505         virtual void        pause();
506         virtual status_t    attachAuxEffect(int effectId);
507         virtual status_t    allocateTimedBuffer(size_t size,
508                                                 sp<IMemory>* buffer);
509         virtual status_t    queueTimedBuffer(const sp<IMemory>& buffer,
510                                              int64_t pts);
511         virtual status_t    setMediaTimeTransform(const LinearTransform& xform,
512                                                   int target);
513         virtual status_t    setParameters(const String8& keyValuePairs);
514         virtual status_t    getTimestamp(AudioTimestamp& timestamp);
515         virtual void        signal(); // signal playback thread for a change in control block
516 
517         virtual status_t onTransact(
518             uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
519 
520     private:
521         const sp<PlaybackThread::Track> mTrack;
522     };
523 
524     // server side of the client's IAudioRecord
525     class RecordHandle : public android::BnAudioRecord {
526     public:
527         RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
528         virtual             ~RecordHandle();
529         virtual status_t    start(int /*AudioSystem::sync_event_t*/ event, int triggerSession);
530         virtual void        stop();
531         virtual status_t onTransact(
532             uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
533     private:
534         const sp<RecordThread::RecordTrack> mRecordTrack;
535 
536         // for use from destructor
537         void                stop_nonvirtual();
538     };
539 
540 
541               PlaybackThread *checkPlaybackThread_l(audio_io_handle_t output) const;
542               MixerThread *checkMixerThread_l(audio_io_handle_t output) const;
543               RecordThread *checkRecordThread_l(audio_io_handle_t input) const;
544               sp<RecordThread> openInput_l(audio_module_handle_t module,
545                                            audio_io_handle_t *input,
546                                            audio_config_t *config,
547                                            audio_devices_t device,
548                                            const String8& address,
549                                            audio_source_t source,
550                                            audio_input_flags_t flags);
551               sp<PlaybackThread> openOutput_l(audio_module_handle_t module,
552                                               audio_io_handle_t *output,
553                                               audio_config_t *config,
554                                               audio_devices_t devices,
555                                               const String8& address,
556                                               audio_output_flags_t flags);
557 
558               void closeOutputFinish(sp<PlaybackThread> thread);
559               void closeInputFinish(sp<RecordThread> thread);
560 
561               // no range check, AudioFlinger::mLock held
streamMute_l(audio_stream_type_t stream)562               bool streamMute_l(audio_stream_type_t stream) const
563                                 { return mStreamTypes[stream].mute; }
564               // no range check, doesn't check per-thread stream volume, AudioFlinger::mLock held
streamVolume_l(audio_stream_type_t stream)565               float streamVolume_l(audio_stream_type_t stream) const
566                                 { return mStreamTypes[stream].volume; }
567               void ioConfigChanged(audio_io_config_event event,
568                                    const sp<AudioIoDescriptor>& ioDesc,
569                                    pid_t pid = 0);
570 
571               // Allocate an audio_io_handle_t, session ID, effect ID, or audio_module_handle_t.
572               // They all share the same ID space, but the namespaces are actually independent
573               // because there are separate KeyedVectors for each kind of ID.
574               // The return value is uint32_t, but is cast to signed for some IDs.
575               // FIXME This API does not handle rollover to zero (for unsigned IDs),
576               //       or from positive to negative (for signed IDs).
577               //       Thus it may fail by returning an ID of the wrong sign,
578               //       or by returning a non-unique ID.
579               uint32_t nextUniqueId();
580 
581               status_t moveEffectChain_l(int sessionId,
582                                      PlaybackThread *srcThread,
583                                      PlaybackThread *dstThread,
584                                      bool reRegister);
585               // return thread associated with primary hardware device, or NULL
586               PlaybackThread *primaryPlaybackThread_l() const;
587               audio_devices_t primaryOutputDevice_l() const;
588 
589               sp<PlaybackThread> getEffectThread_l(int sessionId, int EffectId);
590 
591 
592                 void        removeClient_l(pid_t pid);
593                 void        removeNotificationClient(pid_t pid);
594                 bool isNonOffloadableGlobalEffectEnabled_l();
595                 void onNonOffloadableGlobalEffectEnable();
596 
597                 // Store an effect chain to mOrphanEffectChains keyed vector.
598                 // Called when a thread exits and effects are still attached to it.
599                 // If effects are later created on the same session, they will reuse the same
600                 // effect chain and same instances in the effect library.
601                 // return ALREADY_EXISTS if a chain with the same session already exists in
602                 // mOrphanEffectChains. Note that this should never happen as there is only one
603                 // chain for a given session and it is attached to only one thread at a time.
604                 status_t        putOrphanEffectChain_l(const sp<EffectChain>& chain);
605                 // Get an effect chain for the specified session in mOrphanEffectChains and remove
606                 // it if found. Returns 0 if not found (this is the most common case).
607                 sp<EffectChain> getOrphanEffectChain_l(audio_session_t session);
608                 // Called when the last effect handle on an effect instance is removed. If this
609                 // effect belongs to an effect chain in mOrphanEffectChains, the chain is updated
610                 // and removed from mOrphanEffectChains if it does not contain any effect.
611                 // Return true if the effect was found in mOrphanEffectChains, false otherwise.
612                 bool            updateOrphanEffectChains(const sp<EffectModule>& effect);
613 
614                 void broacastParametersToRecordThreads_l(const String8& keyValuePairs);
615 
616     // AudioStreamIn is immutable, so their fields are const.
617     // For emphasis, we could also make all pointers to them be "const *",
618     // but that would clutter the code unnecessarily.
619 
620     struct AudioStreamIn {
621         AudioHwDevice* const audioHwDev;
622         audio_stream_in_t* const stream;
623 
hwDevAudioStreamIn624         audio_hw_device_t* hwDev() const { return audioHwDev->hwDevice(); }
625 
AudioStreamInAudioStreamIn626         AudioStreamIn(AudioHwDevice *dev, audio_stream_in_t *in) :
627             audioHwDev(dev), stream(in) {}
628     };
629 
630     // for mAudioSessionRefs only
631     struct AudioSessionRef {
AudioSessionRefAudioSessionRef632         AudioSessionRef(int sessionid, pid_t pid) :
633             mSessionid(sessionid), mPid(pid), mCnt(1) {}
634         const int   mSessionid;
635         const pid_t mPid;
636         int         mCnt;
637     };
638 
639     mutable     Mutex                               mLock;
640                 // protects mClients and mNotificationClients.
641                 // must be locked after mLock and ThreadBase::mLock if both must be locked
642                 // avoids acquiring AudioFlinger::mLock from inside thread loop.
643     mutable     Mutex                               mClientLock;
644                 // protected by mClientLock
645                 DefaultKeyedVector< pid_t, wp<Client> >     mClients;   // see ~Client()
646 
647                 mutable     Mutex                   mHardwareLock;
648                 // NOTE: If both mLock and mHardwareLock mutexes must be held,
649                 // always take mLock before mHardwareLock
650 
651                 // These two fields are immutable after onFirstRef(), so no lock needed to access
652                 AudioHwDevice*                      mPrimaryHardwareDev; // mAudioHwDevs[0] or NULL
653                 DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*>  mAudioHwDevs;
654 
655     // for dump, indicates which hardware operation is currently in progress (but not stream ops)
656     enum hardware_call_state {
657         AUDIO_HW_IDLE = 0,              // no operation in progress
658         AUDIO_HW_INIT,                  // init_check
659         AUDIO_HW_OUTPUT_OPEN,           // open_output_stream
660         AUDIO_HW_OUTPUT_CLOSE,          // unused
661         AUDIO_HW_INPUT_OPEN,            // unused
662         AUDIO_HW_INPUT_CLOSE,           // unused
663         AUDIO_HW_STANDBY,               // unused
664         AUDIO_HW_SET_MASTER_VOLUME,     // set_master_volume
665         AUDIO_HW_GET_ROUTING,           // unused
666         AUDIO_HW_SET_ROUTING,           // unused
667         AUDIO_HW_GET_MODE,              // unused
668         AUDIO_HW_SET_MODE,              // set_mode
669         AUDIO_HW_GET_MIC_MUTE,          // get_mic_mute
670         AUDIO_HW_SET_MIC_MUTE,          // set_mic_mute
671         AUDIO_HW_SET_VOICE_VOLUME,      // set_voice_volume
672         AUDIO_HW_SET_PARAMETER,         // set_parameters
673         AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size
674         AUDIO_HW_GET_MASTER_VOLUME,     // get_master_volume
675         AUDIO_HW_GET_PARAMETER,         // get_parameters
676         AUDIO_HW_SET_MASTER_MUTE,       // set_master_mute
677         AUDIO_HW_GET_MASTER_MUTE,       // get_master_mute
678     };
679 
680     mutable     hardware_call_state                 mHardwareStatus;    // for dump only
681 
682 
683                 DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> >  mPlaybackThreads;
684                 stream_type_t                       mStreamTypes[AUDIO_STREAM_CNT];
685 
686                 // member variables below are protected by mLock
687                 float                               mMasterVolume;
688                 bool                                mMasterMute;
689                 // end of variables protected by mLock
690 
691                 DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> >    mRecordThreads;
692 
693                 // protected by mClientLock
694                 DefaultKeyedVector< pid_t, sp<NotificationClient> >    mNotificationClients;
695 
696                 volatile int32_t                    mNextUniqueId;  // updated by android_atomic_inc
697                 // nextUniqueId() returns uint32_t, but this is declared int32_t
698                 // because the atomic operations require an int32_t
699 
700                 audio_mode_t                        mMode;
701                 bool                                mBtNrecIsOff;
702 
703                 // protected by mLock
704                 Vector<AudioSessionRef*> mAudioSessionRefs;
705 
706                 float       masterVolume_l() const;
707                 bool        masterMute_l() const;
708                 audio_module_handle_t loadHwModule_l(const char *name);
709 
710                 Vector < sp<SyncEvent> > mPendingSyncEvents; // sync events awaiting for a session
711                                                              // to be created
712 
713                 // Effect chains without a valid thread
714                 DefaultKeyedVector< audio_session_t , sp<EffectChain> > mOrphanEffectChains;
715 
716                 // list of sessions for which a valid HW A/V sync ID was retrieved from the HAL
717                 DefaultKeyedVector< audio_session_t , audio_hw_sync_t >mHwAvSyncIds;
718 private:
719     sp<Client>  registerPid(pid_t pid);    // always returns non-0
720 
721     // for use from destructor
722     status_t    closeOutput_nonvirtual(audio_io_handle_t output);
723     void        closeOutputInternal_l(sp<PlaybackThread> thread);
724     status_t    closeInput_nonvirtual(audio_io_handle_t input);
725     void        closeInputInternal_l(sp<RecordThread> thread);
726     void        setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId);
727 
728     status_t    checkStreamType(audio_stream_type_t stream) const;
729 
730 #ifdef TEE_SINK
731     // all record threads serially share a common tee sink, which is re-created on format change
732     sp<NBAIO_Sink>   mRecordTeeSink;
733     sp<NBAIO_Source> mRecordTeeSource;
734 #endif
735 
736 public:
737 
738 #ifdef TEE_SINK
739     // tee sink, if enabled by property, allows dumpsys to write most recent audio to .wav file
740     static void dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id = 0);
741 
742     // whether tee sink is enabled by property
743     static bool mTeeSinkInputEnabled;
744     static bool mTeeSinkOutputEnabled;
745     static bool mTeeSinkTrackEnabled;
746 
747     // runtime configured size of each tee sink pipe, in frames
748     static size_t mTeeSinkInputFrames;
749     static size_t mTeeSinkOutputFrames;
750     static size_t mTeeSinkTrackFrames;
751 
752     // compile-time default size of tee sink pipes, in frames
753     // 0x200000 stereo 16-bit PCM frames = 47.5 seconds at 44.1 kHz, 8 megabytes
754     static const size_t kTeeSinkInputFramesDefault = 0x200000;
755     static const size_t kTeeSinkOutputFramesDefault = 0x200000;
756     static const size_t kTeeSinkTrackFramesDefault = 0x200000;
757 #endif
758 
759     // This method reads from a variable without mLock, but the variable is updated under mLock.  So
760     // we might read a stale value, or a value that's inconsistent with respect to other variables.
761     // In this case, it's safe because the return value isn't used for making an important decision.
762     // The reason we don't want to take mLock is because it could block the caller for a long time.
isLowRamDevice()763     bool    isLowRamDevice() const { return mIsLowRamDevice; }
764 
765 private:
766     bool    mIsLowRamDevice;
767     bool    mIsDeviceTypeKnown;
768     nsecs_t mGlobalEffectEnableTime;  // when a global effect was last enabled
769 
770     sp<PatchPanel> mPatchPanel;
771 
772     bool        mSystemReady;
773 };
774 
775 #undef INCLUDING_FROM_AUDIOFLINGER_H
776 
777 const char *formatToString(audio_format_t format);
778 String8 inputFlagsToString(audio_input_flags_t flags);
779 String8 outputFlagsToString(audio_output_flags_t flags);
780 String8 devicesToString(audio_devices_t devices);
781 const char *sourceToString(audio_source_t source);
782 
783 // ----------------------------------------------------------------------------
784 
785 } // namespace android
786 
787 #endif // ANDROID_AUDIO_FLINGER_H
788