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 34 namespace android { 35 36 typedef void (*audio_error_callback)(status_t err); 37 typedef void (*dynamic_policy_callback)(int event, String8 regId, int val); 38 typedef 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 42 class IAudioFlinger; 43 class IAudioPolicyService; 44 class String8; 45 46 class AudioSystem 47 { 48 public: 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 // numSurroundFormats holds the maximum number of formats and bool value allowed in the array. 344 // When numSurroundFormats is 0, surroundFormats and surroundFormatsEnabled will not be 345 // populated. The actual number of surround formats should be returned at numSurroundFormats. 346 static status_t getSurroundFormats(unsigned int *numSurroundFormats, 347 audio_format_t *surroundFormats, 348 bool *surroundFormatsEnabled, 349 bool reported); 350 static status_t setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled); 351 352 // ---------------------------------------------------------------------------- 353 354 class AudioPortCallback : public RefBase 355 { 356 public: 357 358 AudioPortCallback() {} 359 virtual ~AudioPortCallback() {} 360 361 virtual void onAudioPortListUpdate() = 0; 362 virtual void onAudioPatchListUpdate() = 0; 363 virtual void onServiceDied() = 0; 364 365 }; 366 367 static status_t addAudioPortCallback(const sp<AudioPortCallback>& callback); 368 static status_t removeAudioPortCallback(const sp<AudioPortCallback>& callback); 369 370 class AudioDeviceCallback : public RefBase 371 { 372 public: 373 374 AudioDeviceCallback() {} 375 virtual ~AudioDeviceCallback() {} 376 377 virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo, 378 audio_port_handle_t deviceId) = 0; 379 }; 380 381 static status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 382 audio_io_handle_t audioIo); 383 static status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 384 audio_io_handle_t audioIo); 385 386 static audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo); 387 388 private: 389 390 class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient 391 { 392 public: 393 AudioFlingerClient() : 394 mInBuffSize(0), mInSamplingRate(0), 395 mInFormat(AUDIO_FORMAT_DEFAULT), mInChannelMask(AUDIO_CHANNEL_NONE) { 396 } 397 398 void clearIoCache(); 399 status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 400 audio_channel_mask_t channelMask, size_t* buffSize); 401 sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle); 402 403 // DeathRecipient 404 virtual void binderDied(const wp<IBinder>& who); 405 406 // IAudioFlingerClient 407 408 // indicate a change in the configuration of an output or input: keeps the cached 409 // values for output/input parameters up-to-date in client process 410 virtual void ioConfigChanged(audio_io_config_event event, 411 const sp<AudioIoDescriptor>& ioDesc); 412 413 414 status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 415 audio_io_handle_t audioIo); 416 status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 417 audio_io_handle_t audioIo); 418 419 audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo); 420 421 private: 422 Mutex mLock; 423 DefaultKeyedVector<audio_io_handle_t, sp<AudioIoDescriptor> > mIoDescriptors; 424 DefaultKeyedVector<audio_io_handle_t, Vector < wp<AudioDeviceCallback> > > 425 mAudioDeviceCallbacks; 426 // cached values for recording getInputBufferSize() queries 427 size_t mInBuffSize; // zero indicates cache is invalid 428 uint32_t mInSamplingRate; 429 audio_format_t mInFormat; 430 audio_channel_mask_t mInChannelMask; 431 sp<AudioIoDescriptor> getIoDescriptor_l(audio_io_handle_t ioHandle); 432 }; 433 434 class AudioPolicyServiceClient: public IBinder::DeathRecipient, 435 public BnAudioPolicyServiceClient 436 { 437 public: 438 AudioPolicyServiceClient() { 439 } 440 441 int addAudioPortCallback(const sp<AudioPortCallback>& callback); 442 int removeAudioPortCallback(const sp<AudioPortCallback>& callback); 443 bool isAudioPortCbEnabled() const { return (mAudioPortCallbacks.size() != 0); } 444 445 // DeathRecipient 446 virtual void binderDied(const wp<IBinder>& who); 447 448 // IAudioPolicyServiceClient 449 virtual void onAudioPortListUpdate(); 450 virtual void onAudioPatchListUpdate(); 451 virtual void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state); 452 virtual void onRecordingConfigurationUpdate(int event, 453 const record_client_info_t *clientInfo, 454 const audio_config_base_t *clientConfig, 455 const audio_config_base_t *deviceConfig, audio_patch_handle_t patchHandle); 456 457 private: 458 Mutex mLock; 459 Vector <sp <AudioPortCallback> > mAudioPortCallbacks; 460 }; 461 462 static audio_io_handle_t getOutput(audio_stream_type_t stream); 463 static const sp<AudioFlingerClient> getAudioFlingerClient(); 464 static sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle); 465 466 static sp<AudioFlingerClient> gAudioFlingerClient; 467 static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient; 468 friend class AudioFlingerClient; 469 friend class AudioPolicyServiceClient; 470 471 static Mutex gLock; // protects gAudioFlinger and gAudioErrorCallback, 472 static Mutex gLockAPS; // protects gAudioPolicyService and gAudioPolicyServiceClient 473 static sp<IAudioFlinger> gAudioFlinger; 474 static audio_error_callback gAudioErrorCallback; 475 static dynamic_policy_callback gDynPolicyCallback; 476 static record_config_callback gRecordConfigCallback; 477 478 static size_t gInBuffSize; 479 // previous parameters for recording buffer size queries 480 static uint32_t gPrevInSamplingRate; 481 static audio_format_t gPrevInFormat; 482 static audio_channel_mask_t gPrevInChannelMask; 483 484 static sp<IAudioPolicyService> gAudioPolicyService; 485 }; 486 487 }; // namespace android 488 489 #endif /*ANDROID_AUDIOSYSTEM_H_*/ 490