AudioSystem.h revision fee1976a2849c37a53d8a01ac10327d522a1ba93
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 <media/MicrophoneInfo.h> 27#include <system/audio.h> 28#include <system/audio_effect.h> 29#include <system/audio_policy.h> 30#include <utils/Errors.h> 31#include <utils/Mutex.h> 32#include <vector> 33 34namespace android { 35 36typedef void (*audio_error_callback)(status_t err); 37typedef void (*dynamic_policy_callback)(int event, String8 regId, int val); 38typedef void (*record_config_callback)(int event, const record_client_info_t *clientInfo, 39 const audio_config_base_t *clientConfig, const audio_config_base_t *deviceConfig, 40 audio_patch_handle_t patchHandle); 41 42class IAudioFlinger; 43class IAudioPolicyService; 44class String8; 45 46class AudioSystem 47{ 48public: 49 50 // FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp 51 52 /* These are static methods to control the system-wide AudioFlinger 53 * only privileged processes can have access to them 54 */ 55 56 // mute/unmute microphone 57 static status_t muteMicrophone(bool state); 58 static status_t isMicrophoneMuted(bool *state); 59 60 // set/get master volume 61 static status_t setMasterVolume(float value); 62 static status_t getMasterVolume(float* volume); 63 64 // mute/unmute audio outputs 65 static status_t setMasterMute(bool mute); 66 static status_t getMasterMute(bool* mute); 67 68 // set/get stream volume on specified output 69 static status_t setStreamVolume(audio_stream_type_t stream, float value, 70 audio_io_handle_t output); 71 static status_t getStreamVolume(audio_stream_type_t stream, float* volume, 72 audio_io_handle_t output); 73 74 // mute/unmute stream 75 static status_t setStreamMute(audio_stream_type_t stream, bool mute); 76 static status_t getStreamMute(audio_stream_type_t stream, bool* mute); 77 78 // set audio mode in audio hardware 79 static status_t setMode(audio_mode_t mode); 80 81 // returns true in *state if tracks are active on the specified stream or have been active 82 // in the past inPastMs milliseconds 83 static status_t isStreamActive(audio_stream_type_t stream, bool *state, uint32_t inPastMs); 84 // returns true in *state if tracks are active for what qualifies as remote playback 85 // on the specified stream or have been active in the past inPastMs milliseconds. Remote 86 // playback isn't mutually exclusive with local playback. 87 static status_t isStreamActiveRemotely(audio_stream_type_t stream, bool *state, 88 uint32_t inPastMs); 89 // returns true in *state if a recorder is currently recording with the specified source 90 static status_t isSourceActive(audio_source_t source, bool *state); 91 92 // set/get audio hardware parameters. The function accepts a list of parameters 93 // key value pairs in the form: key1=value1;key2=value2;... 94 // Some keys are reserved for standard parameters (See AudioParameter class). 95 // The versions with audio_io_handle_t are intended for internal media framework use only. 96 static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs); 97 static String8 getParameters(audio_io_handle_t ioHandle, const String8& keys); 98 // The versions without audio_io_handle_t are intended for JNI. 99 static status_t setParameters(const String8& keyValuePairs); 100 static String8 getParameters(const String8& keys); 101 102 static void setErrorCallback(audio_error_callback cb); 103 static void setDynPolicyCallback(dynamic_policy_callback cb); 104 static void setRecordConfigCallback(record_config_callback); 105 106 // helper function to obtain AudioFlinger service handle 107 static const sp<IAudioFlinger> get_audio_flinger(); 108 109 static float linearToLog(int volume); 110 static int logToLinear(float volume); 111 static size_t calculateMinFrameCount( 112 uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate, 113 uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/); 114 115 // Returned samplingRate and frameCount output values are guaranteed 116 // to be non-zero if status == NO_ERROR 117 // FIXME This API assumes a route, and so should be deprecated. 118 static status_t getOutputSamplingRate(uint32_t* samplingRate, 119 audio_stream_type_t stream); 120 // FIXME This API assumes a route, and so should be deprecated. 121 static status_t getOutputFrameCount(size_t* frameCount, 122 audio_stream_type_t stream); 123 // FIXME This API assumes a route, and so should be deprecated. 124 static status_t getOutputLatency(uint32_t* latency, 125 audio_stream_type_t stream); 126 // returns the audio HAL sample rate 127 static status_t getSamplingRate(audio_io_handle_t ioHandle, 128 uint32_t* samplingRate); 129 // For output threads with a fast mixer, returns the number of frames per normal mixer buffer. 130 // For output threads without a fast mixer, or for input, this is same as getFrameCountHAL(). 131 static status_t getFrameCount(audio_io_handle_t ioHandle, 132 size_t* frameCount); 133 // returns the audio output latency in ms. Corresponds to 134 // audio_stream_out->get_latency() 135 static status_t getLatency(audio_io_handle_t output, 136 uint32_t* latency); 137 138 // return status NO_ERROR implies *buffSize > 0 139 // FIXME This API assumes a route, and so should deprecated. 140 static status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 141 audio_channel_mask_t channelMask, size_t* buffSize); 142 143 static status_t setVoiceVolume(float volume); 144 145 // return the number of audio frames written by AudioFlinger to audio HAL and 146 // audio dsp to DAC since the specified output has exited standby. 147 // returned status (from utils/Errors.h) can be: 148 // - NO_ERROR: successful operation, halFrames and dspFrames point to valid data 149 // - INVALID_OPERATION: Not supported on current hardware platform 150 // - BAD_VALUE: invalid parameter 151 // NOTE: this feature is not supported on all hardware platforms and it is 152 // necessary to check returned status before using the returned values. 153 static status_t getRenderPosition(audio_io_handle_t output, 154 uint32_t *halFrames, 155 uint32_t *dspFrames); 156 157 // return the number of input frames lost by HAL implementation, or 0 if the handle is invalid 158 static uint32_t getInputFramesLost(audio_io_handle_t ioHandle); 159 160 // Allocate a new unique ID for use as an audio session ID or I/O handle. 161 // If unable to contact AudioFlinger, returns AUDIO_UNIQUE_ID_ALLOCATE instead. 162 // FIXME If AudioFlinger were to ever exhaust the unique ID namespace, 163 // this method could fail by returning either a reserved ID like AUDIO_UNIQUE_ID_ALLOCATE 164 // or an unspecified existing unique ID. 165 static audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use); 166 167 static void acquireAudioSessionId(audio_session_t audioSession, pid_t pid); 168 static void releaseAudioSessionId(audio_session_t audioSession, pid_t pid); 169 170 // Get the HW synchronization source used for an audio session. 171 // Return a valid source or AUDIO_HW_SYNC_INVALID if an error occurs 172 // or no HW sync source is used. 173 static audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId); 174 175 // Indicate JAVA services are ready (scheduling, power management ...) 176 static status_t systemReady(); 177 178 // Returns the number of frames per audio HAL buffer. 179 // Corresponds to audio_stream->get_buffer_size()/audio_stream_in_frame_size() for input. 180 // See also getFrameCount(). 181 static status_t getFrameCountHAL(audio_io_handle_t ioHandle, 182 size_t* frameCount); 183 184 // Events used to synchronize actions between audio sessions. 185 // For instance SYNC_EVENT_PRESENTATION_COMPLETE can be used to delay recording start until 186 // playback is complete on another audio session. 187 // See definitions in MediaSyncEvent.java 188 enum sync_event_t { 189 SYNC_EVENT_SAME = -1, // used internally to indicate restart with same event 190 SYNC_EVENT_NONE = 0, 191 SYNC_EVENT_PRESENTATION_COMPLETE, 192 193 // 194 // Define new events here: SYNC_EVENT_START, SYNC_EVENT_STOP, SYNC_EVENT_TIME ... 195 // 196 SYNC_EVENT_CNT, 197 }; 198 199 // Timeout for synchronous record start. Prevents from blocking the record thread forever 200 // if the trigger event is not fired. 201 static const uint32_t kSyncRecordStartTimeOutMs = 30000; 202 203 // 204 // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions) 205 // 206 static status_t setDeviceConnectionState(audio_devices_t device, audio_policy_dev_state_t state, 207 const char *device_address, const char *device_name); 208 static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, 209 const char *device_address); 210 static status_t handleDeviceConfigChange(audio_devices_t device, 211 const char *device_address, 212 const char *device_name); 213 static status_t setPhoneState(audio_mode_t state); 214 static status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config); 215 static audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage); 216 217 static status_t getOutputForAttr(const audio_attributes_t *attr, 218 audio_io_handle_t *output, 219 audio_session_t session, 220 audio_stream_type_t *stream, 221 pid_t pid, 222 uid_t uid, 223 const audio_config_t *config, 224 audio_output_flags_t flags, 225 audio_port_handle_t *selectedDeviceId, 226 audio_port_handle_t *portId); 227 static status_t startOutput(audio_io_handle_t output, 228 audio_stream_type_t stream, 229 audio_session_t session); 230 static status_t stopOutput(audio_io_handle_t output, 231 audio_stream_type_t stream, 232 audio_session_t session); 233 static void releaseOutput(audio_io_handle_t output, 234 audio_stream_type_t stream, 235 audio_session_t session); 236 237 // Client must successfully hand off the handle reference to AudioFlinger via createRecord(), 238 // or release it with releaseInput(). 239 static status_t getInputForAttr(const audio_attributes_t *attr, 240 audio_io_handle_t *input, 241 audio_session_t session, 242 pid_t pid, 243 uid_t uid, 244 const String16& opPackageName, 245 const audio_config_base_t *config, 246 audio_input_flags_t flags, 247 audio_port_handle_t *selectedDeviceId, 248 audio_port_handle_t *portId); 249 250 static status_t startInput(audio_port_handle_t portId, 251 bool *silenced); 252 static status_t stopInput(audio_port_handle_t portId); 253 static void releaseInput(audio_port_handle_t portId); 254 static status_t initStreamVolume(audio_stream_type_t stream, 255 int indexMin, 256 int indexMax); 257 static status_t setStreamVolumeIndex(audio_stream_type_t stream, 258 int index, 259 audio_devices_t device); 260 static status_t getStreamVolumeIndex(audio_stream_type_t stream, 261 int *index, 262 audio_devices_t device); 263 264 static uint32_t getStrategyForStream(audio_stream_type_t stream); 265 static audio_devices_t getDevicesForStream(audio_stream_type_t stream); 266 267 static audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc); 268 static status_t registerEffect(const effect_descriptor_t *desc, 269 audio_io_handle_t io, 270 uint32_t strategy, 271 audio_session_t session, 272 int id); 273 static status_t unregisterEffect(int id); 274 static status_t setEffectEnabled(int id, bool enabled); 275 276 // clear stream to output mapping cache (gStreamOutputMap) 277 // and output configuration cache (gOutputs) 278 static void clearAudioConfigCache(); 279 280 static const sp<IAudioPolicyService> get_audio_policy_service(); 281 282 // helpers for android.media.AudioManager.getProperty(), see description there for meaning 283 static uint32_t getPrimaryOutputSamplingRate(); 284 static size_t getPrimaryOutputFrameCount(); 285 286 static status_t setLowRamDevice(bool isLowRamDevice, int64_t totalMemory); 287 288 // Check if hw offload is possible for given format, stream type, sample rate, 289 // bit rate, duration, video and streaming or offload property is enabled 290 static bool isOffloadSupported(const audio_offload_info_t& info); 291 292 // check presence of audio flinger service. 293 // returns NO_ERROR if binding to service succeeds, DEAD_OBJECT otherwise 294 static status_t checkAudioFlinger(); 295 296 /* List available audio ports and their attributes */ 297 static status_t listAudioPorts(audio_port_role_t role, 298 audio_port_type_t type, 299 unsigned int *num_ports, 300 struct audio_port *ports, 301 unsigned int *generation); 302 303 /* Get attributes for a given audio port */ 304 static status_t getAudioPort(struct audio_port *port); 305 306 /* Create an audio patch between several source and sink ports */ 307 static status_t createAudioPatch(const struct audio_patch *patch, 308 audio_patch_handle_t *handle); 309 310 /* Release an audio patch */ 311 static status_t releaseAudioPatch(audio_patch_handle_t handle); 312 313 /* List existing audio patches */ 314 static status_t listAudioPatches(unsigned int *num_patches, 315 struct audio_patch *patches, 316 unsigned int *generation); 317 /* Set audio port configuration */ 318 static status_t setAudioPortConfig(const struct audio_port_config *config); 319 320 321 static status_t acquireSoundTriggerSession(audio_session_t *session, 322 audio_io_handle_t *ioHandle, 323 audio_devices_t *device); 324 static status_t releaseSoundTriggerSession(audio_session_t session); 325 326 static audio_mode_t getPhoneState(); 327 328 static status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration); 329 330 static status_t startAudioSource(const struct audio_port_config *source, 331 const audio_attributes_t *attributes, 332 audio_patch_handle_t *handle); 333 static status_t stopAudioSource(audio_patch_handle_t handle); 334 335 static status_t setMasterMono(bool mono); 336 static status_t getMasterMono(bool *mono); 337 338 static float getStreamVolumeDB( 339 audio_stream_type_t stream, int index, audio_devices_t device); 340 341 static status_t getMicrophones(std::vector<media::MicrophoneInfo> *microphones); 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