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 <set> 23 #include <vector> 24 25 #include <android/content/AttributionSourceState.h> 26 #include <android/media/AudioPolicyConfig.h> 27 #include <android/media/AudioPortFw.h> 28 #include <android/media/AudioVibratorInfo.h> 29 #include <android/media/BnAudioFlingerClient.h> 30 #include <android/media/BnAudioPolicyServiceClient.h> 31 #include <android/media/EffectDescriptor.h> 32 #include <android/media/INativeSpatializerCallback.h> 33 #include <android/media/ISoundDose.h> 34 #include <android/media/ISoundDoseCallback.h> 35 #include <android/media/ISpatializer.h> 36 #include <android/media/MicrophoneInfoFw.h> 37 #include <android/media/RecordClientInfo.h> 38 #include <android/media/audio/common/AudioConfigBase.h> 39 #include <android/media/audio/common/AudioMMapPolicyInfo.h> 40 #include <android/media/audio/common/AudioMMapPolicyType.h> 41 #include <android/media/audio/common/AudioPort.h> 42 #include <media/AidlConversionUtil.h> 43 #include <media/AudioContainers.h> 44 #include <media/AudioDeviceTypeAddr.h> 45 #include <media/AudioPolicy.h> 46 #include <media/AudioProductStrategy.h> 47 #include <media/AudioVolumeGroup.h> 48 #include <media/AudioIoDescriptor.h> 49 #include <system/audio.h> 50 #include <system/audio_effect.h> 51 #include <system/audio_policy.h> 52 #include <utils/Errors.h> 53 #include <utils/Mutex.h> 54 55 using android::content::AttributionSourceState; 56 57 namespace android { 58 59 struct record_client_info { 60 audio_unique_id_t riid; 61 uid_t uid; 62 audio_session_t session; 63 audio_source_t source; 64 audio_port_handle_t port_id; 65 bool silenced; 66 }; 67 68 typedef struct record_client_info record_client_info_t; 69 70 // AIDL conversion functions. 71 ConversionResult<record_client_info_t> 72 aidl2legacy_RecordClientInfo_record_client_info_t(const media::RecordClientInfo& aidl); 73 ConversionResult<media::RecordClientInfo> 74 legacy2aidl_record_client_info_t_RecordClientInfo(const record_client_info_t& legacy); 75 76 typedef void (*audio_error_callback)(status_t err); 77 typedef void (*dynamic_policy_callback)(int event, String8 regId, int val); 78 typedef void (*record_config_callback)(int event, 79 const record_client_info_t *clientInfo, 80 const audio_config_base_t *clientConfig, 81 std::vector<effect_descriptor_t> clientEffects, 82 const audio_config_base_t *deviceConfig, 83 std::vector<effect_descriptor_t> effects, 84 audio_patch_handle_t patchHandle, 85 audio_source_t source); 86 typedef void (*routing_callback)(); 87 typedef void (*vol_range_init_req_callback)(); 88 89 class IAudioFlinger; 90 class String8; 91 92 namespace media { 93 class IAudioPolicyService; 94 } 95 96 class AudioSystem 97 { 98 public: 99 100 // FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp 101 102 /* These are static methods to control the system-wide AudioFlinger 103 * only privileged processes can have access to them 104 */ 105 106 // mute/unmute microphone 107 static status_t muteMicrophone(bool state); 108 static status_t isMicrophoneMuted(bool *state); 109 110 // set/get master volume 111 static status_t setMasterVolume(float value); 112 static status_t getMasterVolume(float* volume); 113 114 // mute/unmute audio outputs 115 static status_t setMasterMute(bool mute); 116 static status_t getMasterMute(bool* mute); 117 118 // set/get stream volume on specified output 119 static status_t setStreamVolume(audio_stream_type_t stream, float value, 120 audio_io_handle_t output); 121 static status_t getStreamVolume(audio_stream_type_t stream, float* volume, 122 audio_io_handle_t output); 123 124 // mute/unmute stream 125 static status_t setStreamMute(audio_stream_type_t stream, bool mute); 126 static status_t getStreamMute(audio_stream_type_t stream, bool* mute); 127 128 // set audio mode in audio hardware 129 static status_t setMode(audio_mode_t mode); 130 131 // test API: switch HALs into the mode which simulates external device connections 132 static status_t setSimulateDeviceConnections(bool enabled); 133 134 // returns true in *state if tracks are active on the specified stream or have been active 135 // in the past inPastMs milliseconds 136 static status_t isStreamActive(audio_stream_type_t stream, bool *state, uint32_t inPastMs); 137 // returns true in *state if tracks are active for what qualifies as remote playback 138 // on the specified stream or have been active in the past inPastMs milliseconds. Remote 139 // playback isn't mutually exclusive with local playback. 140 static status_t isStreamActiveRemotely(audio_stream_type_t stream, bool *state, 141 uint32_t inPastMs); 142 // returns true in *state if a recorder is currently recording with the specified source 143 static status_t isSourceActive(audio_source_t source, bool *state); 144 145 // set/get audio hardware parameters. The function accepts a list of parameters 146 // key value pairs in the form: key1=value1;key2=value2;... 147 // Some keys are reserved for standard parameters (See AudioParameter class). 148 // The versions with audio_io_handle_t are intended for internal media framework use only. 149 static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs); 150 static String8 getParameters(audio_io_handle_t ioHandle, const String8& keys); 151 // The versions without audio_io_handle_t are intended for JNI. 152 static status_t setParameters(const String8& keyValuePairs); 153 static String8 getParameters(const String8& keys); 154 155 // Registers an error callback. When this callback is invoked, it means all 156 // state implied by this interface has been reset. 157 // Returns a token that can be used for un-registering. 158 // Might block while callbacks are being invoked. 159 static uintptr_t addErrorCallback(audio_error_callback cb); 160 161 // Un-registers a callback previously added with addErrorCallback. 162 // Might block while callbacks are being invoked. 163 static void removeErrorCallback(uintptr_t cb); 164 165 static void setDynPolicyCallback(dynamic_policy_callback cb); 166 static void setRecordConfigCallback(record_config_callback); 167 static void setRoutingCallback(routing_callback cb); 168 static void setVolInitReqCallback(vol_range_init_req_callback cb); 169 170 // Sets the binder to use for accessing the AudioFlinger service. This enables the system server 171 // to grant specific isolated processes access to the audio system. Currently used only for the 172 // HotwordDetectionService. 173 static void setAudioFlingerBinder(const sp<IBinder>& audioFlinger); 174 175 // Sets a local AudioFlinger interface to be used by AudioSystem. 176 // This is used by audioserver main() to avoid binder AIDL translation. 177 static status_t setLocalAudioFlinger(const sp<IAudioFlinger>& af); 178 179 // helper function to obtain AudioFlinger service handle 180 static const sp<IAudioFlinger> get_audio_flinger(); 181 182 static float linearToLog(int volume); 183 static int logToLinear(float volume); 184 static size_t calculateMinFrameCount( 185 uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate, 186 uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/); 187 188 // Returned samplingRate and frameCount output values are guaranteed 189 // to be non-zero if status == NO_ERROR 190 // FIXME This API assumes a route, and so should be deprecated. 191 static status_t getOutputSamplingRate(uint32_t* samplingRate, 192 audio_stream_type_t stream); 193 // FIXME This API assumes a route, and so should be deprecated. 194 static status_t getOutputFrameCount(size_t* frameCount, 195 audio_stream_type_t stream); 196 // FIXME This API assumes a route, and so should be deprecated. 197 static status_t getOutputLatency(uint32_t* latency, 198 audio_stream_type_t stream); 199 // returns the audio HAL sample rate 200 static status_t getSamplingRate(audio_io_handle_t ioHandle, 201 uint32_t* samplingRate); 202 // For output threads with a fast mixer, returns the number of frames per normal mixer buffer. 203 // For output threads without a fast mixer, or for input, this is same as getFrameCountHAL(). 204 static status_t getFrameCount(audio_io_handle_t ioHandle, 205 size_t* frameCount); 206 // returns the audio output latency in ms. Corresponds to 207 // audio_stream_out->get_latency() 208 static status_t getLatency(audio_io_handle_t output, 209 uint32_t* latency); 210 211 // return status NO_ERROR implies *buffSize > 0 212 // FIXME This API assumes a route, and so should deprecated. 213 static status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 214 audio_channel_mask_t channelMask, size_t* buffSize); 215 216 static status_t setVoiceVolume(float volume); 217 218 // return the number of audio frames written by AudioFlinger to audio HAL and 219 // audio dsp to DAC since the specified output has exited standby. 220 // returned status (from utils/Errors.h) can be: 221 // - NO_ERROR: successful operation, halFrames and dspFrames point to valid data 222 // - INVALID_OPERATION: Not supported on current hardware platform 223 // - BAD_VALUE: invalid parameter 224 // NOTE: this feature is not supported on all hardware platforms and it is 225 // necessary to check returned status before using the returned values. 226 static status_t getRenderPosition(audio_io_handle_t output, 227 uint32_t *halFrames, 228 uint32_t *dspFrames); 229 230 // return the number of input frames lost by HAL implementation, or 0 if the handle is invalid 231 static uint32_t getInputFramesLost(audio_io_handle_t ioHandle); 232 233 // Allocate a new unique ID for use as an audio session ID or I/O handle. 234 // If unable to contact AudioFlinger, returns AUDIO_UNIQUE_ID_ALLOCATE instead. 235 // FIXME If AudioFlinger were to ever exhaust the unique ID namespace, 236 // this method could fail by returning either a reserved ID like AUDIO_UNIQUE_ID_ALLOCATE 237 // or an unspecified existing unique ID. 238 static audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use); 239 240 static void acquireAudioSessionId(audio_session_t audioSession, pid_t pid, uid_t uid); 241 static void releaseAudioSessionId(audio_session_t audioSession, pid_t pid); 242 243 // Get the HW synchronization source used for an audio session. 244 // Return a valid source or AUDIO_HW_SYNC_INVALID if an error occurs 245 // or no HW sync source is used. 246 static audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId); 247 248 // Indicate JAVA services are ready (scheduling, power management ...) 249 static status_t systemReady(); 250 251 // Indicate audio policy service is ready 252 static status_t audioPolicyReady(); 253 254 // Returns the number of frames per audio HAL buffer. 255 // Corresponds to audio_stream->get_buffer_size()/audio_stream_in_frame_size() for input. 256 // See also getFrameCount(). 257 static status_t getFrameCountHAL(audio_io_handle_t ioHandle, 258 size_t* frameCount); 259 260 // Events used to synchronize actions between audio sessions. 261 // For instance SYNC_EVENT_PRESENTATION_COMPLETE can be used to delay recording start until 262 // playback is complete on another audio session. 263 // See definitions in MediaSyncEvent.java 264 enum sync_event_t { 265 SYNC_EVENT_SAME = -1, // used internally to indicate restart with same event 266 SYNC_EVENT_NONE = 0, 267 SYNC_EVENT_PRESENTATION_COMPLETE, 268 269 // 270 // Define new events here: SYNC_EVENT_START, SYNC_EVENT_STOP, SYNC_EVENT_TIME ... 271 // 272 SYNC_EVENT_CNT, 273 }; 274 275 // Timeout for synchronous record start. Prevents from blocking the record thread forever 276 // if the trigger event is not fired. 277 static const uint32_t kSyncRecordStartTimeOutMs = 30000; 278 279 // 280 // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions) 281 // 282 static void onNewAudioModulesAvailable(); 283 static status_t setDeviceConnectionState(audio_policy_dev_state_t state, 284 const android::media::audio::common::AudioPort& port, 285 audio_format_t encodedFormat); 286 static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, 287 const char *device_address); 288 static status_t handleDeviceConfigChange(audio_devices_t device, 289 const char *device_address, 290 const char *device_name, 291 audio_format_t encodedFormat); 292 static status_t setPhoneState(audio_mode_t state, uid_t uid); 293 static status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config); 294 static audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage); 295 296 /** 297 * Get output stream for given parameters. 298 * 299 * @param[in] attr the requested audio attributes 300 * @param[in|out] output the io handle of the output for the playback. It is specified when 301 * starting mmap thread. 302 * @param[in] session the session id for the client 303 * @param[in|out] stream the stream type used for the playback 304 * @param[in] attributionSource a source to which access to permission protected data 305 * @param[in|out] config the requested configuration client, the suggested configuration will 306 * be returned if no proper output is found for requested configuration 307 * @param[in] flags the requested output flag from client 308 * @param[in|out] selectedDeviceId the requested device id for playback, the actual device id 309 * for playback will be returned 310 * @param[out] portId the generated port id to identify the client 311 * @param[out] secondaryOutputs collection of io handle for secondary outputs 312 * @param[out] isSpatialized true if the playback will be spatialized 313 * @param[out] isBitPerfect true if the playback will be bit-perfect 314 * @return if the call is successful or not 315 */ 316 static status_t getOutputForAttr(audio_attributes_t *attr, 317 audio_io_handle_t *output, 318 audio_session_t session, 319 audio_stream_type_t *stream, 320 const AttributionSourceState& attributionSource, 321 audio_config_t *config, 322 audio_output_flags_t flags, 323 audio_port_handle_t *selectedDeviceId, 324 audio_port_handle_t *portId, 325 std::vector<audio_io_handle_t> *secondaryOutputs, 326 bool *isSpatialized, 327 bool *isBitPerfect); 328 static status_t startOutput(audio_port_handle_t portId); 329 static status_t stopOutput(audio_port_handle_t portId); 330 static void releaseOutput(audio_port_handle_t portId); 331 332 /** 333 * Get input stream for given parameters. 334 * Client must successfully hand off the handle reference to AudioFlinger via createRecord(), 335 * or release it with releaseInput(). 336 * 337 * @param[in] attr the requested audio attributes 338 * @param[in|out] input the io handle of the input for the capture. It is specified when 339 * starting mmap thread. 340 * @param[in] riid an unique id to identify the record client 341 * @param[in] session the session id for the client 342 * @param[in] attributionSource a source to which access to permission protected data 343 * @param[in|out] config the requested configuration client, the suggested configuration will 344 * be returned if no proper input is found for requested configuration 345 * @param[in] flags the requested input flag from client 346 * @param[in|out] selectedDeviceId the requested device id for playback, the actual device id 347 * for playback will be returned 348 * @param[out] portId the generated port id to identify the client 349 * @return if the call is successful or not 350 */ 351 static status_t getInputForAttr(const audio_attributes_t *attr, 352 audio_io_handle_t *input, 353 audio_unique_id_t riid, 354 audio_session_t session, 355 const AttributionSourceState& attributionSource, 356 audio_config_base_t *config, 357 audio_input_flags_t flags, 358 audio_port_handle_t *selectedDeviceId, 359 audio_port_handle_t *portId); 360 361 static status_t startInput(audio_port_handle_t portId); 362 static status_t stopInput(audio_port_handle_t portId); 363 static void releaseInput(audio_port_handle_t portId); 364 static status_t initStreamVolume(audio_stream_type_t stream, 365 int indexMin, 366 int indexMax); 367 static status_t setStreamVolumeIndex(audio_stream_type_t stream, 368 int index, 369 audio_devices_t device); 370 static status_t getStreamVolumeIndex(audio_stream_type_t stream, 371 int *index, 372 audio_devices_t device); 373 374 static status_t setVolumeIndexForAttributes(const audio_attributes_t &attr, 375 int index, 376 audio_devices_t device); 377 static status_t getVolumeIndexForAttributes(const audio_attributes_t &attr, 378 int &index, 379 audio_devices_t device); 380 381 static status_t getMaxVolumeIndexForAttributes(const audio_attributes_t &attr, int &index); 382 383 static status_t getMinVolumeIndexForAttributes(const audio_attributes_t &attr, int &index); 384 385 static product_strategy_t getStrategyForStream(audio_stream_type_t stream); 386 static status_t getDevicesForAttributes(const audio_attributes_t &aa, 387 AudioDeviceTypeAddrVector *devices, 388 bool forVolume); 389 390 static audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc); 391 static status_t registerEffect(const effect_descriptor_t *desc, 392 audio_io_handle_t io, 393 product_strategy_t strategy, 394 audio_session_t session, 395 int id); 396 static status_t unregisterEffect(int id); 397 static status_t setEffectEnabled(int id, bool enabled); 398 static status_t moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io); 399 400 // clear stream to output mapping cache (gStreamOutputMap) 401 // and output configuration cache (gOutputs) 402 static void clearAudioConfigCache(); 403 404 static const sp<media::IAudioPolicyService> get_audio_policy_service(); 405 static void clearAudioPolicyService(); 406 407 // helpers for android.media.AudioManager.getProperty(), see description there for meaning 408 static uint32_t getPrimaryOutputSamplingRate(); 409 static size_t getPrimaryOutputFrameCount(); 410 411 static status_t setLowRamDevice(bool isLowRamDevice, int64_t totalMemory); 412 413 static status_t setSupportedSystemUsages(const std::vector<audio_usage_t>& systemUsages); 414 415 static status_t setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy); 416 417 // Indicate if hw offload is possible for given format, stream type, sample rate, 418 // bit rate, duration, video and streaming or offload property is enabled and when possible 419 // if gapless transitions are supported. 420 static audio_offload_mode_t getOffloadSupport(const audio_offload_info_t& info); 421 422 // check presence of audio flinger service. 423 // returns NO_ERROR if binding to service succeeds, DEAD_OBJECT otherwise 424 static status_t checkAudioFlinger(); 425 426 /* List available audio ports and their attributes */ 427 static status_t listAudioPorts(audio_port_role_t role, 428 audio_port_type_t type, 429 unsigned int *num_ports, 430 struct audio_port_v7 *ports, 431 unsigned int *generation); 432 433 static status_t listDeclaredDevicePorts(media::AudioPortRole role, 434 std::vector<media::AudioPortFw>* result); 435 436 /* Get attributes for a given audio port. On input, the port 437 * only needs the 'id' field to be filled in. */ 438 static status_t getAudioPort(struct audio_port_v7 *port); 439 440 /* Create an audio patch between several source and sink ports */ 441 static status_t createAudioPatch(const struct audio_patch *patch, 442 audio_patch_handle_t *handle); 443 444 /* Release an audio patch */ 445 static status_t releaseAudioPatch(audio_patch_handle_t handle); 446 447 /* List existing audio patches */ 448 static status_t listAudioPatches(unsigned int *num_patches, 449 struct audio_patch *patches, 450 unsigned int *generation); 451 /* Set audio port configuration */ 452 static status_t setAudioPortConfig(const struct audio_port_config *config); 453 454 455 static status_t acquireSoundTriggerSession(audio_session_t *session, 456 audio_io_handle_t *ioHandle, 457 audio_devices_t *device); 458 static status_t releaseSoundTriggerSession(audio_session_t session); 459 460 static audio_mode_t getPhoneState(); 461 462 static status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration); 463 464 static status_t setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices); 465 466 static status_t removeUidDeviceAffinities(uid_t uid); 467 468 static status_t setUserIdDeviceAffinities(int userId, const AudioDeviceTypeAddrVector& devices); 469 470 static status_t removeUserIdDeviceAffinities(int userId); 471 472 static status_t startAudioSource(const struct audio_port_config *source, 473 const audio_attributes_t *attributes, 474 audio_port_handle_t *portId); 475 static status_t stopAudioSource(audio_port_handle_t portId); 476 477 static status_t setMasterMono(bool mono); 478 static status_t getMasterMono(bool *mono); 479 480 static status_t setMasterBalance(float balance); 481 static status_t getMasterBalance(float *balance); 482 483 static float getStreamVolumeDB( 484 audio_stream_type_t stream, int index, audio_devices_t device); 485 486 static status_t getMicrophones(std::vector<media::MicrophoneInfoFw> *microphones); 487 488 static status_t getHwOffloadFormatsSupportedForBluetoothMedia( 489 audio_devices_t device, std::vector<audio_format_t> *formats); 490 491 // numSurroundFormats holds the maximum number of formats and bool value allowed in the array. 492 // When numSurroundFormats is 0, surroundFormats and surroundFormatsEnabled will not be 493 // populated. The actual number of surround formats should be returned at numSurroundFormats. 494 static status_t getSurroundFormats(unsigned int *numSurroundFormats, 495 audio_format_t *surroundFormats, 496 bool *surroundFormatsEnabled); 497 static status_t getReportedSurroundFormats(unsigned int *numSurroundFormats, 498 audio_format_t *surroundFormats); 499 static status_t setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled); 500 501 static status_t setAssistantServicesUids(const std::vector<uid_t>& uids); 502 static status_t setActiveAssistantServicesUids(const std::vector<uid_t>& activeUids); 503 504 static status_t setA11yServicesUids(const std::vector<uid_t>& uids); 505 static status_t setCurrentImeUid(uid_t uid); 506 507 static bool isHapticPlaybackSupported(); 508 509 static bool isUltrasoundSupported(); 510 511 static status_t listAudioProductStrategies(AudioProductStrategyVector &strategies); 512 static status_t getProductStrategyFromAudioAttributes( 513 const audio_attributes_t &aa, product_strategy_t &productStrategy, 514 bool fallbackOnDefault = true); 515 516 static audio_attributes_t streamTypeToAttributes(audio_stream_type_t stream); 517 static audio_stream_type_t attributesToStreamType(const audio_attributes_t &attr); 518 519 static status_t listAudioVolumeGroups(AudioVolumeGroupVector &groups); 520 521 static status_t getVolumeGroupFromAudioAttributes( 522 const audio_attributes_t &aa, volume_group_t &volumeGroup, 523 bool fallbackOnDefault = true); 524 525 static status_t setRttEnabled(bool enabled); 526 527 static bool isCallScreenModeSupported(); 528 529 /** 530 * Send audio HAL server process pids to native audioserver process for use 531 * when generating audio HAL servers tombstones 532 */ 533 static status_t setAudioHalPids(const std::vector<pid_t>& pids); 534 535 static status_t setDevicesRoleForStrategy(product_strategy_t strategy, 536 device_role_t role, const AudioDeviceTypeAddrVector &devices); 537 538 static status_t removeDevicesRoleForStrategy(product_strategy_t strategy, 539 device_role_t role, const AudioDeviceTypeAddrVector &devices); 540 541 static status_t clearDevicesRoleForStrategy(product_strategy_t strategy, 542 device_role_t role); 543 544 static status_t getDevicesForRoleAndStrategy(product_strategy_t strategy, 545 device_role_t role, AudioDeviceTypeAddrVector &devices); 546 547 static status_t setDevicesRoleForCapturePreset(audio_source_t audioSource, 548 device_role_t role, const AudioDeviceTypeAddrVector &devices); 549 550 static status_t addDevicesRoleForCapturePreset(audio_source_t audioSource, 551 device_role_t role, const AudioDeviceTypeAddrVector &devices); 552 553 static status_t removeDevicesRoleForCapturePreset( 554 audio_source_t audioSource, device_role_t role, 555 const AudioDeviceTypeAddrVector& devices); 556 557 static status_t clearDevicesRoleForCapturePreset( 558 audio_source_t audioSource, device_role_t role); 559 560 static status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource, 561 device_role_t role, AudioDeviceTypeAddrVector &devices); 562 563 static status_t getDeviceForStrategy(product_strategy_t strategy, 564 AudioDeviceTypeAddr &device); 565 566 567 /** 568 * If a spatializer stage effect is present on the platform, this will return an 569 * ISpatializer interface to control this feature. 570 * If no spatializer stage is present, a null interface is returned. 571 * The INativeSpatializerCallback passed must not be null. 572 * Only one ISpatializer interface can exist at a given time. The native audio policy 573 * service will reject the request if an interface was already acquired and previous owner 574 * did not die or call ISpatializer.release(). 575 * @param callback in: the callback to receive state updates if the ISpatializer 576 * interface is acquired. 577 * @param spatializer out: the ISpatializer interface made available to control the 578 * platform spatializer 579 * @return NO_ERROR in case of success, DEAD_OBJECT, NO_INIT, PERMISSION_DENIED, BAD_VALUE 580 * in case of error. 581 */ 582 static status_t getSpatializer(const sp<media::INativeSpatializerCallback>& callback, 583 sp<media::ISpatializer>* spatializer); 584 585 /** 586 * Queries if some kind of spatialization will be performed if the audio playback context 587 * described by the provided arguments is present. 588 * The context is made of: 589 * - The audio attributes describing the playback use case. 590 * - The audio configuration describing the audio format, channels, sampling rate ... 591 * - The devices describing the sink audio device selected for playback. 592 * All arguments are optional and only the specified arguments are used to match against 593 * supported criteria. For instance, supplying no argument will tell if spatialization is 594 * supported or not in general. 595 * @param attr audio attributes describing the playback use case 596 * @param config audio configuration describing the audio format, channels, sampling rate... 597 * @param devices the sink audio device selected for playback 598 * @param canBeSpatialized out: true if spatialization is enabled for this context, 599 * false otherwise 600 * @return NO_ERROR in case of success, DEAD_OBJECT, NO_INIT, BAD_VALUE 601 * in case of error. 602 */ 603 static status_t canBeSpatialized(const audio_attributes_t *attr, 604 const audio_config_t *config, 605 const AudioDeviceTypeAddrVector &devices, 606 bool *canBeSpatialized); 607 608 /** 609 * Registers the sound dose callback with the audio server and returns the ISoundDose 610 * interface. 611 * 612 * \param callback to send messages to the audio server 613 * \param soundDose binder to send messages to the AudioService 614 **/ 615 static status_t getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback, 616 sp<media::ISoundDose>* soundDose); 617 618 /** 619 * Query how the direct playback is currently supported on the device. 620 * @param attr audio attributes describing the playback use case 621 * @param config audio configuration for the playback 622 * @param directMode out: a set of flags describing how the direct playback is currently 623 * supported on the device 624 * @return NO_ERROR in case of success, DEAD_OBJECT, NO_INIT, BAD_VALUE, PERMISSION_DENIED 625 * in case of error. 626 */ 627 static status_t getDirectPlaybackSupport(const audio_attributes_t *attr, 628 const audio_config_t *config, 629 audio_direct_mode_t *directMode); 630 631 632 /** 633 * Query which direct audio profiles are available for the specified audio attributes. 634 * @param attr audio attributes describing the playback use case 635 * @param audioProfiles out: a vector of audio profiles 636 * @return NO_ERROR in case of success, DEAD_OBJECT, NO_INIT, BAD_VALUE, PERMISSION_DENIED 637 * in case of error. 638 */ 639 static status_t getDirectProfilesForAttributes(const audio_attributes_t* attr, 640 std::vector<audio_profile>* audioProfiles); 641 642 static status_t setRequestedLatencyMode( 643 audio_io_handle_t output, audio_latency_mode_t mode); 644 645 static status_t getSupportedLatencyModes(audio_io_handle_t output, 646 std::vector<audio_latency_mode_t>* modes); 647 648 static status_t setBluetoothVariableLatencyEnabled(bool enabled); 649 650 static status_t isBluetoothVariableLatencyEnabled(bool *enabled); 651 652 static status_t supportsBluetoothVariableLatency(bool *support); 653 654 static status_t getSupportedMixerAttributes(audio_port_handle_t portId, 655 std::vector<audio_mixer_attributes_t> *mixerAttrs); 656 static status_t setPreferredMixerAttributes(const audio_attributes_t *attr, 657 audio_port_handle_t portId, 658 uid_t uid, 659 const audio_mixer_attributes_t *mixerAttr); 660 static status_t getPreferredMixerAttributes(const audio_attributes_t* attr, 661 audio_port_handle_t portId, 662 std::optional<audio_mixer_attributes_t>* mixerAttr); 663 static status_t clearPreferredMixerAttributes(const audio_attributes_t* attr, 664 audio_port_handle_t portId, 665 uid_t uid); 666 667 static status_t getAudioPolicyConfig(media::AudioPolicyConfig *config); 668 669 // A listener for capture state changes. 670 class CaptureStateListener : public virtual RefBase { 671 public: 672 // Called whenever capture state changes. 673 virtual void onStateChanged(bool active) = 0; 674 // Called whenever the service dies (and hence our listener is no longer 675 // registered). 676 virtual void onServiceDied() = 0; 677 678 virtual ~CaptureStateListener() = default; 679 }; 680 681 // Registers a listener for sound trigger capture state changes. 682 // There may only be one such listener registered at any point. 683 // The listener onStateChanged() method will be invoked synchronously from 684 // this call with the initial value. 685 // The listener onServiceDied() method will be invoked synchronously from 686 // this call if initial attempt to register failed. 687 // If the audio policy service cannot be reached, this method will return 688 // PERMISSION_DENIED and will not invoke the callback, otherwise, it will 689 // return NO_ERROR. 690 static status_t registerSoundTriggerCaptureStateListener( 691 const sp<CaptureStateListener>& listener); 692 693 // ---------------------------------------------------------------------------- 694 695 class AudioVolumeGroupCallback : public virtual RefBase 696 { 697 public: 698 AudioVolumeGroupCallback()699 AudioVolumeGroupCallback() {} ~AudioVolumeGroupCallback()700 virtual ~AudioVolumeGroupCallback() {} 701 702 virtual void onAudioVolumeGroupChanged(volume_group_t group, int flags) = 0; 703 virtual void onServiceDied() = 0; 704 705 }; 706 707 static status_t addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback); 708 static status_t removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback); 709 710 class AudioPortCallback : public virtual RefBase 711 { 712 public: 713 AudioPortCallback()714 AudioPortCallback() {} ~AudioPortCallback()715 virtual ~AudioPortCallback() {} 716 717 virtual void onAudioPortListUpdate() = 0; 718 virtual void onAudioPatchListUpdate() = 0; 719 virtual void onServiceDied() = 0; 720 721 }; 722 723 static status_t addAudioPortCallback(const sp<AudioPortCallback>& callback); 724 static status_t removeAudioPortCallback(const sp<AudioPortCallback>& callback); 725 726 class AudioDeviceCallback : public virtual RefBase 727 { 728 public: 729 AudioDeviceCallback()730 AudioDeviceCallback() {} ~AudioDeviceCallback()731 virtual ~AudioDeviceCallback() {} 732 733 virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo, 734 audio_port_handle_t deviceId) = 0; 735 }; 736 737 static status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 738 audio_io_handle_t audioIo, 739 audio_port_handle_t portId); 740 static status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 741 audio_io_handle_t audioIo, 742 audio_port_handle_t portId); 743 744 class SupportedLatencyModesCallback : public virtual RefBase 745 { 746 public: 747 748 SupportedLatencyModesCallback() = default; 749 virtual ~SupportedLatencyModesCallback() = default; 750 751 virtual void onSupportedLatencyModesChanged( 752 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) = 0; 753 }; 754 755 static status_t addSupportedLatencyModesCallback( 756 const sp<SupportedLatencyModesCallback>& callback); 757 static status_t removeSupportedLatencyModesCallback( 758 const sp<SupportedLatencyModesCallback>& callback); 759 760 static audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo); 761 762 static status_t setVibratorInfos(const std::vector<media::AudioVibratorInfo>& vibratorInfos); 763 764 static status_t getMmapPolicyInfo( 765 media::audio::common::AudioMMapPolicyType policyType, 766 std::vector<media::audio::common::AudioMMapPolicyInfo> *policyInfos); 767 768 static int32_t getAAudioMixerBurstCount(); 769 770 static int32_t getAAudioHardwareBurstMinUsec(); 771 772 private: 773 774 class AudioFlingerClient: public IBinder::DeathRecipient, public media::BnAudioFlingerClient 775 { 776 public: AudioFlingerClient()777 AudioFlingerClient() : 778 mInBuffSize(0), mInSamplingRate(0), 779 mInFormat(AUDIO_FORMAT_DEFAULT), mInChannelMask(AUDIO_CHANNEL_NONE) { 780 } 781 782 void clearIoCache(); 783 status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 784 audio_channel_mask_t channelMask, size_t* buffSize); 785 sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle); 786 787 // DeathRecipient 788 virtual void binderDied(const wp<IBinder>& who); 789 790 // IAudioFlingerClient 791 792 // indicate a change in the configuration of an output or input: keeps the cached 793 // values for output/input parameters up-to-date in client process 794 binder::Status ioConfigChanged( 795 media::AudioIoConfigEvent event, 796 const media::AudioIoDescriptor& ioDesc) override; 797 798 binder::Status onSupportedLatencyModesChanged( 799 int output, 800 const std::vector<media::audio::common::AudioLatencyMode>& latencyModes) override; 801 802 status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 803 audio_io_handle_t audioIo, 804 audio_port_handle_t portId); 805 status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback, 806 audio_io_handle_t audioIo, 807 audio_port_handle_t portId); 808 809 status_t addSupportedLatencyModesCallback( 810 const sp<SupportedLatencyModesCallback>& callback); 811 status_t removeSupportedLatencyModesCallback( 812 const sp<SupportedLatencyModesCallback>& callback); 813 814 audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo); 815 816 private: 817 Mutex mLock; 818 DefaultKeyedVector<audio_io_handle_t, sp<AudioIoDescriptor> > mIoDescriptors; 819 820 std::map<audio_io_handle_t, std::map<audio_port_handle_t, wp<AudioDeviceCallback>>> 821 mAudioDeviceCallbacks; 822 823 std::vector<wp<SupportedLatencyModesCallback>> 824 mSupportedLatencyModesCallbacks GUARDED_BY(mLock); 825 826 // cached values for recording getInputBufferSize() queries 827 size_t mInBuffSize; // zero indicates cache is invalid 828 uint32_t mInSamplingRate; 829 audio_format_t mInFormat; 830 audio_channel_mask_t mInChannelMask; 831 sp<AudioIoDescriptor> getIoDescriptor_l(audio_io_handle_t ioHandle); 832 }; 833 834 class AudioPolicyServiceClient: public IBinder::DeathRecipient, 835 public media::BnAudioPolicyServiceClient 836 { 837 public: AudioPolicyServiceClient()838 AudioPolicyServiceClient() { 839 } 840 841 int addAudioPortCallback(const sp<AudioPortCallback>& callback); 842 int removeAudioPortCallback(const sp<AudioPortCallback>& callback); isAudioPortCbEnabled()843 bool isAudioPortCbEnabled() const { return (mAudioPortCallbacks.size() != 0); } 844 845 int addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback); 846 int removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback); isAudioVolumeGroupCbEnabled()847 bool isAudioVolumeGroupCbEnabled() const { return (mAudioVolumeGroupCallback.size() != 0); } 848 849 // DeathRecipient 850 virtual void binderDied(const wp<IBinder>& who); 851 852 // IAudioPolicyServiceClient 853 binder::Status onAudioVolumeGroupChanged(int32_t group, int32_t flags) override; 854 binder::Status onAudioPortListUpdate() override; 855 binder::Status onAudioPatchListUpdate() override; 856 binder::Status onDynamicPolicyMixStateUpdate(const std::string& regId, 857 int32_t state) override; 858 binder::Status onRecordingConfigurationUpdate( 859 int32_t event, 860 const media::RecordClientInfo& clientInfo, 861 const media::audio::common::AudioConfigBase& clientConfig, 862 const std::vector<media::EffectDescriptor>& clientEffects, 863 const media::audio::common::AudioConfigBase& deviceConfig, 864 const std::vector<media::EffectDescriptor>& effects, 865 int32_t patchHandle, 866 media::audio::common::AudioSource source) override; 867 binder::Status onRoutingUpdated(); 868 binder::Status onVolumeRangeInitRequest(); 869 870 private: 871 Mutex mLock; 872 Vector <sp <AudioPortCallback> > mAudioPortCallbacks; 873 Vector <sp <AudioVolumeGroupCallback> > mAudioVolumeGroupCallback; 874 }; 875 876 static audio_io_handle_t getOutput(audio_stream_type_t stream); 877 static const sp<AudioFlingerClient> getAudioFlingerClient(); 878 static sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle); 879 880 // Invokes all registered error callbacks with the given error code. 881 static void reportError(status_t err); 882 883 static sp<AudioFlingerClient> gAudioFlingerClient; 884 static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient; 885 friend class AudioFlingerClient; 886 friend class AudioPolicyServiceClient; 887 888 static Mutex gLock; // protects gAudioFlinger 889 static Mutex gLockErrorCallbacks; // protects gAudioErrorCallbacks 890 static Mutex gLockAPS; // protects gAudioPolicyService and gAudioPolicyServiceClient 891 static sp<IAudioFlinger> gAudioFlinger; 892 static std::set<audio_error_callback> gAudioErrorCallbacks; 893 static dynamic_policy_callback gDynPolicyCallback; 894 static record_config_callback gRecordConfigCallback; 895 static routing_callback gRoutingCallback; 896 static vol_range_init_req_callback gVolRangeInitReqCallback; 897 898 static size_t gInBuffSize; 899 // previous parameters for recording buffer size queries 900 static uint32_t gPrevInSamplingRate; 901 static audio_format_t gPrevInFormat; 902 static audio_channel_mask_t gPrevInChannelMask; 903 904 static sp<media::IAudioPolicyService> gAudioPolicyService; 905 }; 906 907 }; // namespace android 908 909 #endif /*ANDROID_AUDIOSYSTEM_H_*/ 910