AudioSystem.h revision 766fb020a50b64bf9a808bd80df60c54c2ca8cc3
1/* 2 * Copyright (C) 2008 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#ifndef ANDROID_AUDIOSYSTEM_H_ 18#define ANDROID_AUDIOSYSTEM_H_ 19 20#include <sys/types.h> 21 22#include <media/AudioPolicy.h> 23#include <media/AudioIoDescriptor.h> 24#include <media/IAudioFlingerClient.h> 25#include <media/IAudioPolicyServiceClient.h> 26#include <system/audio.h> 27#include <system/audio_effect.h> 28#include <system/audio_policy.h> 29#include <utils/Errors.h> 30#include <utils/Mutex.h> 31 32namespace android { 33 34typedef void (*audio_error_callback)(status_t err); 35typedef void (*dynamic_policy_callback)(int event, String8 regId, int val); 36typedef void (*record_config_callback)(int event, const record_client_info_t *clientInfo, 37 const audio_config_base_t *clientConfig, const audio_config_base_t *deviceConfig, 38 audio_patch_handle_t patchHandle); 39 40class IAudioFlinger; 41class IAudioPolicyService; 42class String8; 43 44class AudioSystem 45{ 46public: 47 48 // FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp 49 50 /* These are static methods to control the system-wide AudioFlinger 51 * only privileged processes can have access to them 52 */ 53 54 // mute/unmute microphone 55 static status_t muteMicrophone(bool state); 56 static status_t isMicrophoneMuted(bool *state); 57 58 // set/get master volume 59 static status_t setMasterVolume(float value); 60 static status_t getMasterVolume(float* volume); 61 62 // mute/unmute audio outputs 63 static status_t setMasterMute(bool mute); 64 static status_t getMasterMute(bool* mute); 65 66 // set/get stream volume on specified output 67 static status_t setStreamVolume(audio_stream_type_t stream, float value, 68 audio_io_handle_t output); 69 static status_t getStreamVolume(audio_stream_type_t stream, float* volume, 70 audio_io_handle_t output); 71 72 // mute/unmute stream 73 static status_t setStreamMute(audio_stream_type_t stream, bool mute); 74 static status_t getStreamMute(audio_stream_type_t stream, bool* mute); 75 76 // set audio mode in audio hardware 77 static status_t setMode(audio_mode_t mode); 78 79 // returns true in *state if tracks are active on the specified stream or have been active 80 // in the past inPastMs milliseconds 81 static status_t isStreamActive(audio_stream_type_t stream, bool *state, uint32_t inPastMs); 82 // returns true in *state if tracks are active for what qualifies as remote playback 83 // on the specified stream or have been active in the past inPastMs milliseconds. Remote 84 // playback isn't mutually exclusive with local playback. 85 static status_t isStreamActiveRemotely(audio_stream_type_t stream, bool *state, 86 uint32_t inPastMs); 87 // returns true in *state if a recorder is currently recording with the specified source 88 static status_t isSourceActive(audio_source_t source, bool *state); 89 90 // set/get audio hardware parameters. The function accepts a list of parameters 91 // key value pairs in the form: key1=value1;key2=value2;... 92 // Some keys are reserved for standard parameters (See AudioParameter class). 93 // The versions with audio_io_handle_t are intended for internal media framework use only. 94 static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs); 95 static String8 getParameters(audio_io_handle_t ioHandle, const String8& keys); 96 // The versions without audio_io_handle_t are intended for JNI. 97 static status_t setParameters(const String8& keyValuePairs); 98 static String8 getParameters(const String8& keys); 99 100 static void setErrorCallback(audio_error_callback cb); 101 static void setDynPolicyCallback(dynamic_policy_callback cb); 102 static void setRecordConfigCallback(record_config_callback); 103 104 // helper function to obtain AudioFlinger service handle 105 static const sp<IAudioFlinger> get_audio_flinger(); 106 107 static float linearToLog(int volume); 108 static int logToLinear(float volume); 109 static size_t calculateMinFrameCount( 110 uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate, 111 uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/); 112 113 // Returned samplingRate and frameCount output values are guaranteed 114 // to be non-zero if status == NO_ERROR 115 // FIXME This API assumes a route, and so should be deprecated. 116 static status_t getOutputSamplingRate(uint32_t* samplingRate, 117 audio_stream_type_t stream); 118 // FIXME This API assumes a route, and so should be deprecated. 119 static status_t getOutputFrameCount(size_t* frameCount, 120 audio_stream_type_t stream); 121 // FIXME This API assumes a route, and so should be deprecated. 122 static status_t getOutputLatency(uint32_t* latency, 123 audio_stream_type_t stream); 124 // returns the audio HAL sample rate 125 static status_t getSamplingRate(audio_io_handle_t ioHandle, 126 uint32_t* samplingRate); 127 // For output threads with a fast mixer, returns the number of frames per normal mixer buffer. 128 // For output threads without a fast mixer, or for input, this is same as getFrameCountHAL(). 129 static status_t getFrameCount(audio_io_handle_t ioHandle, 130 size_t* frameCount); 131 // returns the audio output latency in ms. Corresponds to 132 // audio_stream_out->get_latency() 133 static status_t getLatency(audio_io_handle_t output, 134 uint32_t* latency); 135 136 // return status NO_ERROR implies *buffSize > 0 137 // FIXME This API assumes a route, and so should deprecated. 138 static status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 139 audio_channel_mask_t channelMask, size_t* buffSize); 140 141 static status_t setVoiceVolume(float volume); 142 143 // return the number of audio frames written by AudioFlinger to audio HAL and 144 // audio dsp to DAC since the specified output has exited standby. 145 // returned status (from utils/Errors.h) can be: 146 // - NO_ERROR: successful operation, halFrames and dspFrames point to valid data 147 // - INVALID_OPERATION: Not supported on current hardware platform 148 // - BAD_VALUE: invalid parameter 149 // NOTE: this feature is not supported on all hardware platforms and it is 150 // necessary to check returned status before using the returned values. 151 static status_t getRenderPosition(audio_io_handle_t output, 152 uint32_t *halFrames, 153 uint32_t *dspFrames); 154 155 // return the number of input frames lost by HAL implementation, or 0 if the handle is invalid 156 static uint32_t getInputFramesLost(audio_io_handle_t ioHandle); 157 158 // Allocate a new unique ID for use as an audio session ID or I/O handle. 159 // If unable to contact AudioFlinger, returns AUDIO_UNIQUE_ID_ALLOCATE instead. 160 // FIXME If AudioFlinger were to ever exhaust the unique ID namespace, 161 // this method could fail by returning either a reserved ID like AUDIO_UNIQUE_ID_ALLOCATE 162 // or an unspecified existing unique ID. 163 static audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use); 164 165 static void acquireAudioSessionId(audio_session_t audioSession, pid_t pid); 166 static void releaseAudioSessionId(audio_session_t audioSession, pid_t pid); 167 168 // Get the HW synchronization source used for an audio session. 169 // Return a valid source or AUDIO_HW_SYNC_INVALID if an error occurs 170 // or no HW sync source is used. 171 static audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId); 172 173 // Indicate JAVA services are ready (scheduling, power management ...) 174 static status_t systemReady(); 175 176 // Returns the number of frames per audio HAL buffer. 177 // Corresponds to audio_stream->get_buffer_size()/audio_stream_in_frame_size() for input. 178 // See also getFrameCount(). 179 static status_t getFrameCountHAL(audio_io_handle_t ioHandle, 180 size_t* frameCount); 181 182 // Events used to synchronize actions between audio sessions. 183 // For instance SYNC_EVENT_PRESENTATION_COMPLETE can be used to delay recording start until 184 // playback is complete on another audio session. 185 // See definitions in MediaSyncEvent.java 186 enum sync_event_t { 187 SYNC_EVENT_SAME = -1, // used internally to indicate restart with same event 188 SYNC_EVENT_NONE = 0, 189 SYNC_EVENT_PRESENTATION_COMPLETE, 190 191 // 192 // Define new events here: SYNC_EVENT_START, SYNC_EVENT_STOP, SYNC_EVENT_TIME ... 193 // 194 SYNC_EVENT_CNT, 195 }; 196 197 // Timeout for synchronous record start. Prevents from blocking the record thread forever 198 // if the trigger event is not fired. 199 static const uint32_t kSyncRecordStartTimeOutMs = 30000; 200 201 // 202 // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions) 203 // 204 static status_t setDeviceConnectionState(audio_devices_t device, audio_policy_dev_state_t state, 205 const char *device_address, const char *device_name); 206 static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, 207 const char *device_address); 208 static status_t handleDeviceConfigChange(audio_devices_t device, 209 const char *device_address, 210 const char *device_name); 211 static status_t setPhoneState(audio_mode_t state); 212 static status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config); 213 static audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage); 214 215 static status_t getOutputForAttr(const audio_attributes_t *attr, 216 audio_io_handle_t *output, 217 audio_session_t session, 218 audio_stream_type_t *stream, 219 pid_t pid, 220 uid_t uid, 221 const audio_config_t *config, 222 audio_output_flags_t flags, 223 audio_port_handle_t *selectedDeviceId, 224 audio_port_handle_t *portId); 225 static status_t startOutput(audio_io_handle_t output, 226 audio_stream_type_t stream, 227 audio_session_t session); 228 static status_t stopOutput(audio_io_handle_t output, 229 audio_stream_type_t stream, 230 audio_session_t session); 231 static void releaseOutput(audio_io_handle_t output, 232 audio_stream_type_t stream, 233 audio_session_t session); 234 235 // Client must successfully hand off the handle reference to AudioFlinger via createRecord(), 236 // or release it with releaseInput(). 237 static status_t getInputForAttr(const audio_attributes_t *attr, 238 audio_io_handle_t *input, 239 audio_session_t session, 240 pid_t pid, 241 uid_t uid, 242 const audio_config_base_t *config, 243 audio_input_flags_t flags, 244 audio_port_handle_t *selectedDeviceId, 245 audio_port_handle_t *portId); 246 247 static status_t startInput(audio_io_handle_t input, 248 audio_session_t session, 249 audio_devices_t device, 250 uid_t uid, 251 bool *silenced); 252 static status_t stopInput(audio_io_handle_t input, 253 audio_session_t session); 254 static void releaseInput(audio_io_handle_t input, 255 audio_session_t session); 256 static status_t initStreamVolume(audio_stream_type_t stream, 257 int indexMin, 258 int indexMax); 259 static status_t setStreamVolumeIndex(audio_stream_type_t stream, 260 int index, 261 audio_devices_t device); 262 static status_t getStreamVolumeIndex(audio_stream_type_t stream, 263 int *index, 264 audio_devices_t device); 265 266 static uint32_t getStrategyForStream(audio_stream_type_t stream); 267 static audio_devices_t getDevicesForStream(audio_stream_type_t stream); 268 269 static audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc); 270 static status_t registerEffect(const effect_descriptor_t *desc, 271 audio_io_handle_t io, 272 uint32_t strategy, 273 audio_session_t session, 274 int id); 275 static status_t unregisterEffect(int id); 276 static status_t setEffectEnabled(int id, bool enabled); 277 278 // clear stream to output mapping cache (gStreamOutputMap) 279 // and output configuration cache (gOutputs) 280 static void clearAudioConfigCache(); 281 282 static const sp<IAudioPolicyService> get_audio_policy_service(); 283 284 // helpers for android.media.AudioManager.getProperty(), see description there for meaning 285 static uint32_t getPrimaryOutputSamplingRate(); 286 static size_t getPrimaryOutputFrameCount(); 287 288 static status_t setLowRamDevice(bool isLowRamDevice); 289 290 // Check if hw offload is possible for given format, stream type, sample rate, 291 // bit rate, duration, video and streaming or offload property is enabled 292 static bool isOffloadSupported(const audio_offload_info_t& info); 293 294 // check presence of audio flinger service. 295 // returns NO_ERROR if binding to service succeeds, DEAD_OBJECT otherwise 296 static status_t checkAudioFlinger(); 297 298 /* List available audio ports and their attributes */ 299 static status_t listAudioPorts(audio_port_role_t role, 300 audio_port_type_t type, 301 unsigned int *num_ports, 302 struct audio_port *ports, 303 unsigned int *generation); 304 305 /* Get attributes for a given audio port */ 306 static status_t getAudioPort(struct audio_port *port); 307 308 /* Create an audio patch between several source and sink ports */ 309 static status_t createAudioPatch(const struct audio_patch *patch, 310 audio_patch_handle_t *handle); 311 312 /* Release an audio patch */ 313 static status_t releaseAudioPatch(audio_patch_handle_t handle); 314 315 /* List existing audio patches */ 316 static status_t listAudioPatches(unsigned int *num_patches, 317 struct audio_patch *patches, 318 unsigned int *generation); 319 /* Set audio port configuration */ 320 static status_t setAudioPortConfig(const struct audio_port_config *config); 321 322 323 static status_t acquireSoundTriggerSession(audio_session_t *session, 324 audio_io_handle_t *ioHandle, 325 audio_devices_t *device); 326 static status_t releaseSoundTriggerSession(audio_session_t session); 327 328 static audio_mode_t getPhoneState(); 329 330 static status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration); 331 332 static status_t startAudioSource(const struct audio_port_config *source, 333 const audio_attributes_t *attributes, 334 audio_patch_handle_t *handle); 335 static status_t stopAudioSource(audio_patch_handle_t handle); 336 337 static status_t setMasterMono(bool mono); 338 static status_t getMasterMono(bool *mono); 339 340 static float getStreamVolumeDB( 341 audio_stream_type_t stream, int index, audio_devices_t device); 342 343 // ---------------------------------------------------------------------------- 344 345 class AudioPortCallback : public RefBase 346 { 347 public: 348 349 AudioPortCallback() {} 350 virtual ~AudioPortCallback() {} 351 352 virtual void onAudioPortListUpdate() = 0; 353 virtual void onAudioPatchListUpdate() = 0; 354 virtual void onServiceDied() = 0; 355 356 }; 357 358 static status_t addAudioPortCallback(const sp<AudioPortCallback>& callback); 359 static status_t removeAudioPortCallback(const sp<AudioPortCallback>& callback); 360 361 class AudioDeviceCallback : public RefBase 362 { 363 public: 364 365 AudioDeviceCallback() {} 366 virtual ~AudioDeviceCallback() {} 367 368 virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo, 369 audio_port_handle_t deviceId) = 0; 370 }; 371 372 static status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 373 audio_io_handle_t audioIo); 374 static status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 375 audio_io_handle_t audioIo); 376 377 static audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo); 378 379private: 380 381 class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient 382 { 383 public: 384 AudioFlingerClient() : 385 mInBuffSize(0), mInSamplingRate(0), 386 mInFormat(AUDIO_FORMAT_DEFAULT), mInChannelMask(AUDIO_CHANNEL_NONE) { 387 } 388 389 void clearIoCache(); 390 status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 391 audio_channel_mask_t channelMask, size_t* buffSize); 392 sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle); 393 394 // DeathRecipient 395 virtual void binderDied(const wp<IBinder>& who); 396 397 // IAudioFlingerClient 398 399 // indicate a change in the configuration of an output or input: keeps the cached 400 // values for output/input parameters up-to-date in client process 401 virtual void ioConfigChanged(audio_io_config_event event, 402 const sp<AudioIoDescriptor>& ioDesc); 403 404 405 status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 406 audio_io_handle_t audioIo); 407 status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 408 audio_io_handle_t audioIo); 409 410 audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo); 411 412 private: 413 Mutex mLock; 414 DefaultKeyedVector<audio_io_handle_t, sp<AudioIoDescriptor> > mIoDescriptors; 415 DefaultKeyedVector<audio_io_handle_t, Vector < wp<AudioDeviceCallback> > > 416 mAudioDeviceCallbacks; 417 // cached values for recording getInputBufferSize() queries 418 size_t mInBuffSize; // zero indicates cache is invalid 419 uint32_t mInSamplingRate; 420 audio_format_t mInFormat; 421 audio_channel_mask_t mInChannelMask; 422 sp<AudioIoDescriptor> getIoDescriptor_l(audio_io_handle_t ioHandle); 423 }; 424 425 class AudioPolicyServiceClient: public IBinder::DeathRecipient, 426 public BnAudioPolicyServiceClient 427 { 428 public: 429 AudioPolicyServiceClient() { 430 } 431 432 int addAudioPortCallback(const sp<AudioPortCallback>& callback); 433 int removeAudioPortCallback(const sp<AudioPortCallback>& callback); 434 435 // DeathRecipient 436 virtual void binderDied(const wp<IBinder>& who); 437 438 // IAudioPolicyServiceClient 439 virtual void onAudioPortListUpdate(); 440 virtual void onAudioPatchListUpdate(); 441 virtual void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state); 442 virtual void onRecordingConfigurationUpdate(int event, 443 const record_client_info_t *clientInfo, 444 const audio_config_base_t *clientConfig, 445 const audio_config_base_t *deviceConfig, audio_patch_handle_t patchHandle); 446 447 private: 448 Mutex mLock; 449 Vector <sp <AudioPortCallback> > mAudioPortCallbacks; 450 }; 451 452 static audio_io_handle_t getOutput(audio_stream_type_t stream); 453 static const sp<AudioFlingerClient> getAudioFlingerClient(); 454 static sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle); 455 456 static sp<AudioFlingerClient> gAudioFlingerClient; 457 static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient; 458 friend class AudioFlingerClient; 459 friend class AudioPolicyServiceClient; 460 461 static Mutex gLock; // protects gAudioFlinger and gAudioErrorCallback, 462 static Mutex gLockAPS; // protects gAudioPolicyService and gAudioPolicyServiceClient 463 static sp<IAudioFlinger> gAudioFlinger; 464 static audio_error_callback gAudioErrorCallback; 465 static dynamic_policy_callback gDynPolicyCallback; 466 static record_config_callback gRecordConfigCallback; 467 468 static size_t gInBuffSize; 469 // previous parameters for recording buffer size queries 470 static uint32_t gPrevInSamplingRate; 471 static audio_format_t gPrevInFormat; 472 static audio_channel_mask_t gPrevInChannelMask; 473 474 static sp<IAudioPolicyService> gAudioPolicyService; 475}; 476 477}; // namespace android 478 479#endif /*ANDROID_AUDIOSYSTEM_H_*/ 480