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