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