1 /* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 18 #include <stdint.h> 19 #include <sys/types.h> 20 #include <utils/Timers.h> 21 #include <utils/Errors.h> 22 #include <utils/KeyedVector.h> 23 #include <hardware_legacy/AudioPolicyInterface.h> 24 25 26 namespace android_audio_legacy { 27 using android::KeyedVector; 28 29 // ---------------------------------------------------------------------------- 30 31 #define MAX_DEVICE_ADDRESS_LEN 20 32 // Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB 33 #define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5 34 // Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB 35 #define SONIFICATION_HEADSET_VOLUME_MIN 0.016 36 // Time in milliseconds during which we consider that music is still active after a music 37 // track was stopped - see computeVolume() 38 #define SONIFICATION_HEADSET_MUSIC_DELAY 5000 39 // Time in milliseconds during witch some streams are muted while the audio path 40 // is switched 41 #define MUTE_TIME_MS 2000 42 43 #define NUM_TEST_OUTPUTS 5 44 45 #define NUM_VOL_CURVE_KNEES 2 46 47 // ---------------------------------------------------------------------------- 48 // AudioPolicyManagerBase implements audio policy manager behavior common to all platforms. 49 // Each platform must implement an AudioPolicyManager class derived from AudioPolicyManagerBase 50 // and override methods for which the platform specific behavior differs from the implementation 51 // in AudioPolicyManagerBase. Even if no specific behavior is required, the AudioPolicyManager 52 // class must be implemented as well as the class factory function createAudioPolicyManager() 53 // and provided in a shared library libaudiopolicy.so. 54 // ---------------------------------------------------------------------------- 55 56 class AudioPolicyManagerBase: public AudioPolicyInterface 57 #ifdef AUDIO_POLICY_TEST 58 , public Thread 59 #endif //AUDIO_POLICY_TEST 60 { 61 62 public: 63 AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface); 64 virtual ~AudioPolicyManagerBase(); 65 66 // AudioPolicyInterface 67 virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device, 68 AudioSystem::device_connection_state state, 69 const char *device_address); 70 virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device, 71 const char *device_address); 72 virtual void setPhoneState(int state); 73 virtual void setRingerMode(uint32_t mode, uint32_t mask); 74 virtual void setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config); 75 virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage); 76 virtual void setSystemProperty(const char* property, const char* value); 77 virtual status_t initCheck(); 78 virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream, 79 uint32_t samplingRate = 0, 80 uint32_t format = AudioSystem::FORMAT_DEFAULT, 81 uint32_t channels = 0, 82 AudioSystem::output_flags flags = 83 AudioSystem::OUTPUT_FLAG_INDIRECT); 84 virtual status_t startOutput(audio_io_handle_t output, 85 AudioSystem::stream_type stream, 86 int session = 0); 87 virtual status_t stopOutput(audio_io_handle_t output, 88 AudioSystem::stream_type stream, 89 int session = 0); 90 virtual void releaseOutput(audio_io_handle_t output); 91 virtual audio_io_handle_t getInput(int inputSource, 92 uint32_t samplingRate, 93 uint32_t format, 94 uint32_t channels, 95 AudioSystem::audio_in_acoustics acoustics); 96 // indicates to the audio policy manager that the input starts being used. 97 virtual status_t startInput(audio_io_handle_t input); 98 // indicates to the audio policy manager that the input stops being used. 99 virtual status_t stopInput(audio_io_handle_t input); 100 virtual void releaseInput(audio_io_handle_t input); 101 virtual void initStreamVolume(AudioSystem::stream_type stream, 102 int indexMin, 103 int indexMax); 104 virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream, int index); 105 virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream, int *index); 106 107 // return the strategy corresponding to a given stream type 108 virtual uint32_t getStrategyForStream(AudioSystem::stream_type stream); 109 110 // return the enabled output devices for the given stream type 111 virtual uint32_t getDevicesForStream(AudioSystem::stream_type stream); 112 113 virtual audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc); 114 virtual status_t registerEffect(effect_descriptor_t *desc, 115 audio_io_handle_t io, 116 uint32_t strategy, 117 int session, 118 int id); 119 virtual status_t unregisterEffect(int id); 120 virtual status_t setEffectEnabled(int id, bool enabled); 121 122 virtual bool isStreamActive(int stream, uint32_t inPastMs = 0) const; 123 124 virtual status_t dump(int fd); 125 126 protected: 127 128 enum routing_strategy { 129 STRATEGY_MEDIA, 130 STRATEGY_PHONE, 131 STRATEGY_SONIFICATION, 132 STRATEGY_DTMF, 133 STRATEGY_ENFORCED_AUDIBLE, 134 NUM_STRATEGIES 135 }; 136 137 // 4 points to define the volume attenuation curve, each characterized by the volume 138 // index (from 0 to 100) at which they apply, and the attenuation in dB at that index. 139 // we use 100 steps to avoid rounding errors when computing the volume in volIndexToAmpl() 140 141 enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3, VOLCNT = 4}; 142 143 class VolumeCurvePoint 144 { 145 public: 146 int mIndex; 147 float mDBAttenuation; 148 }; 149 150 // device categories used for volume curve management. 151 enum device_category { 152 DEVICE_CATEGORY_HEADSET, 153 DEVICE_CATEGORY_SPEAKER, 154 DEVICE_CATEGORY_EARPIECE, 155 DEVICE_CATEGORY_CNT 156 }; 157 158 // default volume curve 159 static const VolumeCurvePoint sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT]; 160 // default volume curve for media strategy 161 static const VolumeCurvePoint sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT]; 162 // volume curve for media strategy on speakers 163 static const VolumeCurvePoint sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT]; 164 // volume curve for sonification strategy on speakers 165 static const VolumeCurvePoint sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT]; 166 // default volume curves per strategy and device category. See initializeVolumeCurves() 167 static const VolumeCurvePoint *sVolumeProfiles[NUM_STRATEGIES][DEVICE_CATEGORY_CNT]; 168 169 // descriptor for audio outputs. Used to maintain current configuration of each opened audio output 170 // and keep track of the usage of this output by each audio stream type. 171 class AudioOutputDescriptor 172 { 173 public: 174 AudioOutputDescriptor(); 175 176 status_t dump(int fd); 177 178 uint32_t device(); 179 void changeRefCount(AudioSystem::stream_type, int delta); 180 uint32_t refCount(); 181 uint32_t strategyRefCount(routing_strategy strategy); 182 bool isUsedByStrategy(routing_strategy strategy) { return (strategyRefCount(strategy) != 0);} 183 bool isDuplicated() { return (mOutput1 != NULL && mOutput2 != NULL); } 184 185 audio_io_handle_t mId; // output handle 186 uint32_t mSamplingRate; // 187 uint32_t mFormat; // 188 uint32_t mChannels; // output configuration 189 uint32_t mLatency; // 190 AudioSystem::output_flags mFlags; // 191 uint32_t mDevice; // current device this output is routed to 192 uint32_t mRefCount[AudioSystem::NUM_STREAM_TYPES]; // number of streams of each type using this output 193 nsecs_t mStopTime[AudioSystem::NUM_STREAM_TYPES]; 194 AudioOutputDescriptor *mOutput1; // used by duplicated outputs: first output 195 AudioOutputDescriptor *mOutput2; // used by duplicated outputs: second output 196 float mCurVolume[AudioSystem::NUM_STREAM_TYPES]; // current stream volume 197 int mMuteCount[AudioSystem::NUM_STREAM_TYPES]; // mute request counter 198 }; 199 200 // descriptor for audio inputs. Used to maintain current configuration of each opened audio input 201 // and keep track of the usage of this input. 202 class AudioInputDescriptor 203 { 204 public: 205 AudioInputDescriptor(); 206 207 status_t dump(int fd); 208 209 uint32_t mSamplingRate; // 210 uint32_t mFormat; // input configuration 211 uint32_t mChannels; // 212 AudioSystem::audio_in_acoustics mAcoustics; // 213 uint32_t mDevice; // current device this input is routed to 214 uint32_t mRefCount; // number of AudioRecord clients using this output 215 int mInputSource; // input source selected by application (mediarecorder.h) 216 }; 217 218 // stream descriptor used for volume control 219 class StreamDescriptor 220 { 221 public: 222 StreamDescriptor() 223 : mIndexMin(0), mIndexMax(1), mIndexCur(1), mCanBeMuted(true) {} 224 225 void dump(char* buffer, size_t size); 226 227 int mIndexMin; // min volume index 228 int mIndexMax; // max volume index 229 int mIndexCur; // current volume index 230 bool mCanBeMuted; // true is the stream can be muted 231 232 const VolumeCurvePoint *mVolumeCurve[DEVICE_CATEGORY_CNT]; 233 }; 234 235 // stream descriptor used for volume control 236 class EffectDescriptor 237 { 238 public: 239 240 status_t dump(int fd); 241 242 int mIo; // io the effect is attached to 243 routing_strategy mStrategy; // routing strategy the effect is associated to 244 int mSession; // audio session the effect is on 245 effect_descriptor_t mDesc; // effect descriptor 246 bool mEnabled; // enabled state: CPU load being used or not 247 }; 248 249 void addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc); 250 251 // return the strategy corresponding to a given stream type 252 static routing_strategy getStrategy(AudioSystem::stream_type stream); 253 // return appropriate device for streams handled by the specified strategy according to current 254 // phone state, connected devices... 255 // if fromCache is true, the device is returned from mDeviceForStrategy[], otherwise it is determined 256 // by current state (device connected, phone state, force use, a2dp output...) 257 // This allows to: 258 // 1 speed up process when the state is stable (when starting or stopping an output) 259 // 2 access to either current device selection (fromCache == true) or 260 // "future" device selection (fromCache == false) when called from a context 261 // where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND 262 // before updateDeviceForStrategy() is called. 263 virtual uint32_t getDeviceForStrategy(routing_strategy strategy, bool fromCache = true); 264 // change the route of the specified output 265 void setOutputDevice(audio_io_handle_t output, uint32_t device, bool force = false, int delayMs = 0); 266 // select input device corresponding to requested audio source 267 virtual uint32_t getDeviceForInputSource(int inputSource); 268 // return io handle of active input or 0 if no input is active 269 audio_io_handle_t getActiveInput(); 270 // initialize volume curves for each strategy and device category 271 void initializeVolumeCurves(); 272 // compute the actual volume for a given stream according to the requested index and a particular 273 // device 274 virtual float computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device); 275 // check that volume change is permitted, compute and send new volume to audio hardware 276 status_t checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs = 0, bool force = false); 277 // apply all stream volumes to the specified output and device 278 void applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs = 0, bool force = false); 279 // Mute or unmute all streams handled by the specified strategy on the specified output 280 void setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs = 0); 281 // Mute or unmute the stream on the specified output 282 void setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs = 0); 283 // handle special cases for sonification strategy while in call: mute streams or replace by 284 // a special tone in the device used for communication 285 void handleIncallSonification(int stream, bool starting, bool stateChange); 286 // true is current platform implements a back microphone 287 virtual bool hasBackMicrophone() const { return false; } 288 // true if device is in a telephony or VoIP call 289 virtual bool isInCall(); 290 // true if given state represents a device in a telephony or VoIP call 291 virtual bool isStateInCall(int state); 292 293 #ifdef WITH_A2DP 294 // true is current platform supports suplication of notifications and ringtones over A2DP output 295 virtual bool a2dpUsedForSonification() const { return true; } 296 status_t handleA2dpConnection(AudioSystem::audio_devices device, 297 const char *device_address); 298 status_t handleA2dpDisconnection(AudioSystem::audio_devices device, 299 const char *device_address); 300 void closeA2dpOutputs(); 301 // checks and if necessary changes output (a2dp, duplicated or hardware) used for all strategies. 302 // must be called every time a condition that affects the output choice for a given strategy is 303 // changed: connected device, phone state, force use... 304 // Must be called before updateDeviceForStrategy() 305 void checkOutputForStrategy(routing_strategy strategy); 306 // Same as checkOutputForStrategy() but for a all strategies in order of priority 307 void checkOutputForAllStrategies(); 308 // manages A2DP output suspend/restore according to phone state and BT SCO usage 309 void checkA2dpSuspend(); 310 #endif 311 // selects the most appropriate device on output for current state 312 // must be called every time a condition that affects the device choice for a given output is 313 // changed: connected device, phone state, force use, output start, output stop.. 314 // see getDeviceForStrategy() for the use of fromCache parameter 315 uint32_t getNewDevice(audio_io_handle_t output, bool fromCache = true); 316 // updates cache of device used by all strategies (mDeviceForStrategy[]) 317 // must be called every time a condition that affects the device choice for a given strategy is 318 // changed: connected device, phone state, force use... 319 // cached values are used by getDeviceForStrategy() if parameter fromCache is true. 320 // Must be called after checkOutputForAllStrategies() 321 void updateDeviceForStrategy(); 322 // true if current platform requires a specific output to be opened for this particular 323 // set of parameters. This function is called by getOutput() and is implemented by platform 324 // specific audio policy manager. 325 virtual bool needsDirectOuput(AudioSystem::stream_type stream, 326 uint32_t samplingRate, 327 uint32_t format, 328 uint32_t channels, 329 AudioSystem::output_flags flags, 330 uint32_t device); 331 virtual uint32_t getMaxEffectsCpuLoad(); 332 virtual uint32_t getMaxEffectsMemory(); 333 #ifdef AUDIO_POLICY_TEST 334 virtual bool threadLoop(); 335 void exit(); 336 int testOutputIndex(audio_io_handle_t output); 337 #endif //AUDIO_POLICY_TEST 338 339 status_t setEffectEnabled(EffectDescriptor *pDesc, bool enabled); 340 341 // returns the category the device belongs to with regard to volume curve management 342 static device_category getDeviceCategory(uint32_t device); 343 344 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface 345 audio_io_handle_t mHardwareOutput; // hardware output handler 346 audio_io_handle_t mA2dpOutput; // A2DP output handler 347 audio_io_handle_t mDuplicatedOutput; // duplicated output handler: outputs to hardware and A2DP. 348 349 KeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mOutputs; // list of output descriptors 350 KeyedVector<audio_io_handle_t, AudioInputDescriptor *> mInputs; // list of input descriptors 351 uint32_t mAvailableOutputDevices; // bit field of all available output devices 352 uint32_t mAvailableInputDevices; // bit field of all available input devices 353 int mPhoneState; // current phone state 354 uint32_t mRingerMode; // current ringer mode 355 AudioSystem::forced_config mForceUse[AudioSystem::NUM_FORCE_USE]; // current forced use configuration 356 357 StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES]; // stream descriptors for volume control 358 String8 mA2dpDeviceAddress; // A2DP device MAC address 359 String8 mScoDeviceAddress; // SCO device MAC address 360 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected 361 uint32_t mDeviceForStrategy[NUM_STRATEGIES]; 362 float mLastVoiceVolume; // last voice volume value sent to audio HAL 363 364 // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units 365 static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000; 366 // Maximum memory allocated to audio effects in KB 367 static const uint32_t MAX_EFFECTS_MEMORY = 512; 368 uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects 369 uint32_t mTotalEffectsMemory; // current memory used by effects 370 KeyedVector<int, EffectDescriptor *> mEffects; // list of registered audio effects 371 bool mA2dpSuspended; // true if A2DP output is suspended 372 373 #ifdef AUDIO_POLICY_TEST 374 Mutex mLock; 375 Condition mWaitWorkCV; 376 377 int mCurOutput; 378 bool mDirectOutput; 379 audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS]; 380 int mTestInput; 381 uint32_t mTestDevice; 382 uint32_t mTestSamplingRate; 383 uint32_t mTestFormat; 384 uint32_t mTestChannels; 385 uint32_t mTestLatencyMs; 386 #endif //AUDIO_POLICY_TEST 387 388 private: 389 static float volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc, 390 int indexInUi); 391 }; 392 393 }; 394