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