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