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