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