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