1 /* 2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #ifndef LOG_TAG 16 #define LOG_TAG "AudioPolicyService" 17 #endif 18 19 #include "audio_policy_service.h" 20 #include <ability_manager_client.h> 21 #include "iservice_registry.h" 22 #include "parameter.h" 23 #include "audio_utils.h" 24 #include "audio_manager_listener_stub.h" 25 #include "parameters.h" 26 #include "data_share_observer_callback.h" 27 #include "device_init_callback.h" 28 #include "audio_inner_call.h" 29 30 #ifdef FEATURE_DEVICE_MANAGER 31 #endif 32 #include "audio_spatialization_service.h" 33 #include "audio_converter_parser.h" 34 #include "audio_dialog_ability_connection.h" 35 36 #include "media_monitor_manager.h" 37 #include "client_type_manager.h" 38 39 namespace OHOS { 40 namespace AudioStandard { 41 using namespace std; 42 43 static const std::string INNER_CAPTURER_SINK_LEGACY = "InnerCapturer"; 44 static const std::string PIPE_PRIMARY_OUTPUT = "primary_output"; 45 static const std::string PIPE_FAST_OUTPUT = "fast_output"; 46 static const std::string PIPE_OFFLOAD_OUTPUT = "offload_output"; 47 static const std::string PIPE_VOIP_OUTPUT = "voip_output"; 48 static const std::string PIPE_PRIMARY_INPUT = "primary_input"; 49 static const std::string PIPE_OFFLOAD_INPUT = "offload_input"; 50 static const std::string PIPE_A2DP_OUTPUT = "a2dp_output"; 51 static const std::string PIPE_FAST_A2DP_OUTPUT = "fast_a2dp_output"; 52 static const std::string PIPE_USB_ARM_OUTPUT = "usb_arm_output"; 53 static const std::string PIPE_USB_ARM_INPUT = "usb_arm_input"; 54 static const std::string PIPE_DISTRIBUTED_OUTPUT = "distributed_output"; 55 static const std::string PIPE_FAST_DISTRIBUTED_OUTPUT = "fast_distributed_output"; 56 static const std::string PIPE_DISTRIBUTED_INPUT = "distributed_input"; 57 static const std::string CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#"; 58 static const std::string PIPE_WAKEUP_INPUT = "wakeup_input"; 59 static const int64_t CALL_IPC_COST_TIME_MS = 20000000; // 20ms 60 static const int32_t WAIT_OFFLOAD_CLOSE_TIME_S = 10; // 10s 61 static const int64_t OLD_DEVICE_UNAVALIABLE_MUTE_MS = 1000000; // 1s 62 static const int64_t OLD_DEVICE_UNAVALIABLE_EXT_MUTE_MS = 300000; // 300ms 63 static const int64_t OLD_DEVICE_UNAVALIABLE_MUTE_SLEEP_MS = 150000; // 150ms 64 static const int64_t SELECT_DEVICE_MUTE_MS = 200000; // 200ms 65 static const int64_t SELECT_OFFLOAD_DEVICE_MUTE_MS = 400000; // 400ms 66 static const int64_t NEW_DEVICE_AVALIABLE_MUTE_MS = 400000; // 400ms 67 static const int64_t NEW_DEVICE_AVALIABLE_OFFLOAD_MUTE_MS = 1000000; // 1s 68 static const int64_t SET_BT_ABS_SCENE_DELAY_MS = 120000; // 120ms 69 static const int64_t NEW_DEVICE_REMOTE_CAST_AVALIABLE_MUTE_MS = 300000; // 300ms 70 static const unsigned int BUFFER_CALC_20MS = 20; 71 static const unsigned int BUFFER_CALC_1000MS = 1000; 72 static const int64_t WAIT_LOAD_DEFAULT_DEVICE_TIME_MS = 5000; // 5s 73 static const int64_t WAIT_SET_MUTE_LATENCY_TIME_US = 80000; // 80ms 74 static const int64_t WAIT_MODEM_CALL_SET_VOLUME_TIME_US = 120000; // 120ms 75 static const int64_t WAIT_MOVE_DEVICE_MUTE_TIME_MAX_MS = 5000; // 5s 76 static const int64_t WAIT_RINGER_MODE_MUTE_RESET_TIME_MS = 500; // 500ms 77 static const int32_t INITIAL_VALUE = 1; 78 static const int32_t INVALID_APP_UID = -1; 79 static const int32_t INVALID_APP_CREATED_AUDIO_STREAM_NUM = -1; 80 static const int VOLUME_LEVEL_DEFAULT_SIZE = 3; 81 82 static const std::vector<AudioVolumeType> VOLUME_TYPE_LIST = { 83 STREAM_VOICE_CALL, 84 STREAM_RING, 85 STREAM_MUSIC, 86 STREAM_VOICE_ASSISTANT, 87 STREAM_ALARM, 88 STREAM_ACCESSIBILITY, 89 STREAM_ULTRASONIC, 90 STREAM_VOICE_CALL_ASSISTANT, 91 STREAM_ALL 92 }; 93 94 static std::map<std::string, uint32_t> formatFromParserStrToEnum = { 95 {"s16le", SAMPLE_S16LE}, 96 {"s24le", SAMPLE_S24LE}, 97 {"s32le", SAMPLE_S32LE}, 98 }; 99 100 std::map<std::string, uint32_t> AudioPolicyService::formatStrToEnum = { 101 {"SAMPLE_U8", SAMPLE_U8}, 102 {"SAMPLE_S16E", SAMPLE_S16LE}, 103 {"SAMPLE_S24LE", SAMPLE_S24LE}, 104 {"SAMPLE_S32LE", SAMPLE_S32LE}, 105 {"SAMPLE_F32LE", SAMPLE_F32LE}, 106 {"INVALID_WIDTH", INVALID_WIDTH}, 107 }; 108 109 std::map<std::string, ClassType> AudioPolicyService::classStrToEnum = { 110 {PRIMARY_CLASS, TYPE_PRIMARY}, 111 {A2DP_CLASS, TYPE_A2DP}, 112 {USB_CLASS, TYPE_USB}, 113 {DP_CLASS, TYPE_DP}, 114 {FILE_CLASS, TYPE_FILE_IO}, 115 {REMOTE_CLASS, TYPE_REMOTE_AUDIO}, 116 {INVALID_CLASS, TYPE_INVALID}, 117 }; 118 119 static std::map<std::string, ClassType> portStrToEnum = { 120 {PRIMARY_SPEAKER, TYPE_PRIMARY}, 121 {PRIMARY_MIC, TYPE_PRIMARY}, 122 {PRIMARY_WAKEUP_MIC, TYPE_PRIMARY}, 123 {BLUETOOTH_SPEAKER, TYPE_A2DP}, 124 {USB_SPEAKER, TYPE_USB}, 125 {USB_MIC, TYPE_USB}, 126 {DP_SINK, TYPE_DP}, 127 {FILE_SINK, TYPE_FILE_IO}, 128 {FILE_SOURCE, TYPE_FILE_IO}, 129 {REMOTE_CLASS, TYPE_REMOTE_AUDIO}, 130 }; 131 132 std::map<std::string, std::string> AudioPolicyService::sinkPortStrToClassStrMap_ = { 133 {PRIMARY_SPEAKER, PRIMARY_CLASS}, 134 {BLUETOOTH_SPEAKER, A2DP_CLASS}, 135 {USB_SPEAKER, USB_CLASS}, 136 {DP_SINK, DP_CLASS}, 137 {OFFLOAD_PRIMARY_SPEAKER, OFFLOAD_CLASS}, 138 }; 139 140 static const std::string SETTINGS_DATA_BASE_URI = 141 "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; 142 static const std::string SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility"; 143 static const std::string SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD"; 144 static const std::string SETTINGS_DATA_FIELD_VALUE = "VALUE"; 145 static const std::string PREDICATES_STRING = "settings.general.device_name"; 146 static const std::string EARPIECE_TYPE_NAME = "DEVICE_TYPE_EARPIECE"; 147 static const std::string FLAG_MMAP_STRING = "AUDIO_FLAG_MMAP"; 148 static const std::string USAGE_VOIP_STRING = "AUDIO_USAGE_VOIP"; 149 const uint32_t PCM_8_BIT = 8; 150 const uint32_t PCM_16_BIT = 16; 151 const uint32_t PCM_24_BIT = 24; 152 const uint32_t PCM_32_BIT = 32; 153 const int32_t DEFAULT_MAX_OUTPUT_NORMAL_INSTANCES = 128; 154 const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50; 155 const uint32_t ABS_VOLUME_SUPPORT_RETRY_INTERVAL_IN_MICROSECONDS = 10000; 156 const uint32_t REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS = 30000; 157 const float RENDER_FRAME_INTERVAL_IN_SECONDS = 0.02; 158 const int32_t DUAL_TONE_RING_VOLUME = 0; 159 const uint32_t USER_NOT_SELECT_BT = 1; 160 const uint32_t USER_SELECT_BT = 2; 161 const std::string AUDIO_SERVICE_PKG = "audio_manager_service"; 162 const int32_t UID_AUDIO = 1041; 163 const int MEDIA_RENDER_ID = 0; 164 const int CALL_RENDER_ID = 1; 165 const int CALL_CAPTURE_ID = 2; 166 const int RECORD_CAPTURE_ID = 3; 167 const int32_t ONE_MINUTE = 60; 168 constexpr int32_t MS_PER_S = 1000; 169 constexpr int32_t NS_PER_MS = 1000000; 170 const int32_t DATA_LINK_CONNECTING = 10; 171 const int32_t DATA_LINK_CONNECTED = 11; 172 const int32_t A2DP_PLAYING = 2; 173 const int32_t A2DP_STOPPED = 1; 174 static sptr<IStandardAudioService> g_adProxy = nullptr; 175 #ifdef BLUETOOTH_ENABLE 176 static sptr<IStandardAudioService> g_btProxy = nullptr; 177 #endif 178 static int32_t startDeviceId = 1; 179 static int32_t startMicrophoneId = 1; 180 mutex g_adProxyMutex; 181 #ifdef BLUETOOTH_ENABLE 182 const unsigned int BLUETOOTH_TIME_OUT_SECONDS = 8; 183 mutex g_btProxyMutex; 184 #endif 185 bool AudioPolicyService::isBtListenerRegistered = false; 186 ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat)187 static string ConvertToHDIAudioFormat(AudioSampleFormat sampleFormat) 188 { 189 switch (sampleFormat) { 190 case SAMPLE_U8: 191 return "u8"; 192 case SAMPLE_S16LE: 193 return "s16le"; 194 case SAMPLE_S24LE: 195 return "s24le"; 196 case SAMPLE_S32LE: 197 return "s32le"; 198 default: 199 return ""; 200 } 201 } 202 GetSampleFormatValue(AudioSampleFormat sampleFormat)203 static uint32_t GetSampleFormatValue(AudioSampleFormat sampleFormat) 204 { 205 switch (sampleFormat) { 206 case SAMPLE_U8: 207 return PCM_8_BIT; 208 case SAMPLE_S16LE: 209 return PCM_16_BIT; 210 case SAMPLE_S24LE: 211 return PCM_24_BIT; 212 case SAMPLE_S32LE: 213 return PCM_32_BIT; 214 default: 215 return PCM_16_BIT; 216 } 217 } 218 ParseAudioFormat(string format)219 static string ParseAudioFormat(string format) 220 { 221 if (format == "AUDIO_FORMAT_PCM_16_BIT") { 222 return "s16"; 223 } else if (format == "AUDIO_FORMAT_PCM_24_BIT") { 224 return "s24"; 225 } else if (format == "AUDIO_FORMAT_PCM_32_BIT") { 226 return "s32"; 227 } else { 228 return ""; 229 } 230 } 231 GetUsbModuleInfo(string deviceInfo,AudioModuleInfo & moduleInfo)232 static void GetUsbModuleInfo(string deviceInfo, AudioModuleInfo &moduleInfo) 233 { 234 if (moduleInfo.role == "sink") { 235 auto sinkRate_begin = deviceInfo.find("sink_rate:"); 236 auto sinkRate_end = deviceInfo.find_first_of(";", sinkRate_begin); 237 moduleInfo.rate = deviceInfo.substr(sinkRate_begin + std::strlen("sink_rate:"), 238 sinkRate_end - sinkRate_begin - std::strlen("sink_rate:")); 239 auto sinkFormat_begin = deviceInfo.find("sink_format:"); 240 auto sinkFormat_end = deviceInfo.find_first_of(";", sinkFormat_begin); 241 string format = deviceInfo.substr(sinkFormat_begin + std::strlen("sink_format:"), 242 sinkFormat_end - sinkFormat_begin - std::strlen("sink_format:")); 243 moduleInfo.format = ParseAudioFormat(format); 244 } else { 245 auto sourceRate_begin = deviceInfo.find("source_rate:"); 246 auto sourceRate_end = deviceInfo.find_first_of(";", sourceRate_begin); 247 moduleInfo.rate = deviceInfo.substr(sourceRate_begin + std::strlen("source_rate:"), 248 sourceRate_end - sourceRate_begin - std::strlen("source_rate:")); 249 auto sourceFormat_begin = deviceInfo.find("source_format:"); 250 auto sourceFormat_end = deviceInfo.find_first_of(";", sourceFormat_begin); 251 string format = deviceInfo.substr(sourceFormat_begin + std::strlen("source_format:"), 252 sourceFormat_end - sourceFormat_begin - std::strlen("source_format:")); 253 moduleInfo.format = ParseAudioFormat(format); 254 } 255 } 256 GetDPModuleInfo(AudioModuleInfo & moduleInfo,string deviceInfo)257 static void GetDPModuleInfo(AudioModuleInfo &moduleInfo, string deviceInfo) 258 { 259 if (moduleInfo.role == "sink") { 260 auto sinkRate_begin = deviceInfo.find("rate="); 261 auto sinkRate_end = deviceInfo.find_first_of(" ", sinkRate_begin); 262 moduleInfo.rate = deviceInfo.substr(sinkRate_begin + std::strlen("rate="), 263 sinkRate_end - sinkRate_begin - std::strlen("rate=")); 264 265 auto sinkFormat_begin = deviceInfo.find("format="); 266 auto sinkFormat_end = deviceInfo.find_first_of(" ", sinkFormat_begin); 267 string format = deviceInfo.substr(sinkFormat_begin + std::strlen("format="), 268 sinkFormat_end - sinkFormat_begin - std::strlen("format=")); 269 if (!format.empty()) moduleInfo.format = format; 270 271 auto sinkChannel_begin = deviceInfo.find("channels="); 272 auto sinkChannel_end = deviceInfo.find_first_of(" ", sinkChannel_begin); 273 string channel = deviceInfo.substr(sinkChannel_begin + std::strlen("channels="), 274 sinkChannel_end - sinkChannel_begin - std::strlen("channels=")); 275 moduleInfo.channels = channel; 276 277 auto sinkBSize_begin = deviceInfo.find("buffer_size="); 278 auto sinkBSize_end = deviceInfo.find_first_of(" ", sinkBSize_begin); 279 string bufferSize = deviceInfo.substr(sinkBSize_begin + std::strlen("buffer_size="), 280 sinkBSize_end - sinkBSize_begin - std::strlen("buffer_size=")); 281 moduleInfo.bufferSize = bufferSize; 282 } 283 } 284 GetCurrentTimeMS()285 static int64_t GetCurrentTimeMS() 286 { 287 timespec tm {}; 288 clock_gettime(CLOCK_MONOTONIC, &tm); 289 return tm.tv_sec * MS_PER_S + (tm.tv_nsec / NS_PER_MS); 290 } 291 PcmFormatToBits(AudioSampleFormat format)292 static uint32_t PcmFormatToBits(AudioSampleFormat format) 293 { 294 switch (format) { 295 case SAMPLE_U8: 296 return 1; // 1 byte 297 case SAMPLE_S16LE: 298 return 2; // 2 byte 299 case SAMPLE_S24LE: 300 return 3; // 3 byte 301 case SAMPLE_S32LE: 302 return 4; // 4 byte 303 case SAMPLE_F32LE: 304 return 4; // 4 byte 305 default: 306 return 2; // 2 byte 307 } 308 } 309 ~AudioPolicyService()310 AudioPolicyService::~AudioPolicyService() 311 { 312 AUDIO_WARNING_LOG("~AudioPolicyService()"); 313 Deinit(); 314 } 315 Init(void)316 bool AudioPolicyService::Init(void) 317 { 318 AUDIO_INFO_LOG("Audio policy service init enter"); 319 serviceFlag_.reset(); 320 audioPolicyManager_.Init(); 321 audioEffectManager_.EffectManagerInit(); 322 audioDeviceManager_.ParseDeviceXml(); 323 audioPnpServer_.init(); 324 audioA2dpOffloadManager_ = std::make_shared<AudioA2dpOffloadManager>(this); 325 if (audioA2dpOffloadManager_ != nullptr) {audioA2dpOffloadManager_->Init();} 326 327 bool ret = audioPolicyConfigParser_.LoadConfiguration(); 328 if (!ret) { 329 WriteServiceStartupError("Audio Policy Config Load Configuration failed"); 330 isPolicyConfigParsered_ = true; 331 } 332 CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Policy Config Load Configuration failed"); 333 ret = audioPolicyConfigParser_.Parse(); 334 isPolicyConfigParsered_ = true; 335 isFastControlled_ = getFastControlParam(); 336 if (!ret) { 337 WriteServiceStartupError("Audio Config Parse failed"); 338 } 339 CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Config Parse failed"); 340 341 #ifdef FEATURE_DTMF_TONE 342 ret = LoadToneDtmfConfig(); 343 CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Tone Load Configuration failed"); 344 #endif 345 346 int32_t status = deviceStatusListener_->RegisterDeviceStatusListener(); 347 if (status != SUCCESS) { 348 WriteServiceStartupError("[Policy Service] Register for device status events failed"); 349 } 350 CHECK_AND_RETURN_RET_LOG(status == SUCCESS, false, "[Policy Service] Register for device status events failed"); 351 352 RegisterRemoteDevStatusCallback(); 353 354 if (policyVolumeMap_ == nullptr) { 355 size_t mapSize = IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume) + sizeof(bool); 356 AUDIO_INFO_LOG("InitSharedVolume create shared volume map with size %{public}zu", mapSize); 357 policyVolumeMap_ = AudioSharedMemory::CreateFormLocal(mapSize, "PolicyVolumeMap"); 358 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr, 359 false, "Get shared memory failed!"); 360 volumeVector_ = reinterpret_cast<Volume *>(policyVolumeMap_->GetBase()); 361 sharedAbsVolumeScene_ = reinterpret_cast<bool *>(policyVolumeMap_->GetBase()) + 362 IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume); 363 } 364 365 AUDIO_INFO_LOG("Audio policy service init end"); 366 CreateRecoveryThread(); 367 std::string versionType = OHOS::system::GetParameter("const.logsystem.versiontype", "commercial"); 368 AudioDump::GetInstance().SetVersionType(versionType); 369 370 return true; 371 } 372 GetAudioServerProxy()373 const sptr<IStandardAudioService> AudioPolicyService::GetAudioServerProxy() 374 { 375 AUDIO_DEBUG_LOG("[Policy Service] Start get audio policy service proxy."); 376 lock_guard<mutex> lock(g_adProxyMutex); 377 378 if (g_adProxy == nullptr) { 379 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); 380 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr, "[Policy Service] Get samgr failed."); 381 382 sptr<IRemoteObject> object = samgr->GetSystemAbility(AUDIO_DISTRIBUTED_SERVICE_ID); 383 CHECK_AND_RETURN_RET_LOG(object != nullptr, nullptr, 384 "[Policy Service] audio service remote object is NULL."); 385 386 g_adProxy = iface_cast<IStandardAudioService>(object); 387 CHECK_AND_RETURN_RET_LOG(g_adProxy != nullptr, nullptr, 388 "[Policy Service] init g_adProxy is NULL."); 389 } 390 const sptr<IStandardAudioService> gsp = g_adProxy; 391 return gsp; 392 } 393 CreateRecoveryThread()394 void AudioPolicyService::CreateRecoveryThread() 395 { 396 if (RecoveryDevicesThread_ != nullptr) { 397 RecoveryDevicesThread_->detach(); 398 } 399 RecoveryDevicesThread_ = std::make_unique<std::thread>([this] { this->RecoveryPreferredDevices(); }); 400 pthread_setname_np(RecoveryDevicesThread_->native_handle(), "APSRecovery"); 401 } 402 RecoveryPreferredDevices()403 void AudioPolicyService::RecoveryPreferredDevices() 404 { 405 AUDIO_DEBUG_LOG("Start recovery peferred devices."); 406 int32_t tryCounter = 5; 407 // Waiting for 1000000 渭s. Ensure that the playback/recording stream is restored first 408 uint32_t firstSleepTime = 1000000; 409 // Retry interval 410 uint32_t sleepTime = 300000; 411 int32_t result = -1; 412 std::map<Media::MediaMonitor::PerferredType, 413 std::shared_ptr<Media::MediaMonitor::MonitorDeviceInfo>> preferredDevices; 414 usleep(firstSleepTime); 415 while (result != SUCCESS && tryCounter-- > 0) { 416 Media::MediaMonitor::MediaMonitorManager::GetInstance().GetAudioRouteMsg(preferredDevices); 417 if (preferredDevices.size() == 0) { 418 AUDIO_ERR_LOG("The length of preferredDevices is 0 and does not need to be set."); 419 continue; 420 } 421 for (auto iter = preferredDevices.begin(); iter != preferredDevices.end(); ++iter) { 422 result = HandleRecoveryPreferredDevices(static_cast<int32_t>(iter->first), iter->second->deviceType_, 423 iter->second->usageOrSourceType_); 424 if (result != SUCCESS) { 425 AUDIO_ERR_LOG("Handle recovery preferred devices failed" 426 ", deviceType:%{public}d, usageOrSourceType:%{public}d, tryCounter:%{public}d", 427 iter->second->deviceType_, iter->second->usageOrSourceType_, tryCounter); 428 } 429 } 430 if (result != SUCCESS) { 431 usleep(sleepTime); 432 } 433 } 434 } 435 HandleRecoveryPreferredDevices(int32_t preferredType,int32_t deviceType,int32_t usageOrSourceType)436 int32_t AudioPolicyService::HandleRecoveryPreferredDevices(int32_t preferredType, int32_t deviceType, 437 int32_t usageOrSourceType) 438 { 439 int32_t result = -1; 440 auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) { 441 if (deviceType == desc->deviceType_) { 442 return true; 443 } 444 return false; 445 }; 446 auto it = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent); 447 if (it != connectedDevices_.end()) { 448 vector<sptr<AudioDeviceDescriptor>> deviceDescriptorVector; 449 deviceDescriptorVector.push_back(*it); 450 if (preferredType == Media::MediaMonitor::MEDIA_RENDER || 451 preferredType == Media::MediaMonitor::CALL_RENDER || 452 preferredType == Media::MediaMonitor::RING_RENDER || 453 preferredType == Media::MediaMonitor::TONE_RENDER) { 454 sptr<AudioRendererFilter> audioRendererFilter = new(std::nothrow) AudioRendererFilter(); 455 audioRendererFilter->uid = -1; 456 audioRendererFilter->rendererInfo.streamUsage = 457 static_cast<StreamUsage>(usageOrSourceType); 458 result = SelectOutputDevice(audioRendererFilter, deviceDescriptorVector); 459 } else if (preferredType == Media::MediaMonitor::CALL_CAPTURE || 460 preferredType == Media::MediaMonitor::RECORD_CAPTURE) { 461 sptr<AudioCapturerFilter> audioCapturerFilter = new(std::nothrow) AudioCapturerFilter(); 462 audioCapturerFilter->uid = -1; 463 audioCapturerFilter->capturerInfo.sourceType = 464 static_cast<SourceType>(usageOrSourceType); 465 result = SelectInputDevice(audioCapturerFilter, deviceDescriptorVector); 466 } 467 } 468 return result; 469 } 470 InitKVStore()471 void AudioPolicyService::InitKVStore() 472 { 473 audioPolicyManager_.InitKVStore(); 474 UpdateVolumeForLowLatency(); 475 AudioSpatializationService::GetAudioSpatializationService().InitSpatializationState(); 476 } 477 UpdateVolumeForLowLatency()478 void AudioPolicyService::UpdateVolumeForLowLatency() 479 { 480 // update volumes for low latency streams when loading volumes from the database. 481 Volume vol = {false, 1.0f, 0}; 482 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 483 for (auto iter = VOLUME_TYPE_LIST.begin(); iter != VOLUME_TYPE_LIST.end(); iter++) { 484 int32_t volumeLevel = GetSystemVolumeLevel(*iter); 485 vol.volumeFloat = GetSystemVolumeInDb(*iter, volumeLevel, curOutputDeviceType); 486 SetSharedVolume(*iter, curOutputDeviceType, vol); 487 } 488 SetSharedAbsVolumeScene(IsAbsVolumeScene()); 489 } 490 ConnectServiceAdapter()491 bool AudioPolicyService::ConnectServiceAdapter() 492 { 493 bool ret = audioPolicyManager_.ConnectServiceAdapter(); 494 CHECK_AND_RETURN_RET_LOG(ret, false, "Error in connecting to audio service adapter"); 495 496 OnServiceConnected(AudioServiceIndex::AUDIO_SERVICE_INDEX); 497 498 return true; 499 } 500 Deinit(void)501 void AudioPolicyService::Deinit(void) 502 { 503 AUDIO_WARNING_LOG("Policy service died. closing active ports"); 504 505 std::unique_lock<std::mutex> ioHandleLock(ioHandlesMutex_); 506 std::for_each(IOHandles_.begin(), IOHandles_.end(), [&](std::pair<std::string, AudioIOHandle> handle) { 507 audioPolicyManager_.CloseAudioPort(handle.second); 508 }); 509 audioPolicyManager_.Deinit(); 510 511 IOHandles_.clear(); 512 ioHandleLock.unlock(); 513 #ifdef ACCESSIBILITY_ENABLE 514 accessibilityConfigListener_->UnsubscribeObserver(); 515 #endif 516 deviceStatusListener_->UnRegisterDeviceStatusListener(); 517 audioPnpServer_.StopPnpServer(); 518 519 if (isBtListenerRegistered) { 520 UnregisterBluetoothListener(); 521 } 522 volumeVector_ = nullptr; 523 sharedAbsVolumeScene_ = nullptr; 524 policyVolumeMap_ = nullptr; 525 safeVolumeExit_ = true; 526 if (calculateLoopSafeTime_ != nullptr && calculateLoopSafeTime_->joinable()) { 527 calculateLoopSafeTime_->join(); 528 calculateLoopSafeTime_.reset(); 529 calculateLoopSafeTime_ = nullptr; 530 } 531 if (safeVolumeDialogThrd_ != nullptr && safeVolumeDialogThrd_->joinable()) { 532 safeVolumeDialogThrd_->join(); 533 safeVolumeDialogThrd_.reset(); 534 safeVolumeDialogThrd_ = nullptr; 535 } 536 if (RecoveryDevicesThread_ != nullptr && RecoveryDevicesThread_->joinable()) { 537 RecoveryDevicesThread_->join(); 538 RecoveryDevicesThread_.reset(); 539 RecoveryDevicesThread_ = nullptr; 540 } 541 542 return; 543 } 544 SetAudioStreamRemovedCallback(AudioStreamRemovedCallback * callback)545 int32_t AudioPolicyService::SetAudioStreamRemovedCallback(AudioStreamRemovedCallback *callback) 546 { 547 return audioPolicyManager_.SetAudioStreamRemovedCallback(callback); 548 } 549 GetMaxVolumeLevel(AudioVolumeType volumeType) const550 int32_t AudioPolicyService::GetMaxVolumeLevel(AudioVolumeType volumeType) const 551 { 552 if (volumeType == STREAM_ALL) { 553 volumeType = STREAM_MUSIC; 554 } 555 return audioPolicyManager_.GetMaxVolumeLevel(volumeType); 556 } 557 GetMinVolumeLevel(AudioVolumeType volumeType) const558 int32_t AudioPolicyService::GetMinVolumeLevel(AudioVolumeType volumeType) const 559 { 560 if (volumeType == STREAM_ALL) { 561 volumeType = STREAM_MUSIC; 562 } 563 return audioPolicyManager_.GetMinVolumeLevel(volumeType); 564 } 565 SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel)566 int32_t AudioPolicyService::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel) 567 { 568 int32_t result; 569 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 570 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && 571 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 572 result = SetA2dpDeviceVolume(activeBTDevice_, volumeLevel, true); 573 #ifdef BLUETOOTH_ENABLE 574 if (result == SUCCESS) { 575 // set to avrcp device 576 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_, volumeLevel); 577 } else if (result == ERR_UNKNOWN) { 578 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_, 579 audioPolicyManager_.GetSafeVolumeLevel()); 580 } else { 581 AUDIO_ERR_LOG("AudioPolicyService::SetSystemVolumeLevel set abs volume failed"); 582 } 583 #endif 584 } 585 int32_t sVolumeLevel = SelectDealSafeVolume(streamType, volumeLevel); 586 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERROR, "safevolume did not deal"); 587 result = audioPolicyManager_.SetSystemVolumeLevel(streamType, volumeLevel); 588 if (result == SUCCESS && (streamType == STREAM_VOICE_CALL || streamType == STREAM_VOICE_COMMUNICATION)) { 589 SetVoiceCallVolume(volumeLevel); 590 } 591 // todo 592 Volume vol = {false, 1.0f, 0}; 593 vol.volumeFloat = GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType); 594 SetSharedVolume(streamType, curOutputDeviceType, vol); 595 596 return result; 597 } 598 SelectDealSafeVolume(AudioStreamType streamType,int32_t volumeLevel)599 int32_t AudioPolicyService::SelectDealSafeVolume(AudioStreamType streamType, int32_t volumeLevel) 600 { 601 int32_t sVolumeLevel = volumeLevel; 602 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 603 DeviceCategory curOutputDeviceCategory = GetCurrentOutputDeviceCategory(); 604 if (sVolumeLevel > audioPolicyManager_.GetSafeVolumeLevel() && 605 VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC) { 606 switch (curOutputDeviceType) { 607 case DEVICE_TYPE_BLUETOOTH_A2DP: 608 case DEVICE_TYPE_BLUETOOTH_SCO: 609 if (curOutputDeviceCategory != BT_SOUNDBOX && 610 curOutputDeviceCategory != BT_CAR) { 611 sVolumeLevel = DealWithSafeVolume(volumeLevel, true); 612 } 613 break; 614 case DEVICE_TYPE_WIRED_HEADSET: 615 case DEVICE_TYPE_WIRED_HEADPHONES: 616 case DEVICE_TYPE_USB_HEADSET: 617 case DEVICE_TYPE_USB_ARM_HEADSET: 618 sVolumeLevel = DealWithSafeVolume(volumeLevel, false); 619 break; 620 default: 621 AUDIO_INFO_LOG("unsupport safe volume:%{public}d", curOutputDeviceType); 622 break; 623 } 624 } 625 return sVolumeLevel; 626 } 627 SetVoiceRingtoneMute(bool isMute)628 int32_t AudioPolicyService::SetVoiceRingtoneMute(bool isMute) 629 { 630 AUDIO_INFO_LOG("Set Voice Ringtone is %{public}d", isMute); 631 isVoiceRingtoneMute_ = isMute ? true : false; 632 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL)); 633 return SUCCESS; 634 } 635 SetVoiceCallVolume(int32_t volumeLevel)636 void AudioPolicyService::SetVoiceCallVolume(int32_t volumeLevel) 637 { 638 Trace trace("AudioPolicyService::SetVoiceCallVolume" + std::to_string(volumeLevel)); 639 // set voice volume by the interface from hdi. 640 CHECK_AND_RETURN_LOG(volumeLevel != 0, "SetVoiceVolume: volume of voice_call cannot be set to 0"); 641 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 642 CHECK_AND_RETURN_LOG(gsp != nullptr, "SetVoiceVolume: gsp null"); 643 float volumeDb = static_cast<float>(volumeLevel) / 644 static_cast<float>(audioPolicyManager_.GetMaxVolumeLevel(STREAM_VOICE_CALL)); 645 volumeDb = isVoiceRingtoneMute_ ? 0 : volumeDb; 646 // VGS feature 647 if (audioPolicyManager_.IsVgsVolumeSupported()) { 648 volumeDb = 1; 649 } 650 651 std::string identity = IPCSkeleton::ResetCallingIdentity(); 652 gsp->SetVoiceVolume(volumeDb); 653 IPCSkeleton::SetCallingIdentity(identity); 654 AUDIO_INFO_LOG("SetVoiceVolume: %{public}f", volumeDb); 655 } 656 SetVolumeForSwitchDevice(DeviceType deviceType,const std::string & newSinkName)657 void AudioPolicyService::SetVolumeForSwitchDevice(DeviceType deviceType, const std::string &newSinkName) 658 { 659 Trace trace("AudioPolicyService::SetVolumeForSwitchDevice:" + std::to_string(deviceType)); 660 // Load volume from KvStore and set volume for each stream type 661 audioPolicyManager_.SetVolumeForSwitchDevice(deviceType); 662 663 // The volume of voice_call needs to be adjusted separately 664 if (audioScene_ == AUDIO_SCENE_PHONE_CALL) { 665 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL)); 666 } 667 668 UpdateVolumeForLowLatency(); 669 } 670 GetVolumeGroupType(DeviceType deviceType)671 std::string AudioPolicyService::GetVolumeGroupType(DeviceType deviceType) 672 { 673 std::string volumeGroupType = ""; 674 switch (deviceType) { 675 case DEVICE_TYPE_EARPIECE: 676 case DEVICE_TYPE_SPEAKER: 677 volumeGroupType = "build-in"; 678 break; 679 case DEVICE_TYPE_BLUETOOTH_A2DP: 680 case DEVICE_TYPE_BLUETOOTH_SCO: 681 volumeGroupType = "wireless"; 682 break; 683 case DEVICE_TYPE_WIRED_HEADSET: 684 case DEVICE_TYPE_USB_HEADSET: 685 case DEVICE_TYPE_DP: 686 case DEVICE_TYPE_USB_ARM_HEADSET: 687 volumeGroupType = "wired"; 688 break; 689 default: 690 AUDIO_ERR_LOG("GetVolumeGroupType: device %{public}d is not supported", deviceType); 691 break; 692 } 693 return volumeGroupType; 694 } 695 GetSystemVolumeLevel(AudioStreamType streamType)696 int32_t AudioPolicyService::GetSystemVolumeLevel(AudioStreamType streamType) 697 { 698 if (streamType == STREAM_RING && !IsRingerModeMute()) { 699 AUDIO_PRERELEASE_LOGW("return 0 when dual tone ring"); 700 return DUAL_TONE_RING_VOLUME; 701 } 702 { 703 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_); 704 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 705 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && 706 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 707 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_); 708 if (configInfoPos != connectedA2dpDeviceMap_.end() 709 && configInfoPos->second.absVolumeSupport) { 710 return configInfoPos->second.mute ? 0 : configInfoPos->second.volumeLevel; 711 } else { 712 AUDIO_WARNING_LOG("Get absolute volume failed for activeBTDevice :[%{public}s]", 713 GetEncryptAddr(activeBTDevice_).c_str()); 714 } 715 } 716 } 717 return audioPolicyManager_.GetSystemVolumeLevel(streamType); 718 } 719 GetSystemVolumeDb(AudioStreamType streamType) const720 float AudioPolicyService::GetSystemVolumeDb(AudioStreamType streamType) const 721 { 722 return audioPolicyManager_.GetSystemVolumeDb(streamType); 723 } 724 SetLowPowerVolume(int32_t streamId,float volume) const725 int32_t AudioPolicyService::SetLowPowerVolume(int32_t streamId, float volume) const 726 { 727 return streamCollector_.SetLowPowerVolume(streamId, volume); 728 } 729 GetLowPowerVolume(int32_t streamId) const730 float AudioPolicyService::GetLowPowerVolume(int32_t streamId) const 731 { 732 return streamCollector_.GetLowPowerVolume(streamId); 733 } 734 735 SetOffloadMode()736 void AudioPolicyService::SetOffloadMode() 737 { 738 if (!GetOffloadAvailableFromXml()) { 739 AUDIO_INFO_LOG("Offload not available, skipped"); 740 return; 741 } 742 743 AUDIO_INFO_LOG("sessionId: %{public}d, PowerState: %{public}d, isAppBack: %{public}d", 744 *offloadSessionID_, static_cast<int32_t>(currentPowerState_), currentOffloadSessionIsBackground_); 745 746 streamCollector_.SetOffloadMode(*offloadSessionID_, static_cast<int32_t>(currentPowerState_), 747 currentOffloadSessionIsBackground_); 748 } 749 ResetOffloadMode(int32_t sessionId)750 void AudioPolicyService::ResetOffloadMode(int32_t sessionId) 751 { 752 AUDIO_DEBUG_LOG("Doing reset offload mode!"); 753 754 if (!CheckActiveOutputDeviceSupportOffload()) { 755 AUDIO_DEBUG_LOG("Resetting offload not available on this output device! Release."); 756 OffloadStreamReleaseCheck(*offloadSessionID_); 757 return; 758 } 759 760 OffloadStreamSetCheck(sessionId); 761 } 762 OffloadStreamSetCheck(uint32_t sessionId)763 void AudioPolicyService::OffloadStreamSetCheck(uint32_t sessionId) 764 { 765 AudioPipeType pipeType = PIPE_TYPE_OFFLOAD; 766 int32_t ret = ActivateAudioConcurrency(pipeType); 767 if (ret != SUCCESS) { 768 return; 769 } 770 DeviceInfo deviceInfo; 771 std::string curOutputNetworkId = GetCurrentOutputDeviceNetworkId(); 772 std::string curOutputMacAddr = GetCurrentOutputDeviceMacAddr(); 773 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 774 ret = streamCollector_.GetRendererDeviceInfo(sessionId, deviceInfo); 775 if (ret != SUCCESS || curOutputNetworkId != LOCAL_NETWORK_ID || 776 curOutputDeviceType == DEVICE_TYPE_REMOTE_CAST || 777 deviceInfo.deviceType != curOutputDeviceType || 778 deviceInfo.networkId != curOutputNetworkId || 779 deviceInfo.macAddress != curOutputMacAddr) { 780 AUDIO_INFO_LOG("sessionId[%{public}d] not fetch device, Offload Skipped", sessionId); 781 return; 782 } 783 784 AudioStreamType streamType = GetStreamType(sessionId); 785 if (!CheckStreamOffloadMode(sessionId, streamType)) { 786 return; 787 } 788 789 auto CallingUid = IPCSkeleton::GetCallingUid(); 790 AUDIO_INFO_LOG("sessionId[%{public}d] CallingUid[%{public}d] StreamType[%{public}d] " 791 "Getting offload stream", sessionId, CallingUid, streamType); 792 std::lock_guard<std::mutex> lock(offloadMutex_); 793 794 if (!offloadSessionID_.has_value()) { 795 offloadSessionID_ = sessionId; 796 audioPolicyManager_.SetOffloadSessionId(sessionId); 797 798 AUDIO_DEBUG_LOG("sessionId[%{public}d] try get offload stream", sessionId); 799 if (MoveToNewPipeInner(sessionId, PIPE_TYPE_OFFLOAD) != SUCCESS) { 800 AUDIO_ERR_LOG("sessionId[%{public}d] CallingUid[%{public}d] StreamType[%{public}d] " 801 "failed to offload stream", sessionId, CallingUid, streamType); 802 offloadSessionID_.reset(); 803 audioPolicyManager_.ResetOffloadSessionId(); 804 return; 805 } 806 SetOffloadMode(); 807 } else { 808 if (sessionId == *(offloadSessionID_)) { 809 AUDIO_DEBUG_LOG("sessionId[%{public}d] is already get offload stream", sessionId); 810 } else { 811 AUDIO_DEBUG_LOG("sessionId[%{public}d] no get offload, current offload sessionId[%{public}d]", 812 sessionId, *(offloadSessionID_)); 813 } 814 } 815 816 return; 817 } 818 OffloadStreamReleaseCheck(uint32_t sessionId)819 void AudioPolicyService::OffloadStreamReleaseCheck(uint32_t sessionId) 820 { 821 if (!GetOffloadAvailableFromXml()) { 822 AUDIO_INFO_LOG("Offload not available, skipped for release"); 823 return; 824 } 825 826 std::lock_guard<std::mutex> lock(offloadMutex_); 827 828 if (((*offloadSessionID_) == sessionId) && offloadSessionID_.has_value()) { 829 AUDIO_DEBUG_LOG("Doing unset offload mode!"); 830 streamCollector_.UnsetOffloadMode(*offloadSessionID_); 831 AudioPipeType normalPipe = PIPE_TYPE_NORMAL_OUT; 832 MoveToNewPipe(sessionId, normalPipe); 833 streamCollector_.UpdateRendererPipeInfo(sessionId, normalPipe); 834 DynamicUnloadModule(PIPE_TYPE_OFFLOAD); 835 offloadSessionID_.reset(); 836 audioPolicyManager_.ResetOffloadSessionId(); 837 AUDIO_DEBUG_LOG("sessionId[%{public}d] release offload stream", sessionId); 838 } else { 839 if (offloadSessionID_.has_value()) { 840 AUDIO_DEBUG_LOG("sessionId[%{public}d] stopping stream not get offload, current offload [%{public}d]", 841 sessionId, *offloadSessionID_); 842 } else { 843 AUDIO_DEBUG_LOG("sessionId[%{public}d] stopping stream not get offload, current offload stream is None", 844 sessionId); 845 } 846 } 847 return; 848 } 849 RemoteOffloadStreamRelease(uint32_t sessionId)850 void AudioPolicyService::RemoteOffloadStreamRelease(uint32_t sessionId) 851 { 852 std::lock_guard<std::mutex> lock(offloadMutex_); 853 if (offloadSessionID_.has_value() && ((*offloadSessionID_) == sessionId)) { 854 AUDIO_DEBUG_LOG("Doing unset offload mode!"); 855 streamCollector_.UnsetOffloadMode(*offloadSessionID_); 856 AudioPipeType normalPipe = PIPE_TYPE_UNKNOWN; 857 MoveToNewPipe(sessionId, normalPipe); 858 streamCollector_.UpdateRendererPipeInfo(sessionId, normalPipe); 859 DynamicUnloadModule(PIPE_TYPE_OFFLOAD); 860 offloadSessionID_.reset(); 861 audioPolicyManager_.ResetOffloadSessionId(); 862 AUDIO_DEBUG_LOG("sessionId[%{public}d] release offload stream", sessionId); 863 } 864 } 865 CheckActiveOutputDeviceSupportOffload()866 bool AudioPolicyService::CheckActiveOutputDeviceSupportOffload() 867 { 868 DeviceType dev = GetCurrentOutputDeviceType(); 869 if (GetCurrentOutputDeviceNetworkId() != LOCAL_NETWORK_ID || dev == DEVICE_TYPE_REMOTE_CAST) { 870 return false; 871 } 872 873 return dev == DEVICE_TYPE_SPEAKER || (dev == DEVICE_TYPE_BLUETOOTH_A2DP && a2dpOffloadFlag_ == A2DP_OFFLOAD) || 874 dev == DEVICE_TYPE_USB_HEADSET; 875 } 876 SetOffloadAvailableFromXML(AudioModuleInfo & moduleInfo)877 void AudioPolicyService::SetOffloadAvailableFromXML(AudioModuleInfo &moduleInfo) 878 { 879 if (moduleInfo.name == "Speaker") { 880 for (const auto &portInfo : moduleInfo.ports) { 881 if ((portInfo.adapterName == "primary") && (portInfo.offloadEnable == "1")) { 882 isOffloadAvailable_ = true; 883 } 884 } 885 } 886 } 887 GetOffloadAvailableFromXml() const888 bool AudioPolicyService::GetOffloadAvailableFromXml() const 889 { 890 return isOffloadAvailable_; 891 } 892 HandlePowerStateChanged(PowerMgr::PowerState state)893 void AudioPolicyService::HandlePowerStateChanged(PowerMgr::PowerState state) 894 { 895 if (currentPowerState_ == state) { 896 return; 897 } 898 currentPowerState_ = state; 899 if (!CheckActiveOutputDeviceSupportOffload()) { 900 return; 901 } 902 if (offloadSessionID_.has_value()) { 903 AUDIO_DEBUG_LOG("SetOffloadMode! Offload power is state = %{public}d", state); 904 SetOffloadMode(); 905 } 906 } 907 GetSingleStreamVolume(int32_t streamId) const908 float AudioPolicyService::GetSingleStreamVolume(int32_t streamId) const 909 { 910 return streamCollector_.GetSingleStreamVolume(streamId); 911 } 912 SetStreamMute(AudioStreamType streamType,bool mute,const StreamUsage & streamUsage)913 int32_t AudioPolicyService::SetStreamMute(AudioStreamType streamType, bool mute, const StreamUsage &streamUsage) 914 { 915 int32_t result = SUCCESS; 916 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 917 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && 918 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 919 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_); 920 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_); 921 if (configInfoPos == connectedA2dpDeviceMap_.end() || !configInfoPos->second.absVolumeSupport) { 922 AUDIO_WARNING_LOG("Set failed for macAddress:[%{public}s]", GetEncryptAddr(activeBTDevice_).c_str()); 923 } else { 924 configInfoPos->second.mute = mute; 925 audioPolicyManager_.SetAbsVolumeMute(mute); 926 #ifdef BLUETOOTH_ENABLE 927 // set to avrcp device 928 if (mute) { 929 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_, 0); 930 } else { 931 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(activeBTDevice_, 932 configInfoPos->second.volumeLevel); 933 } 934 #endif 935 } 936 } 937 result = audioPolicyManager_.SetStreamMute(streamType, mute, streamUsage); 938 939 Volume vol = {false, 1.0f, 0}; 940 vol.isMute = mute; 941 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevel(streamType)); 942 vol.volumeFloat = GetSystemVolumeInDb(streamType, vol.volumeInt, curOutputDeviceType); 943 SetSharedVolume(streamType, curOutputDeviceType, vol); 944 945 return result; 946 } 947 SetSourceOutputStreamMute(int32_t uid,bool setMute) const948 int32_t AudioPolicyService::SetSourceOutputStreamMute(int32_t uid, bool setMute) const 949 { 950 int32_t status = audioPolicyManager_.SetSourceOutputStreamMute(uid, setMute); 951 if (status > 0) { 952 streamCollector_.UpdateCapturerInfoMuteStatus(uid, setMute); 953 } 954 return status; 955 } 956 GetStreamMute(AudioStreamType streamType)957 bool AudioPolicyService::GetStreamMute(AudioStreamType streamType) 958 { 959 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 960 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && 961 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 962 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_); 963 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_); 964 if (configInfoPos == connectedA2dpDeviceMap_.end() || !configInfoPos->second.absVolumeSupport) { 965 AUDIO_WARNING_LOG("Get failed for macAddress:[%{public}s]", GetEncryptAddr(activeBTDevice_).c_str()); 966 } else { 967 return configInfoPos->second.mute; 968 } 969 } 970 return audioPolicyManager_.GetStreamMute(streamType); 971 } 972 PrintSinkInput(SinkInput sinkInput)973 inline std::string PrintSinkInput(SinkInput sinkInput) 974 { 975 std::stringstream value; 976 value << "streamId:[" << sinkInput.streamId << "] "; 977 value << "streamType:[" << sinkInput.streamType << "] "; 978 value << "uid:[" << sinkInput.uid << "] "; 979 value << "pid:[" << sinkInput.pid << "] "; 980 value << "statusMark:[" << sinkInput.statusMark << "] "; 981 value << "sinkName:[" << sinkInput.sinkName << "] "; 982 value << "startTime:[" << sinkInput.startTime << "]"; 983 return value.str(); 984 } 985 PrintSourceOutput(SourceOutput sourceOutput)986 inline std::string PrintSourceOutput(SourceOutput sourceOutput) 987 { 988 std::stringstream value; 989 value << "streamId:[" << sourceOutput.streamId << "] "; 990 value << "streamType:[" << sourceOutput.streamType << "] "; 991 value << "uid:[" << sourceOutput.uid << "] "; 992 value << "pid:[" << sourceOutput.pid << "] "; 993 value << "statusMark:[" << sourceOutput.statusMark << "] "; 994 value << "deviceSourceId:[" << sourceOutput.deviceSourceId << "] "; 995 value << "startTime:[" << sourceOutput.startTime << "]"; 996 return value.str(); 997 } 998 GetRemoteModuleName(std::string networkId,DeviceRole role)999 inline std::string GetRemoteModuleName(std::string networkId, DeviceRole role) 1000 { 1001 return networkId + (role == DeviceRole::OUTPUT_DEVICE ? "_out" : "_in"); 1002 } 1003 GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)1004 std::string AudioPolicyService::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType) 1005 { 1006 (void)streamType; 1007 1008 std::lock_guard<std::mutex> lock(routerMapMutex_); 1009 if (!routerMap_.count(uid)) { 1010 AUDIO_INFO_LOG("GetSelectedDeviceInfo no such uid[%{public}d]", uid); 1011 return ""; 1012 } 1013 std::string selectedDevice = ""; 1014 if (routerMap_[uid].second == pid) { 1015 selectedDevice = routerMap_[uid].first; 1016 } else if (routerMap_[uid].second == G_UNKNOWN_PID) { 1017 routerMap_[uid].second = pid; 1018 selectedDevice = routerMap_[uid].first; 1019 } else { 1020 AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d] changed pid, get local as defalut", uid); 1021 routerMap_.erase(uid); 1022 selectedDevice = LOCAL_NETWORK_ID; 1023 } 1024 1025 if (LOCAL_NETWORK_ID == selectedDevice) { 1026 AUDIO_INFO_LOG("GetSelectedDeviceInfo: uid[%{public}d]-->local.", uid); 1027 return ""; 1028 } 1029 // check if connected. 1030 bool isConnected = false; 1031 for (auto device : connectedDevices_) { 1032 if (GetRemoteModuleName(device->networkId_, device->deviceRole_) == selectedDevice) { 1033 isConnected = true; 1034 break; 1035 } 1036 } 1037 1038 if (isConnected) { 1039 AUDIO_INFO_LOG("GetSelectedDeviceInfo result[%{public}s]", selectedDevice.c_str()); 1040 return selectedDevice; 1041 } else { 1042 routerMap_.erase(uid); 1043 AUDIO_INFO_LOG("GetSelectedDeviceInfo device already disconnected."); 1044 return ""; 1045 } 1046 } 1047 NotifyRemoteRenderState(std::string networkId,std::string condition,std::string value)1048 void AudioPolicyService::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value) 1049 { 1050 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 1051 1052 AUDIO_INFO_LOG("device<%{public}s> condition:%{public}s value:%{public}s", 1053 GetEncryptStr(networkId).c_str(), condition.c_str(), value.c_str()); 1054 1055 vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs(); 1056 vector<SinkInput> targetSinkInputs = {}; 1057 for (auto sinkInput : sinkInputs) { 1058 if (sinkInput.sinkName == networkId) { 1059 targetSinkInputs.push_back(sinkInput); 1060 } 1061 } 1062 AUDIO_DEBUG_LOG("move [%{public}zu] of all [%{public}zu]sink-inputs to local.", 1063 targetSinkInputs.size(), sinkInputs.size()); 1064 sptr<AudioDeviceDescriptor> localDevice = new(std::nothrow) AudioDeviceDescriptor(); 1065 CHECK_AND_RETURN_LOG(localDevice != nullptr, "Device error: null device."); 1066 localDevice->networkId_ = LOCAL_NETWORK_ID; 1067 localDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE; 1068 localDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER; 1069 1070 int32_t ret; 1071 AudioDeviceDescriptor curOutputDeviceDesc = GetCurrentOutputDevice(); 1072 if (localDevice->deviceType_ != curOutputDeviceDesc.deviceType_) { 1073 AUDIO_WARNING_LOG("device[%{public}d] not active, use device[%{public}d] instead.", 1074 static_cast<int32_t>(localDevice->deviceType_), static_cast<int32_t>(curOutputDeviceDesc.deviceType_)); 1075 ret = MoveToLocalOutputDevice(targetSinkInputs, new AudioDeviceDescriptor(curOutputDeviceDesc)); 1076 } else { 1077 ret = MoveToLocalOutputDevice(targetSinkInputs, localDevice); 1078 } 1079 CHECK_AND_RETURN_LOG((ret == SUCCESS), "MoveToLocalOutputDevice failed!"); 1080 1081 // Suspend device, notify audio stream manager that device has been changed. 1082 ret = audioPolicyManager_.SuspendAudioDevice(networkId, true); 1083 CHECK_AND_RETURN_LOG((ret == SUCCESS), "SuspendAudioDevice failed!"); 1084 1085 std::vector<sptr<AudioDeviceDescriptor>> desc = {}; 1086 desc.push_back(localDevice); 1087 UpdateTrackerDeviceChange(desc); 1088 OnPreferredOutputDeviceUpdated(curOutputDeviceDesc); 1089 AUDIO_DEBUG_LOG("NotifyRemoteRenderState success"); 1090 } 1091 IsArmUsbDevice(const AudioDeviceDescriptor & desc)1092 bool AudioPolicyService::IsArmUsbDevice(const AudioDeviceDescriptor &desc) 1093 { 1094 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 1095 1096 return audioDeviceManager_.IsArmUsbDevice(desc); 1097 } 1098 IsDeviceConnected(sptr<AudioDeviceDescriptor> & audioDeviceDescriptors) const1099 bool AudioPolicyService::IsDeviceConnected(sptr<AudioDeviceDescriptor> &audioDeviceDescriptors) const 1100 { 1101 return audioDeviceManager_.IsDeviceConnected(audioDeviceDescriptors); 1102 } 1103 DeviceParamsCheck(DeviceRole targetRole,std::vector<sptr<AudioDeviceDescriptor>> & audioDeviceDescriptors) const1104 int32_t AudioPolicyService::DeviceParamsCheck(DeviceRole targetRole, 1105 std::vector<sptr<AudioDeviceDescriptor>> &audioDeviceDescriptors) const 1106 { 1107 size_t targetSize = audioDeviceDescriptors.size(); 1108 CHECK_AND_RETURN_RET_LOG(targetSize == 1, ERR_INVALID_OPERATION, 1109 "Device error: size[%{public}zu]", targetSize); 1110 1111 bool isDeviceTypeCorrect = false; 1112 if (targetRole == DeviceRole::OUTPUT_DEVICE) { 1113 isDeviceTypeCorrect = IsOutputDevice(audioDeviceDescriptors[0]->deviceType_) && 1114 IsDeviceConnected(audioDeviceDescriptors[0]); 1115 } else if (targetRole == DeviceRole::INPUT_DEVICE) { 1116 isDeviceTypeCorrect = IsInputDevice(audioDeviceDescriptors[0]->deviceType_) && 1117 IsDeviceConnected(audioDeviceDescriptors[0]); 1118 } 1119 1120 CHECK_AND_RETURN_RET_LOG(audioDeviceDescriptors[0]->deviceRole_ == targetRole && isDeviceTypeCorrect, 1121 ERR_INVALID_OPERATION, "Device error: size[%{public}zu] deviceRole[%{public}d] isDeviceCorrect[%{public}d]", 1122 targetSize, static_cast<int32_t>(audioDeviceDescriptors[0]->deviceRole_), isDeviceTypeCorrect); 1123 return SUCCESS; 1124 } 1125 NotifyUserSelectionEventToBt(sptr<AudioDeviceDescriptor> audioDeviceDescriptor)1126 void AudioPolicyService::NotifyUserSelectionEventToBt(sptr<AudioDeviceDescriptor> audioDeviceDescriptor) 1127 { 1128 Trace trace("AudioPolicyService::NotifyUserSelectionEventToBt"); 1129 if (audioDeviceDescriptor == nullptr) { 1130 return; 1131 } 1132 #ifdef BLUETOOTH_ENABLE 1133 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 1134 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_SCO || 1135 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 1136 Bluetooth::SendUserSelectionEvent(curOutputDeviceType, 1137 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT); 1138 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 1139 Bluetooth::AudioHfpManager::DisconnectSco(); 1140 } 1141 } 1142 if (audioDeviceDescriptor->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO || 1143 audioDeviceDescriptor->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { 1144 Bluetooth::SendUserSelectionEvent(audioDeviceDescriptor->deviceType_, 1145 audioDeviceDescriptor->macAddress_, USER_SELECT_BT); 1146 } 1147 #endif 1148 } 1149 SetRenderDeviceForUsage(StreamUsage streamUsage,sptr<AudioDeviceDescriptor> desc)1150 int32_t AudioPolicyService::SetRenderDeviceForUsage(StreamUsage streamUsage, sptr<AudioDeviceDescriptor> desc) 1151 { 1152 auto isPresent = [&desc] (const unique_ptr<AudioDeviceDescriptor> &device) { 1153 return (desc->deviceType_ == device->deviceType_) && 1154 (desc->macAddress_ == device->macAddress_) && 1155 (desc->networkId_ == device->networkId_); 1156 }; 1157 int32_t tempId = desc->deviceId_; 1158 if (streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || streamUsage == STREAM_USAGE_VOICE_MODEM_COMMUNICATION || 1159 streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) { 1160 std::vector<unique_ptr<AudioDeviceDescriptor>> devices = GetAvailableDevicesInner(CALL_OUTPUT_DEVICES); 1161 auto itr = std::find_if(devices.begin(), devices.end(), isPresent); 1162 CHECK_AND_RETURN_RET_LOG(itr != devices.end(), ERR_INVALID_OPERATION, 1163 "device not available type:%{public}d macAddress:%{public}s id:%{public}d networkId:%{public}s", 1164 desc->deviceType_, GetEncryptAddr(desc->macAddress_).c_str(), 1165 tempId, GetEncryptStr(desc->networkId_).c_str()); 1166 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor(**itr)); 1167 return SUCCESS; 1168 } else { 1169 std::vector<unique_ptr<AudioDeviceDescriptor>> devices = GetAvailableDevicesInner(MEDIA_OUTPUT_DEVICES); 1170 auto itr = std::find_if(devices.begin(), devices.end(), isPresent); 1171 CHECK_AND_RETURN_RET_LOG(itr != devices.end(), ERR_INVALID_OPERATION, 1172 "device not available type:%{public}d macAddress:%{public}s id:%{public}d networkId:%{public}s", 1173 desc->deviceType_, GetEncryptAddr(desc->macAddress_).c_str(), 1174 tempId, GetEncryptStr(desc->networkId_).c_str()); 1175 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor(**itr)); 1176 return SUCCESS; 1177 } 1178 } 1179 ConnectVirtualDevice(sptr<AudioDeviceDescriptor> & selectedDesc)1180 int32_t AudioPolicyService::ConnectVirtualDevice(sptr<AudioDeviceDescriptor> &selectedDesc) 1181 { 1182 int32_t ret = Bluetooth::AudioA2dpManager::Connect(selectedDesc->macAddress_); 1183 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "A2dp connect failed"); 1184 ret = Bluetooth::AudioHfpManager::Connect(selectedDesc->macAddress_); 1185 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Hfp connect failed"); 1186 AUDIO_INFO_LOG("Connect virtual device[%{public}s]", GetEncryptAddr(selectedDesc->macAddress_).c_str()); 1187 return SUCCESS; 1188 } 1189 SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<sptr<AudioDeviceDescriptor>> selectedDesc)1190 int32_t AudioPolicyService::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter, 1191 std::vector<sptr<AudioDeviceDescriptor>> selectedDesc) 1192 { 1193 Trace trace("AudioPolicyService::SelectOutputDevice"); 1194 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 1195 1196 AUDIO_WARNING_LOG("uid[%{public}d] type[%{public}d] mac[%{public}s] streamUsage[%{public}d] pid[%{public}d]", 1197 audioRendererFilter->uid, selectedDesc[0]->deviceType_, GetEncryptAddr(selectedDesc[0]->macAddress_).c_str(), 1198 audioRendererFilter->rendererInfo.streamUsage, IPCSkeleton::GetCallingPid()); 1199 1200 CHECK_AND_RETURN_RET_LOG((selectedDesc[0]->deviceRole_ == DeviceRole::OUTPUT_DEVICE) && 1201 (selectedDesc.size() == 1), ERR_INVALID_OPERATION, "DeviceCheck no success"); 1202 if (audioRendererFilter->rendererInfo.rendererFlags == STREAM_FLAG_FAST) { 1203 int32_t res = SetRenderDeviceForUsage(audioRendererFilter->rendererInfo.streamUsage, selectedDesc[0]); 1204 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, "SetRenderDeviceForUsage fail"); 1205 SelectFastOutputDevice(audioRendererFilter, selectedDesc[0]); 1206 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); 1207 return SUCCESS; 1208 } 1209 bool isVirtualDevice = false; 1210 if (selectedDesc[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP || 1211 selectedDesc[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 1212 selectedDesc[0]->isEnable_ = true; 1213 audioDeviceManager_.UpdateDevicesListInfo(selectedDesc[0], ENABLE_UPDATE); 1214 isVirtualDevice = audioDeviceManager_.IsVirtualConnectedDevice(selectedDesc[0]); 1215 if (isVirtualDevice == true) { 1216 selectedDesc[0]->connectState_ = VIRTUAL_CONNECTED; 1217 } 1218 } 1219 if (selectedDesc[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 1220 ClearScoDeviceSuspendState(selectedDesc[0]->macAddress_); 1221 } 1222 StreamUsage strUsage = audioRendererFilter->rendererInfo.streamUsage; 1223 int32_t res = SetRenderDeviceForUsage(strUsage, selectedDesc[0]); 1224 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, "SetRenderDeviceForUsage fail"); 1225 1226 // If the selected device is virtual device, connect it. 1227 if (isVirtualDevice) { 1228 int32_t ret = ConnectVirtualDevice(selectedDesc[0]); 1229 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Connect device [%{public}s] failed", 1230 GetEncryptStr(selectedDesc[0]->macAddress_).c_str()); 1231 return SUCCESS; 1232 } 1233 1234 NotifyUserSelectionEventToBt(selectedDesc[0]); 1235 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); 1236 FetchDevice(false); 1237 if ((selectedDesc[0]->deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP) || 1238 (selectedDesc[0]->networkId_ != LOCAL_NETWORK_ID)) { 1239 UpdateOffloadWhenActiveDeviceSwitchFromA2dp(); 1240 } else { 1241 UpdateA2dpOffloadFlagForAllStream(selectedDesc[0]->deviceType_); 1242 } 1243 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice()); 1244 WriteSelectOutputSysEvents(selectedDesc, strUsage); 1245 return SUCCESS; 1246 } 1247 WriteSelectOutputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> & selectedDesc,StreamUsage strUsage)1248 void AudioPolicyService::WriteSelectOutputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc, 1249 StreamUsage strUsage) 1250 { 1251 auto uid = IPCSkeleton::GetCallingUid(); 1252 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 1253 Media::MediaMonitor::AUDIO, Media::MediaMonitor::SET_FORCE_USE_AUDIO_DEVICE, 1254 Media::MediaMonitor::BEHAVIOR_EVENT); 1255 AudioDeviceDescriptor curOutputDeviceDesc = GetCurrentOutputDevice(); 1256 bean->Add("CLIENT_UID", static_cast<int32_t>(uid)); 1257 bean->Add("DEVICE_TYPE", curOutputDeviceDesc.deviceType_); 1258 bean->Add("STREAM_TYPE", strUsage); 1259 bean->Add("BT_TYPE", curOutputDeviceDesc.deviceCategory_); 1260 bean->Add("DEVICE_NAME", curOutputDeviceDesc.deviceName_); 1261 bean->Add("ADDRESS", curOutputDeviceDesc.macAddress_); 1262 bean->Add("IS_PLAYBACK", 1); 1263 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 1264 } 1265 SelectFastOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)1266 int32_t AudioPolicyService::SelectFastOutputDevice(sptr<AudioRendererFilter> audioRendererFilter, 1267 sptr<AudioDeviceDescriptor> deviceDescriptor) 1268 { 1269 AUDIO_INFO_LOG("Start for uid[%{public}d] device[%{public}s]", audioRendererFilter->uid, 1270 GetEncryptStr(deviceDescriptor->networkId_).c_str()); 1271 // note: check if stream is already running 1272 // if is running, call moveProcessToEndpoint. 1273 1274 // otherwises, keep router info in the map 1275 std::lock_guard<std::mutex> lock(routerMapMutex_); 1276 fastRouterMap_[audioRendererFilter->uid] = std::make_pair(deviceDescriptor->networkId_, OUTPUT_DEVICE); 1277 return SUCCESS; 1278 } 1279 FilterSinkInputs(int32_t sessionId)1280 std::vector<SinkInput> AudioPolicyService::FilterSinkInputs(int32_t sessionId) 1281 { 1282 // find sink-input id with audioRendererFilter 1283 std::vector<SinkInput> targetSinkInputs = {}; 1284 std::vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs(); 1285 1286 for (size_t i = 0; i < sinkInputs.size(); i++) { 1287 CHECK_AND_CONTINUE_LOG(sinkInputs[i].uid != dAudioClientUid, 1288 "Find sink-input with daudio[%{public}d]", sinkInputs[i].pid); 1289 CHECK_AND_CONTINUE_LOG(sinkInputs[i].streamType != STREAM_DEFAULT, 1290 "Sink-input[%{public}zu] of effect sink, don't move", i); 1291 AUDIO_DEBUG_LOG("sinkinput[%{public}zu]:%{public}s", i, PrintSinkInput(sinkInputs[i]).c_str()); 1292 if (sessionId == sinkInputs[i].streamId) { 1293 targetSinkInputs.push_back(sinkInputs[i]); 1294 } 1295 } 1296 return targetSinkInputs; 1297 } 1298 FilterSourceOutputs(int32_t sessionId)1299 std::vector<SourceOutput> AudioPolicyService::FilterSourceOutputs(int32_t sessionId) 1300 { 1301 std::vector<SourceOutput> targetSourceOutputs = {}; 1302 std::vector<SourceOutput> sourceOutputs; 1303 { 1304 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 1305 if (std::any_of(IOHandles_.cbegin(), IOHandles_.cend(), [](const auto &pair) { 1306 return std::find(SourceNames.cbegin(), SourceNames.cend(), pair.first) != SourceNames.cend(); 1307 })) { 1308 sourceOutputs = audioPolicyManager_.GetAllSourceOutputs(); 1309 } 1310 } 1311 1312 for (size_t i = 0; i < sourceOutputs.size(); i++) { 1313 AUDIO_DEBUG_LOG("sourceOutput[%{public}zu]:%{public}s", i, PrintSourceOutput(sourceOutputs[i]).c_str()); 1314 if (sessionId == sourceOutputs[i].streamId) { 1315 targetSourceOutputs.push_back(sourceOutputs[i]); 1316 } 1317 } 1318 return targetSourceOutputs; 1319 } 1320 FilterSinkInputs(sptr<AudioRendererFilter> audioRendererFilter,bool moveAll)1321 std::vector<SinkInput> AudioPolicyService::FilterSinkInputs(sptr<AudioRendererFilter> audioRendererFilter, 1322 bool moveAll) 1323 { 1324 int32_t targetUid = audioRendererFilter->uid; 1325 AudioStreamType targetStreamType = audioRendererFilter->streamType; 1326 // find sink-input id with audioRendererFilter 1327 std::vector<SinkInput> targetSinkInputs = {}; 1328 std::vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs(); 1329 1330 for (size_t i = 0; i < sinkInputs.size(); i++) { 1331 CHECK_AND_CONTINUE_LOG(sinkInputs[i].uid != dAudioClientUid, 1332 "Find sink-input with daudio[%{public}d]", sinkInputs[i].pid); 1333 CHECK_AND_CONTINUE_LOG(sinkInputs[i].streamType != STREAM_DEFAULT, 1334 "Sink-input[%{public}zu] of effect sink, don't move", i); 1335 AUDIO_DEBUG_LOG("sinkinput[%{public}zu]:%{public}s", i, PrintSinkInput(sinkInputs[i]).c_str()); 1336 if (moveAll || (targetUid == sinkInputs[i].uid && targetStreamType == sinkInputs[i].streamType)) { 1337 targetSinkInputs.push_back(sinkInputs[i]); 1338 } 1339 } 1340 return targetSinkInputs; 1341 } 1342 RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)1343 int32_t AudioPolicyService::RememberRoutingInfo(sptr<AudioRendererFilter> audioRendererFilter, 1344 sptr<AudioDeviceDescriptor> deviceDescriptor) 1345 { 1346 AUDIO_INFO_LOG("Start for uid[%{public}d] device[%{public}s]", audioRendererFilter->uid, 1347 GetEncryptStr(deviceDescriptor->networkId_).c_str()); 1348 if (deviceDescriptor->networkId_ == LOCAL_NETWORK_ID) { 1349 std::lock_guard<std::mutex> lock(routerMapMutex_); 1350 routerMap_[audioRendererFilter->uid] = std::pair(LOCAL_NETWORK_ID, G_UNKNOWN_PID); 1351 return SUCCESS; 1352 } 1353 // remote device. 1354 std::string networkId = deviceDescriptor->networkId_; 1355 DeviceRole deviceRole = deviceDescriptor->deviceRole_; 1356 1357 std::string moduleName = GetRemoteModuleName(networkId, deviceRole); 1358 CHECK_AND_RETURN_RET_LOG(IOHandles_.count(moduleName), ERR_INVALID_PARAM, 1359 "Device error: no such device:%{public}s", networkId.c_str()); 1360 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 1361 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable"); 1362 std::string identity = IPCSkeleton::ResetCallingIdentity(); 1363 int32_t ret = gsp->CheckRemoteDeviceState(networkId, deviceRole, true); 1364 IPCSkeleton::SetCallingIdentity(identity); 1365 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!"); 1366 1367 std::lock_guard<std::mutex> lock(routerMapMutex_); 1368 routerMap_[audioRendererFilter->uid] = std::pair(moduleName, G_UNKNOWN_PID); 1369 return SUCCESS; 1370 } 1371 MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> localDeviceDescriptor)1372 int32_t AudioPolicyService::MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds, 1373 sptr<AudioDeviceDescriptor> localDeviceDescriptor) 1374 { 1375 AUDIO_INFO_LOG("MoveToLocalOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size()); 1376 // check 1377 CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_, 1378 ERR_INVALID_OPERATION, "MoveToLocalOutputDevice failed: not a local device."); 1379 1380 // start move. 1381 uint32_t sinkId = -1; // invalid sink id, use sink name instead. 1382 for (size_t i = 0; i < sinkInputIds.size(); i++) { 1383 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN; 1384 streamCollector_.GetPipeType(sinkInputIds[i].streamId, pipeType); 1385 std::string sinkName = GetSinkPortName(localDeviceDescriptor->deviceType_, pipeType); 1386 if (sinkName == BLUETOOTH_SPEAKER) { 1387 std::string activePort = BLUETOOTH_SPEAKER; 1388 audioPolicyManager_.SuspendAudioDevice(activePort, false); 1389 } 1390 AUDIO_INFO_LOG("move for session [%{public}d], portName %{public}s pipeType %{public}d", 1391 sinkInputIds[i].streamId, sinkName.c_str(), pipeType); 1392 int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, sinkName); 1393 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, 1394 "move [%{public}d] to local failed", sinkInputIds[i].streamId); 1395 std::lock_guard<std::mutex> lock(routerMapMutex_); 1396 routerMap_[sinkInputIds[i].uid] = std::pair(LOCAL_NETWORK_ID, sinkInputIds[i].pid); 1397 } 1398 1399 isCurrentRemoteRenderer = false; 1400 return SUCCESS; 1401 } 1402 OpenRemoteAudioDevice(std::string networkId,DeviceRole deviceRole,DeviceType deviceType,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1403 int32_t AudioPolicyService::OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType, 1404 sptr<AudioDeviceDescriptor> remoteDeviceDescriptor) 1405 { 1406 // open the test device. We should open it when device is online. 1407 std::string moduleName = GetRemoteModuleName(networkId, deviceRole); 1408 AudioModuleInfo remoteDeviceInfo = ConstructRemoteAudioModuleInfo(networkId, deviceRole, deviceType); 1409 OpenPortAndInsertIOHandle(moduleName, remoteDeviceInfo); 1410 1411 // If device already in list, remove it else do not modify the list. 1412 auto isPresent = [&deviceType, &networkId] (const sptr<AudioDeviceDescriptor> &descriptor) { 1413 return descriptor->deviceType_ == deviceType && descriptor->networkId_ == networkId; 1414 }; 1415 1416 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent), 1417 connectedDevices_.end()); 1418 UpdateDisplayName(remoteDeviceDescriptor); 1419 connectedDevices_.insert(connectedDevices_.begin(), remoteDeviceDescriptor); 1420 AddMicrophoneDescriptor(remoteDeviceDescriptor); 1421 return SUCCESS; 1422 } 1423 MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1424 int32_t AudioPolicyService::MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds, 1425 sptr<AudioDeviceDescriptor> remoteDeviceDescriptor) 1426 { 1427 AUDIO_INFO_LOG("MoveToRemoteOutputDevice for [%{public}zu] sink-inputs", sinkInputIds.size()); 1428 1429 std::string networkId = remoteDeviceDescriptor->networkId_; 1430 DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_; 1431 DeviceType deviceType = remoteDeviceDescriptor->deviceType_; 1432 1433 // check: networkid 1434 CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION, 1435 "MoveToRemoteOutputDevice failed: not a remote device."); 1436 1437 uint32_t sinkId = -1; // invalid sink id, use sink name instead. 1438 std::string moduleName = GetRemoteModuleName(networkId, deviceRole); 1439 if (IOHandles_.count(moduleName)) { 1440 IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id. 1441 } else { 1442 AUDIO_ERR_LOG("no such device."); 1443 if (!isOpenRemoteDevice) { 1444 return ERR_INVALID_PARAM; 1445 } else { 1446 return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor); 1447 } 1448 } 1449 1450 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 1451 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable"); 1452 std::string identity = IPCSkeleton::ResetCallingIdentity(); 1453 int32_t res = gsp->CheckRemoteDeviceState(networkId, deviceRole, true); 1454 IPCSkeleton::SetCallingIdentity(identity); 1455 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!"); 1456 1457 // start move. 1458 for (size_t i = 0; i < sinkInputIds.size(); i++) { 1459 int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, moduleName); 1460 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "move [%{public}d] failed", sinkInputIds[i].streamId); 1461 std::lock_guard<std::mutex> lock(routerMapMutex_); 1462 routerMap_[sinkInputIds[i].uid] = std::pair(moduleName, sinkInputIds[i].pid); 1463 } 1464 1465 if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) { 1466 AUDIO_WARNING_LOG("Not defult type[%{public}d] on device:[%{public}s]", 1467 deviceType, GetEncryptStr(networkId).c_str()); 1468 } 1469 isCurrentRemoteRenderer = true; 1470 return SUCCESS; 1471 } 1472 SelectFastInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,sptr<AudioDeviceDescriptor> deviceDescriptor)1473 int32_t AudioPolicyService::SelectFastInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter, 1474 sptr<AudioDeviceDescriptor> deviceDescriptor) 1475 { 1476 // note: check if stream is already running 1477 // if is running, call moveProcessToEndpoint. 1478 1479 // otherwises, keep router info in the map 1480 std::lock_guard<std::mutex> lock(routerMapMutex_); 1481 fastRouterMap_[audioCapturerFilter->uid] = std::make_pair(deviceDescriptor->networkId_, INPUT_DEVICE); 1482 AUDIO_INFO_LOG("Success for uid[%{public}d] device[%{public}s]", audioCapturerFilter->uid, 1483 GetEncryptStr(deviceDescriptor->networkId_).c_str()); 1484 return SUCCESS; 1485 } 1486 SetCaptureDeviceForUsage(AudioScene scene,SourceType srcType,sptr<AudioDeviceDescriptor> desc)1487 void AudioPolicyService::SetCaptureDeviceForUsage(AudioScene scene, SourceType srcType, 1488 sptr<AudioDeviceDescriptor> desc) 1489 { 1490 AUDIO_INFO_LOG("Scene: %{public}d, srcType: %{public}d", scene, srcType); 1491 if (scene == AUDIO_SCENE_PHONE_CALL || scene == AUDIO_SCENE_PHONE_CHAT || 1492 srcType == SOURCE_TYPE_VOICE_COMMUNICATION) { 1493 SetPreferredDevice(AUDIO_CALL_CAPTURE, desc); 1494 } else { 1495 SetPreferredDevice(AUDIO_RECORD_CAPTURE, desc); 1496 } 1497 } 1498 SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<sptr<AudioDeviceDescriptor>> selectedDesc)1499 int32_t AudioPolicyService::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter, 1500 std::vector<sptr<AudioDeviceDescriptor>> selectedDesc) 1501 { 1502 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 1503 1504 AUDIO_WARNING_LOG("uid[%{public}d] type[%{public}d] mac[%{public}s] pid[%{public}d]", 1505 audioCapturerFilter->uid, selectedDesc[0]->deviceType_, 1506 GetEncryptAddr(selectedDesc[0]->macAddress_).c_str(), IPCSkeleton::GetCallingPid()); 1507 // check size == 1 && input device 1508 int32_t res = DeviceParamsCheck(DeviceRole::INPUT_DEVICE, selectedDesc); 1509 CHECK_AND_RETURN_RET(res == SUCCESS, res); 1510 1511 SourceType srcType = audioCapturerFilter->capturerInfo.sourceType; 1512 1513 if (audioCapturerFilter->capturerInfo.capturerFlags == STREAM_FLAG_FAST && selectedDesc.size() == 1) { 1514 SetCaptureDeviceForUsage(GetAudioScene(true), srcType, selectedDesc[0]); 1515 SelectFastInputDevice(audioCapturerFilter, selectedDesc[0]); 1516 FetchDevice(false); 1517 return SUCCESS; 1518 } 1519 1520 AudioScene scene = GetAudioScene(true); 1521 if (scene == AUDIO_SCENE_PHONE_CALL || scene == AUDIO_SCENE_PHONE_CHAT || 1522 srcType == SOURCE_TYPE_VOICE_COMMUNICATION) { 1523 SetPreferredDevice(AUDIO_CALL_CAPTURE, selectedDesc[0]); 1524 } else { 1525 SetPreferredDevice(AUDIO_RECORD_CAPTURE, selectedDesc[0]); 1526 } 1527 FetchDevice(false); 1528 1529 WriteSelectInputSysEvents(selectedDesc, srcType, scene); 1530 1531 return SUCCESS; 1532 } 1533 WriteSelectInputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> & selectedDesc,SourceType srcType,AudioScene scene)1534 void AudioPolicyService::WriteSelectInputSysEvents(const std::vector<sptr<AudioDeviceDescriptor>> &selectedDesc, 1535 SourceType srcType, AudioScene scene) 1536 { 1537 auto uid = IPCSkeleton::GetCallingUid(); 1538 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 1539 Media::MediaMonitor::AUDIO, Media::MediaMonitor::SET_FORCE_USE_AUDIO_DEVICE, 1540 Media::MediaMonitor::BEHAVIOR_EVENT); 1541 bean->Add("CLIENT_UID", static_cast<int32_t>(uid)); 1542 bean->Add("DEVICE_TYPE", selectedDesc[0]->deviceType_); 1543 bean->Add("STREAM_TYPE", srcType); 1544 bean->Add("BT_TYPE", selectedDesc[0]->deviceCategory_); 1545 bean->Add("DEVICE_NAME", selectedDesc[0]->deviceName_); 1546 bean->Add("ADDRESS", selectedDesc[0]->macAddress_); 1547 bean->Add("AUDIO_SCENE", scene); 1548 bean->Add("IS_PLAYBACK", 0); 1549 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 1550 } 1551 MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputs,sptr<AudioDeviceDescriptor> localDeviceDescriptor)1552 int32_t AudioPolicyService::MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputs, 1553 sptr<AudioDeviceDescriptor> localDeviceDescriptor) 1554 { 1555 AUDIO_DEBUG_LOG("MoveToLocalInputDevice start"); 1556 // check 1557 CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_, ERR_INVALID_OPERATION, 1558 "MoveToLocalInputDevice failed: not a local device."); 1559 // start move. 1560 uint32_t sourceId = -1; // invalid source id, use source name instead. 1561 std::string sourceName = GetSourcePortName(localDeviceDescriptor->deviceType_); 1562 for (size_t i = 0; i < sourceOutputs.size(); i++) { 1563 int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId, 1564 sourceId, sourceName); 1565 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, 1566 "move [%{public}d] to local failed", sourceOutputs[i].paStreamId); 1567 } 1568 1569 return SUCCESS; 1570 } 1571 MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputs,sptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1572 int32_t AudioPolicyService::MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputs, 1573 sptr<AudioDeviceDescriptor> remoteDeviceDescriptor) 1574 { 1575 AUDIO_INFO_LOG("MoveToRemoteInputDevice start"); 1576 1577 std::string networkId = remoteDeviceDescriptor->networkId_; 1578 DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_; 1579 DeviceType deviceType = remoteDeviceDescriptor->deviceType_; 1580 1581 // check: networkid 1582 CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION, 1583 "MoveToRemoteInputDevice failed: not a remote device."); 1584 1585 uint32_t sourceId = -1; // invalid sink id, use sink name instead. 1586 std::string moduleName = GetRemoteModuleName(networkId, deviceRole); 1587 1588 std::unique_lock<std::mutex> ioHandleLock(ioHandlesMutex_); 1589 if (IOHandles_.count(moduleName)) { 1590 IOHandles_[moduleName]; // mIOHandle is module id, not equal to sink id. 1591 ioHandleLock.unlock(); 1592 } else { 1593 ioHandleLock.unlock(); 1594 AUDIO_ERR_LOG("no such device."); 1595 if (!isOpenRemoteDevice) { 1596 return ERR_INVALID_PARAM; 1597 } else { 1598 return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor); 1599 } 1600 } 1601 1602 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 1603 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable"); 1604 std::string identity = IPCSkeleton::ResetCallingIdentity(); 1605 int32_t res = gsp->CheckRemoteDeviceState(networkId, deviceRole, true); 1606 IPCSkeleton::SetCallingIdentity(identity); 1607 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, ERR_OPERATION_FAILED, "remote device state is invalid!"); 1608 1609 // start move. 1610 for (size_t i = 0; i < sourceOutputs.size(); i++) { 1611 int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId, 1612 sourceId, moduleName); 1613 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, 1614 "move [%{public}d] failed", sourceOutputs[i].paStreamId); 1615 } 1616 1617 if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) { 1618 AUDIO_DEBUG_LOG("Not defult type[%{public}d] on device:[%{public}s]", 1619 deviceType, GetEncryptStr(networkId).c_str()); 1620 } 1621 return SUCCESS; 1622 } 1623 IsStreamActive(AudioStreamType streamType) const1624 bool AudioPolicyService::IsStreamActive(AudioStreamType streamType) const 1625 { 1626 CHECK_AND_RETURN_RET(streamType != STREAM_VOICE_CALL || audioScene_ != AUDIO_SCENE_PHONE_CALL, true); 1627 1628 return streamCollector_.IsStreamActive(streamType); 1629 } 1630 ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor,CastType type)1631 void AudioPolicyService::ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor, CastType type) 1632 { 1633 sptr<AudioDeviceDescriptor> intermediateDescriptor = new AudioDeviceDescriptor(descriptor); 1634 StoreDistributedRoutingRoleInfo(intermediateDescriptor, type); 1635 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); 1636 FetchDevice(false); 1637 } 1638 StoreDistributedRoutingRoleInfo(const sptr<AudioDeviceDescriptor> descriptor,CastType type)1639 void AudioPolicyService::StoreDistributedRoutingRoleInfo(const sptr<AudioDeviceDescriptor> descriptor, CastType type) 1640 { 1641 distributedRoutingInfo_.descriptor = descriptor; 1642 distributedRoutingInfo_.type = type; 1643 } 1644 GetDistributedRoutingRoleInfo()1645 DistributedRoutingInfo AudioPolicyService::GetDistributedRoutingRoleInfo() 1646 { 1647 return distributedRoutingInfo_; 1648 } 1649 GetSinkPortName(InternalDeviceType deviceType,AudioPipeType pipeType)1650 std::string AudioPolicyService::GetSinkPortName(InternalDeviceType deviceType, AudioPipeType pipeType) 1651 { 1652 std::string portName = PORT_NONE; 1653 switch (deviceType) { 1654 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP: 1655 // BTH tells us that a2dpoffload is OK 1656 if (a2dpOffloadFlag_ == A2DP_OFFLOAD) { 1657 portName = PRIMARY_SPEAKER; 1658 if (pipeType == PIPE_TYPE_OFFLOAD) { 1659 portName = OFFLOAD_PRIMARY_SPEAKER; 1660 } else if (pipeType == PIPE_TYPE_MULTICHANNEL) { 1661 portName = MCH_PRIMARY_SPEAKER; 1662 } 1663 } else { 1664 portName = BLUETOOTH_SPEAKER; 1665 } 1666 break; 1667 case InternalDeviceType::DEVICE_TYPE_EARPIECE: 1668 case InternalDeviceType::DEVICE_TYPE_SPEAKER: 1669 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET: 1670 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES: 1671 case InternalDeviceType::DEVICE_TYPE_USB_HEADSET: 1672 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: 1673 if (pipeType == PIPE_TYPE_OFFLOAD) { 1674 portName = OFFLOAD_PRIMARY_SPEAKER; 1675 } else if (pipeType == PIPE_TYPE_MULTICHANNEL) { 1676 portName = MCH_PRIMARY_SPEAKER; 1677 } else { 1678 portName = PRIMARY_SPEAKER; 1679 } 1680 break; 1681 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET: 1682 portName = USB_SPEAKER; 1683 break; 1684 case InternalDeviceType::DEVICE_TYPE_DP: 1685 portName = DP_SINK; 1686 break; 1687 case InternalDeviceType::DEVICE_TYPE_FILE_SINK: 1688 portName = FILE_SINK; 1689 break; 1690 case InternalDeviceType::DEVICE_TYPE_REMOTE_CAST: 1691 portName = REMOTE_CAST_INNER_CAPTURER_SINK_NAME; 1692 break; 1693 default: 1694 portName = PORT_NONE; 1695 break; 1696 } 1697 1698 return portName; 1699 } 1700 GetSourcePortName(InternalDeviceType deviceType)1701 std::string AudioPolicyService::GetSourcePortName(InternalDeviceType deviceType) 1702 { 1703 std::string portName = PORT_NONE; 1704 switch (deviceType) { 1705 case InternalDeviceType::DEVICE_TYPE_MIC: 1706 case InternalDeviceType::DEVICE_TYPE_USB_HEADSET: 1707 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: 1708 portName = PRIMARY_MIC; 1709 break; 1710 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET: 1711 portName = USB_MIC; 1712 break; 1713 case InternalDeviceType::DEVICE_TYPE_WAKEUP: 1714 portName = PRIMARY_WAKEUP; 1715 break; 1716 case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE: 1717 portName = FILE_SOURCE; 1718 break; 1719 default: 1720 portName = PORT_NONE; 1721 break; 1722 } 1723 1724 return portName; 1725 } 1726 1727 // private method ConstructRemoteAudioModuleInfo(std::string networkId,DeviceRole deviceRole,DeviceType deviceType)1728 AudioModuleInfo AudioPolicyService::ConstructRemoteAudioModuleInfo(std::string networkId, DeviceRole deviceRole, 1729 DeviceType deviceType) 1730 { 1731 AudioModuleInfo audioModuleInfo = {}; 1732 if (deviceRole == DeviceRole::OUTPUT_DEVICE) { 1733 audioModuleInfo.lib = "libmodule-hdi-sink.z.so"; 1734 audioModuleInfo.format = "s16le"; // 16bit little endian 1735 audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size. 1736 audioModuleInfo.renderInIdleState = "1"; 1737 } else if (deviceRole == DeviceRole::INPUT_DEVICE) { 1738 audioModuleInfo.lib = "libmodule-hdi-source.z.so"; 1739 audioModuleInfo.format = "s16le"; // we assume it is bigger endian 1740 } else { 1741 AUDIO_WARNING_LOG("Invalid flag provided %{public}d", static_cast<int32_t>(deviceType)); 1742 } 1743 1744 // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink. 1745 audioModuleInfo.name = GetRemoteModuleName(networkId, deviceRole); 1746 audioModuleInfo.networkId = networkId; 1747 1748 std::stringstream typeValue; 1749 typeValue << static_cast<int32_t>(deviceType); 1750 audioModuleInfo.deviceType = typeValue.str(); 1751 1752 audioModuleInfo.adapterName = "remote"; 1753 audioModuleInfo.className = "remote"; // used in renderer_sink_adapter.c 1754 audioModuleInfo.fileName = "remote_dump_file"; 1755 1756 audioModuleInfo.channels = "2"; 1757 audioModuleInfo.rate = "48000"; 1758 audioModuleInfo.bufferSize = "3840"; 1759 1760 return audioModuleInfo; 1761 } 1762 MoveToOutputDevice(uint32_t sessionId,std::string portName)1763 int32_t AudioPolicyService::MoveToOutputDevice(uint32_t sessionId, std::string portName) 1764 { 1765 std::vector<SinkInput> sinkInputIds = FilterSinkInputs(sessionId); 1766 1767 if (portName == BLUETOOTH_SPEAKER) { 1768 std::string activePort = BLUETOOTH_SPEAKER; 1769 audioPolicyManager_.SuspendAudioDevice(activePort, false); 1770 } 1771 AUDIO_INFO_LOG("move for session [%{public}d], portName %{public}s", sessionId, portName.c_str()); 1772 // start move. 1773 uint32_t sinkId = -1; // invalid sink id, use sink name instead. 1774 for (size_t i = 0; i < sinkInputIds.size(); i++) { 1775 int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, portName); 1776 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, 1777 "move [%{public}d] to local failed", sinkInputIds[i].streamId); 1778 std::lock_guard<std::mutex> lock(routerMapMutex_); 1779 routerMap_[sinkInputIds[i].uid] = std::pair(LOCAL_NETWORK_ID, sinkInputIds[i].pid); 1780 } 1781 return SUCCESS; 1782 } 1783 1784 // private method FillWakeupStreamPropInfo(const AudioStreamInfo & streamInfo,PipeInfo * pipeInfo,AudioModuleInfo & audioModuleInfo)1785 bool AudioPolicyService::FillWakeupStreamPropInfo(const AudioStreamInfo &streamInfo, PipeInfo *pipeInfo, 1786 AudioModuleInfo &audioModuleInfo) 1787 { 1788 if (pipeInfo == nullptr) { 1789 AUDIO_ERR_LOG("wakeup pipe info is nullptr"); 1790 return false; 1791 } 1792 1793 if (pipeInfo->streamPropInfos_.size() == 0) { 1794 AUDIO_ERR_LOG("no stream prop info"); 1795 return false; 1796 } 1797 1798 auto targetIt = pipeInfo->streamPropInfos_.begin(); 1799 for (auto it = pipeInfo->streamPropInfos_.begin(); it != pipeInfo->streamPropInfos_.end(); ++it) { 1800 if (it -> channelLayout_ == static_cast<uint32_t>(streamInfo.channels)) { 1801 AUDIO_INFO_LOG("find target pipe info"); 1802 targetIt = it; 1803 break; 1804 } 1805 } 1806 1807 audioModuleInfo.format = targetIt->format_; 1808 audioModuleInfo.channels = std::to_string(targetIt->channelLayout_); 1809 audioModuleInfo.rate = std::to_string(targetIt->sampleRate_); 1810 audioModuleInfo.bufferSize = std::to_string(targetIt->bufferSize_); 1811 1812 AUDIO_INFO_LOG("stream prop info, format:%{public}s, channels:%{public}s, rate:%{public}s, buffer size:%{public}s", 1813 audioModuleInfo.format.c_str(), audioModuleInfo.channels.c_str(), 1814 audioModuleInfo.rate.c_str(), audioModuleInfo.bufferSize.c_str()); 1815 return true; 1816 } 1817 ConstructWakeupAudioModuleInfo(const AudioStreamInfo & streamInfo,AudioModuleInfo & audioModuleInfo)1818 bool AudioPolicyService::ConstructWakeupAudioModuleInfo(const AudioStreamInfo &streamInfo, 1819 AudioModuleInfo &audioModuleInfo) 1820 { 1821 if (!isAdapterInfoMap_.load()) { 1822 return false; 1823 } 1824 auto it = adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[std::string(PRIMARY_WAKEUP)])); 1825 if (it == adapterInfoMap_.end()) { 1826 AUDIO_ERR_LOG("can not find adapter info"); 1827 return false; 1828 } 1829 1830 auto pipeInfo = it->second.GetPipeByName(PIPE_WAKEUP_INPUT); 1831 if (pipeInfo == nullptr) { 1832 AUDIO_ERR_LOG("wakeup pipe info is nullptr"); 1833 return false; 1834 } 1835 1836 if (!FillWakeupStreamPropInfo(streamInfo, pipeInfo, audioModuleInfo)) { 1837 AUDIO_ERR_LOG("failed to fill pipe stream prop info"); 1838 return false; 1839 } 1840 1841 audioModuleInfo.adapterName = it->second.adapterName_; 1842 audioModuleInfo.name = pipeInfo->moduleName_; 1843 audioModuleInfo.lib = pipeInfo->lib_; 1844 audioModuleInfo.networkId = "LocalDevice"; 1845 audioModuleInfo.className = "primary"; 1846 audioModuleInfo.fileName = ""; 1847 audioModuleInfo.OpenMicSpeaker = "1"; 1848 audioModuleInfo.sourceType = std::to_string(SourceType::SOURCE_TYPE_WAKEUP); 1849 1850 AUDIO_INFO_LOG("wakeup auido module info, adapter name:%{public}s, name:%{public}s, lib:%{public}s", 1851 audioModuleInfo.adapterName.c_str(), audioModuleInfo.name.c_str(), audioModuleInfo.lib.c_str()); 1852 return true; 1853 } 1854 OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor & deviceDescriptor)1855 void AudioPolicyService::OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor) 1856 { 1857 Trace trace("AudioPolicyService::OnPreferredOutputDeviceUpdated:" + std::to_string(deviceDescriptor.deviceType_)); 1858 AUDIO_INFO_LOG("OnPreferredOutputDeviceUpdated start"); 1859 1860 if (audioPolicyServerHandler_ != nullptr) { 1861 audioPolicyServerHandler_->SendPreferredOutputDeviceUpdated(); 1862 } 1863 spatialDeviceMap_.insert(make_pair(deviceDescriptor.macAddress_, deviceDescriptor.deviceType_)); 1864 1865 if (deviceDescriptor.macAddress_ != 1866 AudioSpatializationService::GetAudioSpatializationService().GetCurrentDeviceAddress()) { 1867 UpdateEffectBtOffloadSupported(false); 1868 } 1869 UpdateEffectDefaultSink(deviceDescriptor.deviceType_); 1870 AudioSpatializationService::GetAudioSpatializationService().UpdateCurrentDevice(deviceDescriptor.macAddress_); 1871 } 1872 OnPreferredInputDeviceUpdated(DeviceType deviceType,std::string networkId)1873 void AudioPolicyService::OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId) 1874 { 1875 AUDIO_INFO_LOG("OnPreferredInputDeviceUpdated start"); 1876 1877 if (audioPolicyServerHandler_ != nullptr) { 1878 audioPolicyServerHandler_->SendPreferredInputDeviceUpdated(); 1879 } 1880 } 1881 OnPreferredDeviceUpdated(const AudioDeviceDescriptor & activeOutputDevice,DeviceType activeInputDevice)1882 void AudioPolicyService::OnPreferredDeviceUpdated(const AudioDeviceDescriptor& activeOutputDevice, 1883 DeviceType activeInputDevice) 1884 { 1885 OnPreferredOutputDeviceUpdated(activeOutputDevice); 1886 OnPreferredInputDeviceUpdated(activeInputDevice, LOCAL_NETWORK_ID); 1887 } 1888 SetWakeUpAudioCapturer(InternalAudioCapturerOptions options)1889 int32_t AudioPolicyService::SetWakeUpAudioCapturer(InternalAudioCapturerOptions options) 1890 { 1891 AUDIO_INFO_LOG("set wakeup audio capturer start"); 1892 AudioModuleInfo moduleInfo = {}; 1893 if (!ConstructWakeupAudioModuleInfo(options.streamInfo, moduleInfo)) { 1894 AUDIO_ERR_LOG("failed to construct wakeup audio module info"); 1895 return ERROR; 1896 } 1897 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 1898 1899 AUDIO_DEBUG_LOG("set wakeup audio capturer end"); 1900 return SUCCESS; 1901 } 1902 SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig & config)1903 int32_t AudioPolicyService::SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig &config) 1904 { 1905 InternalAudioCapturerOptions capturerOptions; 1906 capturerOptions.streamInfo = config.streamInfo; 1907 return SetWakeUpAudioCapturer(capturerOptions); 1908 } 1909 NotifyCapturerAdded(AudioCapturerInfo capturerInfo,AudioStreamInfo streamInfo,uint32_t sessionId)1910 int32_t AudioPolicyService::NotifyCapturerAdded(AudioCapturerInfo capturerInfo, AudioStreamInfo streamInfo, 1911 uint32_t sessionId) 1912 { 1913 int32_t error = SUCCESS; 1914 audioPolicyServerHandler_->SendCapturerCreateEvent(capturerInfo, streamInfo, sessionId, true, error); 1915 return error; 1916 } 1917 NotifyWakeUpCapturerRemoved()1918 int32_t AudioPolicyService::NotifyWakeUpCapturerRemoved() 1919 { 1920 audioPolicyServerHandler_->SendWakeupCloseEvent(false); 1921 return SUCCESS; 1922 } 1923 IsAbsVolumeSupported()1924 bool AudioPolicyService::IsAbsVolumeSupported() 1925 { 1926 return IsAbsVolumeScene(); 1927 } 1928 CloseWakeUpAudioCapturer()1929 int32_t AudioPolicyService::CloseWakeUpAudioCapturer() 1930 { 1931 AUDIO_INFO_LOG("close wakeup audio capturer start"); 1932 std::lock_guard<std::mutex> lck(ioHandlesMutex_); 1933 auto ioHandleIter = IOHandles_.find(std::string(PRIMARY_WAKEUP)); 1934 if (ioHandleIter == IOHandles_.end()) { 1935 AUDIO_ERR_LOG("close wakeup audio capturer failed"); 1936 return ERROR; 1937 } 1938 1939 auto ioHandle = ioHandleIter->second; 1940 IOHandles_.erase(ioHandleIter); 1941 audioPolicyManager_.CloseAudioPort(ioHandle); 1942 return SUCCESS; 1943 } 1944 GetDevices(DeviceFlag deviceFlag)1945 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevices(DeviceFlag deviceFlag) 1946 { 1947 AUDIO_DEBUG_LOG("GetDevices start"); 1948 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 1949 return GetDevicesInner(deviceFlag); 1950 } 1951 GetDevicesInner(DeviceFlag deviceFlag)1952 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevicesInner(DeviceFlag deviceFlag) 1953 { 1954 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {}; 1955 1956 CHECK_AND_RETURN_RET_LOG(deviceFlag >= DeviceFlag::OUTPUT_DEVICES_FLAG && 1957 deviceFlag <= DeviceFlag::ALL_L_D_DEVICES_FLAG, 1958 deviceList, "Invalid flag provided %{public}d", deviceFlag); 1959 1960 CHECK_AND_RETURN_RET(deviceFlag != DeviceFlag::ALL_L_D_DEVICES_FLAG, connectedDevices_); 1961 1962 for (auto device : connectedDevices_) { 1963 if (device == nullptr) { 1964 continue; 1965 } 1966 bool filterAllLocal = deviceFlag == DeviceFlag::ALL_DEVICES_FLAG && device->networkId_ == LOCAL_NETWORK_ID; 1967 bool filterLocalOutput = deviceFlag == DeviceFlag::OUTPUT_DEVICES_FLAG 1968 && device->networkId_ == LOCAL_NETWORK_ID 1969 && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE; 1970 bool filterLocalInput = deviceFlag == DeviceFlag::INPUT_DEVICES_FLAG 1971 && device->networkId_ == LOCAL_NETWORK_ID 1972 && device->deviceRole_ == DeviceRole::INPUT_DEVICE; 1973 1974 bool filterAllRemote = deviceFlag == DeviceFlag::ALL_DISTRIBUTED_DEVICES_FLAG 1975 && device->networkId_ != LOCAL_NETWORK_ID; 1976 bool filterRemoteOutput = deviceFlag == DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG 1977 && (device->networkId_ != LOCAL_NETWORK_ID || device->deviceType_ == DEVICE_TYPE_REMOTE_CAST) 1978 && device->deviceRole_ == DeviceRole::OUTPUT_DEVICE; 1979 bool filterRemoteInput = deviceFlag == DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG 1980 && device->networkId_ != LOCAL_NETWORK_ID 1981 && device->deviceRole_ == DeviceRole::INPUT_DEVICE; 1982 1983 if (filterAllLocal || filterLocalOutput || filterLocalInput || filterAllRemote || filterRemoteOutput 1984 || filterRemoteInput) { 1985 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*device); 1986 deviceList.push_back(devDesc); 1987 } 1988 } 1989 1990 AUDIO_DEBUG_LOG("GetDevices list size = [%{public}zu]", deviceList.size()); 1991 return deviceList; 1992 } 1993 GetPreferredOutputDeviceDescriptors(AudioRendererInfo & rendererInfo,std::string networkId)1994 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescriptors( 1995 AudioRendererInfo &rendererInfo, std::string networkId) 1996 { 1997 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 1998 return GetPreferredOutputDeviceDescInner(rendererInfo, networkId); 1999 } 2000 GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo,std::string networkId)2001 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescriptors( 2002 AudioCapturerInfo &captureInfo, std::string networkId) 2003 { 2004 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 2005 return GetPreferredInputDeviceDescInner(captureInfo, networkId); 2006 } 2007 GetPreferredOutputDeviceDescInner(AudioRendererInfo & rendererInfo,std::string networkId)2008 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescInner( 2009 AudioRendererInfo &rendererInfo, std::string networkId) 2010 { 2011 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {}; 2012 if (rendererInfo.streamUsage <= STREAM_USAGE_UNKNOWN || 2013 rendererInfo.streamUsage > STREAM_USAGE_MAX) { 2014 AUDIO_WARNING_LOG("Invalid usage[%{public}d], return current device.", rendererInfo.streamUsage); 2015 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(GetCurrentOutputDevice()); 2016 deviceList.push_back(devDesc); 2017 return deviceList; 2018 } 2019 if (networkId == LOCAL_NETWORK_ID) { 2020 vector<std::unique_ptr<AudioDeviceDescriptor>> descs = 2021 audioRouterCenter_.FetchOutputDevices(rendererInfo.streamUsage, -1); 2022 for (size_t i = 0; i < descs.size(); i++) { 2023 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*descs[i]); 2024 AUDIO_PRERELEASE_LOGI("streamUsage %{public}d fetch desc[%{public}zu]-device:%{public}d", 2025 rendererInfo.streamUsage, i, descs[i]->deviceType_); 2026 deviceList.push_back(devDesc); 2027 } 2028 } else { 2029 vector<unique_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetRemoteRenderDevices(); 2030 for (auto &desc : descs) { 2031 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc); 2032 deviceList.push_back(devDesc); 2033 } 2034 } 2035 2036 return deviceList; 2037 } 2038 SetCurrenInputDevice(const AudioDeviceDescriptor & desc)2039 void AudioPolicyService::SetCurrenInputDevice(const AudioDeviceDescriptor &desc) 2040 { 2041 std::lock_guard<std::mutex> lock(curInputDevice_); 2042 currentActiveInputDevice_ = AudioDeviceDescriptor(desc); 2043 } 2044 GetCurrentInputDevice()2045 AudioDeviceDescriptor AudioPolicyService::GetCurrentInputDevice() 2046 { 2047 std::lock_guard<std::mutex> lock(curInputDevice_); 2048 return currentActiveInputDevice_; 2049 } 2050 2051 GetCurrentInputDeviceType()2052 DeviceType AudioPolicyService::GetCurrentInputDeviceType() 2053 { 2054 std::lock_guard<std::mutex> lock(curInputDevice_); 2055 return currentActiveInputDevice_.deviceType_; 2056 } 2057 SetCurrentInputDeviceType(DeviceType deviceType)2058 void AudioPolicyService::SetCurrentInputDeviceType(DeviceType deviceType) 2059 { 2060 std::lock_guard<std::mutex> lock(curInputDevice_); 2061 currentActiveInputDevice_.deviceType_ = deviceType; 2062 } 2063 SetCurrentOutputDevice(const AudioDeviceDescriptor & desc)2064 void AudioPolicyService::SetCurrentOutputDevice(const AudioDeviceDescriptor &desc) 2065 { 2066 std::lock_guard<std::mutex> lock(curOutputDevice_); 2067 currentActiveDevice_ = AudioDeviceDescriptor(desc); 2068 } 2069 SetCurrentOutputDeviceType(DeviceType deviceType)2070 void AudioPolicyService::SetCurrentOutputDeviceType(DeviceType deviceType) 2071 { 2072 std::lock_guard<std::mutex> lock(curOutputDevice_); 2073 currentActiveDevice_.deviceType_ = deviceType; 2074 } 2075 GetCurrentOutputDevice()2076 AudioDeviceDescriptor AudioPolicyService::GetCurrentOutputDevice() 2077 { 2078 std::lock_guard<std::mutex> lock(curOutputDevice_); 2079 return currentActiveDevice_; 2080 } 2081 GetCurrentOutputDeviceType()2082 DeviceType AudioPolicyService::GetCurrentOutputDeviceType() 2083 { 2084 std::lock_guard<std::mutex> lock(curOutputDevice_); 2085 return currentActiveDevice_.deviceType_; 2086 } 2087 GetCurrentOutputDeviceCategory()2088 DeviceCategory AudioPolicyService::GetCurrentOutputDeviceCategory() 2089 { 2090 std::lock_guard<std::mutex> lock(curOutputDevice_); 2091 return currentActiveDevice_.deviceCategory_; 2092 } 2093 GetCurrentOutputDeviceNetworkId()2094 std::string AudioPolicyService::GetCurrentOutputDeviceNetworkId() 2095 { 2096 std::lock_guard<std::mutex> lock(curOutputDevice_); 2097 return currentActiveDevice_.networkId_; 2098 } 2099 GetCurrentOutputDeviceMacAddr()2100 std::string AudioPolicyService::GetCurrentOutputDeviceMacAddr() 2101 { 2102 std::lock_guard<std::mutex> lock(curOutputDevice_); 2103 return currentActiveDevice_.macAddress_; 2104 } 2105 GetPreferredInputDeviceDescInner(AudioCapturerInfo & captureInfo,std::string networkId)2106 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescInner( 2107 AudioCapturerInfo &captureInfo, std::string networkId) 2108 { 2109 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {}; 2110 if (captureInfo.sourceType <= SOURCE_TYPE_INVALID || 2111 captureInfo.sourceType > SOURCE_TYPE_MAX) { 2112 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(GetCurrentInputDevice()); 2113 deviceList.push_back(devDesc); 2114 return deviceList; 2115 } 2116 2117 if (captureInfo.sourceType == SOURCE_TYPE_WAKEUP) { 2118 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(DEVICE_TYPE_MIC, INPUT_DEVICE); 2119 devDesc->networkId_ = LOCAL_NETWORK_ID; 2120 deviceList.push_back(devDesc); 2121 return deviceList; 2122 } 2123 2124 if (networkId == LOCAL_NETWORK_ID) { 2125 unique_ptr<AudioDeviceDescriptor> desc = audioRouterCenter_.FetchInputDevice(captureInfo.sourceType, -1); 2126 if (desc->deviceType_ == DEVICE_TYPE_NONE && (captureInfo.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE || 2127 captureInfo.sourceType == SOURCE_TYPE_REMOTE_CAST)) { 2128 desc->deviceType_ = DEVICE_TYPE_INVALID; 2129 desc->deviceRole_ = INPUT_DEVICE; 2130 } 2131 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc); 2132 deviceList.push_back(devDesc); 2133 } else { 2134 vector<unique_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetRemoteCaptureDevices(); 2135 for (auto &desc : descs) { 2136 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc); 2137 deviceList.push_back(devDesc); 2138 } 2139 } 2140 2141 return deviceList; 2142 } 2143 SetClientCallbacksEnable(const CallbackChange & callbackchange,const bool & enable)2144 int32_t AudioPolicyService::SetClientCallbacksEnable(const CallbackChange &callbackchange, const bool &enable) 2145 { 2146 if (audioPolicyServerHandler_ != nullptr) { 2147 return audioPolicyServerHandler_->SetClientCallbacksEnable(callbackchange, enable); 2148 } else { 2149 AUDIO_ERR_LOG("audioPolicyServerHandler_ is nullptr"); 2150 return AUDIO_ERR; 2151 } 2152 } 2153 UpdateActiveDeviceRoute(InternalDeviceType deviceType,DeviceFlag deviceFlag)2154 void AudioPolicyService::UpdateActiveDeviceRoute(InternalDeviceType deviceType, DeviceFlag deviceFlag) 2155 { 2156 Trace trace("AudioPolicyService::UpdateActiveDeviceRoute DeviceType:" + std::to_string(deviceType)); 2157 AUDIO_INFO_LOG("Active route with type[%{public}d]", deviceType); 2158 std::vector<std::pair<InternalDeviceType, DeviceFlag>> activeDevices; 2159 activeDevices.push_back(make_pair(deviceType, deviceFlag)); 2160 UpdateActiveDevicesRoute(activeDevices); 2161 } 2162 UpdateActiveDevicesRoute(std::vector<std::pair<InternalDeviceType,DeviceFlag>> & activeDevices)2163 void AudioPolicyService::UpdateActiveDevicesRoute(std::vector<std::pair<InternalDeviceType, DeviceFlag>> 2164 &activeDevices) 2165 { 2166 CHECK_AND_RETURN_LOG(!activeDevices.empty(), "activeDevices is empty."); 2167 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 2168 CHECK_AND_RETURN_LOG(gsp != nullptr, "UpdateActiveDevicesRoute, Audio Server Proxy is null"); 2169 auto ret = SUCCESS; 2170 2171 std::string deviceTypesInfo = ""; 2172 for (size_t i = 0; i < activeDevices.size(); i++) { 2173 deviceTypesInfo = deviceTypesInfo + " " + std::to_string(activeDevices[i].first); 2174 AUDIO_INFO_LOG("update active devices, device type info:[%{public}s]", 2175 std::to_string(activeDevices[i].first).c_str()); 2176 } 2177 2178 Trace trace("AudioPolicyService::UpdateActiveDevicesRoute DeviceTypes:" + deviceTypesInfo); 2179 std::string identity = IPCSkeleton::ResetCallingIdentity(); 2180 ret = gsp->UpdateActiveDevicesRoute(activeDevices, a2dpOffloadFlag_); 2181 IPCSkeleton::SetCallingIdentity(identity); 2182 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the route for %{public}s", deviceTypesInfo.c_str()); 2183 } 2184 UpdateDualToneState(const bool & enable,const int32_t & sessionId)2185 void AudioPolicyService::UpdateDualToneState(const bool &enable, const int32_t &sessionId) 2186 { 2187 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 2188 CHECK_AND_RETURN_LOG(gsp != nullptr, "UpdateDualToneState, Audio Server Proxy is null"); 2189 AUDIO_INFO_LOG("update dual tone state, enable:%{public}d, sessionId:%{public}d", enable, sessionId); 2190 enableDualHalToneState_ = enable; 2191 if (enableDualHalToneState_) { 2192 enableDualHalToneSessionId_ = sessionId; 2193 } 2194 auto ret = SUCCESS; 2195 Trace trace("AudioPolicyService::UpdateDualToneState sessionId:" + std::to_string(sessionId)); 2196 std::string identity = IPCSkeleton::ResetCallingIdentity(); 2197 ret = gsp->UpdateDualToneState(enable, sessionId); 2198 IPCSkeleton::SetCallingIdentity(identity); 2199 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the dual tone state for sessionId:%{public}d", sessionId); 2200 } 2201 GetSinkName(const DeviceInfo & desc,int32_t sessionId)2202 std::string AudioPolicyService::GetSinkName(const DeviceInfo& desc, int32_t sessionId) 2203 { 2204 if (desc.networkId == LOCAL_NETWORK_ID) { 2205 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN; 2206 streamCollector_.GetPipeType(sessionId, pipeType); 2207 return GetSinkPortName(desc.deviceType, pipeType); 2208 } else { 2209 return GetRemoteModuleName(desc.networkId, desc.deviceRole); 2210 } 2211 } 2212 GetSinkName(const AudioDeviceDescriptor & desc,int32_t sessionId)2213 std::string AudioPolicyService::GetSinkName(const AudioDeviceDescriptor &desc, int32_t sessionId) 2214 { 2215 if (desc.networkId_ == LOCAL_NETWORK_ID) { 2216 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN; 2217 streamCollector_.GetPipeType(sessionId, pipeType); 2218 return GetSinkPortName(desc.deviceType_, pipeType); 2219 } else { 2220 return GetRemoteModuleName(desc.networkId_, desc.deviceRole_); 2221 } 2222 } 2223 SetVoiceCallMuteForSwitchDevice()2224 void AudioPolicyService::SetVoiceCallMuteForSwitchDevice() 2225 { 2226 Trace trace("SetVoiceMuteForSwitchDevice"); 2227 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 2228 CHECK_AND_RETURN_LOG(gsp != nullptr, "SetVoiceMuteForSwitchDevice, Audio Server Proxy is null"); 2229 std::string identity = IPCSkeleton::ResetCallingIdentity(); 2230 gsp->SetVoiceVolume(0); 2231 IPCSkeleton::SetCallingIdentity(identity); 2232 2233 AUDIO_INFO_LOG("%{public}" PRId64" us for modem call update route", WAIT_MODEM_CALL_SET_VOLUME_TIME_US); 2234 usleep(WAIT_MODEM_CALL_SET_VOLUME_TIME_US); 2235 // Unmute in SetVolumeForSwitchDevice after update route. 2236 } 2237 MuteSinkPortForSwtichDevice(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices,const AudioStreamDeviceChangeReasonExt reason)2238 void AudioPolicyService::MuteSinkPortForSwtichDevice(unique_ptr<AudioRendererChangeInfo>& rendererChangeInfo, 2239 vector<std::unique_ptr<AudioDeviceDescriptor>>& outputDevices, const AudioStreamDeviceChangeReasonExt reason) 2240 { 2241 Trace trace("AudioPolicyService::MuteSinkPortForSwtichDevice"); 2242 if (outputDevices.size() != 1) { 2243 // mute primary when play music and ring 2244 if (IsStreamActive(STREAM_MUSIC)) { 2245 MuteSinkPort(PRIMARY_SPEAKER, SET_BT_ABS_SCENE_DELAY_MS, true); 2246 } 2247 return; 2248 } 2249 if (outputDevices.front()->isSameDevice(rendererChangeInfo->outputDeviceInfo)) return; 2250 2251 moveDeviceFinished_ = false; 2252 2253 if (audioScene_ == AUDIO_SCENE_PHONE_CALL) { 2254 return SetVoiceCallMuteForSwitchDevice(); 2255 } 2256 2257 std::string oldSinkName = GetSinkName(rendererChangeInfo->outputDeviceInfo, rendererChangeInfo->sessionId); 2258 std::string newSinkName = GetSinkName(*outputDevices.front(), rendererChangeInfo->sessionId); 2259 AUDIO_INFO_LOG("mute sink old:[%{public}s] new:[%{public}s]", oldSinkName.c_str(), newSinkName.c_str()); 2260 MuteSinkPort(oldSinkName, newSinkName, reason); 2261 } 2262 MoveToNewOutputDevice(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices,const AudioStreamDeviceChangeReasonExt reason)2263 void AudioPolicyService::MoveToNewOutputDevice(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, 2264 vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices, const AudioStreamDeviceChangeReasonExt reason) 2265 { 2266 Trace trace("AudioPolicyService::MoveToNewOutputDevice"); 2267 std::vector<SinkInput> targetSinkInputs = FilterSinkInputs(rendererChangeInfo->sessionId); 2268 2269 bool needTriggerCallback = true; 2270 if (outputDevices.front()->isSameDevice(rendererChangeInfo->outputDeviceInfo)) { 2271 needTriggerCallback = false; 2272 } 2273 2274 AUDIO_WARNING_LOG("move session %{public}d [%{public}d][%{public}s]-->[%{public}d][%{public}s], reason %{public}d", 2275 rendererChangeInfo->sessionId, rendererChangeInfo->outputDeviceInfo.deviceType, 2276 GetEncryptAddr(rendererChangeInfo->outputDeviceInfo.macAddress).c_str(), 2277 outputDevices.front()->deviceType_, GetEncryptAddr(outputDevices.front()->macAddress_).c_str(), 2278 static_cast<int>(reason)); 2279 2280 DeviceType oldDevice = rendererChangeInfo->outputDeviceInfo.deviceType; 2281 2282 UpdateDeviceInfo(rendererChangeInfo->outputDeviceInfo, 2283 new AudioDeviceDescriptor(*outputDevices.front()), true, true); 2284 2285 if (needTriggerCallback) { 2286 audioPolicyServerHandler_->SendRendererDeviceChangeEvent(rendererChangeInfo->callerPid, 2287 rendererChangeInfo->sessionId, rendererChangeInfo->outputDeviceInfo, reason); 2288 } 2289 2290 UpdateEffectDefaultSink(outputDevices.front()->deviceType_); 2291 // MoveSinkInputByIndexOrName 2292 auto ret = (outputDevices.front()->networkId_ == LOCAL_NETWORK_ID) 2293 ? MoveToLocalOutputDevice(targetSinkInputs, new AudioDeviceDescriptor(*outputDevices.front())) 2294 : MoveToRemoteOutputDevice(targetSinkInputs, new AudioDeviceDescriptor(*outputDevices.front())); 2295 if (ret != SUCCESS) { 2296 UpdateEffectDefaultSink(oldDevice); 2297 AUDIO_ERR_LOG("Move sink input %{public}d to device %{public}d failed!", 2298 rendererChangeInfo->sessionId, outputDevices.front()->deviceType_); 2299 std::unique_lock<std::mutex> lock(moveDeviceMutex_); 2300 moveDeviceFinished_ = true; 2301 moveDeviceCV_.notify_all(); 2302 return; 2303 } 2304 2305 if (isUpdateRouteSupported_ && outputDevices.front()->networkId_ == LOCAL_NETWORK_ID && 2306 !reason.isSetAudioScene()) { 2307 UpdateRoute(rendererChangeInfo, outputDevices); 2308 } 2309 2310 std::string newSinkName = GetSinkName(*outputDevices.front(), rendererChangeInfo->sessionId); 2311 SetVolumeForSwitchDevice(outputDevices.front()->deviceType_, newSinkName); 2312 2313 streamCollector_.UpdateRendererDeviceInfo(rendererChangeInfo->clientUID, rendererChangeInfo->sessionId, 2314 rendererChangeInfo->outputDeviceInfo); 2315 ResetOffloadAndMchMode(rendererChangeInfo, outputDevices); 2316 std::unique_lock<std::mutex> lock(moveDeviceMutex_); 2317 moveDeviceFinished_ = true; 2318 moveDeviceCV_.notify_all(); 2319 } 2320 MoveToNewInputDevice(unique_ptr<AudioCapturerChangeInfo> & capturerChangeInfo,unique_ptr<AudioDeviceDescriptor> & inputDevice)2321 void AudioPolicyService::MoveToNewInputDevice(unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo, 2322 unique_ptr<AudioDeviceDescriptor> &inputDevice) 2323 { 2324 std::vector<SourceOutput> targetSourceOutputs = FilterSourceOutputs(capturerChangeInfo->sessionId); 2325 2326 // MoveSourceOuputByIndexName 2327 auto ret = (inputDevice->networkId_ == LOCAL_NETWORK_ID) 2328 ? MoveToLocalInputDevice(targetSourceOutputs, new AudioDeviceDescriptor(*inputDevice)) 2329 : MoveToRemoteInputDevice(targetSourceOutputs, new AudioDeviceDescriptor(*inputDevice)); 2330 CHECK_AND_RETURN_LOG((ret == SUCCESS), "Move source output %{public}d to device %{public}d failed!", 2331 capturerChangeInfo->sessionId, inputDevice->deviceType_); 2332 AUDIO_WARNING_LOG("move session %{public}d [%{public}d][%{public}s]-->[%{public}d][%{public}s]", 2333 capturerChangeInfo->sessionId, capturerChangeInfo->inputDeviceInfo.deviceType, 2334 GetEncryptAddr(capturerChangeInfo->inputDeviceInfo.macAddress).c_str(), 2335 inputDevice->deviceType_, GetEncryptAddr(inputDevice->macAddress_).c_str()); 2336 2337 if (isUpdateRouteSupported_ && inputDevice->networkId_ == LOCAL_NETWORK_ID) { 2338 UpdateActiveDeviceRoute(inputDevice->deviceType_, DeviceFlag::INPUT_DEVICES_FLAG); 2339 } 2340 UpdateDeviceInfo(capturerChangeInfo->inputDeviceInfo, new AudioDeviceDescriptor(*inputDevice), true, true); 2341 streamCollector_.UpdateCapturerDeviceInfo(capturerChangeInfo->clientUID, capturerChangeInfo->sessionId, 2342 capturerChangeInfo->inputDeviceInfo); 2343 } 2344 FetchOutputDeviceWhenNoRunningStream()2345 void AudioPolicyService::FetchOutputDeviceWhenNoRunningStream() 2346 { 2347 AUDIO_PRERELEASE_LOGI("In"); 2348 vector<std::unique_ptr<AudioDeviceDescriptor>> descs = 2349 audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1); 2350 CHECK_AND_RETURN_LOG(!descs.empty(), "descs is empty"); 2351 AudioDeviceDescriptor tmpOutputDeviceDesc = GetCurrentOutputDevice(); 2352 if (descs.front()->deviceType_ == DEVICE_TYPE_NONE || IsSameDevice(descs.front(), tmpOutputDeviceDesc)) { 2353 AUDIO_DEBUG_LOG("output device is not change"); 2354 return; 2355 } 2356 SetCurrentOutputDevice(*descs.front()); 2357 AUDIO_DEBUG_LOG("currentActiveDevice update %{public}d", GetCurrentOutputDeviceType()); 2358 SetVolumeForSwitchDevice(descs.front()->deviceType_); 2359 if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { 2360 SwitchActiveA2dpDevice(new AudioDeviceDescriptor(*descs.front())); 2361 } 2362 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice()); 2363 } 2364 FetchInputDeviceWhenNoRunningStream()2365 void AudioPolicyService::FetchInputDeviceWhenNoRunningStream() 2366 { 2367 AUDIO_PRERELEASE_LOGI("In"); 2368 unique_ptr<AudioDeviceDescriptor> desc; 2369 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice(); 2370 if (tempDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && 2371 (Bluetooth::AudioHfpManager::GetScoCategory() == Bluetooth::ScoCategory::SCO_RECOGNITION || 2372 Bluetooth::AudioHfpManager::GetRecognitionStatus() == Bluetooth::RecognitionStatus::RECOGNITION_CONNECTING)) { 2373 desc = audioRouterCenter_.FetchInputDevice(SOURCE_TYPE_VOICE_RECOGNITION, -1); 2374 } else { 2375 desc = audioRouterCenter_.FetchInputDevice(SOURCE_TYPE_MIC, -1); 2376 } 2377 2378 if (desc->deviceType_ == DEVICE_TYPE_NONE || IsSameDevice(desc, tempDesc)) { 2379 AUDIO_DEBUG_LOG("input device is not change"); 2380 return; 2381 } 2382 SetCurrenInputDevice(*desc); 2383 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP || desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 2384 activeBTDevice_ = desc->macAddress_; 2385 } 2386 DeviceType deviceType = GetCurrentInputDeviceType(); 2387 AUDIO_DEBUG_LOG("currentActiveInputDevice update %{public}d", deviceType); 2388 OnPreferredInputDeviceUpdated(deviceType, ""); // networkId is not used 2389 } 2390 ActivateA2dpDevice(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2391 int32_t AudioPolicyService::ActivateA2dpDevice(unique_ptr<AudioDeviceDescriptor> &desc, 2392 vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos, const AudioStreamDeviceChangeReasonExt reason) 2393 { 2394 Trace trace("AudioPolicyService::ActivateA2dpDevice"); 2395 sptr<AudioDeviceDescriptor> deviceDesc = new AudioDeviceDescriptor(*desc); 2396 int32_t ret = SwitchActiveA2dpDevice(deviceDesc); 2397 if (ret != SUCCESS) { 2398 AUDIO_ERR_LOG("Active A2DP device failed, retrigger fetch output device"); 2399 deviceDesc->exceptionFlag_ = true; 2400 audioDeviceManager_.UpdateDevicesListInfo(deviceDesc, EXCEPTION_FLAG_UPDATE); 2401 FetchOutputDevice(rendererChangeInfos, reason); 2402 return ERROR; 2403 } 2404 return SUCCESS; 2405 } 2406 HandleScoOutputDeviceFetched(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2407 int32_t AudioPolicyService::HandleScoOutputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc, 2408 vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos, 2409 const AudioStreamDeviceChangeReasonExt reason) 2410 { 2411 Trace trace("AudioPolicyService::HandleScoOutputDeviceFetched"); 2412 #ifdef BLUETOOTH_ENABLE 2413 int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_); 2414 if (ret != SUCCESS) { 2415 AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch output device."); 2416 desc->exceptionFlag_ = true; 2417 audioDeviceManager_.UpdateDevicesListInfo(new AudioDeviceDescriptor(*desc), EXCEPTION_FLAG_UPDATE); 2418 FetchOutputDevice(rendererChangeInfos, reason); 2419 return ERROR; 2420 } 2421 if (desc->connectState_ == DEACTIVE_CONNECTED || lastAudioScene_ != audioScene_) { 2422 Bluetooth::AudioHfpManager::ConnectScoWithAudioScene(audioScene_); 2423 return SUCCESS; 2424 } 2425 #endif 2426 return SUCCESS; 2427 } 2428 IsRendererStreamRunning(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)2429 bool AudioPolicyService::IsRendererStreamRunning(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo) 2430 { 2431 StreamUsage usage = rendererChangeInfo->rendererInfo.streamUsage; 2432 RendererState rendererState = rendererChangeInfo->rendererState; 2433 if ((usage == STREAM_USAGE_VOICE_MODEM_COMMUNICATION && audioScene_ != AUDIO_SCENE_PHONE_CALL) || 2434 (usage != STREAM_USAGE_VOICE_MODEM_COMMUNICATION && 2435 (rendererState != RENDERER_RUNNING && !rendererChangeInfo->prerunningState))) { 2436 return false; 2437 } 2438 return true; 2439 } 2440 NeedRehandleA2DPDevice(unique_ptr<AudioDeviceDescriptor> & desc)2441 bool AudioPolicyService::NeedRehandleA2DPDevice(unique_ptr<AudioDeviceDescriptor> &desc) 2442 { 2443 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 2444 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && IOHandles_.find(BLUETOOTH_SPEAKER) == IOHandles_.end()) { 2445 AUDIO_WARNING_LOG("A2DP module is not loaded, need rehandle"); 2446 return true; 2447 } 2448 return false; 2449 } 2450 MuteSinkPort(const std::string & portName,int32_t duration,bool isSync)2451 void AudioPolicyService::MuteSinkPort(const std::string &portName, int32_t duration, bool isSync) 2452 { 2453 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 2454 CHECK_AND_RETURN_LOG(gsp != nullptr, "MuteSinkPort, Audio Server Proxy is null"); 2455 2456 std::string identity = IPCSkeleton::ResetCallingIdentity(); 2457 if (sinkPortStrToClassStrMap_.count(portName) > 0) { 2458 // Mute by render sink. (primary、a2dp、usb、dp、offload) 2459 gsp->SetSinkMuteForSwitchDevice(sinkPortStrToClassStrMap_.at(portName), duration, true); 2460 } else { 2461 // Mute by pa. 2462 audioPolicyManager_.SetSinkMute(portName, true, isSync); 2463 } 2464 IPCSkeleton::SetCallingIdentity(identity); 2465 usleep(WAIT_SET_MUTE_LATENCY_TIME_US); // sleep fix data cache pop. 2466 2467 // Muted and then unmute. 2468 thread switchThread(&AudioPolicyService::UnmutePortAfterMuteDuration, this, duration, portName, DEVICE_TYPE_NONE); 2469 switchThread.detach(); 2470 } 2471 MuteSinkPort(const std::string & oldSinkname,const std::string & newSinkName,AudioStreamDeviceChangeReasonExt reason)2472 void AudioPolicyService::MuteSinkPort(const std::string &oldSinkname, const std::string &newSinkName, 2473 AudioStreamDeviceChangeReasonExt reason) 2474 { 2475 auto ringermode = GetRingerMode(); 2476 if (reason.isOverride()) { 2477 int64_t muteTime = SELECT_DEVICE_MUTE_MS; 2478 if (newSinkName == OFFLOAD_PRIMARY_SPEAKER || oldSinkname == OFFLOAD_PRIMARY_SPEAKER) { 2479 muteTime = SELECT_OFFLOAD_DEVICE_MUTE_MS; 2480 } 2481 MuteSinkPort(newSinkName, SELECT_DEVICE_MUTE_MS, true); 2482 MuteSinkPort(oldSinkname, muteTime, true); 2483 } else if (reason == AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE) { 2484 int64_t muteTime = NEW_DEVICE_AVALIABLE_MUTE_MS; 2485 if (newSinkName == OFFLOAD_PRIMARY_SPEAKER || oldSinkname == OFFLOAD_PRIMARY_SPEAKER) { 2486 muteTime = NEW_DEVICE_AVALIABLE_OFFLOAD_MUTE_MS; 2487 } 2488 MuteSinkPort(newSinkName, NEW_DEVICE_AVALIABLE_MUTE_MS, true); 2489 MuteSinkPort(oldSinkname, muteTime, true); 2490 } else if (reason.IsOldDeviceUnavaliable() && ((audioScene_ == AUDIO_SCENE_DEFAULT) || 2491 ((audioScene_ == AUDIO_SCENE_RINGING || audioScene_ == AUDIO_SCENE_VOICE_RINGING) && 2492 ringermode != RINGER_MODE_NORMAL))) { 2493 MuteSinkPort(newSinkName, OLD_DEVICE_UNAVALIABLE_MUTE_MS, true); 2494 usleep(OLD_DEVICE_UNAVALIABLE_MUTE_SLEEP_MS); // sleep fix data cache pop. 2495 } else if (reason.IsOldDeviceUnavaliableExt() && ((audioScene_ == AUDIO_SCENE_DEFAULT) || 2496 ((audioScene_ == AUDIO_SCENE_RINGING || audioScene_ == AUDIO_SCENE_VOICE_RINGING) && 2497 ringermode != RINGER_MODE_NORMAL))) { 2498 MuteSinkPort(newSinkName, OLD_DEVICE_UNAVALIABLE_EXT_MUTE_MS, true); 2499 usleep(OLD_DEVICE_UNAVALIABLE_MUTE_SLEEP_MS); // sleep fix data cache pop. 2500 } else if (reason == AudioStreamDeviceChangeReason::UNKNOWN && 2501 oldSinkname == REMOTE_CAST_INNER_CAPTURER_SINK_NAME) { 2502 // remote cast -> earpiece 300ms fix sound leak 2503 MuteSinkPort(newSinkName, NEW_DEVICE_REMOTE_CAST_AVALIABLE_MUTE_MS, true); 2504 } 2505 } 2506 MuteDefaultSinkPort()2507 void AudioPolicyService::MuteDefaultSinkPort() 2508 { 2509 AudioDeviceDescriptor currentDeviceDescriptor = GetCurrentOutputDevice(); 2510 if (currentDeviceDescriptor.networkId_ != LOCAL_NETWORK_ID || 2511 (currentDeviceDescriptor.networkId_ == LOCAL_NETWORK_ID && 2512 GetSinkPortName(currentDeviceDescriptor.deviceType_) != PRIMARY_SPEAKER)) { 2513 // PA may move the sink to default when unloading module. 2514 MuteSinkPort(PRIMARY_SPEAKER, OLD_DEVICE_UNAVALIABLE_MUTE_MS, true); 2515 } 2516 } 2517 HandleDeviceChangeForFetchOutputDevice(unique_ptr<AudioDeviceDescriptor> & desc,unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)2518 int32_t AudioPolicyService::HandleDeviceChangeForFetchOutputDevice(unique_ptr<AudioDeviceDescriptor> &desc, 2519 unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo) 2520 { 2521 if (desc->deviceType_ == DEVICE_TYPE_NONE || (IsSameDevice(desc, rendererChangeInfo->outputDeviceInfo) && 2522 !NeedRehandleA2DPDevice(desc) && desc->connectState_ != DEACTIVE_CONNECTED && 2523 lastAudioScene_ == audioScene_ && !shouldUpdateDeviceDueToDualTone_)) { 2524 AUDIO_WARNING_LOG("stream %{public}d device not change, no need move device", rendererChangeInfo->sessionId); 2525 AudioDeviceDescriptor tmpOutputDeviceDesc = GetCurrentOutputDevice(); 2526 if (!IsSameDevice(desc, tmpOutputDeviceDesc)) { 2527 SetCurrentOutputDevice(*desc); 2528 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 2529 SetVolumeForSwitchDevice(curOutputDeviceType); 2530 UpdateActiveDeviceRoute(curOutputDeviceType, DeviceFlag::OUTPUT_DEVICES_FLAG); 2531 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice()); 2532 } 2533 return ERR_NEED_NOT_SWITCH_DEVICE; 2534 } 2535 return SUCCESS; 2536 } 2537 UpdateDevice(unique_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReasonExt reason,const std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)2538 bool AudioPolicyService::UpdateDevice(unique_ptr<AudioDeviceDescriptor> &desc, 2539 const AudioStreamDeviceChangeReasonExt reason, const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo) 2540 { 2541 bool isUpdate = false; 2542 AudioDeviceDescriptor tmpOutputDeviceDesc = GetCurrentOutputDevice(); 2543 if (!IsSameDevice(desc, tmpOutputDeviceDesc)) { 2544 WriteOutputRouteChangeEvent(desc, reason); 2545 SetCurrentOutputDevice(*desc); 2546 AUDIO_DEBUG_LOG("currentActiveDevice update %{public}d", GetCurrentOutputDeviceType()); 2547 isUpdate = true; 2548 } 2549 return isUpdate; 2550 } 2551 FetchOutputDevice(vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2552 void AudioPolicyService::FetchOutputDevice(vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos, 2553 const AudioStreamDeviceChangeReasonExt reason) 2554 { 2555 Trace trace("AudioPolicyService::FetchOutputDevice"); 2556 AUDIO_PRERELEASE_LOGI("Start for %{public}zu stream, connected %{public}s", 2557 rendererChangeInfos.size(), audioDeviceManager_.GetConnDevicesStr().c_str()); 2558 bool needUpdateActiveDevice = true; 2559 bool isUpdateActiveDevice = false; 2560 int32_t runningStreamCount = 0; 2561 bool hasDirectChangeDevice = false; 2562 for (auto &rendererChangeInfo : rendererChangeInfos) { 2563 if (!IsRendererStreamRunning(rendererChangeInfo) || (audioScene_ == AUDIO_SCENE_DEFAULT && 2564 audioRouterCenter_.isCallRenderRouter(rendererChangeInfo->rendererInfo.streamUsage))) { 2565 AUDIO_WARNING_LOG("stream %{public}d not running, no need fetch device", rendererChangeInfo->sessionId); 2566 continue; 2567 } 2568 runningStreamCount++; 2569 vector<std::unique_ptr<AudioDeviceDescriptor>> descs = 2570 audioRouterCenter_.FetchOutputDevices(rendererChangeInfo->rendererInfo.streamUsage, 2571 rendererChangeInfo->clientUID); 2572 if (HandleDeviceChangeForFetchOutputDevice(descs.front(), rendererChangeInfo) == ERR_NEED_NOT_SWITCH_DEVICE && 2573 !Util::IsRingerOrAlarmerStreamUsage(rendererChangeInfo->rendererInfo.streamUsage)) { 2574 continue; 2575 } 2576 MuteSinkPortForSwtichDevice(rendererChangeInfo, descs, reason); 2577 std::string encryptMacAddr = GetEncryptAddr(descs.front()->macAddress_); 2578 if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { 2579 if (IsFastFromA2dpToA2dp(descs.front(), rendererChangeInfo, reason)) { continue; } 2580 int32_t ret = ActivateA2dpDeviceWhenDescEnabled(descs.front(), rendererChangeInfos, reason); 2581 CHECK_AND_RETURN_LOG(ret == SUCCESS, "activate a2dp [%{public}s] failed", encryptMacAddr.c_str()); 2582 } else if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 2583 int32_t ret = HandleScoOutputDeviceFetched(descs.front(), rendererChangeInfos, reason); 2584 CHECK_AND_RETURN_LOG(ret == SUCCESS, "sco [%{public}s] is not connected yet", encryptMacAddr.c_str()); 2585 } 2586 if (needUpdateActiveDevice) { 2587 isUpdateActiveDevice = UpdateDevice(descs.front(), reason, rendererChangeInfo); 2588 needUpdateActiveDevice = false; 2589 } 2590 if (!hasDirectChangeDevice && isUpdateActiveDevice && NotifyRecreateDirectStream(rendererChangeInfo, reason)) { 2591 hasDirectChangeDevice = true; 2592 } 2593 NotifyRecreateRendererStream(descs.front(), rendererChangeInfo, reason); 2594 MoveToNewOutputDevice(rendererChangeInfo, descs, reason); 2595 } 2596 if (isUpdateActiveDevice) { 2597 OnPreferredOutputDeviceUpdated(GetCurrentOutputDevice()); 2598 } 2599 if (runningStreamCount == 0) { 2600 FetchOutputDeviceWhenNoRunningStream(); 2601 } 2602 } 2603 ActivateA2dpDeviceWhenDescEnabled(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioRendererChangeInfo>> & rendererChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2604 int32_t AudioPolicyService::ActivateA2dpDeviceWhenDescEnabled(unique_ptr<AudioDeviceDescriptor> &desc, 2605 vector<unique_ptr<AudioRendererChangeInfo>> &rendererChangeInfos, const AudioStreamDeviceChangeReasonExt reason) 2606 { 2607 if (desc->isEnable_) { 2608 AUDIO_INFO_LOG("descs front is enabled"); 2609 return ActivateA2dpDevice(desc, rendererChangeInfos, reason); 2610 } 2611 return SUCCESS; 2612 } 2613 IsFastFromA2dpToA2dp(const std::unique_ptr<AudioDeviceDescriptor> & desc,const std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2614 bool AudioPolicyService::IsFastFromA2dpToA2dp(const std::unique_ptr<AudioDeviceDescriptor> &desc, 2615 const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, const AudioStreamDeviceChangeReasonExt reason) 2616 { 2617 if (rendererChangeInfo->outputDeviceInfo.deviceType == DEVICE_TYPE_BLUETOOTH_A2DP && 2618 rendererChangeInfo->rendererInfo.originalFlag == AUDIO_FLAG_MMAP && 2619 rendererChangeInfo->outputDeviceInfo.deviceId != desc->deviceId_) { 2620 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId, 2621 AUDIO_FLAG_MMAP, reason); 2622 AUDIO_INFO_LOG("Switch fast stream from a2dp to a2dp"); 2623 return true; 2624 } 2625 return false; 2626 } 2627 NotifyRecreateRendererStream(std::unique_ptr<AudioDeviceDescriptor> & desc,const std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2628 bool AudioPolicyService::NotifyRecreateRendererStream(std::unique_ptr<AudioDeviceDescriptor> &desc, 2629 const std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, const AudioStreamDeviceChangeReasonExt reason) 2630 { 2631 AUDIO_INFO_LOG("New device type: %{public}d, current rendererFlag: %{public}d, origianl flag: %{public}d", 2632 desc->deviceType_, rendererChangeInfo->rendererInfo.rendererFlags, 2633 rendererChangeInfo->rendererInfo.originalFlag); 2634 CHECK_AND_RETURN_RET_LOG(rendererChangeInfo->outputDeviceInfo.deviceType != DEVICE_TYPE_INVALID && 2635 desc->deviceType_ != DEVICE_TYPE_INVALID, false, "isUpdateActiveDevice is false"); 2636 CHECK_AND_RETURN_RET_LOG(rendererChangeInfo->rendererInfo.originalFlag != AUDIO_FLAG_NORMAL && 2637 rendererChangeInfo->rendererInfo.originalFlag != AUDIO_FLAG_FORCED_NORMAL, false, "original flag is normal"); 2638 // Switch between old and new stream as they have different hals 2639 std::string oldDevicePortName = GetSinkPortName(rendererChangeInfo->outputDeviceInfo.deviceType); 2640 bool isOldDeviceLocal = rendererChangeInfo->outputDeviceInfo.networkId == "" || 2641 rendererChangeInfo->outputDeviceInfo.networkId == LOCAL_NETWORK_ID; 2642 bool isNewDeviceLocal = desc->networkId_ == "" || desc->networkId_ == LOCAL_NETWORK_ID; 2643 if ((strcmp(oldDevicePortName.c_str(), GetSinkPortName(desc->deviceType_).c_str())) || 2644 (isOldDeviceLocal ^ isNewDeviceLocal)) { 2645 int32_t streamClass = GetPreferredOutputStreamTypeInner(rendererChangeInfo->rendererInfo.streamUsage, 2646 desc->deviceType_, rendererChangeInfo->rendererInfo.originalFlag, desc->networkId_, 2647 rendererChangeInfo->rendererInfo.samplingRate); 2648 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, 2649 rendererChangeInfo->sessionId, streamClass, reason); 2650 return true; 2651 } 2652 return false; 2653 } 2654 NotifyRecreateDirectStream(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2655 bool AudioPolicyService::NotifyRecreateDirectStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, 2656 const AudioStreamDeviceChangeReasonExt reason) 2657 { 2658 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 2659 AUDIO_INFO_LOG("current pipe type is:%{public}d", rendererChangeInfo->rendererInfo.pipeType); 2660 if (!IsDirectSupportedDevice(curOutputDeviceType) && 2661 rendererChangeInfo->rendererInfo.pipeType == PIPE_TYPE_DIRECT_MUSIC) { 2662 if (rendererChangeInfo->outputDeviceInfo.deviceType == DEVICE_TYPE_USB_ARM_HEADSET) { 2663 AUDIO_INFO_LOG("old device is arm usb"); 2664 return false; 2665 } 2666 AUDIO_DEBUG_LOG("direct stream changed to normal."); 2667 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId, 2668 AUDIO_FLAG_DIRECT, reason); 2669 return true; 2670 } else if (IsDirectSupportedDevice(curOutputDeviceType) && 2671 rendererChangeInfo->rendererInfo.pipeType != PIPE_TYPE_DIRECT_MUSIC) { 2672 AudioRendererInfo info = rendererChangeInfo->rendererInfo; 2673 if (info.streamUsage == STREAM_USAGE_MUSIC && info.rendererFlags == AUDIO_FLAG_NORMAL && 2674 info.samplingRate >= SAMPLE_RATE_48000 && info.format >= SAMPLE_S24LE) { 2675 AUDIO_DEBUG_LOG("stream change to direct."); 2676 TriggerRecreateRendererStreamCallback(rendererChangeInfo->callerPid, rendererChangeInfo->sessionId, 2677 AUDIO_FLAG_DIRECT, reason); 2678 return true; 2679 } 2680 } 2681 return false; 2682 } 2683 IsDirectSupportedDevice(DeviceType deviceType)2684 bool AudioPolicyService::IsDirectSupportedDevice(DeviceType deviceType) 2685 { 2686 return deviceType == DEVICE_TYPE_WIRED_HEADSET || deviceType == DEVICE_TYPE_USB_HEADSET; 2687 } 2688 TriggerRecreateRendererStreamCallback(int32_t callerPid,int32_t sessionId,int32_t streamFlag,const AudioStreamDeviceChangeReasonExt reason)2689 void AudioPolicyService::TriggerRecreateRendererStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag, 2690 const AudioStreamDeviceChangeReasonExt reason) 2691 { 2692 Trace trace("AudioPolicyService::TriggerRecreateRendererStreamCallback"); 2693 AUDIO_INFO_LOG("Trigger recreate renderer stream, pid: %{public}d, sessionId: %{public}d, flag: %{public}d", 2694 callerPid, sessionId, streamFlag); 2695 if (audioPolicyServerHandler_ != nullptr) { 2696 audioPolicyServerHandler_->SendRecreateRendererStreamEvent(callerPid, sessionId, streamFlag, reason); 2697 } else { 2698 AUDIO_WARNING_LOG("No audio policy server handler"); 2699 } 2700 } 2701 WriteOutputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReason reason)2702 void AudioPolicyService::WriteOutputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc, 2703 const AudioStreamDeviceChangeReason reason) 2704 { 2705 int64_t timeStamp = GetCurrentTimeMS(); 2706 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 2707 Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_ROUTE_CHANGE, 2708 Media::MediaMonitor::BEHAVIOR_EVENT); 2709 bean->Add("REASON", static_cast<int32_t>(reason)); 2710 bean->Add("TIMESTAMP", static_cast<uint64_t>(timeStamp)); 2711 bean->Add("DEVICE_TYPE_BEFORE_CHANGE", currentActiveDevice_.deviceType_); 2712 bean->Add("DEVICE_TYPE_AFTER_CHANGE", desc->deviceType_); 2713 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 2714 } 2715 FetchStreamForA2dpMchStream(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & descs)2716 void AudioPolicyService::FetchStreamForA2dpMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, 2717 vector<std::unique_ptr<AudioDeviceDescriptor>> &descs) 2718 { 2719 if (CheckStreamMultichannelMode(rendererChangeInfo->sessionId)) { 2720 JudgeIfLoadMchModule(); 2721 UpdateActiveDeviceRoute(DEVICE_TYPE_BLUETOOTH_A2DP, DeviceFlag::OUTPUT_DEVICES_FLAG); 2722 std::string portName = GetSinkPortName(descs.front()->deviceType_, PIPE_TYPE_MULTICHANNEL); 2723 int32_t ret = MoveToOutputDevice(rendererChangeInfo->sessionId, portName); 2724 if (ret == SUCCESS) { 2725 streamCollector_.UpdateRendererPipeInfo(rendererChangeInfo->sessionId, PIPE_TYPE_MULTICHANNEL); 2726 } 2727 } else { 2728 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN; 2729 streamCollector_.GetPipeType(rendererChangeInfo->sessionId, pipeType); 2730 if (pipeType == PIPE_TYPE_MULTICHANNEL) { 2731 std::string currentActivePort = MCH_PRIMARY_SPEAKER; 2732 auto ioHandleIter = IOHandles_.find(currentActivePort); 2733 CHECK_AND_RETURN_LOG(ioHandleIter != IOHandles_.end(), "Can not find port MCH_PRIMARY_SPEAKER in io map"); 2734 AudioIOHandle activateDeviceIOHandle = ioHandleIter->second; 2735 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true); 2736 audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle); 2737 IOHandles_.erase(currentActivePort); 2738 streamCollector_.UpdateRendererPipeInfo(rendererChangeInfo->sessionId, PIPE_TYPE_NORMAL_OUT); 2739 } 2740 ResetOffloadMode(rendererChangeInfo->sessionId); 2741 MoveToNewOutputDevice(rendererChangeInfo, descs); 2742 } 2743 } 2744 FetchStreamForA2dpOffload(const bool & requireReset)2745 void AudioPolicyService::FetchStreamForA2dpOffload(const bool &requireReset) 2746 { 2747 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfos; 2748 streamCollector_.GetCurrentRendererChangeInfos(rendererChangeInfos); 2749 AUDIO_INFO_LOG("FetchStreamForA2dpOffload start for %{public}zu stream", rendererChangeInfos.size()); 2750 for (auto &rendererChangeInfo : rendererChangeInfos) { 2751 if (!IsRendererStreamRunning(rendererChangeInfo)) { 2752 continue; 2753 } 2754 vector<std::unique_ptr<AudioDeviceDescriptor>> descs = 2755 audioRouterCenter_.FetchOutputDevices(rendererChangeInfo->rendererInfo.streamUsage, 2756 rendererChangeInfo->clientUID); 2757 2758 if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { 2759 if (requireReset) { 2760 int32_t ret = ActivateA2dpDevice(descs.front(), rendererChangeInfos); 2761 CHECK_AND_RETURN_LOG(ret == SUCCESS, "activate a2dp [%{public}s] failed", 2762 GetEncryptAddr(descs.front()->macAddress_).c_str()); 2763 } 2764 if (rendererChangeInfo->rendererInfo.rendererFlags == AUDIO_FLAG_MMAP) { 2765 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 2766 CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable"); 2767 std::string identity = IPCSkeleton::ResetCallingIdentity(); 2768 gsp->ResetAudioEndpoint(); 2769 IPCSkeleton::SetCallingIdentity(identity); 2770 } 2771 FetchStreamForA2dpMchStream(rendererChangeInfo, descs); 2772 } 2773 } 2774 } 2775 IsSameDevice(unique_ptr<AudioDeviceDescriptor> & desc,DeviceInfo & deviceInfo)2776 bool AudioPolicyService::IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, DeviceInfo &deviceInfo) 2777 { 2778 if (desc->networkId_ == deviceInfo.networkId && desc->deviceType_ == deviceInfo.deviceType && 2779 desc->macAddress_ == deviceInfo.macAddress && desc->connectState_ == deviceInfo.connectState) { 2780 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && 2781 // switch to A2dp 2782 ((deviceInfo.a2dpOffloadFlag == A2DP_OFFLOAD && a2dpOffloadFlag_ != A2DP_OFFLOAD) || 2783 // switch to A2dp offload 2784 (deviceInfo.a2dpOffloadFlag != A2DP_OFFLOAD && a2dpOffloadFlag_ == A2DP_OFFLOAD))) { 2785 return false; 2786 } 2787 return true; 2788 } else { 2789 return false; 2790 } 2791 } 2792 IsSameDevice(unique_ptr<AudioDeviceDescriptor> & desc,const AudioDeviceDescriptor & deviceDesc)2793 bool AudioPolicyService::IsSameDevice(unique_ptr<AudioDeviceDescriptor> &desc, const AudioDeviceDescriptor &deviceDesc) 2794 { 2795 if (desc->networkId_ == deviceDesc.networkId_ && desc->deviceType_ == deviceDesc.deviceType_ && 2796 desc->macAddress_ == deviceDesc.macAddress_ && desc->connectState_ == deviceDesc.connectState_) { 2797 return true; 2798 } else { 2799 return false; 2800 } 2801 } 2802 HandleScoInputDeviceFetched(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioCapturerChangeInfo>> & capturerChangeInfos)2803 int32_t AudioPolicyService::HandleScoInputDeviceFetched(unique_ptr<AudioDeviceDescriptor> &desc, 2804 vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos) 2805 { 2806 #ifdef BLUETOOTH_ENABLE 2807 int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_); 2808 if (ret != SUCCESS) { 2809 AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch input device"); 2810 desc->exceptionFlag_ = true; 2811 audioDeviceManager_.UpdateDevicesListInfo(new AudioDeviceDescriptor(*desc), EXCEPTION_FLAG_UPDATE); 2812 FetchInputDevice(capturerChangeInfos); 2813 return ERROR; 2814 } 2815 if (desc->connectState_ == DEACTIVE_CONNECTED || lastAudioScene_ != audioScene_) { 2816 Bluetooth::AudioHfpManager::ConnectScoWithAudioScene(audioScene_); 2817 return SUCCESS; 2818 } 2819 #endif 2820 return SUCCESS; 2821 } 2822 FetchInputDevice(vector<unique_ptr<AudioCapturerChangeInfo>> & capturerChangeInfos,const AudioStreamDeviceChangeReasonExt reason)2823 void AudioPolicyService::FetchInputDevice(vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos, 2824 const AudioStreamDeviceChangeReasonExt reason) 2825 { 2826 Trace trace("AudioPolicyService::FetchInputDevice"); 2827 AUDIO_INFO_LOG("Start for %{public}zu stream, connected %{public}s", 2828 capturerChangeInfos.size(), audioDeviceManager_.GetConnDevicesStr().c_str()); 2829 bool needUpdateActiveDevice = true; 2830 bool isUpdateActiveDevice = false; 2831 int32_t runningStreamCount = 0; 2832 for (auto &capturerChangeInfo : capturerChangeInfos) { 2833 SourceType sourceType = capturerChangeInfo->capturerInfo.sourceType; 2834 if ((sourceType == SOURCE_TYPE_VIRTUAL_CAPTURE && audioScene_ != AUDIO_SCENE_PHONE_CALL) || 2835 (sourceType != SOURCE_TYPE_VIRTUAL_CAPTURE && capturerChangeInfo->capturerState != CAPTURER_RUNNING)) { 2836 AUDIO_WARNING_LOG("stream %{public}d not running, no need fetch device", capturerChangeInfo->sessionId); 2837 continue; 2838 } 2839 runningStreamCount++; 2840 unique_ptr<AudioDeviceDescriptor> desc = audioRouterCenter_.FetchInputDevice(sourceType, 2841 capturerChangeInfo->clientUID); 2842 DeviceInfo inputDeviceInfo = capturerChangeInfo->inputDeviceInfo; 2843 if (HandleDeviceChangeForFetchInputDevice(desc, capturerChangeInfo) == ERR_NEED_NOT_SWITCH_DEVICE) { 2844 continue; 2845 } 2846 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 2847 BluetoothScoFetch(desc, capturerChangeInfos, sourceType); 2848 } 2849 if (needUpdateActiveDevice) { 2850 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice(); 2851 if (!IsSameDevice(desc, tempDesc)) { 2852 WriteInputRouteChangeEvent(desc, reason); 2853 SetCurrenInputDevice(*desc); 2854 AUDIO_DEBUG_LOG("currentActiveInputDevice update %{public}d", GetCurrentInputDeviceType()); 2855 isUpdateActiveDevice = true; 2856 } 2857 needUpdateActiveDevice = false; 2858 } 2859 if (NotifyRecreateCapturerStream(isUpdateActiveDevice, capturerChangeInfo, reason)) { 2860 continue; 2861 } 2862 // move sourceoutput to target device 2863 MoveToNewInputDevice(capturerChangeInfo, desc); 2864 AddAudioCapturerMicrophoneDescriptor(capturerChangeInfo->sessionId, desc->deviceType_); 2865 } 2866 if (isUpdateActiveDevice) { 2867 OnPreferredInputDeviceUpdated(GetCurrentInputDeviceType(), ""); // networkId is not used. 2868 } 2869 if (runningStreamCount == 0) { 2870 FetchInputDeviceWhenNoRunningStream(); 2871 } 2872 } 2873 HandleDeviceChangeForFetchInputDevice(unique_ptr<AudioDeviceDescriptor> & desc,unique_ptr<AudioCapturerChangeInfo> & capturerChangeInfo)2874 int32_t AudioPolicyService::HandleDeviceChangeForFetchInputDevice(unique_ptr<AudioDeviceDescriptor> &desc, 2875 unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo) 2876 { 2877 if (desc->deviceType_ == DEVICE_TYPE_NONE || 2878 (IsSameDevice(desc, capturerChangeInfo->inputDeviceInfo) && desc->connectState_ != DEACTIVE_CONNECTED)) { 2879 AUDIO_WARNING_LOG("stream %{public}d device not change, no need move device", capturerChangeInfo->sessionId); 2880 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice(); 2881 if (!IsSameDevice(desc, tempDesc) && IsSameDevice(desc, capturerChangeInfo->inputDeviceInfo)) { 2882 SetCurrenInputDevice(*desc); 2883 OnPreferredInputDeviceUpdated(GetCurrentInputDeviceType(), ""); // networkId is not used 2884 UpdateActiveDeviceRoute(GetCurrentInputDeviceType(), DeviceFlag::INPUT_DEVICES_FLAG); 2885 } 2886 return ERR_NEED_NOT_SWITCH_DEVICE; 2887 } 2888 return SUCCESS; 2889 } 2890 BluetoothScoFetch(unique_ptr<AudioDeviceDescriptor> & desc,vector<unique_ptr<AudioCapturerChangeInfo>> & capturerChangeInfos,SourceType sourceType)2891 void AudioPolicyService::BluetoothScoFetch(unique_ptr<AudioDeviceDescriptor> &desc, 2892 vector<unique_ptr<AudioCapturerChangeInfo>> &capturerChangeInfos, SourceType sourceType) 2893 { 2894 int32_t ret; 2895 if (sourceType == SOURCE_TYPE_VOICE_RECOGNITION) { 2896 int32_t activeRet = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_); 2897 if (activeRet != SUCCESS) { 2898 AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch input device"); 2899 desc->exceptionFlag_ = true; 2900 audioDeviceManager_.UpdateDevicesListInfo(new AudioDeviceDescriptor(*desc), EXCEPTION_FLAG_UPDATE); 2901 FetchInputDevice(capturerChangeInfos); 2902 } 2903 ret = ScoInputDeviceFetchedForRecongnition(true, desc->macAddress_, desc->connectState_); 2904 } else { 2905 ret = HandleScoInputDeviceFetched(desc, capturerChangeInfos); 2906 } 2907 if (ret != SUCCESS) { 2908 AUDIO_ERR_LOG("sco [%{public}s] is not connected yet", GetEncryptAddr(desc->macAddress_).c_str()); 2909 } 2910 } 2911 BluetoothScoDisconectForRecongnition()2912 void AudioPolicyService::BluetoothScoDisconectForRecongnition() 2913 { 2914 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice(); 2915 AUDIO_INFO_LOG("Recongnition scoCategory: %{public}d, deviceType: %{public}d, scoState: %{public}d", 2916 Bluetooth::AudioHfpManager::GetScoCategory(), tempDesc.deviceType_, 2917 audioDeviceManager_.GetScoState()); 2918 if (tempDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 2919 int32_t ret = ScoInputDeviceFetchedForRecongnition(false, tempDesc.macAddress_, tempDesc.connectState_); 2920 CHECK_AND_RETURN_LOG(ret == SUCCESS, "sco [%{public}s] disconnected failed", 2921 GetEncryptAddr(tempDesc.macAddress_).c_str()); 2922 } 2923 } 2924 NotifyRecreateCapturerStream(bool isUpdateActiveDevice,const std::unique_ptr<AudioCapturerChangeInfo> & capturerChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2925 bool AudioPolicyService::NotifyRecreateCapturerStream(bool isUpdateActiveDevice, 2926 const std::unique_ptr<AudioCapturerChangeInfo> &capturerChangeInfo, 2927 const AudioStreamDeviceChangeReasonExt reason) 2928 { 2929 AUDIO_INFO_LOG("Is update active device: %{public}d, current capturerFlag: %{public}d, origianl flag: %{public}d", 2930 isUpdateActiveDevice, capturerChangeInfo->capturerInfo.capturerFlags, 2931 capturerChangeInfo->capturerInfo.originalFlag); 2932 CHECK_AND_RETURN_RET_LOG(isUpdateActiveDevice, false, "isUpdateActiveDevice is false"); 2933 CHECK_AND_RETURN_RET_LOG(capturerChangeInfo->capturerInfo.originalFlag == AUDIO_FLAG_MMAP, false, 2934 "original flag is false"); 2935 // Switch between old and new stream as they have different hals 2936 std::string oldDevicePortName = GetSourcePortName(capturerChangeInfo->inputDeviceInfo.deviceType); 2937 if ((strcmp(oldDevicePortName.c_str(), GetSourcePortName(currentActiveDevice_.deviceType_).c_str())) || 2938 ((capturerChangeInfo->inputDeviceInfo.networkId == LOCAL_NETWORK_ID) ^ 2939 (currentActiveDevice_.networkId_ == LOCAL_NETWORK_ID))) { 2940 int32_t streamClass = GetPreferredInputStreamTypeInner(capturerChangeInfo->capturerInfo.sourceType, 2941 currentActiveDevice_.deviceType_, capturerChangeInfo->capturerInfo.originalFlag, 2942 GetCurrentInputDevice().networkId_, capturerChangeInfo->capturerInfo.samplingRate); 2943 TriggerRecreateCapturerStreamCallback(capturerChangeInfo->callerPid, 2944 capturerChangeInfo->sessionId, streamClass, reason); 2945 return true; 2946 } 2947 return false; 2948 } 2949 TriggerRecreateCapturerStreamCallback(int32_t callerPid,int32_t sessionId,int32_t streamFlag,const AudioStreamDeviceChangeReasonExt reason)2950 void AudioPolicyService::TriggerRecreateCapturerStreamCallback(int32_t callerPid, int32_t sessionId, int32_t streamFlag, 2951 const AudioStreamDeviceChangeReasonExt reason) 2952 { 2953 Trace trace("AudioPolicyService::TriggerRecreateCapturerStreamCallback"); 2954 AUDIO_WARNING_LOG("Trigger recreate capturer stream, pid: %{public}d, sessionId: %{public}d, flag: %{public}d", 2955 callerPid, sessionId, streamFlag); 2956 if (audioPolicyServerHandler_ != nullptr) { 2957 audioPolicyServerHandler_->SendRecreateCapturerStreamEvent(callerPid, sessionId, streamFlag, reason); 2958 } else { 2959 AUDIO_WARNING_LOG("No audio policy server handler"); 2960 } 2961 } 2962 WriteInputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReason reason)2963 void AudioPolicyService::WriteInputRouteChangeEvent(unique_ptr<AudioDeviceDescriptor> &desc, 2964 const AudioStreamDeviceChangeReason reason) 2965 { 2966 int64_t timeStamp = GetCurrentTimeMS(); 2967 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 2968 Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_ROUTE_CHANGE, 2969 Media::MediaMonitor::BEHAVIOR_EVENT); 2970 bean->Add("REASON", static_cast<int32_t>(reason)); 2971 bean->Add("TIMESTAMP", static_cast<uint64_t>(timeStamp)); 2972 bean->Add("DEVICE_TYPE_BEFORE_CHANGE", GetCurrentInputDeviceType()); 2973 bean->Add("DEVICE_TYPE_AFTER_CHANGE", desc->deviceType_); 2974 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 2975 } 2976 FetchDevice(bool isOutputDevice,const AudioStreamDeviceChangeReasonExt reason)2977 void AudioPolicyService::FetchDevice(bool isOutputDevice, const AudioStreamDeviceChangeReasonExt reason) 2978 { 2979 Trace trace("AudioPolicyService::FetchDevice reason:" + std::to_string(static_cast<int>(reason))); 2980 AUDIO_DEBUG_LOG("FetchDevice start"); 2981 2982 if (isOutputDevice) { 2983 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfos; 2984 streamCollector_.GetCurrentRendererChangeInfos(rendererChangeInfos); 2985 FetchOutputDevice(rendererChangeInfos, reason); 2986 } else { 2987 vector<unique_ptr<AudioCapturerChangeInfo>> capturerChangeInfos; 2988 streamCollector_.GetCurrentCapturerChangeInfos(capturerChangeInfos); 2989 FetchInputDevice(capturerChangeInfos, reason); 2990 } 2991 } 2992 SetMicrophoneMute(bool isMute)2993 int32_t AudioPolicyService::SetMicrophoneMute(bool isMute) 2994 { 2995 AUDIO_DEBUG_LOG("SetMicrophoneMute state[%{public}d]", isMute); 2996 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 2997 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable"); 2998 std::string identity = IPCSkeleton::ResetCallingIdentity(); 2999 int32_t ret = gsp->SetMicrophoneMute(isMute | isMicrophoneMutePersistent_); 3000 IPCSkeleton::SetCallingIdentity(identity); 3001 if (ret == SUCCESS) { 3002 isMicrophoneMuteTemporary_ = isMute; 3003 streamCollector_.UpdateCapturerInfoMuteStatus(0, isMicrophoneMuteTemporary_ | isMicrophoneMutePersistent_); 3004 } 3005 return ret; 3006 } 3007 SetMicrophoneMutePersistent(const bool isMute)3008 int32_t AudioPolicyService::SetMicrophoneMutePersistent(const bool isMute) 3009 { 3010 AUDIO_DEBUG_LOG("state[%{public}d]", isMute); 3011 isMicrophoneMutePersistent_ = isMute; 3012 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 3013 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable"); 3014 std::string identity = IPCSkeleton::ResetCallingIdentity(); 3015 int32_t ret = gsp->SetMicrophoneMute(isMicrophoneMuteTemporary_ | isMicrophoneMutePersistent_); 3016 IPCSkeleton::SetCallingIdentity(identity); 3017 if (ret == SUCCESS) { 3018 AUDIO_INFO_LOG("UpdateCapturerInfoMuteStatus when set mic mute state persistent."); 3019 streamCollector_.UpdateCapturerInfoMuteStatus(0, isMicrophoneMuteTemporary_|isMicrophoneMutePersistent_); 3020 } 3021 ret = audioPolicyManager_.SetPersistMicMuteState(isMicrophoneMutePersistent_); 3022 if (ret != SUCCESS) { 3023 AUDIO_ERR_LOG("Failed to save the persistent microphone mute status in setting database."); 3024 return ERROR; 3025 } 3026 return ret; 3027 } 3028 GetPersistentMicMuteState()3029 bool AudioPolicyService::GetPersistentMicMuteState() 3030 { 3031 return isMicrophoneMutePersistent_; 3032 } 3033 InitPersistentMicrophoneMuteState(bool & isMute)3034 int32_t AudioPolicyService::InitPersistentMicrophoneMuteState(bool &isMute) 3035 { 3036 int32_t ret = audioPolicyManager_.GetPersistMicMuteState(isMute); 3037 if (ret != SUCCESS) { 3038 AUDIO_ERR_LOG("GetPersistMicMuteState failed."); 3039 return ret; 3040 } 3041 // Ensure persistent mic mute state takes effect when first startup 3042 isMicrophoneMutePersistent_ = isMute; 3043 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 3044 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable"); 3045 std::string identity = IPCSkeleton::ResetCallingIdentity(); 3046 ret = gsp->SetMicrophoneMute(isMicrophoneMutePersistent_); 3047 IPCSkeleton::SetCallingIdentity(identity); 3048 if (ret == SUCCESS) { 3049 AUDIO_INFO_LOG("UpdateCapturerInfoMuteStatus when audio service restart."); 3050 streamCollector_.UpdateCapturerInfoMuteStatus(0, isMicrophoneMutePersistent_); 3051 } 3052 return ret; 3053 } 3054 IsMicrophoneMute()3055 bool AudioPolicyService::IsMicrophoneMute() 3056 { 3057 return isMicrophoneMuteTemporary_ | isMicrophoneMutePersistent_; 3058 } 3059 SetSystemSoundUri(const std::string & key,const std::string & uri)3060 int32_t AudioPolicyService::SetSystemSoundUri(const std::string &key, const std::string &uri) 3061 { 3062 return audioPolicyManager_.SetSystemSoundUri(key, uri); 3063 } 3064 GetSystemSoundUri(const std::string & key)3065 std::string AudioPolicyService::GetSystemSoundUri(const std::string &key) 3066 { 3067 return audioPolicyManager_.GetSystemSoundUri(key); 3068 } 3069 SwitchActiveA2dpDevice(const sptr<AudioDeviceDescriptor> & deviceDescriptor)3070 int32_t AudioPolicyService::SwitchActiveA2dpDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor) 3071 { 3072 auto iter = connectedA2dpDeviceMap_.find(deviceDescriptor->macAddress_); 3073 CHECK_AND_RETURN_RET_LOG(iter != connectedA2dpDeviceMap_.end(), ERR_INVALID_PARAM, 3074 "SelectNewDevice: the target A2DP device doesn't exist."); 3075 int32_t result = ERROR; 3076 #ifdef BLUETOOTH_ENABLE 3077 AUDIO_INFO_LOG("a2dp device name [%{public}s]", (deviceDescriptor->deviceName_).c_str()); 3078 std::string lastActiveA2dpDevice = activeBTDevice_; 3079 activeBTDevice_ = deviceDescriptor->macAddress_; 3080 DeviceType lastDevice = audioPolicyManager_.GetActiveDevice(); 3081 audioPolicyManager_.SetActiveDevice(DEVICE_TYPE_BLUETOOTH_A2DP); 3082 3083 { 3084 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 3085 if (Bluetooth::AudioA2dpManager::GetActiveA2dpDevice() == deviceDescriptor->macAddress_ && 3086 IOHandles_.find(BLUETOOTH_SPEAKER) != IOHandles_.end()) { 3087 AUDIO_WARNING_LOG("a2dp device [%{public}s] is already active", 3088 GetEncryptAddr(deviceDescriptor->macAddress_).c_str()); 3089 return SUCCESS; 3090 } 3091 } 3092 3093 result = Bluetooth::AudioA2dpManager::SetActiveA2dpDevice(deviceDescriptor->macAddress_); 3094 if (result != SUCCESS) { 3095 activeBTDevice_ = lastActiveA2dpDevice; 3096 audioPolicyManager_.SetActiveDevice(lastDevice); 3097 AUDIO_ERR_LOG("Active [%{public}s] failed, using original [%{public}s] device", 3098 GetEncryptAddr(activeBTDevice_).c_str(), GetEncryptAddr(lastActiveA2dpDevice).c_str()); 3099 return result; 3100 } 3101 3102 result = LoadA2dpModule(); 3103 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "LoadA2dpModule failed %{public}d", result); 3104 #endif 3105 return result; 3106 } 3107 UnloadA2dpModule()3108 void AudioPolicyService::UnloadA2dpModule() 3109 { 3110 MuteDefaultSinkPort(); 3111 ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER); 3112 } 3113 LoadA2dpModule()3114 int32_t AudioPolicyService::LoadA2dpModule() 3115 { 3116 std::list<AudioModuleInfo> moduleInfoList; 3117 { 3118 auto primaryModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP); 3119 CHECK_AND_RETURN_RET_LOG(primaryModulesPos != deviceClassInfo_.end(), ERR_OPERATION_FAILED, 3120 "A2dp module is not exist in the configuration file"); 3121 moduleInfoList = primaryModulesPos->second; 3122 } 3123 for (auto &moduleInfo : moduleInfoList) { 3124 AudioStreamInfo audioStreamInfo = {}; 3125 GetActiveDeviceStreamInfo(DEVICE_TYPE_BLUETOOTH_A2DP, audioStreamInfo); 3126 3127 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 3128 if (IOHandles_.find(moduleInfo.name) == IOHandles_.end()) { 3129 // a2dp device connects for the first time 3130 AUDIO_DEBUG_LOG("Load a2dp module [%{public}s]", moduleInfo.name.c_str()); 3131 uint32_t bufferSize = (audioStreamInfo.samplingRate * GetSampleFormatValue(audioStreamInfo.format) * 3132 audioStreamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR); 3133 AUDIO_INFO_LOG("a2dp rate: %{public}d, format: %{public}d, channel: %{public}d", 3134 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels); 3135 moduleInfo.channels = to_string(audioStreamInfo.channels); 3136 moduleInfo.rate = to_string(audioStreamInfo.samplingRate); 3137 moduleInfo.format = ConvertToHDIAudioFormat(audioStreamInfo.format); 3138 moduleInfo.bufferSize = to_string(bufferSize); 3139 moduleInfo.renderInIdleState = "1"; 3140 moduleInfo.sinkLatency = "0"; 3141 3142 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo); 3143 CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED, 3144 "LoadA2dpModule: OpenAudioPort failed %{public}d", ioHandle); 3145 IOHandles_[moduleInfo.name] = ioHandle; 3146 } else { 3147 // At least one a2dp device is already connected. A new a2dp device is connecting. 3148 // Need to reload a2dp module when switching to a2dp device. 3149 int32_t result = ReloadA2dpAudioPort(moduleInfo, audioStreamInfo); 3150 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "ReloadA2dpAudioPort failed %{public}d", result); 3151 } 3152 } 3153 3154 return SUCCESS; 3155 } 3156 ReloadA2dpAudioPort(AudioModuleInfo & moduleInfo,const AudioStreamInfo & audioStreamInfo)3157 int32_t AudioPolicyService::ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, const AudioStreamInfo& audioStreamInfo) 3158 { 3159 AUDIO_INFO_LOG("switch device from a2dp to another a2dp, reload a2dp module"); 3160 MuteDefaultSinkPort(); 3161 3162 // Firstly, unload the existing a2dp sink. 3163 AudioIOHandle activateDeviceIOHandle = IOHandles_[BLUETOOTH_SPEAKER]; 3164 int32_t result = audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle); 3165 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, 3166 "ReloadA2dpAudioPort: CloseAudioPort failed %{public}d", result); 3167 3168 // Load a2dp sink module again with the configuration of active a2dp device. 3169 uint32_t bufferSize = (audioStreamInfo.samplingRate * GetSampleFormatValue(audioStreamInfo.format) * 3170 audioStreamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR); 3171 AUDIO_DEBUG_LOG("ReloadA2dpAudioPort: a2dp rate: %{public}d, format: %{public}d, channel: %{public}d", 3172 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels); 3173 moduleInfo.channels = to_string(audioStreamInfo.channels); 3174 moduleInfo.rate = to_string(audioStreamInfo.samplingRate); 3175 moduleInfo.format = ConvertToHDIAudioFormat(audioStreamInfo.format); 3176 moduleInfo.bufferSize = to_string(bufferSize); 3177 moduleInfo.renderInIdleState = "1"; 3178 moduleInfo.sinkLatency = "0"; 3179 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo); 3180 CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED, 3181 "ReloadA2dpAudioPort: OpenAudioPort failed %{public}d", ioHandle); 3182 IOHandles_[moduleInfo.name] = ioHandle; 3183 return SUCCESS; 3184 } 3185 LoadUsbModule(string deviceInfo,DeviceRole deviceRole)3186 int32_t AudioPolicyService::LoadUsbModule(string deviceInfo, DeviceRole deviceRole) 3187 { 3188 std::list<AudioModuleInfo> moduleInfoList; 3189 { 3190 auto usbModulesPos = deviceClassInfo_.find(ClassType::TYPE_USB); 3191 if (usbModulesPos == deviceClassInfo_.end()) { 3192 return ERR_OPERATION_FAILED; 3193 } 3194 moduleInfoList = usbModulesPos->second; 3195 } 3196 for (auto &moduleInfo : moduleInfoList) { 3197 DeviceRole configRole = moduleInfo.role == "sink" ? OUTPUT_DEVICE : INPUT_DEVICE; 3198 AUDIO_INFO_LOG("[module_load]::load module[%{public}s], load role[%{public}d] config role[%{public}d]", 3199 moduleInfo.name.c_str(), deviceRole, configRole); 3200 if (configRole != deviceRole) {continue;} 3201 GetUsbModuleInfo(deviceInfo, moduleInfo); 3202 int32_t ret = OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 3203 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, 3204 "Load usb %{public}s failed %{public}d", moduleInfo.role.c_str(), ret); 3205 } 3206 3207 return SUCCESS; 3208 } 3209 LoadDpModule(string deviceInfo)3210 int32_t AudioPolicyService::LoadDpModule(string deviceInfo) 3211 { 3212 AUDIO_INFO_LOG("LoadDpModule"); 3213 std::list<AudioModuleInfo> moduleInfoList; 3214 { 3215 auto usbModulesPos = deviceClassInfo_.find(ClassType::TYPE_DP); 3216 if (usbModulesPos == deviceClassInfo_.end()) { 3217 return ERR_OPERATION_FAILED; 3218 } 3219 moduleInfoList = usbModulesPos->second; 3220 } 3221 for (auto &moduleInfo : moduleInfoList) { 3222 AUDIO_INFO_LOG("[module_load]::load module[%{public}s]", moduleInfo.name.c_str()); 3223 if (IOHandles_.find(moduleInfo.name) == IOHandles_.end()) { 3224 GetDPModuleInfo(moduleInfo, deviceInfo); 3225 return OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 3226 } 3227 } 3228 3229 return SUCCESS; 3230 } 3231 LoadDefaultUsbModule(DeviceRole deviceRole)3232 int32_t AudioPolicyService::LoadDefaultUsbModule(DeviceRole deviceRole) 3233 { 3234 AUDIO_INFO_LOG("LoadDefaultUsbModule"); 3235 3236 std::list<AudioModuleInfo> moduleInfoList; 3237 { 3238 auto usbModulesPos = deviceClassInfo_.find(ClassType::TYPE_USB); 3239 if (usbModulesPos == deviceClassInfo_.end()) { 3240 return ERR_OPERATION_FAILED; 3241 } 3242 moduleInfoList = usbModulesPos->second; 3243 } 3244 for (auto &moduleInfo : moduleInfoList) { 3245 DeviceRole configRole = moduleInfo.role == "sink" ? OUTPUT_DEVICE : INPUT_DEVICE; 3246 AUDIO_INFO_LOG("[module_load]::load default module[%{public}s], load role[%{public}d] config role[%{public}d]", 3247 moduleInfo.name.c_str(), deviceRole, configRole); 3248 if (configRole != deviceRole) {continue;} 3249 int32_t ret = OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 3250 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, 3251 "Load usb %{public}s failed %{public}d", moduleInfo.role.c_str(), ret); 3252 } 3253 3254 return SUCCESS; 3255 } 3256 HandleActiveDevice(DeviceType deviceType)3257 int32_t AudioPolicyService::HandleActiveDevice(DeviceType deviceType) 3258 { 3259 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 3260 if (GetVolumeGroupType(curOutputDeviceType) != GetVolumeGroupType(deviceType)) { 3261 SetVolumeForSwitchDevice(deviceType); 3262 } 3263 if (isUpdateRouteSupported_) { 3264 UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG); 3265 } 3266 std::string sinkPortName = GetSinkPortName(deviceType); 3267 std::string sourcePortName = GetSourcePortName(deviceType); 3268 if (sinkPortName == PORT_NONE && sourcePortName == PORT_NONE) { 3269 AUDIO_ERR_LOG("HandleActiveDevice failed for sinkPortName and sourcePortName are none"); 3270 return ERR_OPERATION_FAILED; 3271 } 3272 if (sinkPortName != PORT_NONE) { 3273 GetSinkIOHandle(deviceType); 3274 audioPolicyManager_.SuspendAudioDevice(sinkPortName, false); 3275 } 3276 if (sourcePortName != PORT_NONE) { 3277 GetSourceIOHandle(deviceType); 3278 audioPolicyManager_.SuspendAudioDevice(sourcePortName, false); 3279 } 3280 UpdateInputDeviceInfo(deviceType); 3281 3282 return SUCCESS; 3283 } 3284 HandleArmUsbDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)3285 int32_t AudioPolicyService::HandleArmUsbDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address) 3286 { 3287 Trace trace("AudioPolicyService::HandleArmUsbDevice"); 3288 3289 if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) { 3290 string deviceInfo = ""; 3291 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 3292 if (gsp != nullptr) { 3293 std::string identity = IPCSkeleton::ResetCallingIdentity(); 3294 deviceInfo = gsp->GetAudioParameter(LOCAL_NETWORK_ID, USB_DEVICE, address); 3295 IPCSkeleton::SetCallingIdentity(identity); 3296 AUDIO_INFO_LOG("device info from usb hal is %{public}s", deviceInfo.c_str()); 3297 } 3298 int32_t ret; 3299 if (!deviceInfo.empty()) { 3300 ret = LoadUsbModule(deviceInfo, deviceRole); 3301 } else { 3302 ret = LoadDefaultUsbModule(deviceRole); 3303 } 3304 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "load usb role[%{public}d] module failed", deviceRole); 3305 3306 std::string activePort = GetSinkPortName(DEVICE_TYPE_USB_ARM_HEADSET); 3307 AUDIO_DEBUG_LOG("port %{public}s, active arm usb device", activePort.c_str()); 3308 } else if (GetCurrentOutputDeviceType() == DEVICE_TYPE_USB_HEADSET) { 3309 std::string activePort = GetSinkPortName(DEVICE_TYPE_USB_ARM_HEADSET); 3310 audioPolicyManager_.SuspendAudioDevice(activePort, true); 3311 } 3312 3313 return SUCCESS; 3314 } 3315 RehandlePnpDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)3316 int32_t AudioPolicyService::RehandlePnpDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address) 3317 { 3318 Trace trace("AudioPolicyService::RehandlePnpDevice"); 3319 3320 // Maximum number of attempts, preventing situations where hal has not yet finished coming online. 3321 int32_t maxRetries = 3; 3322 int32_t retryCount = 0; 3323 int32_t ret = ERROR; 3324 bool isConnected = true; 3325 while (retryCount < maxRetries) { 3326 retryCount++; 3327 AUDIO_INFO_LOG("rehandle device[%{public}d], retry count[%{public}d]", deviceType, retryCount); 3328 3329 ret = HandleSpecialDeviceType(deviceType, isConnected, address); 3330 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Rehandle special device type failed"); 3331 if (deviceType == DEVICE_TYPE_USB_HEADSET) { 3332 AUDIO_INFO_LOG("Hifi device, don't load module"); 3333 hasArmUsbDevice_ = false; 3334 return ret; 3335 } 3336 if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) { 3337 if (HandleArmUsbDevice(deviceType, deviceRole, address) == SUCCESS) { 3338 return SUCCESS; 3339 } 3340 } else if (deviceType == DEVICE_TYPE_DP) { 3341 if (HandleDpDevice(deviceType, address) == SUCCESS) { 3342 return SUCCESS; 3343 } 3344 } 3345 usleep(REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS); 3346 } 3347 3348 AUDIO_ERR_LOG("rehandle device[%{public}d] failed", deviceType); 3349 return ERROR; 3350 } 3351 GetModuleInfo(ClassType classType,std::string & moduleInfoStr)3352 int32_t AudioPolicyService::GetModuleInfo(ClassType classType, std::string &moduleInfoStr) 3353 { 3354 std::list<AudioModuleInfo> moduleInfoList; 3355 { 3356 auto modulesPos = deviceClassInfo_.find(classType); 3357 if (modulesPos == deviceClassInfo_.end()) { 3358 AUDIO_ERR_LOG("find %{public}d type failed", classType); 3359 return ERR_OPERATION_FAILED; 3360 } 3361 moduleInfoList = modulesPos->second; 3362 } 3363 moduleInfoStr = audioPolicyManager_.GetModuleArgs(*moduleInfoList.begin()); 3364 return SUCCESS; 3365 } 3366 HandleDpDevice(DeviceType deviceType,const std::string & address)3367 int32_t AudioPolicyService::HandleDpDevice(DeviceType deviceType, const std::string &address) 3368 { 3369 Trace trace("AudioPolicyService::HandleDpDevice"); 3370 if (deviceType == DEVICE_TYPE_DP) { 3371 std::string defaulyDPInfo = ""; 3372 std::string getDPInfo = ""; 3373 GetModuleInfo(ClassType::TYPE_DP, defaulyDPInfo); 3374 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device"); 3375 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 3376 if (gsp != nullptr) { 3377 std::string identity = IPCSkeleton::ResetCallingIdentity(); 3378 getDPInfo = gsp->GetAudioParameter(LOCAL_NETWORK_ID, GET_DP_DEVICE_INFO, 3379 defaulyDPInfo + " address=" + address + " "); 3380 IPCSkeleton::SetCallingIdentity(identity); 3381 AUDIO_DEBUG_LOG("device info from dp hal is \n defaulyDPInfo:%{public}s", defaulyDPInfo.c_str()); 3382 } 3383 getDPInfo = getDPInfo.empty() ? defaulyDPInfo : getDPInfo; 3384 int32_t ret = LoadDpModule(getDPInfo); 3385 if (ret != SUCCESS) { 3386 AUDIO_ERR_LOG ("load dp module failed"); 3387 return ERR_OPERATION_FAILED; 3388 } 3389 std::string activePort = GetSinkPortName(DEVICE_TYPE_DP); 3390 AUDIO_INFO_LOG("port %{public}s, active dp device", activePort.c_str()); 3391 } else if (GetCurrentOutputDeviceType() == DEVICE_TYPE_DP) { 3392 std::string activePort = GetSinkPortName(DEVICE_TYPE_DP); 3393 audioPolicyManager_.SuspendAudioDevice(activePort, true); 3394 } 3395 3396 return SUCCESS; 3397 } 3398 UnmutePortAfterMuteDuration(int32_t muteDuration,std::string portName,DeviceType deviceType)3399 void AudioPolicyService::UnmutePortAfterMuteDuration(int32_t muteDuration, std::string portName, DeviceType deviceType) 3400 { 3401 Trace trace("UnmutePortAfterMuteDuration:" + portName + " for " + std::to_string(muteDuration) + "us"); 3402 3403 if (!moveDeviceFinished_.load()) { 3404 std::unique_lock<std::mutex> lock(moveDeviceMutex_); 3405 bool loadWaiting = moveDeviceCV_.wait_for(lock, 3406 std::chrono::milliseconds(WAIT_MOVE_DEVICE_MUTE_TIME_MAX_MS), 3407 [this] { return moveDeviceFinished_.load(); } 3408 ); 3409 if (!loadWaiting) { 3410 AUDIO_ERR_LOG("move device time out"); 3411 } 3412 } 3413 AUDIO_INFO_LOG("%{public}d us for device type[%{public}s]", muteDuration, portName.c_str()); 3414 3415 usleep(muteDuration); 3416 if (sinkPortStrToClassStrMap_.count(portName) > 0) { 3417 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 3418 if (gsp != nullptr) { 3419 std::string identity = IPCSkeleton::ResetCallingIdentity(); 3420 gsp->SetSinkMuteForSwitchDevice(sinkPortStrToClassStrMap_.at(portName), muteDuration, false); 3421 IPCSkeleton::SetCallingIdentity(identity); 3422 } 3423 } else { 3424 audioPolicyManager_.SetSinkMute(portName, false); 3425 } 3426 } 3427 ActivateNewDevice(std::string networkId,DeviceType deviceType,bool isRemote)3428 int32_t AudioPolicyService::ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote) 3429 { 3430 if (isRemote) { 3431 AudioModuleInfo moduleInfo = ConstructRemoteAudioModuleInfo(networkId, GetDeviceRole(deviceType), deviceType); 3432 std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(deviceType)); 3433 OpenPortAndInsertIOHandle(moduleName, moduleInfo); 3434 } 3435 return SUCCESS; 3436 } 3437 SetDeviceActive(InternalDeviceType deviceType,bool active)3438 int32_t AudioPolicyService::SetDeviceActive(InternalDeviceType deviceType, bool active) 3439 { 3440 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 3441 3442 AUDIO_WARNING_LOG("Device type[%{public}d] flag[%{public}d]", deviceType, active); 3443 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device"); 3444 3445 // Activate new device if its already connected 3446 auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) { 3447 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "SetDeviceActive::Invalid device descriptor"); 3448 return ((deviceType == desc->deviceType_) || (deviceType == DEVICE_TYPE_FILE_SINK)); 3449 }; 3450 3451 vector<unique_ptr<AudioDeviceDescriptor>> callDevices = GetAvailableDevicesInner(CALL_OUTPUT_DEVICES); 3452 std::vector<sptr<AudioDeviceDescriptor>> deviceList = {}; 3453 for (auto &desc : callDevices) { 3454 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc); 3455 deviceList.push_back(devDesc); 3456 } 3457 3458 auto itr = std::find_if(deviceList.begin(), deviceList.end(), isPresent); 3459 CHECK_AND_RETURN_RET_LOG(itr != deviceList.end(), ERR_OPERATION_FAILED, 3460 "Requested device not available %{public}d ", deviceType); 3461 if (!active) { 3462 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 3463 #ifdef BLUETOOTH_ENABLE 3464 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO && 3465 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 3466 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO, 3467 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT); 3468 Bluetooth::AudioHfpManager::DisconnectSco(); 3469 } 3470 #endif 3471 } else { 3472 SetPreferredDevice(AUDIO_CALL_RENDER, *itr); 3473 #ifdef BLUETOOTH_ENABLE 3474 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO && 3475 deviceType != DEVICE_TYPE_BLUETOOTH_SCO) { 3476 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO, 3477 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT); 3478 Bluetooth::AudioHfpManager::DisconnectSco(); 3479 } 3480 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_BLUETOOTH_SCO && 3481 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 3482 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO, 3483 (*itr)->macAddress_, USER_SELECT_BT); 3484 } 3485 #endif 3486 } 3487 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); 3488 return SUCCESS; 3489 } 3490 IsDeviceActive(InternalDeviceType deviceType)3491 bool AudioPolicyService::IsDeviceActive(InternalDeviceType deviceType) 3492 { 3493 AUDIO_DEBUG_LOG("type [%{public}d]", deviceType); 3494 CHECK_AND_RETURN_RET(GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID, false); 3495 return GetCurrentOutputDeviceType() == deviceType; 3496 } 3497 GetActiveOutputDevice()3498 DeviceType AudioPolicyService::GetActiveOutputDevice() 3499 { 3500 return GetCurrentOutputDeviceType(); 3501 } 3502 GetActiveOutputDeviceDescriptor()3503 unique_ptr<AudioDeviceDescriptor> AudioPolicyService::GetActiveOutputDeviceDescriptor() 3504 { 3505 return make_unique<AudioDeviceDescriptor>(GetCurrentOutputDevice()); 3506 } 3507 GetActiveInputDevice()3508 DeviceType AudioPolicyService::GetActiveInputDevice() 3509 { 3510 return GetCurrentInputDeviceType(); 3511 } 3512 SetRingerMode(AudioRingerMode ringMode)3513 int32_t AudioPolicyService::SetRingerMode(AudioRingerMode ringMode) 3514 { 3515 int32_t result = audioPolicyManager_.SetRingerMode(ringMode); 3516 if (result == SUCCESS) { 3517 if (Util::IsRingerAudioScene(audioScene_)) { 3518 AUDIO_INFO_LOG("fetch output device after switch new ringmode."); 3519 FetchDevice(true); 3520 } 3521 Volume vol = {false, 1.0f, 0}; 3522 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 3523 vol.isMute = (ringMode == RINGER_MODE_NORMAL) ? false : true; 3524 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevel(STREAM_RING)); 3525 vol.volumeFloat = GetSystemVolumeInDb(STREAM_RING, vol.volumeInt, curOutputDeviceType); 3526 SetSharedVolume(STREAM_RING, curOutputDeviceType, vol); 3527 } 3528 return result; 3529 } 3530 GetRingerMode() const3531 AudioRingerMode AudioPolicyService::GetRingerMode() const 3532 { 3533 return audioPolicyManager_.GetRingerMode(); 3534 } 3535 SetAudioScene(AudioScene audioScene)3536 int32_t AudioPolicyService::SetAudioScene(AudioScene audioScene) 3537 { 3538 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 3539 3540 AUDIO_INFO_LOG("Set audio scene start %{public}d", audioScene); 3541 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 3542 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "Service proxy unavailable"); 3543 3544 lastAudioScene_ = audioScene_; 3545 audioScene_ = audioScene; 3546 Bluetooth::AudioHfpManager::SetAudioSceneFromPolicy(audioScene_); 3547 if (lastAudioScene_ != AUDIO_SCENE_DEFAULT && audioScene_ == AUDIO_SCENE_DEFAULT) { 3548 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 3549 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor()); 3550 #ifdef BLUETOOTH_ENABLE 3551 Bluetooth::AudioHfpManager::DisconnectSco(); 3552 #endif 3553 } 3554 if (audioScene_ == AUDIO_SCENE_DEFAULT) { 3555 ClearScoDeviceSuspendState(); 3556 } 3557 3558 // fetch input&output device 3559 FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::SET_AUDIO_SCENE); 3560 FetchDevice(false); 3561 3562 std::vector<DeviceType> activeOutputDevices; 3563 bool haveArmUsbDevice = false; 3564 DealAudioSceneOutputDevices(audioScene, activeOutputDevices, haveArmUsbDevice); 3565 // mute primary when play music and ring 3566 if (activeOutputDevices.size() > 1 && IsStreamActive(STREAM_MUSIC)) { 3567 MuteSinkPort(PRIMARY_SPEAKER, SET_BT_ABS_SCENE_DELAY_MS, true); 3568 } 3569 int32_t result = SUCCESS; 3570 std::string identity = IPCSkeleton::ResetCallingIdentity(); 3571 if (haveArmUsbDevice) { 3572 result = gsp->SetAudioScene(audioScene, activeOutputDevices, DEVICE_TYPE_USB_ARM_HEADSET, 3573 a2dpOffloadFlag_); 3574 } else { 3575 result = gsp->SetAudioScene(audioScene, activeOutputDevices, GetCurrentInputDeviceType(), 3576 a2dpOffloadFlag_); 3577 } 3578 IPCSkeleton::SetCallingIdentity(identity); 3579 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "SetAudioScene failed [%{public}d]", result); 3580 3581 if (audioScene_ == AUDIO_SCENE_PHONE_CALL) { 3582 // Make sure the STREAM_VOICE_CALL volume is set before the calling starts. 3583 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL)); 3584 } else { 3585 SetVoiceRingtoneMute(false); 3586 } 3587 3588 return SUCCESS; 3589 } 3590 AddEarpiece()3591 void AudioPolicyService::AddEarpiece() 3592 { 3593 if (!hasEarpiece_) { 3594 return; 3595 } 3596 sptr<AudioDeviceDescriptor> audioDescriptor = 3597 new (std::nothrow) AudioDeviceDescriptor(DEVICE_TYPE_EARPIECE, OUTPUT_DEVICE); 3598 CHECK_AND_RETURN_LOG(audioDescriptor != nullptr, "Create earpiect device descriptor failed"); 3599 3600 std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_); 3601 // Use speaker streaminfo for earpiece cap 3602 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), 3603 [](const sptr<AudioDeviceDescriptor> &devDesc) { 3604 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor"); 3605 return (devDesc->deviceType_ == DEVICE_TYPE_SPEAKER); 3606 }); 3607 if (itr != connectedDevices_.end()) { 3608 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0); 3609 } 3610 audioDescriptor->deviceId_ = startDeviceId++; 3611 UpdateDisplayName(audioDescriptor); 3612 audioDeviceManager_.AddNewDevice(audioDescriptor); 3613 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor); 3614 AUDIO_INFO_LOG("Add earpiece to device list"); 3615 } 3616 GetAudioScene(bool hasSystemPermission) const3617 AudioScene AudioPolicyService::GetAudioScene(bool hasSystemPermission) const 3618 { 3619 AUDIO_DEBUG_LOG("GetAudioScene return value: %{public}d", audioScene_); 3620 if (!hasSystemPermission) { 3621 switch (audioScene_) { 3622 case AUDIO_SCENE_CALL_START: 3623 case AUDIO_SCENE_CALL_END: 3624 return AUDIO_SCENE_DEFAULT; 3625 default: 3626 break; 3627 } 3628 } 3629 return audioScene_; 3630 } 3631 GetLastAudioScene() const3632 AudioScene AudioPolicyService::GetLastAudioScene() const 3633 { 3634 return lastAudioScene_; 3635 } 3636 OnUpdateRouteSupport(bool isSupported)3637 void AudioPolicyService::OnUpdateRouteSupport(bool isSupported) 3638 { 3639 isUpdateRouteSupported_ = isSupported; 3640 } 3641 GetActiveDeviceStreamInfo(DeviceType deviceType,AudioStreamInfo & streamInfo)3642 bool AudioPolicyService::GetActiveDeviceStreamInfo(DeviceType deviceType, AudioStreamInfo &streamInfo) 3643 { 3644 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_); 3645 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 3646 auto configInfoPos = connectedA2dpDeviceMap_.find(activeBTDevice_); 3647 if (configInfoPos != connectedA2dpDeviceMap_.end()) { 3648 streamInfo.samplingRate = *configInfoPos->second.streamInfo.samplingRate.rbegin(); 3649 streamInfo.format = configInfoPos->second.streamInfo.format; 3650 streamInfo.channels = *configInfoPos->second.streamInfo.channels.rbegin(); 3651 return true; 3652 } 3653 } 3654 3655 return false; 3656 } 3657 IsConfigurationUpdated(DeviceType deviceType,const AudioStreamInfo & streamInfo)3658 bool AudioPolicyService::IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo) 3659 { 3660 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 3661 AudioStreamInfo audioStreamInfo = {}; 3662 if (GetActiveDeviceStreamInfo(deviceType, audioStreamInfo)) { 3663 AUDIO_DEBUG_LOG("Device configurations current rate: %{public}d, format: %{public}d, channel: %{public}d", 3664 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels); 3665 AUDIO_DEBUG_LOG("Device configurations updated rate: %{public}d, format: %{public}d, channel: %{public}d", 3666 streamInfo.samplingRate, streamInfo.format, streamInfo.channels); 3667 if ((audioStreamInfo.samplingRate != streamInfo.samplingRate) 3668 || (audioStreamInfo.channels != streamInfo.channels) 3669 || (audioStreamInfo.format != streamInfo.format)) { 3670 return true; 3671 } 3672 } 3673 } 3674 3675 return false; 3676 } 3677 CheckAndNotifyUserSelectedDevice(const sptr<AudioDeviceDescriptor> & deviceDescriptor)3678 void AudioPolicyService::CheckAndNotifyUserSelectedDevice(const sptr<AudioDeviceDescriptor> &deviceDescriptor) 3679 { 3680 unique_ptr<AudioDeviceDescriptor> userSelectedMediaDevice = audioStateManager_.GetPreferredMediaRenderDevice(); 3681 unique_ptr<AudioDeviceDescriptor> userSelectedCallDevice = audioStateManager_.GetPreferredCallRenderDevice(); 3682 if (userSelectedMediaDevice != nullptr 3683 && userSelectedMediaDevice->connectState_ == VIRTUAL_CONNECTED 3684 && deviceDescriptor->isSameDeviceDesc(userSelectedMediaDevice)) { 3685 NotifyUserSelectionEventToBt(deviceDescriptor); 3686 } 3687 if (userSelectedCallDevice != nullptr 3688 && userSelectedCallDevice->connectState_ == VIRTUAL_CONNECTED 3689 && deviceDescriptor->isSameDeviceDesc(userSelectedCallDevice)) { 3690 NotifyUserSelectionEventToBt(deviceDescriptor); 3691 } 3692 } 3693 UpdateConnectedDevicesWhenConnectingForOutputDevice(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3694 void AudioPolicyService::UpdateConnectedDevicesWhenConnectingForOutputDevice( 3695 const AudioDeviceDescriptor &updatedDesc, std::vector<sptr<AudioDeviceDescriptor>> &descForCb) 3696 { 3697 AUDIO_INFO_LOG("Filling output device for %{public}d", updatedDesc.deviceType_); 3698 3699 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(updatedDesc); 3700 audioDescriptor->deviceRole_ = OUTPUT_DEVICE; 3701 // Use speaker streaminfo for all output devices cap 3702 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), 3703 [](const sptr<AudioDeviceDescriptor> &devDesc) { 3704 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor"); 3705 return (devDesc->deviceType_ == DEVICE_TYPE_SPEAKER); 3706 }); 3707 if (itr != connectedDevices_.end()) { 3708 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0); 3709 } 3710 bool wasVirtualConnected = audioDeviceManager_.IsVirtualConnectedDevice(audioDescriptor); 3711 if (!wasVirtualConnected) { 3712 audioDescriptor->deviceId_ = startDeviceId++; 3713 } else { 3714 audioDeviceManager_.UpdateDeviceDescDeviceId(audioDescriptor); 3715 CheckAndNotifyUserSelectedDevice(audioDescriptor); 3716 } 3717 descForCb.push_back(audioDescriptor); 3718 UpdateDisplayName(audioDescriptor); 3719 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor); 3720 audioDeviceManager_.AddNewDevice(audioDescriptor); 3721 3722 if (updatedDesc.connectState_ == VIRTUAL_CONNECTED) { 3723 AUDIO_INFO_LOG("The device is virtual device, no need to update preferred device"); 3724 return; // No need to update preferred device for virtual device 3725 } 3726 DeviceUsage usage = GetDeviceUsage(updatedDesc); 3727 if (audioDescriptor->networkId_ == LOCAL_NETWORK_ID && audioDescriptor->isSameDeviceDesc( 3728 std::move(audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1, 3729 ROUTER_TYPE_USER_SELECT).front())) && (usage & MEDIA) == MEDIA) { 3730 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 3731 } 3732 if (audioDescriptor->networkId_ == LOCAL_NETWORK_ID && audioDescriptor->isSameDeviceDesc( 3733 std::move(audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_COMMUNICATION, -1, 3734 ROUTER_TYPE_USER_SELECT).front())) && (usage & VOICE) == VOICE) { 3735 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 3736 } 3737 } 3738 UpdateConnectedDevicesWhenConnectingForInputDevice(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3739 void AudioPolicyService::UpdateConnectedDevicesWhenConnectingForInputDevice( 3740 const AudioDeviceDescriptor &updatedDesc, std::vector<sptr<AudioDeviceDescriptor>> &descForCb) 3741 { 3742 AUDIO_INFO_LOG("Filling input device for %{public}d", updatedDesc.deviceType_); 3743 3744 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(updatedDesc); 3745 audioDescriptor->deviceRole_ = INPUT_DEVICE; 3746 // Use mic streaminfo for all input devices cap 3747 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), 3748 [](const sptr<AudioDeviceDescriptor> &devDesc) { 3749 CHECK_AND_RETURN_RET_LOG(devDesc != nullptr, false, "Invalid device descriptor"); 3750 return (devDesc->deviceType_ == DEVICE_TYPE_MIC); 3751 }); 3752 if (itr != connectedDevices_.end()) { 3753 audioDescriptor->SetDeviceCapability((*itr)->audioStreamInfo_, 0); 3754 } 3755 bool wasVirtualConnected = audioDeviceManager_.IsVirtualConnectedDevice(audioDescriptor); 3756 if (!wasVirtualConnected) { 3757 audioDescriptor->deviceId_ = startDeviceId++; 3758 } else { 3759 audioDeviceManager_.UpdateDeviceDescDeviceId(audioDescriptor); 3760 } 3761 descForCb.push_back(audioDescriptor); 3762 UpdateDisplayName(audioDescriptor); 3763 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor); 3764 AddMicrophoneDescriptor(audioDescriptor); 3765 audioDeviceManager_.AddNewDevice(audioDescriptor); 3766 if (updatedDesc.connectState_ == VIRTUAL_CONNECTED) { 3767 return; 3768 } 3769 if (audioDescriptor->deviceCategory_ != BT_UNWEAR_HEADPHONE && audioDescriptor->deviceCategory_ != BT_WATCH) { 3770 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor()); 3771 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor()); 3772 } 3773 } 3774 UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3775 void AudioPolicyService::UpdateConnectedDevicesWhenConnecting(const AudioDeviceDescriptor &updatedDesc, 3776 std::vector<sptr<AudioDeviceDescriptor>> &descForCb) 3777 { 3778 AUDIO_INFO_LOG("UpdateConnectedDevicesWhenConnecting In, deviceType: %{public}d", updatedDesc.deviceType_); 3779 if (IsOutputDevice(updatedDesc.deviceType_, updatedDesc.deviceRole_)) { 3780 UpdateConnectedDevicesWhenConnectingForOutputDevice(updatedDesc, descForCb); 3781 } 3782 if (IsInputDevice(updatedDesc.deviceType_, updatedDesc.deviceRole_)) { 3783 UpdateConnectedDevicesWhenConnectingForInputDevice(updatedDesc, descForCb); 3784 } 3785 } 3786 UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor & updatedDesc,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)3787 void AudioPolicyService::UpdateConnectedDevicesWhenDisconnecting(const AudioDeviceDescriptor& updatedDesc, 3788 std::vector<sptr<AudioDeviceDescriptor>> &descForCb) 3789 { 3790 AUDIO_INFO_LOG("[%{public}s], devType:[%{public}d]", __func__, updatedDesc.deviceType_); 3791 auto isPresent = [&updatedDesc](const sptr<AudioDeviceDescriptor>& descriptor) { 3792 return descriptor->deviceType_ == updatedDesc.deviceType_ && 3793 descriptor->macAddress_ == updatedDesc.macAddress_ && 3794 descriptor->networkId_ == updatedDesc.networkId_; 3795 }; 3796 3797 // Remember the disconnected device descriptor and remove it 3798 for (auto it = connectedDevices_.begin(); it != connectedDevices_.end();) { 3799 it = find_if(it, connectedDevices_.end(), isPresent); 3800 if (it != connectedDevices_.end()) { 3801 if ((*it)->deviceType_ == DEVICE_TYPE_DP) { hasDpDevice_ = false; } 3802 if ((*it)->isSameDeviceDesc(audioStateManager_.GetPreferredMediaRenderDevice())) { 3803 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 3804 } 3805 if ((*it)->isSameDeviceDesc(audioStateManager_.GetPreferredCallRenderDevice())) { 3806 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 3807 } 3808 if ((*it)->isSameDeviceDesc(audioStateManager_.GetPreferredCallCaptureDevice())) { 3809 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor()); 3810 } 3811 if ((*it)->isSameDeviceDesc(audioStateManager_.GetPreferredRecordCaptureDevice())) { 3812 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor()); 3813 } 3814 descForCb.push_back(*it); 3815 it = connectedDevices_.erase(it); 3816 } 3817 } 3818 3819 // reset disconnected device info in stream 3820 if (IsOutputDevice(updatedDesc.deviceType_)) { 3821 streamCollector_.ResetRendererStreamDeviceInfo(updatedDesc); 3822 } 3823 if (IsInputDevice(updatedDesc.deviceType_)) { 3824 streamCollector_.ResetCapturerStreamDeviceInfo(updatedDesc); 3825 } 3826 3827 sptr<AudioDeviceDescriptor> devDesc = new (std::nothrow) AudioDeviceDescriptor(updatedDesc); 3828 CHECK_AND_RETURN_LOG(devDesc != nullptr, "Create device descriptor failed"); 3829 audioDeviceManager_.RemoveNewDevice(devDesc); 3830 RemoveMicrophoneDescriptor(devDesc); 3831 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && 3832 GetCurrentOutputDeviceMacAddr() == updatedDesc.macAddress_) { 3833 a2dpOffloadFlag_ = NO_A2DP_DEVICE; 3834 } 3835 } 3836 OnPnpDeviceStatusUpdated(DeviceType devType,bool isConnected)3837 void AudioPolicyService::OnPnpDeviceStatusUpdated(DeviceType devType, bool isConnected) 3838 { 3839 CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type"); 3840 if (!hasModulesLoaded) { 3841 AUDIO_WARNING_LOG("modules has not loaded"); 3842 pnpDeviceList_.push_back({devType, isConnected}); 3843 return; 3844 } 3845 if (g_adProxy == nullptr) { 3846 GetAudioServerProxy(); 3847 } 3848 AudioStreamInfo streamInfo = {}; 3849 OnDeviceStatusUpdated(devType, isConnected, "", "", streamInfo); 3850 } 3851 OnPnpDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & name,const std::string & adderess)3852 void AudioPolicyService::OnPnpDeviceStatusUpdated(DeviceType devType, bool isConnected, 3853 const std::string &name, const std::string &adderess) 3854 { 3855 CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type"); 3856 if (!hasModulesLoaded) { 3857 AUDIO_WARNING_LOG("modules has not loaded"); 3858 pnpDeviceList_.push_back({devType, isConnected}); 3859 return; 3860 } 3861 if (g_adProxy == nullptr) { 3862 GetAudioServerProxy(); 3863 } 3864 AudioStreamInfo streamInfo = {}; 3865 OnDeviceStatusUpdated(devType, isConnected, adderess, name, streamInfo); 3866 } 3867 OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)3868 void AudioPolicyService::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status) 3869 { 3870 CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type"); 3871 if (g_adProxy == nullptr) { 3872 GetAudioServerProxy(); 3873 } 3874 OnBlockedStatusUpdated(devType, status); 3875 } 3876 OnBlockedStatusUpdated(DeviceType devType,DeviceBlockStatus status)3877 void AudioPolicyService::OnBlockedStatusUpdated(DeviceType devType, DeviceBlockStatus status) 3878 { 3879 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {}; 3880 sptr<AudioDeviceDescriptor> audioDescriptor = new AudioDeviceDescriptor(devType, GetDeviceRole(devType)); 3881 descForCb.push_back(audioDescriptor); 3882 3883 vector<unique_ptr<AudioCapturerChangeInfo>> audioChangeInfos; 3884 streamCollector_.GetCurrentCapturerChangeInfos(audioChangeInfos); 3885 for (auto it = audioChangeInfos.begin(); it != audioChangeInfos.end(); it++) { 3886 if ((*it)->capturerState == CAPTURER_RUNNING) { 3887 AUDIO_INFO_LOG("record running"); 3888 TriggerMicrophoneBlockedCallback(descForCb, status); 3889 } 3890 } 3891 } 3892 UpdateLocalGroupInfo(bool isConnected,const std::string & macAddress,const std::string & deviceName,const DeviceStreamInfo & streamInfo,AudioDeviceDescriptor & deviceDesc)3893 void AudioPolicyService::UpdateLocalGroupInfo(bool isConnected, const std::string& macAddress, 3894 const std::string& deviceName, const DeviceStreamInfo& streamInfo, AudioDeviceDescriptor& deviceDesc) 3895 { 3896 deviceDesc.SetDeviceInfo(deviceName, macAddress); 3897 deviceDesc.SetDeviceCapability(streamInfo, 0); 3898 UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, LOCAL_NETWORK_ID, isConnected, 3899 NO_REMOTE_ID); 3900 UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, LOCAL_NETWORK_ID, isConnected, 3901 NO_REMOTE_ID); 3902 deviceDesc.networkId_ = LOCAL_NETWORK_ID; 3903 } 3904 HandleLocalDeviceConnected(AudioDeviceDescriptor & updatedDesc)3905 int32_t AudioPolicyService::HandleLocalDeviceConnected(AudioDeviceDescriptor &updatedDesc) 3906 { 3907 AUDIO_INFO_LOG("macAddress:[%{public}s]", GetEncryptAddr(updatedDesc.macAddress_).c_str()); 3908 { 3909 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_); 3910 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { 3911 A2dpDeviceConfigInfo configInfo = {updatedDesc.audioStreamInfo_, false}; 3912 connectedA2dpDeviceMap_.insert(make_pair(updatedDesc.macAddress_, configInfo)); 3913 } 3914 } 3915 3916 if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) { 3917 int32_t loadOutputResult = HandleArmUsbDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_); 3918 if (loadOutputResult != SUCCESS) { 3919 loadOutputResult = RehandlePnpDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_); 3920 } 3921 int32_t loadInputResult = HandleArmUsbDevice(updatedDesc.deviceType_, INPUT_DEVICE, updatedDesc.macAddress_); 3922 if (loadInputResult != SUCCESS) { 3923 loadInputResult = RehandlePnpDevice(updatedDesc.deviceType_, INPUT_DEVICE, updatedDesc.macAddress_); 3924 } 3925 if (loadOutputResult != SUCCESS && loadInputResult != SUCCESS) { 3926 hasArmUsbDevice_ = false; 3927 updatedDesc.deviceType_ = DEVICE_TYPE_USB_HEADSET; 3928 AUDIO_ERR_LOG("Load usb failed, set arm usb flag to false"); 3929 return ERROR; 3930 } 3931 // Distinguish between USB input and output (need fix) 3932 if (loadOutputResult == SUCCESS && loadInputResult == SUCCESS) { 3933 updatedDesc.deviceRole_ = DEVICE_ROLE_MAX; 3934 } else { 3935 updatedDesc.deviceRole_ = (loadOutputResult == SUCCESS) ? OUTPUT_DEVICE : INPUT_DEVICE; 3936 } 3937 AUDIO_INFO_LOG("Load usb role is %{public}d", updatedDesc.deviceRole_); 3938 return SUCCESS; 3939 } 3940 3941 // DP device only for output. 3942 if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) { 3943 CHECK_AND_RETURN_RET_LOG(!hasDpDevice_, ERROR, "DP device already exists, ignore this one."); 3944 int32_t result = HandleDpDevice(updatedDesc.deviceType_, updatedDesc.macAddress_); 3945 if (result != SUCCESS) { 3946 result = RehandlePnpDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_); 3947 } 3948 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Load dp failed."); 3949 hasDpDevice_ = true; 3950 } 3951 3952 return SUCCESS; 3953 } 3954 HandleLocalDeviceDisconnected(const AudioDeviceDescriptor & updatedDesc)3955 int32_t AudioPolicyService::HandleLocalDeviceDisconnected(const AudioDeviceDescriptor &updatedDesc) 3956 { 3957 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { 3958 UpdateActiveA2dpDeviceWhenDisconnecting(updatedDesc.macAddress_); 3959 } 3960 3961 if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) { 3962 ClosePortAndEraseIOHandle(USB_SPEAKER); 3963 ClosePortAndEraseIOHandle(USB_MIC); 3964 } 3965 if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) { 3966 ClosePortAndEraseIOHandle(DP_SINK); 3967 } 3968 3969 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 3970 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERROR, "UpdateActiveDevicesRoute, Audio Server Proxy is null"); 3971 std::string identity = IPCSkeleton::ResetCallingIdentity(); 3972 gsp->ResetRouteForDisconnect(updatedDesc.deviceType_); 3973 IPCSkeleton::SetCallingIdentity(identity); 3974 3975 return SUCCESS; 3976 } 3977 UpdateActiveA2dpDeviceWhenDisconnecting(const std::string & macAddress)3978 void AudioPolicyService::UpdateActiveA2dpDeviceWhenDisconnecting(const std::string& macAddress) 3979 { 3980 bool flag = false; 3981 { 3982 std::unique_lock<std::mutex> lock(a2dpDeviceMapMutex_); 3983 connectedA2dpDeviceMap_.erase(macAddress); 3984 flag = (connectedA2dpDeviceMap_.size() == 0); 3985 } 3986 3987 if (flag) { 3988 activeBTDevice_ = ""; 3989 ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER); 3990 audioPolicyManager_.SetAbsVolumeScene(false); 3991 SetSharedAbsVolumeScene(false); 3992 #ifdef BLUETOOTH_ENABLE 3993 Bluetooth::AudioA2dpManager::SetActiveA2dpDevice(""); 3994 #endif 3995 return; 3996 } 3997 } 3998 FindConnectedHeadset()3999 DeviceType AudioPolicyService::FindConnectedHeadset() 4000 { 4001 DeviceType retType = DEVICE_TYPE_NONE; 4002 for (const auto& devDesc: connectedDevices_) { 4003 if ((devDesc->deviceType_ == DEVICE_TYPE_WIRED_HEADSET) || 4004 (devDesc->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES) || 4005 (devDesc->deviceType_ == DEVICE_TYPE_USB_HEADSET) || 4006 (devDesc->deviceType_ == DEVICE_TYPE_DP) || 4007 (devDesc->deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET)) { 4008 retType = devDesc->deviceType_; 4009 break; 4010 } 4011 } 4012 return retType; 4013 } 4014 HandleSpecialDeviceType(DeviceType & devType,bool & isConnected,const std::string & address)4015 int32_t AudioPolicyService::HandleSpecialDeviceType(DeviceType &devType, bool &isConnected, const std::string &address) 4016 { 4017 // usb device needs to be distinguished form arm or hifi 4018 if (devType == DEVICE_TYPE_USB_HEADSET || devType == DEVICE_TYPE_USB_ARM_HEADSET) { 4019 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 4020 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERROR, "HandleSpecialDeviceType, Audio server Proxy is null"); 4021 AUDIO_INFO_LOG("has hifi:%{public}d, has arm:%{public}d", hasHifiUsbDevice_, hasArmUsbDevice_); 4022 std::string identity = IPCSkeleton::ResetCallingIdentity(); 4023 4024 // Hal only support one HiFi device, If HiFi is already online, the following devices should be ARM. 4025 // But when the second usb device went online, the return value of this interface was not accurate. 4026 // So special handling was done when usb device was connected and disconnected. 4027 const std::string value = gsp->GetAudioParameter("need_change_usb_device"); 4028 4029 IPCSkeleton::SetCallingIdentity(identity); 4030 AUDIO_INFO_LOG("get value %{public}s from hal when usb device connect", value.c_str()); 4031 if (isConnected) { 4032 bool isArmConnect = (value == "false" || hasHifiUsbDevice_); 4033 if (isArmConnect) { 4034 hasArmUsbDevice_ = true; 4035 devType = DEVICE_TYPE_USB_ARM_HEADSET; 4036 CHECK_AND_RETURN_RET_LOG(!hasHifiUsbDevice_, ERROR, "Hifi device already exists, ignore this one."); 4037 } else { 4038 hasHifiUsbDevice_ = true; 4039 CHECK_AND_RETURN_RET_LOG(!hasArmUsbDevice_, ERROR, "Arm device already exists, ignore this one."); 4040 } 4041 } else { 4042 bool isArmDisconnect = ((hasArmUsbDevice_ && !hasHifiUsbDevice_) || 4043 (hasArmUsbDevice_ && hasHifiUsbDevice_ && value == "true")); 4044 if (isArmDisconnect) { 4045 devType = DEVICE_TYPE_USB_ARM_HEADSET; 4046 hasArmUsbDevice_ = false; 4047 } else { 4048 hasHifiUsbDevice_ = false; 4049 } 4050 } 4051 } 4052 4053 // Special logic for extern cable, need refactor 4054 if (devType == DEVICE_TYPE_EXTERN_CABLE) { 4055 CHECK_AND_RETURN_RET_LOG(isConnected, ERROR, "Extern cable disconnected, do nothing"); 4056 DeviceType connectedHeadsetType = FindConnectedHeadset(); 4057 if (connectedHeadsetType == DEVICE_TYPE_NONE) { 4058 AUDIO_INFO_LOG("Extern cable connect without headset connected before, do nothing"); 4059 return ERROR; 4060 } 4061 devType = connectedHeadsetType; 4062 isConnected = false; 4063 } 4064 4065 return SUCCESS; 4066 } 4067 ResetToSpeaker(DeviceType devType)4068 void AudioPolicyService::ResetToSpeaker(DeviceType devType) 4069 { 4070 if (devType != GetCurrentOutputDeviceType()) { 4071 return; 4072 } 4073 if (devType == DEVICE_TYPE_BLUETOOTH_SCO || devType == DEVICE_TYPE_USB_HEADSET || 4074 devType == DEVICE_TYPE_WIRED_HEADSET || devType == DEVICE_TYPE_WIRED_HEADPHONES) { 4075 UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG); 4076 } 4077 } 4078 OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)4079 void AudioPolicyService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress, 4080 const std::string& deviceName, const AudioStreamInfo& streamInfo) 4081 { 4082 // Pnp device status update 4083 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 4084 4085 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN; 4086 // fill device change action for callback 4087 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {}; 4088 4089 int32_t result = ERROR; 4090 result = HandleSpecialDeviceType(devType, isConnected, macAddress); 4091 CHECK_AND_RETURN_LOG(result == SUCCESS, "handle special deviceType failed."); 4092 4093 AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], address[%{public}s]", 4094 devType, isConnected, GetEncryptStr(macAddress).c_str()); 4095 4096 AudioDeviceDescriptor updatedDesc(devType, GetDeviceRole(devType)); 4097 UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc); 4098 4099 auto isPresent = [&updatedDesc] (const sptr<AudioDeviceDescriptor> &descriptor) { 4100 return descriptor->deviceType_ == updatedDesc.deviceType_ && 4101 descriptor->macAddress_ == updatedDesc.macAddress_ && 4102 descriptor->networkId_ == updatedDesc.networkId_; 4103 }; 4104 if (isConnected) { 4105 // If device already in list, remove it else do not modify the list 4106 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent), 4107 connectedDevices_.end()); 4108 // If the pnp device fails to load, it will not connect 4109 result = HandleLocalDeviceConnected(updatedDesc); 4110 CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed."); 4111 UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb); 4112 4113 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE; 4114 } else { 4115 UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb); 4116 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; 4117 FetchDevice(true, reason); // fix pop, fetch device before unload module 4118 result = HandleLocalDeviceDisconnected(updatedDesc); 4119 CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed."); 4120 } 4121 4122 TriggerDeviceChangedCallback(descForCb, isConnected); 4123 TriggerAvailableDeviceChangedCallback(descForCb, isConnected); 4124 4125 // fetch input&output device 4126 FetchDevice(true, reason); 4127 FetchDevice(false); 4128 4129 // update a2dp offload 4130 UpdateA2dpOffloadFlagForAllStream(); 4131 } 4132 OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,bool isConnected)4133 void AudioPolicyService::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected) 4134 { 4135 // Bluetooth device status updated 4136 DeviceType devType = updatedDesc.deviceType_; 4137 string macAddress = updatedDesc.macAddress_; 4138 string deviceName = updatedDesc.deviceName_; 4139 bool isActualConnection = (updatedDesc.connectState_ != VIRTUAL_CONNECTED); 4140 AUDIO_WARNING_LOG("Device connection is actual connection: %{public}d", isActualConnection); 4141 4142 AudioStreamInfo streamInfo = {}; 4143 #ifdef BLUETOOTH_ENABLE 4144 if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && isActualConnection && isConnected) { 4145 int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpDeviceStreamInfo(macAddress, streamInfo); 4146 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp device stream info failed!"); 4147 } 4148 #endif 4149 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 4150 AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], mac[%{public}s]", 4151 devType, isConnected, GetEncryptStr(macAddress).c_str()); 4152 4153 UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc); 4154 // fill device change action for callback 4155 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN; 4156 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {}; 4157 UpdateDeviceList(updatedDesc, isConnected, descForCb, reason); 4158 4159 TriggerDeviceChangedCallback(descForCb, isConnected); 4160 TriggerAvailableDeviceChangedCallback(descForCb, isConnected); 4161 4162 if (!isActualConnection) { 4163 return; 4164 } 4165 // fetch input&output device 4166 FetchDevice(true, reason); 4167 FetchDevice(false); 4168 // update a2dp offload 4169 if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) { 4170 UpdateA2dpOffloadFlagForAllStream(); 4171 } 4172 } 4173 UpdateDeviceList(AudioDeviceDescriptor & updatedDesc,bool isConnected,std::vector<sptr<AudioDeviceDescriptor>> & descForCb,AudioStreamDeviceChangeReasonExt & reason)4174 void AudioPolicyService::UpdateDeviceList(AudioDeviceDescriptor &updatedDesc, bool isConnected, 4175 std::vector<sptr<AudioDeviceDescriptor>> &descForCb, 4176 AudioStreamDeviceChangeReasonExt &reason) 4177 { 4178 auto isPresent = [&updatedDesc] (const sptr<AudioDeviceDescriptor> &descriptor) { 4179 return descriptor->deviceType_ == updatedDesc.deviceType_ && 4180 descriptor->macAddress_ == updatedDesc.macAddress_ && 4181 descriptor->networkId_ == updatedDesc.networkId_; 4182 }; 4183 if (isConnected) { 4184 // deduplicate 4185 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent), 4186 connectedDevices_.end()); 4187 UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb); 4188 int32_t result = HandleLocalDeviceConnected(updatedDesc); 4189 CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed."); 4190 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE; 4191 #ifdef BLUETOOTH_ENABLE 4192 CheckAndActiveHfpDevice(updatedDesc); 4193 #endif 4194 } else { 4195 UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb); 4196 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; 4197 FetchDevice(true, reason); // fix pop, fetch device before unload module 4198 int32_t result = HandleLocalDeviceDisconnected(updatedDesc); 4199 CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed."); 4200 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; 4201 } 4202 } 4203 4204 #ifdef FEATURE_DTMF_TONE GetSupportedTones()4205 std::vector<int32_t> AudioPolicyService::GetSupportedTones() 4206 { 4207 std::vector<int> supportedToneList = {}; 4208 for (auto i = toneDescriptorMap.begin(); i != toneDescriptorMap.end(); i++) { 4209 supportedToneList.push_back(i->first); 4210 } 4211 return supportedToneList; 4212 } 4213 GetToneConfig(int32_t ltonetype)4214 std::shared_ptr<ToneInfo> AudioPolicyService::GetToneConfig(int32_t ltonetype) 4215 { 4216 if (toneDescriptorMap.find(ltonetype) == toneDescriptorMap.end()) { 4217 return nullptr; 4218 } 4219 AUDIO_DEBUG_LOG("AudioPolicyService GetToneConfig %{public}d", ltonetype); 4220 return toneDescriptorMap[ltonetype]; 4221 } 4222 #endif 4223 UpdateA2dpOffloadFlagBySpatialService(const std::string & macAddress,std::unordered_map<uint32_t,bool> & sessionIDToSpatializationEnabledMap)4224 void AudioPolicyService::UpdateA2dpOffloadFlagBySpatialService( 4225 const std::string& macAddress, std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnabledMap) 4226 { 4227 auto it = spatialDeviceMap_.find(macAddress); 4228 DeviceType spatialDevice; 4229 if (it != spatialDeviceMap_.end()) { 4230 spatialDevice = it->second; 4231 } else { 4232 AUDIO_DEBUG_LOG("we can't find the spatialDevice of hvs"); 4233 spatialDevice = DEVICE_TYPE_NONE; 4234 } 4235 AUDIO_INFO_LOG("Update a2dpOffloadFlag spatialDevice: %{public}d", spatialDevice); 4236 UpdateA2dpOffloadFlagForAllStream(sessionIDToSpatializationEnabledMap, spatialDevice); 4237 } 4238 UpdateA2dpOffloadFlagForAllStream(std::unordered_map<uint32_t,bool> & sessionIDToSpatializationEnabledMap,DeviceType deviceType)4239 void AudioPolicyService::UpdateA2dpOffloadFlagForAllStream( 4240 std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnabledMap, DeviceType deviceType) 4241 { 4242 #ifdef BLUETOOTH_ENABLE 4243 vector<Bluetooth::A2dpStreamInfo> allSessionInfos; 4244 Bluetooth::A2dpStreamInfo a2dpStreamInfo; 4245 vector<unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos; 4246 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos); 4247 std::vector<int32_t> stopPlayingStream(0); 4248 for (auto &changeInfo : audioRendererChangeInfos) { 4249 if (changeInfo->rendererState != RENDERER_RUNNING) { 4250 stopPlayingStream.emplace_back(changeInfo->sessionId); 4251 continue; 4252 } 4253 a2dpStreamInfo.sessionId = changeInfo->sessionId; 4254 a2dpStreamInfo.streamType = GetStreamType(changeInfo->sessionId); 4255 if (sessionIDToSpatializationEnabledMap.count(static_cast<uint32_t>(a2dpStreamInfo.sessionId))) { 4256 a2dpStreamInfo.isSpatialAudio = 4257 sessionIDToSpatializationEnabledMap[static_cast<uint32_t>(a2dpStreamInfo.sessionId)]; 4258 } else { 4259 a2dpStreamInfo.isSpatialAudio = 0; 4260 } 4261 allSessionInfos.push_back(a2dpStreamInfo); 4262 } 4263 if (stopPlayingStream.size() > 0) { 4264 OffloadStopPlaying(stopPlayingStream); 4265 } 4266 UpdateA2dpOffloadFlag(allSessionInfos, deviceType); 4267 #endif 4268 AUDIO_DEBUG_LOG("deviceType %{public}d", deviceType); 4269 } 4270 UpdateA2dpOffloadFlagForAllStream(DeviceType deviceType)4271 int32_t AudioPolicyService::UpdateA2dpOffloadFlagForAllStream(DeviceType deviceType) 4272 { 4273 int32_t activeSessionsSize = 0; 4274 #ifdef BLUETOOTH_ENABLE 4275 vector<Bluetooth::A2dpStreamInfo> allSessionInfos; 4276 Bluetooth::A2dpStreamInfo a2dpStreamInfo; 4277 vector<unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos; 4278 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos); 4279 { 4280 AudioXCollie audioXCollie("AudioPolicyService::UpdateA2dpOffloadFlagForAllStream", BLUETOOTH_TIME_OUT_SECONDS); 4281 std::vector<int32_t> stopPlayingStream(0); 4282 for (auto &changeInfo : audioRendererChangeInfos) { 4283 if (changeInfo->rendererState != RENDERER_RUNNING) { 4284 stopPlayingStream.emplace_back(changeInfo->sessionId); 4285 continue; 4286 } 4287 a2dpStreamInfo.sessionId = changeInfo->sessionId; 4288 a2dpStreamInfo.streamType = GetStreamType(changeInfo->sessionId); 4289 StreamUsage tempStreamUsage = changeInfo->rendererInfo.streamUsage; 4290 AudioSpatializationState spatialState = 4291 AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState(tempStreamUsage); 4292 a2dpStreamInfo.isSpatialAudio = spatialState.spatializationEnabled; 4293 allSessionInfos.push_back(a2dpStreamInfo); 4294 } 4295 if (stopPlayingStream.size() > 0) { 4296 OffloadStopPlaying(stopPlayingStream); 4297 } 4298 } 4299 UpdateA2dpOffloadFlag(allSessionInfos, deviceType); 4300 activeSessionsSize = static_cast<int32_t>(allSessionInfos.size()); 4301 #endif 4302 AUDIO_DEBUG_LOG("deviceType %{public}d", deviceType); 4303 return activeSessionsSize; 4304 } 4305 OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)4306 void AudioPolicyService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress, 4307 const std::string &deviceName, const AudioStreamInfo &streamInfo) 4308 { 4309 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 4310 4311 AUDIO_INFO_LOG("OnDeviceConfigurationChanged start, deviceType: %{public}d, currentActiveDevice_: %{public}d, " 4312 "macAddress:[%{public}s], activeBTDevice_:[%{public}s]", deviceType, GetCurrentOutputDeviceType(), 4313 GetEncryptAddr(macAddress).c_str(), GetEncryptAddr(activeBTDevice_).c_str()); 4314 // only for the active a2dp device. 4315 if ((deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) && !macAddress.compare(activeBTDevice_)) { 4316 auto activeSessionsSize = UpdateA2dpOffloadFlagForAllStream(); 4317 AUDIO_DEBUG_LOG("streamInfo.sampleRate: %{public}d, a2dpOffloadFlag_: %{public}d", 4318 streamInfo.samplingRate, a2dpOffloadFlag_); 4319 if (!IsConfigurationUpdated(deviceType, streamInfo) || 4320 (activeSessionsSize > 0 && a2dpOffloadFlag_ == A2DP_OFFLOAD)) { 4321 AUDIO_DEBUG_LOG("Audio configuration same"); 4322 return; 4323 } 4324 4325 connectedA2dpDeviceMap_[macAddress].streamInfo = streamInfo; 4326 ReloadA2dpOffloadOnDeviceChanged(deviceType, macAddress, deviceName, streamInfo); 4327 } else if (connectedA2dpDeviceMap_.find(macAddress) != connectedA2dpDeviceMap_.end()) { 4328 AUDIO_DEBUG_LOG("Audio configuration update, macAddress:[%{public}s], streamInfo.sampleRate: %{public}d", 4329 GetEncryptAddr(macAddress).c_str(), streamInfo.samplingRate); 4330 connectedA2dpDeviceMap_[macAddress].streamInfo = streamInfo; 4331 } 4332 } 4333 ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)4334 void AudioPolicyService::ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, const std::string &macAddress, 4335 const std::string &deviceName, const AudioStreamInfo &streamInfo) 4336 { 4337 uint32_t bufferSize = (streamInfo.samplingRate * GetSampleFormatValue(streamInfo.format) 4338 * streamInfo.channels) / (PCM_8_BIT * BT_BUFFER_ADJUSTMENT_FACTOR); 4339 AUDIO_DEBUG_LOG("Updated buffer size: %{public}d", bufferSize); 4340 4341 auto a2dpModulesPos = deviceClassInfo_.find(ClassType::TYPE_A2DP); 4342 if (a2dpModulesPos != deviceClassInfo_.end()) { 4343 auto moduleInfoList = a2dpModulesPos->second; 4344 for (auto &moduleInfo : moduleInfoList) { 4345 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 4346 CHECK_AND_CONTINUE_LOG(IOHandles_.find(moduleInfo.name) != IOHandles_.end(), 4347 "Cannot find module %{public}s", moduleInfo.name.c_str()); 4348 moduleInfo.channels = to_string(streamInfo.channels); 4349 moduleInfo.rate = to_string(streamInfo.samplingRate); 4350 moduleInfo.format = ConvertToHDIAudioFormat(streamInfo.format); 4351 moduleInfo.bufferSize = to_string(bufferSize); 4352 moduleInfo.renderInIdleState = "1"; 4353 moduleInfo.sinkLatency = "0"; 4354 4355 // First unload the existing bt sink 4356 AUDIO_DEBUG_LOG("UnLoad existing a2dp module"); 4357 std::string currentActivePort = GetSinkPortName(GetCurrentOutputDeviceType()); 4358 AudioIOHandle activateDeviceIOHandle = IOHandles_[BLUETOOTH_SPEAKER]; 4359 MuteDefaultSinkPort(); 4360 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true); 4361 audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle); 4362 4363 // Load bt sink module again with new configuration 4364 AUDIO_DEBUG_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str()); 4365 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo); 4366 if (ioHandle == OPEN_PORT_FAILURE) { 4367 audioPolicyManager_.SuspendAudioDevice(currentActivePort, false); 4368 AUDIO_ERR_LOG("OpenAudioPort failed %{public}d", ioHandle); 4369 return; 4370 } 4371 IOHandles_[moduleInfo.name] = ioHandle; 4372 std::string portName = GetSinkPortName(deviceType); 4373 if (!IsVoiceCallRelatedScene()) { 4374 audioPolicyManager_.SetDeviceActive(deviceType, portName, true); 4375 } 4376 audioPolicyManager_.SuspendAudioDevice(portName, false); 4377 audioPolicyManager_.SuspendAudioDevice(currentActivePort, false); 4378 4379 auto isPresent = [&macAddress] (const sptr<AudioDeviceDescriptor> &descriptor) { 4380 return descriptor->macAddress_ == macAddress; 4381 }; 4382 4383 sptr<AudioDeviceDescriptor> audioDescriptor 4384 = new(std::nothrow) AudioDeviceDescriptor(deviceType, OUTPUT_DEVICE); 4385 audioDescriptor->SetDeviceInfo(deviceName, macAddress); 4386 audioDescriptor->SetDeviceCapability(streamInfo, 0); 4387 std::replace_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent, audioDescriptor); 4388 break; 4389 } 4390 } 4391 } 4392 RemoveDeviceInRouterMap(std::string networkId)4393 void AudioPolicyService::RemoveDeviceInRouterMap(std::string networkId) 4394 { 4395 std::lock_guard<std::mutex> lock(routerMapMutex_); 4396 std::unordered_map<int32_t, std::pair<std::string, int32_t>>::iterator it; 4397 for (it = routerMap_.begin();it != routerMap_.end();) { 4398 if (it->second.first == networkId) { 4399 routerMap_.erase(it++); 4400 } else { 4401 it++; 4402 } 4403 } 4404 } 4405 RemoveDeviceInFastRouterMap(std::string networkId)4406 void AudioPolicyService::RemoveDeviceInFastRouterMap(std::string networkId) 4407 { 4408 std::lock_guard<std::mutex> lock(routerMapMutex_); 4409 std::unordered_map<int32_t, std::pair<std::string, DeviceRole>>::iterator it; 4410 for (it = fastRouterMap_.begin();it != fastRouterMap_.end();) { 4411 if (it->second.first == networkId) { 4412 fastRouterMap_.erase(it++); 4413 } else { 4414 it++; 4415 } 4416 } 4417 } 4418 SetDisplayName(const std::string & deviceName,bool isLocalDevice)4419 void AudioPolicyService::SetDisplayName(const std::string &deviceName, bool isLocalDevice) 4420 { 4421 for (const auto& deviceInfo : connectedDevices_) { 4422 if ((isLocalDevice && deviceInfo->networkId_ == LOCAL_NETWORK_ID) || 4423 (!isLocalDevice && deviceInfo->networkId_ != LOCAL_NETWORK_ID)) { 4424 deviceInfo->displayName_ = deviceName; 4425 } 4426 } 4427 } 4428 RegisterRemoteDevStatusCallback()4429 void AudioPolicyService::RegisterRemoteDevStatusCallback() 4430 { 4431 #ifdef FEATURE_DEVICE_MANAGER 4432 AUDIO_INFO_LOG("RegisterRemoteDevStatusCallback start"); 4433 std::shared_ptr<DistributedHardware::DmInitCallback> initCallback = std::make_shared<DeviceInitCallBack>(); 4434 int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, initCallback); 4435 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Init device manage failed"); 4436 std::shared_ptr<DistributedHardware::DeviceStatusCallback> callback = std::make_shared<DeviceStatusCallbackImpl>(); 4437 DistributedHardware::DeviceManager::GetInstance().RegisterDevStatusCallback(AUDIO_SERVICE_PKG, "", callback); 4438 AUDIO_INFO_LOG("Done"); 4439 #endif 4440 } 4441 CreateDataShareHelperInstance()4442 std::shared_ptr<DataShare::DataShareHelper> AudioPolicyService::CreateDataShareHelperInstance() 4443 { 4444 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); 4445 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr, "[Policy Service] Get samgr failed."); 4446 4447 sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(AUDIO_POLICY_SERVICE_ID); 4448 CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, nullptr, "[Policy Service] audio service remote object is NULL."); 4449 4450 int64_t startTime = ClockTime::GetCurNano(); 4451 sptr<IRemoteObject> dataSharedServer = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); 4452 int64_t cost = ClockTime::GetCurNano() - startTime; 4453 if (cost > CALL_IPC_COST_TIME_MS) { 4454 AUDIO_WARNING_LOG("Call get DataShare server cost too long: %{public}" PRId64"ms.", cost / AUDIO_US_PER_SECOND); 4455 } 4456 4457 CHECK_AND_RETURN_RET_LOG(dataSharedServer != nullptr, nullptr, "DataShare server is not started!"); 4458 4459 WatchTimeout guard("DataShare::DataShareHelper::Create", CALL_IPC_COST_TIME_MS); 4460 std::pair<int, std::shared_ptr<DataShare::DataShareHelper>> res = DataShare::DataShareHelper::Create(remoteObject, 4461 SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI); 4462 guard.CheckCurrTimeout(); 4463 if (res.first == DataShare::E_DATA_SHARE_NOT_READY) { 4464 AUDIO_WARNING_LOG("DataShareHelper::Create failed: E_DATA_SHARE_NOT_READY"); 4465 return nullptr; 4466 } 4467 std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = res.second; 4468 CHECK_AND_RETURN_RET_LOG(res.first == DataShare::E_OK && dataShareHelper != nullptr, nullptr, "fail:%{public}d", 4469 res.first); 4470 return dataShareHelper; 4471 } 4472 GetDeviceNameFromDataShareHelper(std::string & deviceName)4473 int32_t AudioPolicyService::GetDeviceNameFromDataShareHelper(std::string &deviceName) 4474 { 4475 std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = CreateDataShareHelperInstance(); 4476 CHECK_AND_RETURN_RET_LOG(dataShareHelper != nullptr, ERROR, "GetDeviceNameFromDataShareHelper NULL"); 4477 4478 std::shared_ptr<Uri> uri = std::make_shared<Uri>(SETTINGS_DATA_BASE_URI); 4479 std::vector<std::string> columns; 4480 columns.emplace_back(SETTINGS_DATA_FIELD_VALUE); 4481 DataShare::DataSharePredicates predicates; 4482 predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, PREDICATES_STRING); 4483 4484 WatchTimeout guard("dataShareHelper->Query:DefaultDeviceName"); 4485 auto resultSet = dataShareHelper->Query(*uri, predicates, columns); 4486 if (resultSet == nullptr) { 4487 AUDIO_ERR_LOG("Failed to query device name from dataShareHelper!"); 4488 dataShareHelper->Release(); 4489 return ERROR; 4490 } 4491 guard.CheckCurrTimeout(); 4492 4493 int32_t numRows = 0; 4494 resultSet->GetRowCount(numRows); 4495 if (numRows <= 0) { 4496 AUDIO_ERR_LOG("The result of querying is zero row!"); 4497 resultSet->Close(); 4498 dataShareHelper->Release(); 4499 return ERROR; 4500 } 4501 4502 int columnIndex; 4503 resultSet->GoToFirstRow(); 4504 resultSet->GetColumnIndex(SETTINGS_DATA_FIELD_VALUE, columnIndex); 4505 resultSet->GetString(columnIndex, deviceName); 4506 AUDIO_INFO_LOG("GetDeviceNameFromDataShareHelper deviceName[%{public}s]", deviceName.c_str()); 4507 4508 resultSet->Close(); 4509 dataShareHelper->Release(); 4510 return SUCCESS; 4511 } 4512 IsDataShareReady()4513 bool AudioPolicyService::IsDataShareReady() 4514 { 4515 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); 4516 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, false, "[Policy Service] Get samgr failed."); 4517 sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(AUDIO_POLICY_SERVICE_ID); 4518 CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, false, "[Policy Service] audio service remote object is NULL."); 4519 WatchTimeout guard("DataShare::DataShareHelper::Create:IsDataShareReady", CALL_IPC_COST_TIME_MS); 4520 std::pair<int, std::shared_ptr<DataShare::DataShareHelper>> res = DataShare::DataShareHelper::Create(remoteObject, 4521 SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI); 4522 guard.CheckCurrTimeout(); 4523 if (res.first == DataShare::E_OK) { 4524 AUDIO_INFO_LOG("DataShareHelper is ready."); 4525 auto helper = res.second; 4526 if (helper != nullptr) { 4527 helper->Release(); 4528 } 4529 return true; 4530 } else { 4531 AUDIO_WARNING_LOG("DataShareHelper::Create failed: E_DATA_SHARE_NOT_READY"); 4532 return false; 4533 } 4534 } 4535 SetDataShareReady(std::atomic<bool> isDataShareReady)4536 void AudioPolicyService::SetDataShareReady(std::atomic<bool> isDataShareReady) 4537 { 4538 audioPolicyManager_.SetDataShareReady(std::atomic_load(&isDataShareReady)); 4539 } 4540 RegisterNameMonitorHelper()4541 void AudioPolicyService::RegisterNameMonitorHelper() 4542 { 4543 std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = CreateDataShareHelperInstance(); 4544 CHECK_AND_RETURN_LOG(dataShareHelper != nullptr, "dataShareHelper is NULL"); 4545 4546 auto uri = std::make_shared<Uri>(std::string(SETTINGS_DATA_BASE_URI) + "&key=" + PREDICATES_STRING); 4547 sptr<AAFwk::DataAbilityObserverStub> settingDataObserver = std::make_unique<DataShareObserverCallBack>().release(); 4548 dataShareHelper->RegisterObserver(*uri, settingDataObserver); 4549 4550 dataShareHelper->Release(); 4551 } 4552 UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor)4553 void AudioPolicyService::UpdateDisplayName(sptr<AudioDeviceDescriptor> deviceDescriptor) 4554 { 4555 if (deviceDescriptor->networkId_ == LOCAL_NETWORK_ID) { 4556 std::string devicesName = ""; 4557 int32_t ret = GetDeviceNameFromDataShareHelper(devicesName); 4558 CHECK_AND_RETURN_LOG(ret == SUCCESS, "Local UpdateDisplayName init device failed"); 4559 deviceDescriptor->displayName_ = devicesName; 4560 } else { 4561 #ifdef FEATURE_DEVICE_MANAGER 4562 std::shared_ptr<DistributedHardware::DmInitCallback> callback = std::make_shared<DeviceInitCallBack>(); 4563 int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, callback); 4564 CHECK_AND_RETURN_LOG(ret == SUCCESS, "UpdateDisplayName init device failed"); 4565 std::vector<DistributedHardware::DmDeviceInfo> deviceList; 4566 if (DistributedHardware::DeviceManager::GetInstance() 4567 .GetTrustedDeviceList(AUDIO_SERVICE_PKG, "", deviceList) == SUCCESS) { 4568 for (auto deviceInfo : deviceList) { 4569 std::string strNetworkId(deviceInfo.networkId); 4570 if (strNetworkId == deviceDescriptor->networkId_) { 4571 AUDIO_INFO_LOG("UpdateDisplayName remote name [%{public}s]", deviceInfo.deviceName); 4572 deviceDescriptor->displayName_ = deviceInfo.deviceName; 4573 break; 4574 } 4575 } 4576 }; 4577 #endif 4578 } 4579 } 4580 HandleOfflineDistributedDevice()4581 void AudioPolicyService::HandleOfflineDistributedDevice() 4582 { 4583 std::vector<sptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {}; 4584 4585 std::vector<sptr<AudioDeviceDescriptor>> connectedDevices = connectedDevices_; 4586 for (auto deviceDesc : connectedDevices) { 4587 if (deviceDesc != nullptr && deviceDesc->networkId_ != LOCAL_NETWORK_ID) { 4588 const std::string networkId = deviceDesc->networkId_; 4589 UpdateConnectedDevicesWhenDisconnecting(deviceDesc, deviceChangeDescriptor); 4590 std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(deviceDesc->deviceType_)); 4591 MuteDefaultSinkPort(); 4592 ClosePortAndEraseIOHandle(moduleName); 4593 RemoveDeviceInRouterMap(moduleName); 4594 RemoveDeviceInFastRouterMap(networkId); 4595 if (GetDeviceRole(deviceDesc->deviceType_) == DeviceRole::INPUT_DEVICE) { 4596 remoteCapturerSwitch_ = true; 4597 } 4598 } 4599 } 4600 4601 TriggerDeviceChangedCallback(deviceChangeDescriptor, false); 4602 TriggerAvailableDeviceChangedCallback(deviceChangeDescriptor, false); 4603 4604 FetchDevice(true); 4605 FetchDevice(false); 4606 } 4607 HandleDistributedDeviceUpdate(DStatusInfo & statusInfo,std::vector<sptr<AudioDeviceDescriptor>> & descForCb)4608 int32_t AudioPolicyService::HandleDistributedDeviceUpdate(DStatusInfo &statusInfo, 4609 std::vector<sptr<AudioDeviceDescriptor>> &descForCb) 4610 { 4611 DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin); 4612 const std::string networkId = statusInfo.networkId; 4613 AudioDeviceDescriptor deviceDesc(devType, GetDeviceRole(devType)); 4614 deviceDesc.SetDeviceInfo(statusInfo.deviceName, statusInfo.macAddress); 4615 deviceDesc.SetDeviceCapability(statusInfo.streamInfo, 0); 4616 deviceDesc.networkId_ = networkId; 4617 UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, networkId, statusInfo.isConnected, 4618 statusInfo.mappingVolumeId); 4619 UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, networkId, 4620 statusInfo.isConnected, statusInfo.mappingInterruptId); 4621 if (statusInfo.isConnected) { 4622 for (auto devDes : connectedDevices_) { 4623 if (devDes->deviceType_ == devType && devDes->networkId_ == networkId) { 4624 return ERROR; 4625 } 4626 } 4627 int32_t ret = ActivateNewDevice(statusInfo.networkId, devType, 4628 statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED); 4629 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "DEVICE online but open audio device failed."); 4630 UpdateConnectedDevicesWhenConnecting(deviceDesc, descForCb); 4631 4632 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 4633 if (gsp != nullptr && statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED) { 4634 std::string identity = IPCSkeleton::ResetCallingIdentity(); 4635 gsp->NotifyDeviceInfo(networkId, true); 4636 IPCSkeleton::SetCallingIdentity(identity); 4637 } 4638 } else { 4639 UpdateConnectedDevicesWhenDisconnecting(deviceDesc, descForCb); 4640 std::string moduleName = GetRemoteModuleName(networkId, GetDeviceRole(devType)); 4641 ClosePortAndEraseIOHandle(moduleName); 4642 RemoveDeviceInRouterMap(moduleName); 4643 RemoveDeviceInFastRouterMap(networkId); 4644 } 4645 return SUCCESS; 4646 } 4647 OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)4648 void AudioPolicyService::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop) 4649 { 4650 // Distributed devices status update 4651 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 4652 4653 AUDIO_WARNING_LOG("Device connection updated | HDI_PIN[%{public}d] CONNECT_STATUS[%{public}d] NETWORKID\ 4654 [%{public}s]", statusInfo.hdiPin, statusInfo.isConnected, GetEncryptStr(statusInfo.networkId).c_str()); 4655 if (isStop) { 4656 HandleOfflineDistributedDevice(); 4657 return; 4658 } 4659 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {}; 4660 int32_t ret = HandleDistributedDeviceUpdate(statusInfo, descForCb); 4661 CHECK_AND_RETURN_LOG(ret == SUCCESS, "HandleDistributedDeviceUpdate return directly."); 4662 4663 TriggerDeviceChangedCallback(descForCb, statusInfo.isConnected); 4664 TriggerAvailableDeviceChangedCallback(descForCb, statusInfo.isConnected); 4665 4666 FetchDevice(true); 4667 FetchDevice(false); 4668 4669 DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin); 4670 if (GetDeviceRole(devType) == DeviceRole::INPUT_DEVICE) { 4671 remoteCapturerSwitch_ = true; 4672 } 4673 4674 // update a2dp offload 4675 UpdateA2dpOffloadFlagForAllStream(); 4676 } 4677 OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo & moduleInfo)4678 bool AudioPolicyService::OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo &moduleInfo) 4679 { 4680 auto devType = GetDeviceType(moduleInfo.name); 4681 if (devType != DEVICE_TYPE_MIC) { 4682 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 4683 4684 if (devType == DEVICE_TYPE_SPEAKER) { 4685 auto result = audioPolicyManager_.SetDeviceActive(devType, moduleInfo.name, true); 4686 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, false, "[module_load]::Device failed %{public}d", devType); 4687 } 4688 } 4689 4690 if (devType == DEVICE_TYPE_MIC) { 4691 primaryMicModuleInfo_ = moduleInfo; 4692 } 4693 4694 if (devType == DEVICE_TYPE_SPEAKER || devType == DEVICE_TYPE_MIC) { 4695 AddAudioDevice(moduleInfo, devType); 4696 } 4697 4698 std::lock_guard<std::mutex> lock(defaultDeviceLoadMutex_); 4699 SetDefaultDeviceLoadFlag(true); 4700 loadDefaultDeviceCV_.notify_all(); 4701 4702 return true; 4703 } 4704 OnServiceConnected(AudioServiceIndex serviceIndex)4705 void AudioPolicyService::OnServiceConnected(AudioServiceIndex serviceIndex) 4706 { 4707 AUDIO_INFO_LOG("[module_load]::OnServiceConnected for [%{public}d]", serviceIndex); 4708 CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index"); 4709 4710 // If audio service or hdi service is not ready, donot load default modules 4711 lock_guard<mutex> lock(serviceFlagMutex_); 4712 serviceFlag_.set(serviceIndex, true); 4713 if (serviceFlag_.count() != MIN_SERVICE_COUNT) { 4714 AUDIO_INFO_LOG("[module_load]::hdi service or audio service not up. Cannot load default module now"); 4715 return; 4716 } 4717 4718 int32_t result = ERROR; 4719 AUDIO_DEBUG_LOG("[module_load]::HDI and AUDIO SERVICE is READY. Loading default modules"); 4720 for (const auto &device : deviceClassInfo_) { 4721 if (device.first == ClassType::TYPE_PRIMARY || device.first == ClassType::TYPE_FILE_IO) { 4722 auto moduleInfoList = device.second; 4723 for (auto &moduleInfo : moduleInfoList) { 4724 AUDIO_INFO_LOG("[module_load]::Load module[%{public}s]", moduleInfo.name.c_str()); 4725 moduleInfo.sinkLatency = sinkLatencyInMsec_ != 0 ? to_string(sinkLatencyInMsec_) : ""; 4726 if (OpenPortAndAddDeviceOnServiceConnected(moduleInfo)) { 4727 result = SUCCESS; 4728 } 4729 SetOffloadAvailableFromXML(moduleInfo); 4730 } 4731 } 4732 } 4733 4734 if (result == SUCCESS) { 4735 AUDIO_INFO_LOG("[module_load]::Setting speaker as active device on bootup"); 4736 hasModulesLoaded = true; 4737 unique_ptr<AudioDeviceDescriptor> outDevice = audioDeviceManager_.GetRenderDefaultDevice(); 4738 SetCurrentOutputDevice(*outDevice); 4739 unique_ptr<AudioDeviceDescriptor> inDevice = audioDeviceManager_.GetCaptureDefaultDevice(); 4740 SetCurrenInputDevice(*inDevice); 4741 SetVolumeForSwitchDevice(GetCurrentOutputDeviceType()); 4742 OnPreferredDeviceUpdated(GetCurrentOutputDevice(), GetCurrentInputDeviceType()); 4743 AddEarpiece(); 4744 for (auto it = pnpDeviceList_.begin(); it != pnpDeviceList_.end(); ++it) { 4745 OnPnpDeviceStatusUpdated((*it).first, (*it).second); 4746 } 4747 audioEffectManager_.SetMasterSinkAvailable(); 4748 } 4749 // load inner-cap-sink 4750 LoadModernInnerCapSink(); 4751 // RegisterBluetoothListener() will be called when bluetooth_host is online 4752 // load hdi-effect-model 4753 LoadHdiEffectModel(); 4754 } 4755 checkOffloadAvailable(AudioModuleInfo & moduleInfo)4756 void AudioPolicyService::checkOffloadAvailable(AudioModuleInfo& moduleInfo) 4757 { 4758 if (moduleInfo.name == "Speaker") { 4759 for (auto& portInfo: moduleInfo.ports) { 4760 if ((portInfo.adapterName == "primary") && (portInfo.offloadEnable == "1")) { 4761 isOffloadAvailable_ = true; 4762 } 4763 } 4764 } 4765 } 4766 OnServiceDisconnected(AudioServiceIndex serviceIndex)4767 void AudioPolicyService::OnServiceDisconnected(AudioServiceIndex serviceIndex) 4768 { 4769 AUDIO_WARNING_LOG("Start for [%{public}d]", serviceIndex); 4770 } 4771 OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)4772 void AudioPolicyService::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress) 4773 { 4774 if (macAddress.empty()) { 4775 AUDIO_ERR_LOG("OnForcedDeviceSelected failed as the macAddress is empty!"); 4776 return; 4777 } 4778 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 4779 AUDIO_INFO_LOG("bt select device type[%{public}d] address[%{public}s]", 4780 devType, GetEncryptAddr(macAddress).c_str()); 4781 std::vector<unique_ptr<AudioDeviceDescriptor>> bluetoothDevices = 4782 audioDeviceManager_.GetAvailableBluetoothDevice(devType, macAddress); 4783 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors; 4784 for (auto &dec : bluetoothDevices) { 4785 if (dec->deviceRole_ == DeviceRole::OUTPUT_DEVICE) { 4786 sptr<AudioDeviceDescriptor> tempDec = new(std::nothrow) AudioDeviceDescriptor(*dec); 4787 audioDeviceDescriptors.push_back(move(tempDec)); 4788 } 4789 } 4790 int32_t res = DeviceParamsCheck(DeviceRole::OUTPUT_DEVICE, audioDeviceDescriptors); 4791 CHECK_AND_RETURN_LOG(res == SUCCESS, "OnForcedDeviceSelected DeviceParamsCheck no success"); 4792 audioDeviceDescriptors[0]->isEnable_ = true; 4793 audioDeviceManager_.UpdateDevicesListInfo(audioDeviceDescriptors[0], ENABLE_UPDATE); 4794 if (devType == DEVICE_TYPE_BLUETOOTH_SCO) { 4795 SetPreferredDevice(AUDIO_CALL_RENDER, audioDeviceDescriptors[0]); 4796 ClearScoDeviceSuspendState(audioDeviceDescriptors[0]->macAddress_); 4797 } else { 4798 SetPreferredDevice(AUDIO_MEDIA_RENDER, audioDeviceDescriptors[0]); 4799 } 4800 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); 4801 } 4802 OnMonoAudioConfigChanged(bool audioMono)4803 void AudioPolicyService::OnMonoAudioConfigChanged(bool audioMono) 4804 { 4805 AUDIO_DEBUG_LOG("audioMono = %{public}s", audioMono? "true": "false"); 4806 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 4807 CHECK_AND_RETURN_LOG(gsp != nullptr, "OnMonoAudioConfigChanged, Audio Server Proxy is null"); 4808 std::string identity = IPCSkeleton::ResetCallingIdentity(); 4809 gsp->SetAudioMonoState(audioMono); 4810 IPCSkeleton::SetCallingIdentity(identity); 4811 } 4812 OnAudioBalanceChanged(float audioBalance)4813 void AudioPolicyService::OnAudioBalanceChanged(float audioBalance) 4814 { 4815 AUDIO_DEBUG_LOG("audioBalance = %{public}f", audioBalance); 4816 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 4817 CHECK_AND_RETURN_LOG(gsp != nullptr, "OnMonoAudioConfigChanged, Audio Server Proxy is null"); 4818 std::string identity = IPCSkeleton::ResetCallingIdentity(); 4819 gsp->SetAudioBalanceValue(audioBalance); 4820 IPCSkeleton::SetCallingIdentity(identity); 4821 } 4822 UpdateEffectDefaultSink(DeviceType deviceType)4823 void AudioPolicyService::UpdateEffectDefaultSink(DeviceType deviceType) 4824 { 4825 Trace trace("OnPreferredOutputDeviceUpdated:" + std::to_string(deviceType)); 4826 effectActiveDevice_ = deviceType; 4827 switch (deviceType) { 4828 case DeviceType::DEVICE_TYPE_EARPIECE: 4829 case DeviceType::DEVICE_TYPE_SPEAKER: 4830 case DeviceType::DEVICE_TYPE_FILE_SINK: 4831 case DeviceType::DEVICE_TYPE_WIRED_HEADSET: 4832 case DeviceType::DEVICE_TYPE_USB_HEADSET: 4833 case DeviceType::DEVICE_TYPE_DP: 4834 case DeviceType::DEVICE_TYPE_USB_ARM_HEADSET: 4835 case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP: 4836 case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO: { 4837 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 4838 CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable"); 4839 std::string sinkName = GetSinkPortName(deviceType); 4840 std::string identity = IPCSkeleton::ResetCallingIdentity(); 4841 gsp->SetOutputDeviceSink(deviceType, sinkName); 4842 IPCSkeleton::SetCallingIdentity(identity); 4843 4844 break; 4845 } 4846 default: 4847 break; 4848 } 4849 } 4850 LoadSinksForCapturer()4851 void AudioPolicyService::LoadSinksForCapturer() 4852 { 4853 AUDIO_INFO_LOG("Start"); 4854 AudioStreamInfo streamInfo; 4855 LoadInnerCapturerSink(INNER_CAPTURER_SINK_LEGACY, streamInfo); 4856 4857 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 4858 CHECK_AND_RETURN_LOG(gsp != nullptr, "LoadSinksForCapturer error for gsp null"); 4859 std::string identity = IPCSkeleton::ResetCallingIdentity(); 4860 bool ret = gsp->CreatePlaybackCapturerManager(); 4861 IPCSkeleton::SetCallingIdentity(identity); 4862 CHECK_AND_RETURN_LOG(ret, "PlaybackCapturerManager create failed"); 4863 } 4864 LoadInnerCapturerSink(string moduleName,AudioStreamInfo streamInfo)4865 void AudioPolicyService::LoadInnerCapturerSink(string moduleName, AudioStreamInfo streamInfo) 4866 { 4867 AUDIO_INFO_LOG("Start"); 4868 uint32_t bufferSize = (streamInfo.samplingRate * GetSampleFormatValue(streamInfo.format) 4869 * streamInfo.channels) / PCM_8_BIT * RENDER_FRAME_INTERVAL_IN_SECONDS; 4870 4871 AudioModuleInfo moduleInfo = {}; 4872 moduleInfo.lib = "libmodule-inner-capturer-sink.z.so"; 4873 moduleInfo.format = ConvertToHDIAudioFormat(streamInfo.format); 4874 moduleInfo.name = moduleName; 4875 moduleInfo.networkId = "LocalDevice"; 4876 moduleInfo.channels = std::to_string(streamInfo.channels); 4877 moduleInfo.rate = std::to_string(streamInfo.samplingRate); 4878 moduleInfo.bufferSize = std::to_string(bufferSize); 4879 4880 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 4881 } 4882 UnloadInnerCapturerSink(string moduleName)4883 void AudioPolicyService::UnloadInnerCapturerSink(string moduleName) 4884 { 4885 ClosePortAndEraseIOHandle(moduleName); 4886 } 4887 LoadModernInnerCapSink()4888 void AudioPolicyService::LoadModernInnerCapSink() 4889 { 4890 AUDIO_INFO_LOG("Start"); 4891 AudioModuleInfo moduleInfo = {}; 4892 moduleInfo.lib = "libmodule-inner-capturer-sink.z.so"; 4893 moduleInfo.name = INNER_CAPTURER_SINK; 4894 4895 moduleInfo.format = "s16le"; 4896 moduleInfo.channels = "2"; // 2 channel 4897 moduleInfo.rate = "48000"; 4898 moduleInfo.bufferSize = "3840"; // 20ms 4899 4900 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 4901 } 4902 LoadEffectLibrary()4903 void AudioPolicyService::LoadEffectLibrary() 4904 { 4905 // IPC -> audioservice load library 4906 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 4907 CHECK_AND_RETURN_LOG(gsp != nullptr, "LoadEffectLibrary, Audio Server Proxy is null"); 4908 OriginalEffectConfig oriEffectConfig = {}; 4909 audioEffectManager_.GetOriginalEffectConfig(oriEffectConfig); 4910 vector<Effect> successLoadedEffects; 4911 std::string identity = IPCSkeleton::ResetCallingIdentity(); 4912 bool loadSuccess = gsp->LoadAudioEffectLibraries(oriEffectConfig.libraries, 4913 oriEffectConfig.effects, 4914 successLoadedEffects); 4915 IPCSkeleton::SetCallingIdentity(identity); 4916 if (!loadSuccess) { 4917 AUDIO_ERR_LOG("Load audio effect failed, please check log"); 4918 } 4919 4920 audioEffectManager_.UpdateAvailableEffects(successLoadedEffects); 4921 audioEffectManager_.BuildAvailableAEConfig(); 4922 4923 // Initialize EffectChainManager in audio service through IPC 4924 SupportedEffectConfig supportedEffectConfig; 4925 audioEffectManager_.GetSupportedEffectConfig(supportedEffectConfig); 4926 EffectChainManagerParam effectChainManagerParam; 4927 EffectChainManagerParam enhanceChainManagerParam; 4928 audioEffectManager_.ConstructEffectChainManagerParam(effectChainManagerParam); 4929 audioEffectManager_.ConstructEnhanceChainManagerParam(enhanceChainManagerParam); 4930 4931 identity = IPCSkeleton::ResetCallingIdentity(); 4932 bool ret = gsp->CreateEffectChainManager(supportedEffectConfig.effectChains, 4933 effectChainManagerParam, enhanceChainManagerParam); 4934 IPCSkeleton::SetCallingIdentity(identity); 4935 CHECK_AND_RETURN_LOG(ret, "EffectChainManager create failed"); 4936 4937 audioEffectManager_.SetEffectChainManagerAvailable(); 4938 AudioSpatializationService::GetAudioSpatializationService().Init(supportedEffectConfig.effectChains); 4939 } 4940 GetEffectManagerInfo()4941 void AudioPolicyService::GetEffectManagerInfo() 4942 { 4943 converterConfig_ = GetConverterConfig(); 4944 audioEffectManager_.GetSupportedEffectConfig(supportedEffectConfig_); 4945 } 4946 AddAudioDevice(AudioModuleInfo & moduleInfo,InternalDeviceType devType)4947 void AudioPolicyService::AddAudioDevice(AudioModuleInfo& moduleInfo, InternalDeviceType devType) 4948 { 4949 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 4950 4951 // add new device into active device list 4952 std::string volumeGroupName = GetGroupName(moduleInfo.name, VOLUME_TYPE); 4953 std::string interruptGroupName = GetGroupName(moduleInfo.name, INTERRUPT_TYPE); 4954 int32_t volumeGroupId = GROUP_ID_NONE; 4955 int32_t interruptGroupId = GROUP_ID_NONE; 4956 UpdateGroupInfo(GroupType::VOLUME_TYPE, volumeGroupName, volumeGroupId, LOCAL_NETWORK_ID, true, 4957 NO_REMOTE_ID); 4958 UpdateGroupInfo(GroupType::INTERRUPT_TYPE, interruptGroupName, interruptGroupId, LOCAL_NETWORK_ID, 4959 true, NO_REMOTE_ID); 4960 4961 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(devType, 4962 GetDeviceRole(moduleInfo.role), volumeGroupId, interruptGroupId, LOCAL_NETWORK_ID); 4963 if (!moduleInfo.supportedRate_.empty() && !moduleInfo.supportedChannels_.empty()) { 4964 DeviceStreamInfo streamInfo = {}; 4965 for (auto supportedRate : moduleInfo.supportedRate_) { 4966 streamInfo.samplingRate.insert(static_cast<AudioSamplingRate>(supportedRate)); 4967 } 4968 for (auto supportedChannels : moduleInfo.supportedChannels_) { 4969 streamInfo.channels.insert(static_cast<AudioChannel>(supportedChannels)); 4970 } 4971 audioDescriptor->SetDeviceCapability(streamInfo, 0); 4972 } 4973 4974 audioDescriptor->deviceId_ = startDeviceId++; 4975 UpdateDisplayName(audioDescriptor); 4976 audioDeviceManager_.AddNewDevice(audioDescriptor); 4977 connectedDevices_.insert(connectedDevices_.begin(), audioDescriptor); 4978 AddMicrophoneDescriptor(audioDescriptor); 4979 } 4980 OnAudioPolicyXmlParsingCompleted(const std::unordered_map<AdaptersType,AudioAdapterInfo> adapterInfoMap)4981 void AudioPolicyService::OnAudioPolicyXmlParsingCompleted( 4982 const std::unordered_map<AdaptersType, AudioAdapterInfo> adapterInfoMap) 4983 { 4984 AUDIO_INFO_LOG("adapterInfo num [%{public}zu]", adapterInfoMap.size()); 4985 CHECK_AND_RETURN_LOG(!adapterInfoMap.empty(), "failed to parse audiopolicy xml file. Received data is empty"); 4986 adapterInfoMap_ = adapterInfoMap; 4987 4988 for (auto &adapterInfo : adapterInfoMap_) { 4989 for (auto &deviceInfos : (adapterInfo.second).deviceInfos_) { 4990 if (deviceInfos.type_ == EARPIECE_TYPE_NAME) { 4991 AUDIO_INFO_LOG("Has earpiece"); 4992 hasEarpiece_ = true; 4993 break; 4994 } 4995 } 4996 if (hasEarpiece_) { 4997 break; 4998 } 4999 } 5000 isAdapterInfoMap_.store(true); 5001 5002 audioDeviceManager_.UpdateEarpieceStatus(hasEarpiece_); 5003 } 5004 5005 // Parser callbacks OnXmlParsingCompleted(const std::unordered_map<ClassType,std::list<AudioModuleInfo>> & xmlData)5006 void AudioPolicyService::OnXmlParsingCompleted(const std::unordered_map<ClassType, std::list<AudioModuleInfo>> &xmlData) 5007 { 5008 AUDIO_INFO_LOG("device class num [%{public}zu]", xmlData.size()); 5009 CHECK_AND_RETURN_LOG(!xmlData.empty(), "failed to parse xml file. Received data is empty"); 5010 5011 deviceClassInfo_ = xmlData; 5012 } 5013 OnVolumeGroupParsed(std::unordered_map<std::string,std::string> & volumeGroupData)5014 void AudioPolicyService::OnVolumeGroupParsed(std::unordered_map<std::string, std::string>& volumeGroupData) 5015 { 5016 AUDIO_INFO_LOG("group data num [%{public}zu]", volumeGroupData.size()); 5017 CHECK_AND_RETURN_LOG(!volumeGroupData.empty(), "failed to parse xml file. Received data is empty"); 5018 5019 volumeGroupData_ = volumeGroupData; 5020 } 5021 OnInterruptGroupParsed(std::unordered_map<std::string,std::string> & interruptGroupData)5022 void AudioPolicyService::OnInterruptGroupParsed(std::unordered_map<std::string, std::string>& interruptGroupData) 5023 { 5024 AUDIO_INFO_LOG("group data num [%{public}zu]", interruptGroupData.size()); 5025 CHECK_AND_RETURN_LOG(!interruptGroupData.empty(), "failed to parse xml file. Received data is empty"); 5026 5027 interruptGroupData_ = interruptGroupData; 5028 } 5029 OnGlobalConfigsParsed(GlobalConfigs & globalConfigs)5030 void AudioPolicyService::OnGlobalConfigsParsed(GlobalConfigs &globalConfigs) 5031 { 5032 globalConfigs_ = globalConfigs; 5033 } 5034 OnVoipConfigParsed(bool enableFastVoip)5035 void AudioPolicyService::OnVoipConfigParsed(bool enableFastVoip) 5036 { 5037 enableFastVoip_ = enableFastVoip; 5038 } 5039 GetAudioAdapterInfos(std::unordered_map<AdaptersType,AudioAdapterInfo> & adapterInfoMap)5040 void AudioPolicyService::GetAudioAdapterInfos(std::unordered_map<AdaptersType, AudioAdapterInfo> &adapterInfoMap) 5041 { 5042 adapterInfoMap = adapterInfoMap_; 5043 } 5044 GetVolumeGroupData(std::unordered_map<std::string,std::string> & volumeGroupData)5045 void AudioPolicyService::GetVolumeGroupData(std::unordered_map<std::string, std::string>& volumeGroupData) 5046 { 5047 volumeGroupData = volumeGroupData_; 5048 } 5049 GetInterruptGroupData(std::unordered_map<std::string,std::string> & interruptGroupData)5050 void AudioPolicyService::GetInterruptGroupData(std::unordered_map<std::string, std::string>& interruptGroupData) 5051 { 5052 interruptGroupData = interruptGroupData_; 5053 } 5054 GetDeviceClassInfo(std::unordered_map<ClassType,std::list<AudioModuleInfo>> & deviceClassInfo)5055 void AudioPolicyService::GetDeviceClassInfo(std::unordered_map<ClassType, std::list<AudioModuleInfo>> &deviceClassInfo) 5056 { 5057 deviceClassInfo = deviceClassInfo_; 5058 } 5059 GetGlobalConfigs(GlobalConfigs & globalConfigs)5060 void AudioPolicyService::GetGlobalConfigs(GlobalConfigs &globalConfigs) 5061 { 5062 globalConfigs = globalConfigs_; 5063 } 5064 GetVoipConfig()5065 bool AudioPolicyService::GetVoipConfig() 5066 { 5067 return enableFastVoip_; 5068 } 5069 AddAudioPolicyClientProxyMap(int32_t clientPid,const sptr<IAudioPolicyClient> & cb)5070 void AudioPolicyService::AddAudioPolicyClientProxyMap(int32_t clientPid, const sptr<IAudioPolicyClient>& cb) 5071 { 5072 if (audioPolicyServerHandler_ != nullptr) { 5073 audioPolicyServerHandler_->AddAudioPolicyClientProxyMap(clientPid, cb); 5074 } 5075 } 5076 ReduceAudioPolicyClientProxyMap(pid_t clientPid)5077 void AudioPolicyService::ReduceAudioPolicyClientProxyMap(pid_t clientPid) 5078 { 5079 if (audioPolicyServerHandler_ != nullptr) { 5080 audioPolicyServerHandler_->RemoveAudioPolicyClientProxyMap(clientPid); 5081 } 5082 } 5083 SetAvailableDeviceChangeCallback(const int32_t clientId,const AudioDeviceUsage usage,const sptr<IRemoteObject> & object,bool hasBTPermission)5084 int32_t AudioPolicyService::SetAvailableDeviceChangeCallback(const int32_t clientId, const AudioDeviceUsage usage, 5085 const sptr<IRemoteObject> &object, bool hasBTPermission) 5086 { 5087 sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object); 5088 5089 if (callback != nullptr) { 5090 callback->hasBTPermission_ = hasBTPermission; 5091 5092 if (audioPolicyServerHandler_ != nullptr) { 5093 audioPolicyServerHandler_->AddAvailableDeviceChangeMap(clientId, usage, callback); 5094 } 5095 } 5096 5097 return SUCCESS; 5098 } 5099 SetQueryClientTypeCallback(const sptr<IRemoteObject> & object)5100 int32_t AudioPolicyService::SetQueryClientTypeCallback(const sptr<IRemoteObject> &object) 5101 { 5102 #ifdef FEATURE_APPGALLERY 5103 sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object); 5104 if (callback != nullptr) { 5105 ClientTypeManager::GetInstance()->SetQueryClientTypeCallback(callback); 5106 } else { 5107 AUDIO_ERR_LOG("Client type callback is null"); 5108 } 5109 #endif 5110 return SUCCESS; 5111 } 5112 UnsetAvailableDeviceChangeCallback(const int32_t clientId,AudioDeviceUsage usage)5113 int32_t AudioPolicyService::UnsetAvailableDeviceChangeCallback(const int32_t clientId, AudioDeviceUsage usage) 5114 { 5115 AUDIO_INFO_LOG("UnsetAvailableDeviceChangeCallback start"); 5116 5117 if (audioPolicyServerHandler_ != nullptr) { 5118 audioPolicyServerHandler_->RemoveAvailableDeviceChangeMap(clientId, usage); 5119 } 5120 return SUCCESS; 5121 } 5122 UpdateRendererInfoWhenNoPermission(const unique_ptr<AudioRendererChangeInfo> & audioRendererChangeInfos,bool hasSystemPermission)5123 static void UpdateRendererInfoWhenNoPermission(const unique_ptr<AudioRendererChangeInfo> &audioRendererChangeInfos, 5124 bool hasSystemPermission) 5125 { 5126 if (!hasSystemPermission) { 5127 audioRendererChangeInfos->clientUID = 0; 5128 audioRendererChangeInfos->rendererState = RENDERER_INVALID; 5129 } 5130 } 5131 UpdateCapturerInfoWhenNoPermission(const unique_ptr<AudioCapturerChangeInfo> & audioCapturerChangeInfos,bool hasSystemPermission)5132 static void UpdateCapturerInfoWhenNoPermission(const unique_ptr<AudioCapturerChangeInfo> &audioCapturerChangeInfos, 5133 bool hasSystemPermission) 5134 { 5135 if (!hasSystemPermission) { 5136 audioCapturerChangeInfos->clientUID = 0; 5137 audioCapturerChangeInfos->capturerState = CAPTURER_INVALID; 5138 } 5139 } 5140 HasLowLatencyCapability(DeviceType deviceType,bool isRemote)5141 bool AudioPolicyService::HasLowLatencyCapability(DeviceType deviceType, bool isRemote) 5142 { 5143 // Distributed devices are low latency devices 5144 if (isRemote) { 5145 return true; 5146 } 5147 5148 switch (deviceType) { 5149 case DeviceType::DEVICE_TYPE_EARPIECE: 5150 case DeviceType::DEVICE_TYPE_SPEAKER: 5151 case DeviceType::DEVICE_TYPE_WIRED_HEADSET: 5152 case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES: 5153 case DeviceType::DEVICE_TYPE_USB_HEADSET: 5154 case DeviceType::DEVICE_TYPE_DP: 5155 return true; 5156 5157 case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO: 5158 case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP: 5159 return false; 5160 default: 5161 return false; 5162 } 5163 } 5164 UpdateDeviceInfo(DeviceInfo & deviceInfo,const sptr<AudioDeviceDescriptor> & desc,bool hasBTPermission,bool hasSystemPermission)5165 void AudioPolicyService::UpdateDeviceInfo(DeviceInfo &deviceInfo, const sptr<AudioDeviceDescriptor> &desc, 5166 bool hasBTPermission, bool hasSystemPermission) 5167 { 5168 deviceInfo.deviceType = desc->deviceType_; 5169 deviceInfo.deviceRole = desc->deviceRole_; 5170 deviceInfo.deviceId = desc->deviceId_; 5171 deviceInfo.channelMasks = desc->channelMasks_; 5172 deviceInfo.channelIndexMasks = desc->channelIndexMasks_; 5173 deviceInfo.displayName = desc->displayName_; 5174 deviceInfo.connectState = desc->connectState_; 5175 5176 if (deviceInfo.deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 5177 deviceInfo.a2dpOffloadFlag = a2dpOffloadFlag_; 5178 } 5179 5180 if (hasBTPermission) { 5181 deviceInfo.deviceName = desc->deviceName_; 5182 deviceInfo.macAddress = desc->macAddress_; 5183 deviceInfo.deviceCategory = desc->deviceCategory_; 5184 } else { 5185 deviceInfo.deviceName = ""; 5186 deviceInfo.macAddress = ""; 5187 deviceInfo.deviceCategory = CATEGORY_DEFAULT; 5188 } 5189 5190 deviceInfo.isLowLatencyDevice = HasLowLatencyCapability(deviceInfo.deviceType, 5191 desc->networkId_ != LOCAL_NETWORK_ID); 5192 5193 if (hasSystemPermission) { 5194 deviceInfo.networkId = desc->networkId_; 5195 deviceInfo.volumeGroupId = desc->volumeGroupId_; 5196 deviceInfo.interruptGroupId = desc->interruptGroupId_; 5197 } else { 5198 deviceInfo.networkId = ""; 5199 deviceInfo.volumeGroupId = GROUP_ID_NONE; 5200 deviceInfo.interruptGroupId = GROUP_ID_NONE; 5201 } 5202 deviceInfo.audioStreamInfo.samplingRate = desc->audioStreamInfo_.samplingRate; 5203 deviceInfo.audioStreamInfo.encoding = desc->audioStreamInfo_.encoding; 5204 deviceInfo.audioStreamInfo.format = desc->audioStreamInfo_.format; 5205 deviceInfo.audioStreamInfo.channels = desc->audioStreamInfo_.channels; 5206 } 5207 RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object,const int32_t apiVersion)5208 int32_t AudioPolicyService::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo, 5209 const sptr<IRemoteObject> &object, const int32_t apiVersion) 5210 { 5211 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 5212 5213 if (mode == AUDIO_MODE_RECORD) { 5214 AddAudioCapturerMicrophoneDescriptor(streamChangeInfo.audioCapturerChangeInfo.sessionId, DEVICE_TYPE_NONE); 5215 if (apiVersion > 0 && apiVersion < API_11) { 5216 UpdateDeviceInfo(streamChangeInfo.audioCapturerChangeInfo.inputDeviceInfo, 5217 new AudioDeviceDescriptor(GetCurrentInputDevice()), false, false); 5218 } 5219 } else if (apiVersion > 0 && apiVersion < API_11) { 5220 UpdateDeviceInfo(streamChangeInfo.audioRendererChangeInfo.outputDeviceInfo, 5221 new AudioDeviceDescriptor(GetCurrentOutputDevice()), false, false); 5222 } 5223 return streamCollector_.RegisterTracker(mode, streamChangeInfo, object); 5224 } 5225 UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)5226 int32_t AudioPolicyService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo) 5227 { 5228 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 5229 5230 HandleAudioCaptureState(mode, streamChangeInfo); 5231 int32_t ret = streamCollector_.UpdateTracker(mode, streamChangeInfo); 5232 5233 const auto &rendererState = streamChangeInfo.audioRendererChangeInfo.rendererState; 5234 if (rendererState == RENDERER_PREPARED || rendererState == RENDERER_NEW || rendererState == RENDERER_INVALID) { 5235 return ret; // only update tracker in new and prepared 5236 } 5237 5238 if (rendererState == RENDERER_RELEASED && !streamCollector_.ExistStreamForPipe(PIPE_TYPE_MULTICHANNEL)) { 5239 DynamicUnloadModule(PIPE_TYPE_MULTICHANNEL); 5240 } 5241 5242 if (mode == AUDIO_MODE_PLAYBACK && (rendererState == RENDERER_STOPPED || rendererState == RENDERER_PAUSED || 5243 rendererState == RENDERER_RELEASED)) { 5244 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(streamChangeInfo.audioRendererChangeInfo.sessionId); 5245 if (rendererState == RENDERER_RELEASED) { 5246 audioDeviceManager_.RemoveSelectedDefaultOutputDevice(streamChangeInfo.audioRendererChangeInfo.sessionId); 5247 } 5248 FetchDevice(true); 5249 } 5250 5251 if (enableDualHalToneState_ && (mode == AUDIO_MODE_PLAYBACK) 5252 && (rendererState == RENDERER_STOPPED || rendererState == RENDERER_RELEASED)) { 5253 const int32_t sessionId = streamChangeInfo.audioRendererChangeInfo.sessionId; 5254 const StreamUsage streamUsage = streamChangeInfo.audioRendererChangeInfo.rendererInfo.streamUsage; 5255 if ((sessionId == enableDualHalToneSessionId_) && Util::IsRingerOrAlarmerStreamUsage(streamUsage)) { 5256 AUDIO_INFO_LOG("disable dual hal tone when ringer/alarm renderer stop/release."); 5257 UpdateDualToneState(false, enableDualHalToneSessionId_); 5258 } 5259 } 5260 5261 UpdateA2dpOffloadFlagForAllStream(GetCurrentOutputDeviceType()); 5262 SendA2dpConnectedWhileRunning(rendererState, streamChangeInfo.audioRendererChangeInfo.sessionId); 5263 return ret; 5264 } 5265 HandleAudioCaptureState(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)5266 void AudioPolicyService::HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo) 5267 { 5268 if (mode == AUDIO_MODE_RECORD && 5269 (streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_RELEASED || 5270 streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_STOPPED)) { 5271 if (streamChangeInfo.audioCapturerChangeInfo.capturerInfo.sourceType == SOURCE_TYPE_VOICE_RECOGNITION) { 5272 BluetoothScoDisconectForRecongnition(); 5273 Bluetooth::AudioHfpManager::ClearRecongnitionStatus(); 5274 } 5275 audioCaptureMicrophoneDescriptor_.erase(streamChangeInfo.audioCapturerChangeInfo.sessionId); 5276 } 5277 } 5278 SendA2dpConnectedWhileRunning(const RendererState & rendererState,const uint32_t & sessionId)5279 void AudioPolicyService::SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId) 5280 { 5281 if ((rendererState == RENDERER_RUNNING) && (audioA2dpOffloadManager_ != nullptr) && 5282 !audioA2dpOffloadManager_->IsA2dpOffloadConnecting(sessionId)) { 5283 AUDIO_INFO_LOG("Notify client not to block."); 5284 std::thread sendConnectedToClient(&AudioPolicyService::UpdateSessionConnectionState, this, sessionId, 5285 DATA_LINK_CONNECTED); 5286 sendConnectedToClient.detach(); 5287 } 5288 } 5289 FetchOutputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo,const AudioStreamDeviceChangeReasonExt reason)5290 void AudioPolicyService::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo, 5291 const AudioStreamDeviceChangeReasonExt reason) 5292 { 5293 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 5294 AUDIO_INFO_LOG("fetch device for track, sessionid:%{public}d start", 5295 streamChangeInfo.audioRendererChangeInfo.sessionId); 5296 5297 AudioMode mode = AudioMode::AUDIO_MODE_PLAYBACK; 5298 // Set prerunningState true to refetch devices when device info change before update tracker to running 5299 streamChangeInfo.audioRendererChangeInfo.prerunningState = true; 5300 if (streamCollector_.UpdateTrackerInternal(mode, streamChangeInfo) != SUCCESS) { 5301 return; 5302 } 5303 5304 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfo; 5305 rendererChangeInfo.push_back( 5306 make_unique<AudioRendererChangeInfo>(streamChangeInfo.audioRendererChangeInfo)); 5307 streamCollector_.GetRendererStreamInfo(streamChangeInfo, *rendererChangeInfo[0]); 5308 5309 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStarting(streamChangeInfo.audioRendererChangeInfo.sessionId); 5310 5311 FetchOutputDevice(rendererChangeInfo, reason); 5312 } 5313 FetchInputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo)5314 void AudioPolicyService::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo) 5315 { 5316 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 5317 AUDIO_INFO_LOG("fetch device for track, sessionid:%{public}d start", 5318 streamChangeInfo.audioRendererChangeInfo.sessionId); 5319 5320 vector<unique_ptr<AudioCapturerChangeInfo>> capturerChangeInfo; 5321 capturerChangeInfo.push_back( 5322 make_unique<AudioCapturerChangeInfo>(streamChangeInfo.audioCapturerChangeInfo)); 5323 streamCollector_.GetCapturerStreamInfo(streamChangeInfo, *capturerChangeInfo[0]); 5324 5325 FetchInputDevice(capturerChangeInfo); 5326 } 5327 GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos,bool hasBTPermission,bool hasSystemPermission)5328 int32_t AudioPolicyService::GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> 5329 &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission) 5330 { 5331 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 5332 5333 int32_t status = streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos); 5334 CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status, 5335 "AudioPolicyServer:: Get renderer change info failed"); 5336 5337 std::vector<sptr<AudioDeviceDescriptor>> outputDevices = GetDevicesInner(OUTPUT_DEVICES_FLAG); 5338 DeviceType activeDeviceType = GetCurrentOutputDeviceType(); 5339 DeviceRole activeDeviceRole = OUTPUT_DEVICE; 5340 for (sptr<AudioDeviceDescriptor> desc : outputDevices) { 5341 if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) { 5342 if (activeDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP && 5343 desc->macAddress_ != GetCurrentOutputDeviceMacAddr()) { 5344 // This A2DP device is not the active A2DP device. Skip it. 5345 continue; 5346 } 5347 size_t rendererInfosSize = audioRendererChangeInfos.size(); 5348 for (size_t i = 0; i < rendererInfosSize; i++) { 5349 UpdateRendererInfoWhenNoPermission(audioRendererChangeInfos[i], hasSystemPermission); 5350 UpdateDeviceInfo(audioRendererChangeInfos[i]->outputDeviceInfo, desc, hasBTPermission, 5351 hasSystemPermission); 5352 } 5353 break; 5354 } 5355 } 5356 5357 return status; 5358 } 5359 GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos,bool hasBTPermission,bool hasSystemPermission)5360 int32_t AudioPolicyService::GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> 5361 &audioCapturerChangeInfos, bool hasBTPermission, bool hasSystemPermission) 5362 { 5363 int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos); 5364 CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status, 5365 "AudioPolicyServer:: Get capturer change info failed"); 5366 5367 std::vector<sptr<AudioDeviceDescriptor>> inputDevices = GetDevicesInner(INPUT_DEVICES_FLAG); 5368 DeviceType activeDeviceType = GetCurrentInputDeviceType(); 5369 DeviceRole activeDeviceRole = INPUT_DEVICE; 5370 for (sptr<AudioDeviceDescriptor> desc : inputDevices) { 5371 if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) { 5372 size_t capturerInfosSize = audioCapturerChangeInfos.size(); 5373 for (size_t i = 0; i < capturerInfosSize; i++) { 5374 UpdateCapturerInfoWhenNoPermission(audioCapturerChangeInfos[i], hasSystemPermission); 5375 UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc, hasBTPermission, 5376 hasSystemPermission); 5377 } 5378 break; 5379 } 5380 } 5381 5382 return status; 5383 } 5384 RegisteredTrackerClientDied(pid_t uid)5385 void AudioPolicyService::RegisteredTrackerClientDied(pid_t uid) 5386 { 5387 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 5388 5389 UpdateDefaultOutputDeviceWhenStopping(static_cast<int32_t>(uid)); 5390 5391 RemoveAudioCapturerMicrophoneDescriptor(static_cast<int32_t>(uid)); 5392 streamCollector_.RegisteredTrackerClientDied(static_cast<int32_t>(uid)); 5393 5394 ClientDiedDisconnectScoNormal(); 5395 ClientDiedDisconnectScoRecognition(); 5396 5397 if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_OFFLOAD)) { 5398 DynamicUnloadModule(PIPE_TYPE_OFFLOAD); 5399 } 5400 5401 if (!streamCollector_.ExistStreamForPipe(PIPE_TYPE_MULTICHANNEL)) { 5402 DynamicUnloadModule(PIPE_TYPE_MULTICHANNEL); 5403 } 5404 } 5405 ClientDiedDisconnectScoNormal()5406 void AudioPolicyService::ClientDiedDisconnectScoNormal() 5407 { 5408 DeviceType deviceType = GetCurrentOutputDeviceType(); 5409 bool hasRunningRendererStream = streamCollector_.HasRunningRendererStream(); 5410 if (hasRunningRendererStream && deviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 5411 return; 5412 } 5413 AUDIO_WARNING_LOG("Client died disconnect sco for normal"); 5414 Bluetooth::AudioHfpManager::DisconnectSco(); 5415 } 5416 ClientDiedDisconnectScoRecognition()5417 void AudioPolicyService::ClientDiedDisconnectScoRecognition() 5418 { 5419 bool hasRunningRecognitionCapturerStream = streamCollector_.HasRunningRecognitionCapturerStream(); 5420 if (hasRunningRecognitionCapturerStream) { 5421 return; 5422 } 5423 AudioDeviceDescriptor tempDesc = GetCurrentInputDevice(); 5424 if (tempDesc.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) { 5425 return; 5426 } 5427 if (Bluetooth::AudioHfpManager::GetScoCategory() == Bluetooth::ScoCategory::SCO_RECOGNITION || 5428 Bluetooth::AudioHfpManager::GetRecognitionStatus() == Bluetooth::RecognitionStatus::RECOGNITION_CONNECTING) { 5429 AUDIO_WARNING_LOG("Client died disconnect sco for recognition"); 5430 BluetoothScoDisconectForRecongnition(); 5431 Bluetooth::AudioHfpManager::ClearRecongnitionStatus(); 5432 } 5433 } 5434 ReconfigureAudioChannel(const uint32_t & channelCount,DeviceType deviceType)5435 int32_t AudioPolicyService::ReconfigureAudioChannel(const uint32_t &channelCount, DeviceType deviceType) 5436 { 5437 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_FILE_SINK) { 5438 AUDIO_INFO_LOG("FILE_SINK_DEVICE is not active. Cannot reconfigure now"); 5439 return ERROR; 5440 } 5441 5442 std::string module = FILE_SINK; 5443 5444 if (deviceType == DeviceType::DEVICE_TYPE_FILE_SINK) { 5445 CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_8 && channelCount >= MONO, ERROR, "Invalid sink channel"); 5446 module = FILE_SINK; 5447 } else if (deviceType == DeviceType::DEVICE_TYPE_FILE_SOURCE) { 5448 CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_6 && channelCount >= MONO, ERROR, "Invalid src channel"); 5449 module = FILE_SOURCE; 5450 } else { 5451 AUDIO_ERR_LOG("Invalid DeviceType"); 5452 return ERROR; 5453 } 5454 5455 ClosePortAndEraseIOHandle(module); 5456 5457 auto fileClass = deviceClassInfo_.find(ClassType::TYPE_FILE_IO); 5458 if (fileClass != deviceClassInfo_.end()) { 5459 auto moduleInfoList = fileClass->second; 5460 for (auto &moduleInfo : moduleInfoList) { 5461 if (module == moduleInfo.name) { 5462 moduleInfo.channels = to_string(channelCount); 5463 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 5464 audioPolicyManager_.SetDeviceActive(deviceType, module, true); 5465 } 5466 } 5467 } 5468 5469 return SUCCESS; 5470 } 5471 5472 // private methods GetSinkIOHandle(InternalDeviceType deviceType)5473 AudioIOHandle AudioPolicyService::GetSinkIOHandle(InternalDeviceType deviceType) 5474 { 5475 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 5476 AudioIOHandle ioHandle; 5477 switch (deviceType) { 5478 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADSET: 5479 case InternalDeviceType::DEVICE_TYPE_WIRED_HEADPHONES: 5480 case InternalDeviceType::DEVICE_TYPE_USB_HEADSET: 5481 case InternalDeviceType::DEVICE_TYPE_EARPIECE: 5482 case InternalDeviceType::DEVICE_TYPE_SPEAKER: 5483 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_SCO: 5484 ioHandle = IOHandles_[PRIMARY_SPEAKER]; 5485 break; 5486 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET: 5487 ioHandle = IOHandles_[USB_SPEAKER]; 5488 break; 5489 case InternalDeviceType::DEVICE_TYPE_BLUETOOTH_A2DP: 5490 ioHandle = IOHandles_[BLUETOOTH_SPEAKER]; 5491 break; 5492 case InternalDeviceType::DEVICE_TYPE_FILE_SINK: 5493 ioHandle = IOHandles_[FILE_SINK]; 5494 break; 5495 case InternalDeviceType::DEVICE_TYPE_DP: 5496 ioHandle = IOHandles_[DP_SINK]; 5497 break; 5498 default: 5499 ioHandle = IOHandles_[PRIMARY_SPEAKER]; 5500 break; 5501 } 5502 return ioHandle; 5503 } 5504 GetSourceIOHandle(InternalDeviceType deviceType)5505 AudioIOHandle AudioPolicyService::GetSourceIOHandle(InternalDeviceType deviceType) 5506 { 5507 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 5508 AudioIOHandle ioHandle; 5509 switch (deviceType) { 5510 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET: 5511 ioHandle = IOHandles_[USB_MIC]; 5512 break; 5513 case InternalDeviceType::DEVICE_TYPE_MIC: 5514 ioHandle = IOHandles_[PRIMARY_MIC]; 5515 break; 5516 case InternalDeviceType::DEVICE_TYPE_FILE_SOURCE: 5517 ioHandle = IOHandles_[FILE_SOURCE]; 5518 break; 5519 default: 5520 ioHandle = IOHandles_[PRIMARY_MIC]; 5521 break; 5522 } 5523 return ioHandle; 5524 } 5525 GetDeviceType(const std::string & deviceName)5526 InternalDeviceType AudioPolicyService::GetDeviceType(const std::string &deviceName) 5527 { 5528 InternalDeviceType devType = InternalDeviceType::DEVICE_TYPE_NONE; 5529 if (deviceName == "Speaker") { 5530 devType = InternalDeviceType::DEVICE_TYPE_SPEAKER; 5531 } else if (deviceName == "Built_in_mic") { 5532 devType = InternalDeviceType::DEVICE_TYPE_MIC; 5533 } else if (deviceName == "Built_in_wakeup") { 5534 devType = InternalDeviceType::DEVICE_TYPE_WAKEUP; 5535 } else if (deviceName == "fifo_output" || deviceName == "fifo_input") { 5536 devType = DEVICE_TYPE_BLUETOOTH_SCO; 5537 } else if (deviceName == "file_sink") { 5538 devType = DEVICE_TYPE_FILE_SINK; 5539 } else if (deviceName == "file_source") { 5540 devType = DEVICE_TYPE_FILE_SOURCE; 5541 } 5542 5543 return devType; 5544 } 5545 GetGroupName(const std::string & deviceName,const GroupType type)5546 std::string AudioPolicyService::GetGroupName(const std::string& deviceName, const GroupType type) 5547 { 5548 std::string groupName = GROUP_NAME_NONE; 5549 if (type == VOLUME_TYPE) { 5550 auto iter = volumeGroupData_.find(deviceName); 5551 if (iter != volumeGroupData_.end()) { 5552 groupName = iter->second; 5553 } 5554 } else { 5555 auto iter = interruptGroupData_.find(deviceName); 5556 if (iter != interruptGroupData_.end()) { 5557 groupName = iter->second; 5558 } 5559 } 5560 return groupName; 5561 } 5562 WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)5563 void AudioPolicyService::WriteDeviceChangedSysEvents(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected) 5564 { 5565 Trace trace("AudioPolicyService::WriteDeviceChangedSysEvents"); 5566 for (auto deviceDescriptor : desc) { 5567 if (deviceDescriptor != nullptr) { 5568 if ((deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADSET) 5569 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_USB_HEADSET) 5570 || (deviceDescriptor->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES)) { 5571 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 5572 Media::MediaMonitor::AUDIO, Media::MediaMonitor::HEADSET_CHANGE, 5573 Media::MediaMonitor::BEHAVIOR_EVENT); 5574 bean->Add("HASMIC", 1); 5575 bean->Add("ISCONNECT", isConnected ? 1 : 0); 5576 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_); 5577 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 5578 } 5579 5580 if (!isConnected) { 5581 continue; 5582 } 5583 5584 if (deviceDescriptor->deviceRole_ == OUTPUT_DEVICE) { 5585 vector<SinkInput> sinkInputs = audioPolicyManager_.GetAllSinkInputs(); 5586 for (SinkInput sinkInput : sinkInputs) { 5587 WriteOutDeviceChangedSysEvents(deviceDescriptor, sinkInput); 5588 } 5589 } else if (deviceDescriptor->deviceRole_ == INPUT_DEVICE) { 5590 vector<SourceOutput> sourceOutputs; 5591 { 5592 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 5593 if (std::any_of(IOHandles_.cbegin(), IOHandles_.cend(), [](const auto &pair) { 5594 return std::find(SourceNames.cbegin(), SourceNames.cend(), pair.first) != SourceNames.end(); 5595 })) { 5596 sourceOutputs = audioPolicyManager_.GetAllSourceOutputs(); 5597 } 5598 } 5599 for (SourceOutput sourceOutput : sourceOutputs) { 5600 WriteInDeviceChangedSysEvents(deviceDescriptor, sourceOutput); 5601 } 5602 } 5603 } 5604 } 5605 } 5606 WriteOutDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> & deviceDescriptor,const SinkInput & sinkInput)5607 void AudioPolicyService::WriteOutDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor, 5608 const SinkInput &sinkInput) 5609 { 5610 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 5611 Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE, 5612 Media::MediaMonitor::BEHAVIOR_EVENT); 5613 bean->Add("ISOUTPUT", 1); 5614 bean->Add("STREAMID", sinkInput.streamId); 5615 bean->Add("STREAMTYPE", sinkInput.streamType); 5616 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_); 5617 bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_)); 5618 bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_)); 5619 bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_); 5620 bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_); 5621 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 5622 } 5623 WriteInDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> & deviceDescriptor,const SourceOutput & sourceOutput)5624 void AudioPolicyService::WriteInDeviceChangedSysEvents(const sptr<AudioDeviceDescriptor> &deviceDescriptor, 5625 const SourceOutput &sourceOutput) 5626 { 5627 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 5628 Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE, 5629 Media::MediaMonitor::BEHAVIOR_EVENT); 5630 bean->Add("ISOUTPUT", 0); 5631 bean->Add("STREAMID", sourceOutput.streamId); 5632 bean->Add("STREAMTYPE", sourceOutput.streamType); 5633 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_); 5634 bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_)); 5635 bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_)); 5636 bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_); 5637 bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_); 5638 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 5639 } 5640 UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> & desc)5641 void AudioPolicyService::UpdateTrackerDeviceChange(const vector<sptr<AudioDeviceDescriptor>> &desc) 5642 { 5643 AUDIO_INFO_LOG("UpdateTrackerDeviceChange start"); 5644 5645 DeviceType activeDevice = DEVICE_TYPE_NONE; 5646 auto isOutputDevicePresent = [&activeDevice, this] (const sptr<AudioDeviceDescriptor> &desc) { 5647 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor"); 5648 if ((activeDevice == desc->deviceType_) && (OUTPUT_DEVICE == desc->deviceRole_)) { 5649 if (activeDevice == DEVICE_TYPE_BLUETOOTH_A2DP) { 5650 // If the device type is A2DP, need to compare mac address in addition. 5651 return desc->macAddress_ == GetCurrentOutputDeviceMacAddr(); 5652 } 5653 return true; 5654 } 5655 return false; 5656 }; 5657 auto isInputDevicePresent = [&activeDevice] (const sptr<AudioDeviceDescriptor> &desc) { 5658 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor"); 5659 return ((activeDevice == desc->deviceType_) && (INPUT_DEVICE == desc->deviceRole_)); 5660 }; 5661 5662 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 5663 for (sptr<AudioDeviceDescriptor> deviceDesc : desc) { 5664 if (deviceDesc->deviceRole_ == OUTPUT_DEVICE) { 5665 activeDevice = curOutputDeviceType; 5666 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isOutputDevicePresent); 5667 if (itr != connectedDevices_.end()) { 5668 DeviceInfo outputDevice = {}; 5669 UpdateDeviceInfo(outputDevice, *itr, true, true); 5670 streamCollector_.UpdateTracker(AUDIO_MODE_PLAYBACK, outputDevice); 5671 } 5672 } 5673 5674 if (deviceDesc->deviceRole_ == INPUT_DEVICE) { 5675 activeDevice = GetCurrentInputDeviceType(); 5676 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isInputDevicePresent); 5677 if (itr != connectedDevices_.end()) { 5678 DeviceInfo inputDevice = {}; 5679 UpdateDeviceInfo(inputDevice, *itr, true, true); 5680 UpdateAudioCapturerMicrophoneDescriptor((*itr)->deviceType_); 5681 streamCollector_.UpdateTracker(AUDIO_MODE_RECORD, inputDevice); 5682 } 5683 } 5684 } 5685 } 5686 UpdateGroupInfo(GroupType type,std::string groupName,int32_t & groupId,std::string networkId,bool connected,int32_t mappingId)5687 void AudioPolicyService::UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId, std::string networkId, 5688 bool connected, int32_t mappingId) 5689 { 5690 ConnectType connectType = CONNECT_TYPE_LOCAL; 5691 if (networkId != LOCAL_NETWORK_ID) { 5692 connectType = CONNECT_TYPE_DISTRIBUTED; 5693 } 5694 if (type == GroupType::VOLUME_TYPE) { 5695 auto isPresent = [&groupName, &networkId] (const sptr<VolumeGroupInfo> &volumeInfo) { 5696 return ((groupName == volumeInfo->groupName_) || (networkId == volumeInfo->networkId_)); 5697 }; 5698 5699 auto iter = std::find_if(volumeGroups_.begin(), volumeGroups_.end(), isPresent); 5700 if (iter != volumeGroups_.end()) { 5701 groupId = (*iter)->volumeGroupId_; 5702 // if status is disconnected, remove the group that has none audio device 5703 std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId); 5704 if (!connected && devsInGroup.size() == 0) { 5705 volumeGroups_.erase(iter); 5706 } 5707 return; 5708 } 5709 if (groupName != GROUP_NAME_NONE && connected) { 5710 groupId = AudioGroupHandle::GetInstance().GetNextId(type); 5711 sptr<VolumeGroupInfo> volumeGroupInfo = new(std::nothrow) VolumeGroupInfo(groupId, 5712 mappingId, groupName, networkId, connectType); 5713 volumeGroups_.push_back(volumeGroupInfo); 5714 } 5715 } else { 5716 auto isPresent = [&groupName, &networkId] (const sptr<InterruptGroupInfo> &info) { 5717 return ((groupName == info->groupName_) || (networkId == info->networkId_)); 5718 }; 5719 5720 auto iter = std::find_if(interruptGroups_.begin(), interruptGroups_.end(), isPresent); 5721 if (iter != interruptGroups_.end()) { 5722 groupId = (*iter)->interruptGroupId_; 5723 // if status is disconnected, remove the group that has none audio device 5724 std::vector<sptr<AudioDeviceDescriptor>> devsInGroup = GetDevicesForGroup(type, groupId); 5725 if (!connected && devsInGroup.size() == 0) { 5726 interruptGroups_.erase(iter); 5727 } 5728 return; 5729 } 5730 if (groupName != GROUP_NAME_NONE && connected) { 5731 groupId = AudioGroupHandle::GetInstance().GetNextId(type); 5732 sptr<InterruptGroupInfo> interruptGroupInfo = new(std::nothrow) InterruptGroupInfo(groupId, mappingId, 5733 groupName, networkId, connectType); 5734 interruptGroups_.push_back(interruptGroupInfo); 5735 } 5736 } 5737 } 5738 GetDevicesForGroup(GroupType type,int32_t groupId)5739 std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> AudioPolicyService::GetDevicesForGroup(GroupType type, 5740 int32_t groupId) 5741 { 5742 std::vector<sptr<OHOS::AudioStandard::AudioDeviceDescriptor>> devices = {}; 5743 for (auto devDes : connectedDevices_) { 5744 if (devDes == nullptr) { 5745 continue; 5746 } 5747 bool inVolumeGroup = type == VOLUME_TYPE && devDes->volumeGroupId_ == groupId; 5748 bool inInterruptGroup = type == INTERRUPT_TYPE && devDes->interruptGroupId_ == groupId; 5749 5750 if (inVolumeGroup || inInterruptGroup) { 5751 sptr<AudioDeviceDescriptor> device = new AudioDeviceDescriptor(*devDes); 5752 devices.push_back(device); 5753 } 5754 } 5755 return devices; 5756 } 5757 UpdateDescWhenNoBTPermission(vector<sptr<AudioDeviceDescriptor>> & deviceDescs)5758 void AudioPolicyService::UpdateDescWhenNoBTPermission(vector<sptr<AudioDeviceDescriptor>> &deviceDescs) 5759 { 5760 AUDIO_WARNING_LOG("UpdateDescWhenNoBTPermission: No bt permission"); 5761 5762 for (sptr<AudioDeviceDescriptor> &desc : deviceDescs) { 5763 if ((desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) || (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO)) { 5764 sptr<AudioDeviceDescriptor> copyDesc = new AudioDeviceDescriptor(desc); 5765 copyDesc->deviceName_ = ""; 5766 copyDesc->macAddress_ = ""; 5767 desc = copyDesc; 5768 } 5769 } 5770 } 5771 SetSharedAbsVolumeScene(const bool support)5772 void AudioPolicyService::SetSharedAbsVolumeScene(const bool support) 5773 { 5774 CHECK_AND_RETURN_LOG(sharedAbsVolumeScene_ != nullptr, "sharedAbsVolumeScene is nullptr"); 5775 *sharedAbsVolumeScene_ = support; 5776 } 5777 SetAbsVolumeSceneAsync(const std::string & macAddress,const bool support)5778 void AudioPolicyService::SetAbsVolumeSceneAsync(const std::string &macAddress, const bool support) 5779 { 5780 usleep(SET_BT_ABS_SCENE_DELAY_MS); 5781 AUDIO_INFO_LOG("success for macAddress:[%{public}s], support: %{public}d, active bt:[%{public}s]", 5782 GetEncryptAddr(macAddress).c_str(), support, GetEncryptAddr(activeBTDevice_).c_str()); 5783 5784 if (activeBTDevice_ == macAddress) { 5785 audioPolicyManager_.SetAbsVolumeScene(support); 5786 int32_t volumeLevel = audioPolicyManager_.GetSystemVolumeLevelNoMuteState(STREAM_MUSIC); 5787 audioPolicyManager_.SetSystemVolumeLevel(STREAM_MUSIC, volumeLevel); 5788 } 5789 } 5790 SetDeviceAbsVolumeSupported(const std::string & macAddress,const bool support)5791 int32_t AudioPolicyService::SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support) 5792 { 5793 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_); 5794 // Maximum number of attempts, preventing situations where a2dp device has not yet finished coming online. 5795 int maxRetries = 3; 5796 int retryCount = 0; 5797 while (retryCount < maxRetries) { 5798 retryCount++; 5799 auto configInfoPos = connectedA2dpDeviceMap_.find(macAddress); 5800 if (configInfoPos != connectedA2dpDeviceMap_.end()) { 5801 configInfoPos->second.absVolumeSupport = support; 5802 break; 5803 } 5804 CHECK_AND_RETURN_RET_LOG(retryCount != maxRetries, ERROR, 5805 "failed, can't find device for macAddress:[%{public}s]", GetEncryptAddr(macAddress).c_str());; 5806 usleep(ABS_VOLUME_SUPPORT_RETRY_INTERVAL_IN_MICROSECONDS); 5807 } 5808 5809 // The delay setting is due to move a2dp sink after this 5810 std::thread setAbsSceneThrd(&AudioPolicyService::SetAbsVolumeSceneAsync, this, macAddress, support); 5811 setAbsSceneThrd.detach(); 5812 5813 return SUCCESS; 5814 } 5815 IsAbsVolumeScene() const5816 bool AudioPolicyService::IsAbsVolumeScene() const 5817 { 5818 return audioPolicyManager_.IsAbsVolumeScene(); 5819 } 5820 IsWiredHeadSet(const DeviceType & deviceType)5821 bool AudioPolicyService::IsWiredHeadSet(const DeviceType &deviceType) 5822 { 5823 switch (deviceType) { 5824 case DEVICE_TYPE_WIRED_HEADSET: 5825 case DEVICE_TYPE_WIRED_HEADPHONES: 5826 case DEVICE_TYPE_USB_HEADSET: 5827 case DEVICE_TYPE_USB_ARM_HEADSET: 5828 return true; 5829 default: 5830 return false; 5831 } 5832 } 5833 IsBlueTooth(const DeviceType & deviceType)5834 bool AudioPolicyService::IsBlueTooth(const DeviceType &deviceType) 5835 { 5836 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP || deviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 5837 if (GetCurrentOutputDeviceCategory() == BT_HEADPHONE) { 5838 return true; 5839 } 5840 } 5841 return false; 5842 } 5843 CheckBlueToothActiveMusicTime(int32_t safeVolume)5844 void AudioPolicyService::CheckBlueToothActiveMusicTime(int32_t safeVolume) 5845 { 5846 if (startSafeTimeBt_ == 0) { 5847 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); 5848 } 5849 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); 5850 if (activeSafeTimeBt_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) { 5851 AUDIO_INFO_LOG("safe volume timeout"); 5852 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, SAFE_ACTIVE); 5853 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0); 5854 startSafeTimeBt_ = 0; 5855 safeStatusBt_ = SAFE_ACTIVE; 5856 RestoreSafeVolume(STREAM_MUSIC, safeVolume); 5857 activeSafeTimeBt_ = 0; 5858 } else if (currentTime - startSafeTimeBt_ >= ONE_MINUTE) { 5859 AUDIO_INFO_LOG("safe volume 1 min timeout"); 5860 activeSafeTimeBt_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP); 5861 activeSafeTimeBt_ += currentTime - startSafeTimeBt_; 5862 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, activeSafeTimeBt_); 5863 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); 5864 } 5865 startSafeTime_ = 0; 5866 } 5867 CheckWiredActiveMusicTime(int32_t safeVolume)5868 void AudioPolicyService::CheckWiredActiveMusicTime(int32_t safeVolume) 5869 { 5870 if (startSafeTime_ == 0) { 5871 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); 5872 } 5873 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); 5874 if (activeSafeTime_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) { 5875 AUDIO_INFO_LOG("safe volume timeout"); 5876 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, SAFE_ACTIVE); 5877 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, 0); 5878 startSafeTime_ = 0; 5879 safeStatus_ = SAFE_ACTIVE; 5880 RestoreSafeVolume(STREAM_MUSIC, safeVolume); 5881 activeSafeTime_ = 0; 5882 } else if (currentTime - startSafeTime_ >= ONE_MINUTE) { 5883 AUDIO_INFO_LOG("safe volume 1 min timeout"); 5884 activeSafeTime_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET); 5885 activeSafeTime_ += currentTime - startSafeTime_; 5886 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, activeSafeTime_); 5887 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); 5888 } 5889 startSafeTimeBt_ = 0; 5890 } 5891 RestoreSafeVolume(AudioStreamType streamType,int32_t safeVolume)5892 void AudioPolicyService::RestoreSafeVolume(AudioStreamType streamType, int32_t safeVolume) 5893 { 5894 userSelect_ = false; 5895 isDialogSelectDestroy_.store(false); 5896 5897 if (GetSystemVolumeLevel(streamType) <= safeVolume) { 5898 AUDIO_INFO_LOG("current volume <= safe volume, don't update volume."); 5899 return; 5900 } 5901 5902 AUDIO_INFO_LOG("restore safe volume."); 5903 SetSystemVolumeLevel(streamType, safeVolume); 5904 5905 VolumeEvent volumeEvent; 5906 volumeEvent.volumeType = streamType; 5907 volumeEvent.volume = GetSystemVolumeLevel(streamType); 5908 volumeEvent.updateUi = true; 5909 volumeEvent.volumeGroupId = 0; 5910 volumeEvent.networkId = LOCAL_NETWORK_ID; 5911 if (audioPolicyServerHandler_ != nullptr && IsRingerModeMute()) { 5912 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent); 5913 } 5914 } 5915 CheckActiveMusicTime()5916 int32_t AudioPolicyService::CheckActiveMusicTime() 5917 { 5918 AUDIO_INFO_LOG("enter"); 5919 int32_t safeVolume = audioPolicyManager_.GetSafeVolumeLevel(); 5920 bool isUpSafeVolume = false; 5921 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 5922 while (!safeVolumeExit_) { 5923 isUpSafeVolume = GetSystemVolumeLevel(STREAM_MUSIC) > safeVolume ? true : false; 5924 AUDIO_INFO_LOG("deviceType_:%{public}d, isUpSafeVolume:%{public}d", 5925 curOutputDeviceType, isUpSafeVolume); 5926 if ((safeStatusBt_ == SAFE_INACTIVE || isUpSafeVolume) && 5927 IsBlueTooth(curOutputDeviceType)) { 5928 CheckBlueToothActiveMusicTime(safeVolume); 5929 } else if ((safeStatus_ == SAFE_INACTIVE || isUpSafeVolume) && 5930 IsWiredHeadSet(curOutputDeviceType)) { 5931 CheckWiredActiveMusicTime(safeVolume); 5932 } else { 5933 startSafeTime_ = 0; 5934 startSafeTimeBt_ = 0; 5935 } 5936 sleep(ONE_MINUTE); 5937 } 5938 return 0; 5939 } 5940 CreateCheckMusicActiveThread()5941 void AudioPolicyService::CreateCheckMusicActiveThread() 5942 { 5943 std::lock_guard<std::mutex> lock(checkMusicActiveThreadMutex_); 5944 if (calculateLoopSafeTime_ == nullptr) { 5945 calculateLoopSafeTime_ = std::make_unique<std::thread>([this] { this->CheckActiveMusicTime(); }); 5946 pthread_setname_np(calculateLoopSafeTime_->native_handle(), "OS_AudioPolicySafe"); 5947 } 5948 } 5949 CreateSafeVolumeDialogThread()5950 void AudioPolicyService::CreateSafeVolumeDialogThread() 5951 { 5952 std::lock_guard<std::mutex> safeVolumeLock(safeVolumeMutex_); 5953 AUDIO_INFO_LOG("enter"); 5954 if (safeVolumeDialogThrd_ != nullptr && safeVolumeDialogThrd_->joinable()) { 5955 AUDIO_INFO_LOG("safeVolumeDialogThread exit begin"); 5956 safeVolumeDialogThrd_->join(); 5957 safeVolumeDialogThrd_.reset(); 5958 safeVolumeDialogThrd_ = nullptr; 5959 AUDIO_INFO_LOG("safeVolumeDialogThread exit end"); 5960 } 5961 5962 AUDIO_INFO_LOG("create thread begin"); 5963 safeVolumeDialogThrd_ = std::make_unique<std::thread>([this] { this->ShowDialog(); }); 5964 pthread_setname_np(safeVolumeDialogThrd_->native_handle(), "OS_AudioSafeDialog"); 5965 isSafeVolumeDialogShowing_.store(true); 5966 AUDIO_INFO_LOG("create thread end"); 5967 } 5968 DealWithSafeVolume(const int32_t volumeLevel,bool isA2dpDevice)5969 int32_t AudioPolicyService::DealWithSafeVolume(const int32_t volumeLevel, bool isA2dpDevice) 5970 { 5971 if (isA2dpDevice) { 5972 DeviceCategory curOutputDeviceCategory = GetCurrentOutputDeviceCategory(); 5973 AUDIO_INFO_LOG("bluetooth Category:%{public}d", curOutputDeviceCategory); 5974 if (curOutputDeviceCategory != BT_HEADPHONE) { 5975 return volumeLevel; 5976 } 5977 } 5978 5979 int32_t sVolumeLevel = volumeLevel; 5980 safeStatusBt_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP); 5981 safeStatus_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET); 5982 if ((safeStatusBt_ == SAFE_INACTIVE && isA2dpDevice) || 5983 (safeStatus_ == SAFE_INACTIVE && !isA2dpDevice)) { 5984 CreateCheckMusicActiveThread(); 5985 return sVolumeLevel; 5986 } 5987 5988 if ((isA2dpDevice && safeStatusBt_ == SAFE_ACTIVE) || 5989 (!isA2dpDevice && safeStatus_ == SAFE_ACTIVE)) { 5990 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel(); 5991 if (!isSafeVolumeDialogShowing_.load()) { 5992 CreateSafeVolumeDialogThread(); 5993 } else { 5994 AUDIO_INFO_LOG("Safe volume dialog is showing"); 5995 } 5996 return sVolumeLevel; 5997 } 5998 return sVolumeLevel; 5999 } 6000 ShowDialog()6001 int32_t AudioPolicyService::ShowDialog() 6002 { 6003 auto abilityMgrClient = AAFwk::AbilityManagerClient::GetInstance(); 6004 if (abilityMgrClient == nullptr) { 6005 isSafeVolumeDialogShowing_.store(false); 6006 AUDIO_INFO_LOG("abilityMgrClient malloc failed"); 6007 return ERROR; 6008 } 6009 sptr<OHOS::AAFwk::IAbilityConnection> dialogConnectionCallback = new (std::nothrow)AudioDialogAbilityConnection(); 6010 if (dialogConnectionCallback == nullptr) { 6011 isSafeVolumeDialogShowing_.store(false); 6012 AUDIO_INFO_LOG("dialogConnectionCallback malloc failed"); 6013 return ERROR; 6014 } 6015 6016 AAFwk::Want want; 6017 std::string bundleName = "com.ohos.sceneboard"; 6018 std::string abilityName = "com.ohos.sceneboard.systemdialog"; 6019 want.SetElementName(bundleName, abilityName); 6020 ErrCode result = abilityMgrClient->ConnectAbility(want, dialogConnectionCallback, 6021 AppExecFwk::Constants::INVALID_USERID); 6022 if (result != SUCCESS) { 6023 isSafeVolumeDialogShowing_.store(false); 6024 AUDIO_INFO_LOG("ConnectAbility failed"); 6025 return result; 6026 } 6027 6028 AUDIO_INFO_LOG("show safe Volume Dialog"); 6029 std::unique_lock<std::mutex> lock(dialogMutex_); 6030 isSafeVolumeDialogShowing_.store(true); 6031 if (!isDialogSelectDestroy_.load()) { 6032 auto status = dialogSelectCondition_.wait_for(lock, std::chrono::seconds(WAIT_DIALOG_CLOSE_TIME_S), 6033 [this] () { return isDialogSelectDestroy_.load() || !isSafeVolumeDialogShowing_.load(); }); 6034 if (!status) { 6035 AUDIO_ERR_LOG("user cancel or not select."); 6036 } 6037 isDialogSelectDestroy_.store(false); 6038 } 6039 return result; 6040 } 6041 HandleAbsBluetoothVolume(const std::string & macAddress,const int32_t volumeLevel)6042 int32_t AudioPolicyService::HandleAbsBluetoothVolume(const std::string &macAddress, const int32_t volumeLevel) 6043 { 6044 int32_t sVolumeLevel = volumeLevel; 6045 if (isAbsBtFirstBoot_) { 6046 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel(); 6047 isAbsBtFirstBoot_ = false; 6048 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel); 6049 } else { 6050 sVolumeLevel = DealWithSafeVolume(volumeLevel, true); 6051 if (sVolumeLevel != volumeLevel) { 6052 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel); 6053 } 6054 } 6055 return sVolumeLevel; 6056 } 6057 IsVgsVolumeSupported() const6058 bool AudioPolicyService::IsVgsVolumeSupported() const 6059 { 6060 return audioPolicyManager_.IsVgsVolumeSupported(); 6061 } 6062 SetA2dpDeviceVolume(const std::string & macAddress,const int32_t volumeLevel,bool internalCall)6063 int32_t AudioPolicyService::SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volumeLevel, 6064 bool internalCall) 6065 { 6066 std::lock_guard<std::mutex> lock(a2dpDeviceMapMutex_); 6067 auto configInfoPos = connectedA2dpDeviceMap_.find(macAddress); 6068 CHECK_AND_RETURN_RET_LOG(configInfoPos != connectedA2dpDeviceMap_.end() && configInfoPos->second.absVolumeSupport, 6069 ERROR, "failed for macAddress:[%{public}s]", GetEncryptAddr(macAddress).c_str()); 6070 configInfoPos->second.volumeLevel = volumeLevel; 6071 int32_t sVolumeLevel = volumeLevel; 6072 if (volumeLevel > audioPolicyManager_.GetSafeVolumeLevel()) { 6073 if (internalCall) { 6074 sVolumeLevel = DealWithSafeVolume(volumeLevel, true); 6075 } else { 6076 sVolumeLevel = HandleAbsBluetoothVolume(macAddress, volumeLevel); 6077 } 6078 } 6079 configInfoPos->second.volumeLevel = sVolumeLevel; 6080 bool mute = sVolumeLevel == 0 ? true : false; 6081 configInfoPos->second.mute = mute; 6082 audioPolicyManager_.SetAbsVolumeMute(mute); 6083 AUDIO_INFO_LOG("success for macaddress:[%{public}s], volume value:[%{public}d]", 6084 GetEncryptAddr(macAddress).c_str(), sVolumeLevel); 6085 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERR_UNKNOWN, "safevolume did not deal"); 6086 return SUCCESS; 6087 } 6088 TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)6089 void AudioPolicyService::TriggerDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected) 6090 { 6091 Trace trace("AudioPolicyService::TriggerDeviceChangedCallback"); 6092 WriteDeviceChangedSysEvents(desc, isConnected); 6093 if (audioPolicyServerHandler_ != nullptr) { 6094 audioPolicyServerHandler_->SendDeviceChangedCallback(desc, isConnected); 6095 } 6096 } 6097 TriggerMicrophoneBlockedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,DeviceBlockStatus status)6098 void AudioPolicyService::TriggerMicrophoneBlockedCallback(const vector<sptr<AudioDeviceDescriptor>> &desc, 6099 DeviceBlockStatus status) 6100 { 6101 Trace trace("AudioPolicyService::TriggerMicrophoneBlockedCallback"); 6102 if (audioPolicyServerHandler_ != nullptr) { 6103 audioPolicyServerHandler_->SendMicrophoneBlockedCallback(desc, status); 6104 } 6105 } 6106 GetDeviceRole(DeviceType deviceType) const6107 DeviceRole AudioPolicyService::GetDeviceRole(DeviceType deviceType) const 6108 { 6109 switch (deviceType) { 6110 case DeviceType::DEVICE_TYPE_EARPIECE: 6111 case DeviceType::DEVICE_TYPE_SPEAKER: 6112 case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO: 6113 case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP: 6114 case DeviceType::DEVICE_TYPE_WIRED_HEADSET: 6115 case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES: 6116 case DeviceType::DEVICE_TYPE_USB_HEADSET: 6117 case DeviceType::DEVICE_TYPE_DP: 6118 case DeviceType::DEVICE_TYPE_USB_ARM_HEADSET: 6119 case DeviceType::DEVICE_TYPE_REMOTE_CAST: 6120 return DeviceRole::OUTPUT_DEVICE; 6121 case DeviceType::DEVICE_TYPE_MIC: 6122 case DeviceType::DEVICE_TYPE_WAKEUP: 6123 return DeviceRole::INPUT_DEVICE; 6124 default: 6125 return DeviceRole::DEVICE_ROLE_NONE; 6126 } 6127 } 6128 GetDeviceRole(const std::string & role)6129 DeviceRole AudioPolicyService::GetDeviceRole(const std::string &role) 6130 { 6131 if (role == ROLE_SINK) { 6132 return DeviceRole::OUTPUT_DEVICE; 6133 } else if (role == ROLE_SOURCE) { 6134 return DeviceRole::INPUT_DEVICE; 6135 } else { 6136 return DeviceRole::DEVICE_ROLE_NONE; 6137 } 6138 } 6139 GetDeviceRole(AudioPin pin) const6140 DeviceRole AudioPolicyService::GetDeviceRole(AudioPin pin) const 6141 { 6142 switch (pin) { 6143 case OHOS::AudioStandard::AUDIO_PIN_NONE: 6144 return DeviceRole::DEVICE_ROLE_NONE; 6145 case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER: 6146 case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET: 6147 case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT: 6148 case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI: 6149 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB: 6150 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT: 6151 case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT: 6152 return DeviceRole::OUTPUT_DEVICE; 6153 case OHOS::AudioStandard::AUDIO_PIN_IN_MIC: 6154 case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC: 6155 case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN: 6156 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT: 6157 case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT: 6158 return DeviceRole::INPUT_DEVICE; 6159 default: 6160 return DeviceRole::DEVICE_ROLE_NONE; 6161 } 6162 } 6163 OnAudioLatencyParsed(uint64_t latency)6164 void AudioPolicyService::OnAudioLatencyParsed(uint64_t latency) 6165 { 6166 audioLatencyInMsec_ = latency; 6167 } 6168 GetAudioLatencyFromXml() const6169 int32_t AudioPolicyService::GetAudioLatencyFromXml() const 6170 { 6171 return audioLatencyInMsec_; 6172 } 6173 OnSinkLatencyParsed(uint32_t latency)6174 void AudioPolicyService::OnSinkLatencyParsed(uint32_t latency) 6175 { 6176 sinkLatencyInMsec_ = latency; 6177 } 6178 GetSinkLatencyFromXml() const6179 uint32_t AudioPolicyService::GetSinkLatencyFromXml() const 6180 { 6181 return sinkLatencyInMsec_; 6182 } 6183 getFastControlParam()6184 bool AudioPolicyService::getFastControlParam() 6185 { 6186 int32_t fastControlFlag = 0; 6187 GetSysPara("persist.multimedia.audioflag.fastcontrolled", fastControlFlag); 6188 if (fastControlFlag == 1) { 6189 isFastControlled_ = true; 6190 } 6191 return isFastControlled_; 6192 } 6193 GetPreferredOutputStreamType(AudioRendererInfo & rendererInfo,const std::string & bundleName)6194 int32_t AudioPolicyService::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo, const std::string &bundleName) 6195 { 6196 // Use GetPreferredOutputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream 6197 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList = GetPreferredOutputDeviceDescriptors(rendererInfo); 6198 if (preferredDeviceList.size() == 0) { 6199 return AUDIO_FLAG_INVALID; 6200 } 6201 6202 int32_t flag = GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage, preferredDeviceList[0]->deviceType_, 6203 rendererInfo.rendererFlags, preferredDeviceList[0]->networkId_, rendererInfo.samplingRate); 6204 if (isFastControlled_ && (flag == AUDIO_FLAG_MMAP || flag == AUDIO_FLAG_VOIP_FAST)) { 6205 std::string bundleNamePre = CHECK_FAST_BLOCK_PREFIX + bundleName; 6206 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 6207 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, AUDIO_FLAG_NORMAL, 6208 "GetPreferredOutputStreamType, Audio server Proxy is null"); 6209 std::string result = gsp->GetAudioParameter(bundleNamePre); 6210 if (result == "true") { 6211 AUDIO_INFO_LOG("%{public}s not in fast list", bundleName.c_str()); 6212 return AUDIO_FLAG_NORMAL; 6213 } 6214 } 6215 return flag; 6216 } 6217 SetNormalVoipFlag(const bool & normalVoipFlag)6218 void AudioPolicyService::SetNormalVoipFlag(const bool &normalVoipFlag) 6219 { 6220 normalVoipFlag_ = normalVoipFlag; 6221 } 6222 GetVoipRendererFlag(const std::string & sinkPortName,const std::string & networkId,const AudioSamplingRate & samplingRate)6223 int32_t AudioPolicyService::GetVoipRendererFlag(const std::string &sinkPortName, const std::string &networkId, 6224 const AudioSamplingRate &samplingRate) 6225 { 6226 // VoIP stream has three mode for different products. 6227 if (enableFastVoip_ && (sinkPortName == PRIMARY_SPEAKER && networkId == LOCAL_NETWORK_ID)) { 6228 if (samplingRate != SAMPLE_RATE_48000 && samplingRate != SAMPLE_RATE_16000) { 6229 return AUDIO_FLAG_NORMAL; 6230 } 6231 return AUDIO_FLAG_VOIP_FAST; 6232 } else if (!normalVoipFlag_ && (sinkPortName == PRIMARY_SPEAKER) && (networkId == LOCAL_NETWORK_ID)) { 6233 AUDIO_INFO_LOG("Direct VoIP mode is supported for the device"); 6234 return AUDIO_FLAG_VOIP_DIRECT; 6235 } 6236 6237 return AUDIO_FLAG_NORMAL; 6238 } 6239 GetPreferredOutputStreamTypeInner(StreamUsage streamUsage,DeviceType deviceType,int32_t flags,std::string & networkId,AudioSamplingRate & samplingRate)6240 int32_t AudioPolicyService::GetPreferredOutputStreamTypeInner(StreamUsage streamUsage, DeviceType deviceType, 6241 int32_t flags, std::string &networkId, AudioSamplingRate &samplingRate) 6242 { 6243 AUDIO_INFO_LOG("Device type: %{public}d, stream usage: %{public}d, flag: %{public}d", 6244 deviceType, streamUsage, flags); 6245 std::string sinkPortName = GetSinkPortName(deviceType); 6246 if (streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) { 6247 // Avoid two voip stream existing 6248 if (streamCollector_.HasVoipRendererStream()) { 6249 AUDIO_WARNING_LOG("Voip Change To Normal"); 6250 return AUDIO_FLAG_NORMAL; 6251 } 6252 6253 // VoIP stream. Need to judge whether it is fast or direct mode. 6254 int32_t flag = GetVoipRendererFlag(sinkPortName, networkId, samplingRate); 6255 if (flag == AUDIO_FLAG_VOIP_FAST || flag == AUDIO_FLAG_VOIP_DIRECT) { 6256 return flag; 6257 } 6258 } 6259 if (!isAdapterInfoMap_.load()) { 6260 return AUDIO_FLAG_NORMAL; 6261 } 6262 if (adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sinkPortName])) == adapterInfoMap_.end()) { 6263 return AUDIO_FLAG_INVALID; 6264 } 6265 AudioAdapterInfo adapterInfo; 6266 auto it = adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sinkPortName])); 6267 if (it != adapterInfoMap_.end()) { 6268 adapterInfo = it->second; 6269 } else { 6270 AUDIO_ERR_LOG("Invalid adapter"); 6271 return AUDIO_FLAG_INVALID; 6272 } 6273 6274 AudioPipeDeviceInfo* deviceInfo = adapterInfo.GetDeviceInfoByDeviceType(deviceType); 6275 CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, AUDIO_FLAG_INVALID, "Device type is not supported"); 6276 for (auto &supportPipe : deviceInfo->supportPipes_) { 6277 PipeInfo* pipeInfo = adapterInfo.GetPipeByName(supportPipe); 6278 if (pipeInfo == nullptr) { 6279 continue; 6280 } 6281 if (flags == AUDIO_FLAG_MMAP && pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { 6282 return AUDIO_FLAG_MMAP; 6283 } 6284 if (flags == AUDIO_FLAG_VOIP_FAST && pipeInfo->audioUsage_ == AUDIO_USAGE_VOIP && 6285 pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { 6286 return AUDIO_FLAG_VOIP_FAST; 6287 } 6288 } 6289 return AUDIO_FLAG_NORMAL; 6290 } 6291 GetPreferredInputStreamType(AudioCapturerInfo & capturerInfo)6292 int32_t AudioPolicyService::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo) 6293 { 6294 // Use GetPreferredInputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream 6295 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList = GetPreferredInputDeviceDescriptors(capturerInfo); 6296 if (preferredDeviceList.size() == 0) { 6297 return AUDIO_FLAG_INVALID; 6298 } 6299 return GetPreferredInputStreamTypeInner(capturerInfo.sourceType, preferredDeviceList[0]->deviceType_, 6300 capturerInfo.originalFlag, preferredDeviceList[0]->networkId_, capturerInfo.samplingRate); 6301 } 6302 GetPreferredInputStreamTypeFromDeviceInfo(AudioAdapterInfo & adapterInfo,DeviceType deviceType,int32_t flags)6303 int32_t AudioPolicyService::GetPreferredInputStreamTypeFromDeviceInfo(AudioAdapterInfo &adapterInfo, 6304 DeviceType deviceType, int32_t flags) 6305 { 6306 AudioPipeDeviceInfo* deviceInfo = adapterInfo.GetDeviceInfoByDeviceType(deviceType); 6307 CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, AUDIO_FLAG_INVALID, "Device type is not supported"); 6308 for (auto &supportPipe : deviceInfo->supportPipes_) { 6309 PipeInfo* pipeInfo = adapterInfo.GetPipeByName(supportPipe); 6310 if (pipeInfo == nullptr) { 6311 continue; 6312 } 6313 if (flags == AUDIO_FLAG_MMAP && pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { 6314 return AUDIO_FLAG_MMAP; 6315 } 6316 if (flags == AUDIO_FLAG_VOIP_FAST && pipeInfo->audioUsage_ == AUDIO_USAGE_VOIP && 6317 pipeInfo->audioFlag_ == AUDIO_FLAG_MMAP) { 6318 // Avoid voip stream existing with other 6319 if (streamCollector_.ChangeVoipCapturerStreamToNormal()) { 6320 AUDIO_WARNING_LOG("Voip Change To Normal By DeviceInfo"); 6321 return AUDIO_FLAG_NORMAL; 6322 } 6323 return AUDIO_FLAG_VOIP_FAST; 6324 } 6325 } 6326 return AUDIO_FLAG_NORMAL; 6327 } 6328 GetPreferredInputStreamTypeInner(SourceType sourceType,DeviceType deviceType,int32_t flags,const std::string & networkId,const AudioSamplingRate & samplingRate)6329 int32_t AudioPolicyService::GetPreferredInputStreamTypeInner(SourceType sourceType, DeviceType deviceType, 6330 int32_t flags, const std::string &networkId, const AudioSamplingRate &samplingRate) 6331 { 6332 AUDIO_INFO_LOG("Device type: %{public}d, source type: %{public}d, flag: %{public}d", 6333 deviceType, sourceType, flags); 6334 6335 std::string sourcePortName = GetSourcePortName(deviceType); 6336 AUDIO_INFO_LOG("sourcePortName: %{public}s", sourcePortName.c_str()); 6337 if (sourceType == SOURCE_TYPE_VOICE_COMMUNICATION && 6338 (sourcePortName == PRIMARY_MIC && networkId == LOCAL_NETWORK_ID)) { 6339 if (enableFastVoip_ && (samplingRate == SAMPLE_RATE_16000 || samplingRate == SAMPLE_RATE_48000)) { 6340 // Avoid voip stream existing with other 6341 if (streamCollector_.ChangeVoipCapturerStreamToNormal()) { 6342 AUDIO_WARNING_LOG("Voip Change To Normal"); 6343 return AUDIO_FLAG_NORMAL; 6344 } 6345 return AUDIO_FLAG_VOIP_FAST; 6346 } 6347 return AUDIO_FLAG_NORMAL; 6348 } 6349 if (!isAdapterInfoMap_.load()) { 6350 return AUDIO_FLAG_NORMAL; 6351 } 6352 if (adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sourcePortName])) == adapterInfoMap_.end()) { 6353 return AUDIO_FLAG_INVALID; 6354 } 6355 AudioAdapterInfo adapterInfo; 6356 auto it = adapterInfoMap_.find(static_cast<AdaptersType>(portStrToEnum[sourcePortName])); 6357 if (it != adapterInfoMap_.end()) { 6358 adapterInfo = it->second; 6359 } else { 6360 AUDIO_ERR_LOG("Invalid adapter"); 6361 return AUDIO_FLAG_INVALID; 6362 } 6363 6364 return GetPreferredInputStreamTypeFromDeviceInfo(adapterInfo, deviceType, flags); 6365 } 6366 UpdateInputDeviceInfo(DeviceType deviceType)6367 void AudioPolicyService::UpdateInputDeviceInfo(DeviceType deviceType) 6368 { 6369 DeviceType curType = GetCurrentInputDeviceType(); 6370 6371 switch (deviceType) { 6372 case DEVICE_TYPE_EARPIECE: 6373 case DEVICE_TYPE_SPEAKER: 6374 case DEVICE_TYPE_BLUETOOTH_A2DP: 6375 curType = DEVICE_TYPE_MIC; 6376 break; 6377 case DEVICE_TYPE_FILE_SINK: 6378 curType = DEVICE_TYPE_FILE_SOURCE; 6379 break; 6380 case DEVICE_TYPE_USB_ARM_HEADSET: 6381 curType = DEVICE_TYPE_USB_HEADSET; 6382 break; 6383 case DEVICE_TYPE_WIRED_HEADSET: 6384 case DEVICE_TYPE_USB_HEADSET: 6385 case DEVICE_TYPE_BLUETOOTH_SCO: 6386 curType = deviceType; 6387 break; 6388 default: 6389 break; 6390 } 6391 6392 SetCurrentInputDeviceType(curType); 6393 AUDIO_DEBUG_LOG("Input device updated to %{public}d", curType); 6394 } 6395 UpdateStreamState(int32_t clientUid,StreamSetStateEventInternal & streamSetStateEventInternal)6396 int32_t AudioPolicyService::UpdateStreamState(int32_t clientUid, 6397 StreamSetStateEventInternal &streamSetStateEventInternal) 6398 { 6399 return streamCollector_.UpdateStreamState(clientUid, streamSetStateEventInternal); 6400 } 6401 GetStreamType(int32_t sessionId)6402 AudioStreamType AudioPolicyService::GetStreamType(int32_t sessionId) 6403 { 6404 return streamCollector_.GetStreamType(sessionId); 6405 } 6406 GetChannelCount(uint32_t sessionId)6407 int32_t AudioPolicyService::GetChannelCount(uint32_t sessionId) 6408 { 6409 return streamCollector_.GetChannelCount(sessionId); 6410 } 6411 GetUid(int32_t sessionId)6412 int32_t AudioPolicyService::GetUid(int32_t sessionId) 6413 { 6414 return streamCollector_.GetUid(sessionId); 6415 } 6416 GetDeviceTypeFromPin(AudioPin hdiPin)6417 DeviceType AudioPolicyService::GetDeviceTypeFromPin(AudioPin hdiPin) 6418 { 6419 switch (hdiPin) { 6420 case OHOS::AudioStandard::AUDIO_PIN_NONE: 6421 break; 6422 case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER: 6423 case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT: 6424 return DeviceType::DEVICE_TYPE_SPEAKER; 6425 case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET: 6426 break; 6427 case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT: 6428 break; 6429 case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI: 6430 break; 6431 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB: 6432 break; 6433 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT: 6434 break; 6435 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_HEADSET: 6436 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_HEADSET: 6437 return DeviceType::DEVICE_TYPE_USB_ARM_HEADSET; 6438 case OHOS::AudioStandard::AUDIO_PIN_IN_MIC: 6439 case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT: 6440 return DeviceType::DEVICE_TYPE_MIC; 6441 case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC: 6442 break; 6443 case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN: 6444 break; 6445 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT: 6446 break; 6447 default: 6448 break; 6449 } 6450 return DeviceType::DEVICE_TYPE_DEFAULT; 6451 } 6452 SetDefaultDeviceLoadFlag(bool isLoad)6453 void AudioPolicyService::SetDefaultDeviceLoadFlag(bool isLoad) 6454 { 6455 isPrimaryMicModuleInfoLoaded_.store(isLoad); 6456 } 6457 GetVolumeGroupInfos()6458 std::vector<sptr<VolumeGroupInfo>> AudioPolicyService::GetVolumeGroupInfos() 6459 { 6460 if (!isPrimaryMicModuleInfoLoaded_.load()) { 6461 std::unique_lock<std::mutex> lock(defaultDeviceLoadMutex_); 6462 bool loadWaiting = loadDefaultDeviceCV_.wait_for(lock, 6463 std::chrono::milliseconds(WAIT_LOAD_DEFAULT_DEVICE_TIME_MS), 6464 [this] { return isPrimaryMicModuleInfoLoaded_.load(); } 6465 ); 6466 if (!loadWaiting) { 6467 AUDIO_ERR_LOG("load default device time out"); 6468 } 6469 } 6470 6471 std::vector<sptr<VolumeGroupInfo>> volumeGroupInfos = {}; 6472 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 6473 for (auto& v : volumeGroups_) { 6474 sptr<VolumeGroupInfo> info = new(std::nothrow) VolumeGroupInfo(v->volumeGroupId_, v->mappingId_, v->groupName_, 6475 v->networkId_, v->connectType_); 6476 volumeGroupInfos.push_back(info); 6477 } 6478 return volumeGroupInfos; 6479 } 6480 RegiestPolicy()6481 void AudioPolicyService::RegiestPolicy() 6482 { 6483 AUDIO_INFO_LOG("RegiestPolicy start"); 6484 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 6485 CHECK_AND_RETURN_LOG(gsp != nullptr, "RegiestPolicy gsp null"); 6486 audioPolicyManager_.SetAudioServerProxy(gsp); 6487 6488 sptr<PolicyProviderWrapper> wrapper = new(std::nothrow) PolicyProviderWrapper(this); 6489 CHECK_AND_RETURN_LOG(wrapper != nullptr, "Get null PolicyProviderWrapper"); 6490 sptr<IRemoteObject> object = wrapper->AsObject(); 6491 CHECK_AND_RETURN_LOG(object != nullptr, "RegiestPolicy AsObject is nullptr"); 6492 std::string identity = IPCSkeleton::ResetCallingIdentity(); 6493 int32_t ret = gsp->RegiestPolicyProvider(object); 6494 IPCSkeleton::SetCallingIdentity(identity); 6495 AUDIO_DEBUG_LOG("RegiestPolicy result:%{public}d", ret); 6496 } 6497 6498 /* 6499 * lockFlag is use to determinewhether GetPreferredOutputDeviceDescriptor or GetPreferredOutputDeviceDescInner 6500 * is invoked. If deviceStatusUpdateSharedMutex_ write lock is not invoked at the outer layer, lockFlag can be 6501 * set to true. When deviceStatusUpdateSharedMutex_ write lock has been invoked, lockFlag must be set to false. 6502 */ GetProcessDeviceInfo(const AudioProcessConfig & config,bool lockFlag,DeviceInfo & deviceInfo)6503 int32_t AudioPolicyService::GetProcessDeviceInfo(const AudioProcessConfig &config, bool lockFlag, 6504 DeviceInfo &deviceInfo) 6505 { 6506 AUDIO_INFO_LOG("%{public}s", ProcessConfig::DumpProcessConfig(config).c_str()); 6507 AudioSamplingRate samplingRate = config.streamInfo.samplingRate; 6508 if (config.audioMode == AUDIO_MODE_PLAYBACK) { 6509 if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION || 6510 config.rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) { 6511 AudioRendererInfo rendererInfo = config.rendererInfo; 6512 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList = 6513 (lockFlag ? GetPreferredOutputDeviceDescriptors(rendererInfo, LOCAL_NETWORK_ID) 6514 : GetPreferredOutputDeviceDescInner(rendererInfo, LOCAL_NETWORK_ID)); 6515 int32_t type = GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage, 6516 preferredDeviceList[0]->deviceType_, rendererInfo.originalFlag, preferredDeviceList[0]->networkId_, 6517 samplingRate); 6518 deviceInfo.deviceRole = OUTPUT_DEVICE; 6519 return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList); 6520 } 6521 AudioDeviceDescriptor curOutputDeviceDesc = GetCurrentOutputDevice(); 6522 deviceInfo.deviceId = curOutputDeviceDesc.deviceId_; 6523 deviceInfo.networkId = curOutputDeviceDesc.networkId_; 6524 deviceInfo.deviceType = curOutputDeviceDesc.deviceType_; 6525 deviceInfo.deviceRole = OUTPUT_DEVICE; 6526 } else { 6527 if (config.capturerInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) { 6528 AudioCapturerInfo capturerInfo = config.capturerInfo; 6529 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList = 6530 (lockFlag ? GetPreferredInputDeviceDescriptors(capturerInfo, LOCAL_NETWORK_ID) 6531 : GetPreferredInputDeviceDescInner(capturerInfo, LOCAL_NETWORK_ID)); 6532 int32_t type = GetPreferredInputStreamTypeInner(capturerInfo.sourceType, 6533 preferredDeviceList[0]->deviceType_, capturerInfo.originalFlag, preferredDeviceList[0]->networkId_, 6534 samplingRate); 6535 deviceInfo.deviceRole = INPUT_DEVICE; 6536 return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList); 6537 } 6538 deviceInfo.deviceId = GetCurrentInputDevice().deviceId_; 6539 deviceInfo.networkId = GetCurrentInputDevice().networkId_; 6540 deviceInfo.deviceRole = INPUT_DEVICE; 6541 deviceInfo.deviceType = GetCurrentInputDeviceType(); 6542 } 6543 6544 // todo 6545 // check process in routerMap, return target device for it 6546 // put the currentActiveDevice_ in deviceinfo, so it can create with current using device. 6547 // genarate the unique deviceid? 6548 AudioStreamInfo targetStreamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; // note: read from xml 6549 deviceInfo.audioStreamInfo = targetStreamInfo; 6550 deviceInfo.deviceName = "mmap_device"; 6551 std::lock_guard<std::mutex> lock(routerMapMutex_); 6552 if (fastRouterMap_.count(config.appInfo.appUid) && 6553 fastRouterMap_[config.appInfo.appUid].second == deviceInfo.deviceRole) { 6554 deviceInfo.networkId = fastRouterMap_[config.appInfo.appUid].first; 6555 AUDIO_INFO_LOG("use networkid in fastRouterMap_ :%{public}s ", GetEncryptStr(deviceInfo.networkId).c_str()); 6556 } 6557 deviceInfo.a2dpOffloadFlag = a2dpOffloadFlag_; 6558 return SUCCESS; 6559 } 6560 GetVoipDeviceInfo(const AudioProcessConfig & config,DeviceInfo & deviceInfo,int32_t type,std::vector<sptr<AudioDeviceDescriptor>> & preferredDeviceList)6561 int32_t AudioPolicyService::GetVoipDeviceInfo(const AudioProcessConfig &config, DeviceInfo &deviceInfo, int32_t type, 6562 std::vector<sptr<AudioDeviceDescriptor>> &preferredDeviceList) 6563 { 6564 if (type == AUDIO_FLAG_NORMAL) { 6565 AUDIO_WARNING_LOG("Current device %{public}d not support", type); 6566 return ERROR; 6567 } 6568 deviceInfo.deviceId = preferredDeviceList[0]->deviceId_; 6569 deviceInfo.networkId = preferredDeviceList[0]->networkId_; 6570 deviceInfo.deviceType = preferredDeviceList[0]->deviceType_; 6571 deviceInfo.deviceName = preferredDeviceList[0]->deviceName_; 6572 if (config.streamInfo.samplingRate <= SAMPLE_RATE_16000) { 6573 deviceInfo.audioStreamInfo = {SAMPLE_RATE_16000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; 6574 } else { 6575 deviceInfo.audioStreamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; 6576 } 6577 if (type == AUDIO_FLAG_VOIP_DIRECT) { 6578 AUDIO_INFO_LOG("Direct VoIP stream, deviceInfo has been updated: deviceInfo.deviceType %{public}d", 6579 deviceInfo.deviceType); 6580 return SUCCESS; 6581 } 6582 std::lock_guard<std::mutex> lock(routerMapMutex_); 6583 if (fastRouterMap_.count(config.appInfo.appUid) && 6584 fastRouterMap_[config.appInfo.appUid].second == deviceInfo.deviceRole) { 6585 deviceInfo.networkId = fastRouterMap_[config.appInfo.appUid].first; 6586 AUDIO_INFO_LOG("use networkid in fastRouterMap_ :%{public}s ", GetEncryptStr(deviceInfo.networkId).c_str()); 6587 } 6588 deviceInfo.a2dpOffloadFlag = a2dpOffloadFlag_; 6589 deviceInfo.isLowLatencyDevice = true; 6590 return SUCCESS; 6591 } 6592 InitSharedVolume(std::shared_ptr<AudioSharedMemory> & buffer)6593 int32_t AudioPolicyService::InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer) 6594 { 6595 AUDIO_INFO_LOG("InitSharedVolume start"); 6596 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr, 6597 ERR_OPERATION_FAILED, "Get shared memory failed!"); 6598 6599 // init volume map 6600 // todo device 6601 for (size_t i = 0; i < IPolicyProvider::GetVolumeVectorSize(); i++) { 6602 int32_t currentVolumeLevel = audioPolicyManager_.GetSystemVolumeLevel(g_volumeIndexVector[i].first); 6603 float volFloat = 6604 GetSystemVolumeInDb(g_volumeIndexVector[i].first, currentVolumeLevel, GetCurrentOutputDeviceType()); 6605 volumeVector_[i].isMute = false; 6606 volumeVector_[i].volumeFloat = volFloat; 6607 volumeVector_[i].volumeInt = 0; 6608 } 6609 SetSharedAbsVolumeScene(false); 6610 buffer = policyVolumeMap_; 6611 6612 return SUCCESS; 6613 } 6614 GetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume & vol)6615 bool AudioPolicyService::GetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume &vol) 6616 { 6617 CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Get shared memory failed!"); 6618 size_t index = 0; 6619 if (!IPolicyProvider::GetVolumeIndex(streamType, GetVolumeGroupForDevice(deviceType), index) || 6620 index >= IPolicyProvider::GetVolumeVectorSize()) { 6621 return false; 6622 } 6623 vol.isMute = volumeVector_[index].isMute; 6624 vol.volumeFloat = volumeVector_[index].volumeFloat; 6625 vol.volumeInt = volumeVector_[index].volumeInt; 6626 return true; 6627 } 6628 SetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume vol)6629 bool AudioPolicyService::SetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume vol) 6630 { 6631 CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Set shared memory failed!"); 6632 size_t index = 0; 6633 if (!IPolicyProvider::GetVolumeIndex(streamType, GetVolumeGroupForDevice(deviceType), index) || 6634 index >= IPolicyProvider::GetVolumeVectorSize()) { 6635 return false; 6636 } 6637 volumeVector_[index].isMute = vol.isMute; 6638 volumeVector_[index].volumeFloat = vol.volumeFloat; 6639 volumeVector_[index].volumeInt = vol.volumeInt; 6640 6641 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 6642 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, false, "SetSharedVolume, Audio server Proxy is null"); 6643 6644 std::string identity = IPCSkeleton::ResetCallingIdentity(); 6645 gsp->NotifyStreamVolumeChanged(streamType, vol.volumeFloat); 6646 IPCSkeleton::SetCallingIdentity(identity); 6647 return true; 6648 } 6649 SetParameterCallback(const std::shared_ptr<AudioParameterCallback> & callback)6650 void AudioPolicyService::SetParameterCallback(const std::shared_ptr<AudioParameterCallback>& callback) 6651 { 6652 AUDIO_INFO_LOG("AudioPolicyService::SetParameterCallback"); 6653 sptr<AudioManagerListenerStub> parameterChangeCbStub = new(std::nothrow) AudioManagerListenerStub(); 6654 CHECK_AND_RETURN_LOG(parameterChangeCbStub != nullptr, 6655 "SetParameterCallback parameterChangeCbStub null"); 6656 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 6657 CHECK_AND_RETURN_LOG(gsp != nullptr, "SetParameterCallback gsp null"); 6658 parameterChangeCbStub->SetParameterCallback(callback); 6659 6660 sptr<IRemoteObject> object = parameterChangeCbStub->AsObject(); 6661 if (object == nullptr) { 6662 AUDIO_ERR_LOG("SetParameterCallback listenerStub object is nullptr"); 6663 return; 6664 } 6665 AUDIO_DEBUG_LOG("SetParameterCallback done"); 6666 std::string identity = IPCSkeleton::ResetCallingIdentity(); 6667 gsp->SetParameterCallback(object); 6668 IPCSkeleton::SetCallingIdentity(identity); 6669 } 6670 CheckStreamOffloadMode(int64_t activateSessionId,AudioStreamType streamType)6671 bool AudioPolicyService::CheckStreamOffloadMode(int64_t activateSessionId, AudioStreamType streamType) 6672 { 6673 if (!GetOffloadAvailableFromXml()) { 6674 AUDIO_INFO_LOG("Offload not available, skipped for set"); 6675 return false; 6676 } 6677 6678 if (!CheckActiveOutputDeviceSupportOffload()) { 6679 AUDIO_PRERELEASE_LOGI("Offload not available on current output device, skipped"); 6680 return false; 6681 } 6682 6683 if (!streamCollector_.IsOffloadAllowed(activateSessionId)) { 6684 AUDIO_PRERELEASE_LOGI("Offload is not allowed, Skipped"); 6685 return false; 6686 } 6687 6688 if ((streamType != STREAM_MUSIC) && (streamType != STREAM_SPEECH)) { 6689 AUDIO_DEBUG_LOG("StreamType not allowed get offload mode, Skipped"); 6690 return false; 6691 } 6692 6693 AudioPipeType pipeType; 6694 streamCollector_.GetPipeType(activateSessionId, pipeType); 6695 if (pipeType == PIPE_TYPE_DIRECT_MUSIC) { 6696 AUDIO_INFO_LOG("stream is direct, Skipped"); 6697 return false; 6698 } 6699 6700 int32_t channelCount = GetChannelCount(activateSessionId); 6701 if ((channelCount != AudioChannel::MONO) && (channelCount != AudioChannel::STEREO)) { 6702 AUDIO_DEBUG_LOG("ChannelNum not allowed get offload mode, Skipped"); 6703 return false; 6704 } 6705 6706 int32_t offloadUID = GetUid(activateSessionId); 6707 if (offloadUID == -1) { 6708 AUDIO_DEBUG_LOG("offloadUID not valid, Skipped"); 6709 return false; 6710 } 6711 if (offloadUID == UID_AUDIO) { 6712 AUDIO_DEBUG_LOG("Skip anco_audio out of offload mode"); 6713 return false; 6714 } 6715 6716 if (CheckSpatializationAndEffectState()) { 6717 AUDIO_INFO_LOG("spatialization effect in arm, Skipped"); 6718 return false; 6719 } 6720 return true; 6721 } 6722 ConstructOffloadAudioModuleInfo(DeviceType deviceType)6723 AudioModuleInfo AudioPolicyService::ConstructOffloadAudioModuleInfo(DeviceType deviceType) 6724 { 6725 AudioModuleInfo audioModuleInfo = {}; 6726 audioModuleInfo.lib = "libmodule-hdi-sink.z.so"; 6727 audioModuleInfo.format = "s32le"; // 32bit little endian 6728 audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size. 6729 6730 // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink. 6731 audioModuleInfo.name = OFFLOAD_PRIMARY_SPEAKER; 6732 6733 std::stringstream typeValue; 6734 typeValue << static_cast<int32_t>(deviceType); 6735 audioModuleInfo.deviceType = typeValue.str(); 6736 6737 audioModuleInfo.adapterName = "primary"; 6738 audioModuleInfo.className = "offload"; // used in renderer_sink_adapter.c 6739 audioModuleInfo.fileName = "offload_dump_file"; 6740 audioModuleInfo.offloadEnable = "1"; 6741 6742 audioModuleInfo.channels = "2"; 6743 audioModuleInfo.rate = "48000"; 6744 audioModuleInfo.bufferSize = "7680"; 6745 6746 return audioModuleInfo; 6747 } 6748 LoadOffloadModule()6749 int32_t AudioPolicyService::LoadOffloadModule() 6750 { 6751 AUDIO_INFO_LOG("load offload mode"); 6752 std::unique_lock<std::mutex> lock(offloadCloseMutex_); 6753 isOffloadOpened_.store(true); 6754 offloadCloseCondition_.notify_all(); 6755 { 6756 std::lock_guard<std::mutex> lock(offloadOpenMutex_); 6757 if (IOHandles_.find(OFFLOAD_PRIMARY_SPEAKER) != IOHandles_.end()) { 6758 AUDIO_INFO_LOG("offload is open"); 6759 return SUCCESS; 6760 } 6761 6762 DeviceType deviceType = DEVICE_TYPE_SPEAKER; 6763 AudioModuleInfo moduleInfo = ConstructOffloadAudioModuleInfo(deviceType); 6764 return OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 6765 } 6766 return SUCCESS; 6767 } 6768 UnloadOffloadModule()6769 int32_t AudioPolicyService::UnloadOffloadModule() 6770 { 6771 AUDIO_INFO_LOG("unload offload module"); 6772 std::unique_lock<std::mutex> lock(offloadCloseMutex_); 6773 // Try to wait 3 seconds before unloading the module, because the audio driver takes some time to process 6774 // the shutdown process.. 6775 offloadCloseCondition_.wait_for(lock, std::chrono::seconds(WAIT_OFFLOAD_CLOSE_TIME_S), 6776 [this] () { return isOffloadOpened_.load(); }); 6777 { 6778 std::lock_guard<std::mutex> lock(offloadOpenMutex_); 6779 if (isOffloadOpened_.load()) { 6780 AUDIO_INFO_LOG("offload restart"); 6781 return ERROR; 6782 } 6783 ClosePortAndEraseIOHandle(OFFLOAD_PRIMARY_SPEAKER); 6784 } 6785 return SUCCESS; 6786 } 6787 CheckStreamMultichannelMode(const int64_t activateSessionId)6788 bool AudioPolicyService::CheckStreamMultichannelMode(const int64_t activateSessionId) 6789 { 6790 if (GetCurrentOutputDeviceNetworkId() != LOCAL_NETWORK_ID || 6791 GetCurrentOutputDeviceType() == DEVICE_TYPE_REMOTE_CAST) { 6792 return false; 6793 } 6794 6795 // Multi-channel mode only when the number of channels is greater than 2. 6796 int32_t channelCount = GetChannelCount(activateSessionId); 6797 if (channelCount < AudioChannel::CHANNEL_3) { 6798 AUDIO_DEBUG_LOG("ChannelNum not allowed get multichannel mode, Skipped"); 6799 return false; 6800 } 6801 6802 // The multi-channel algorithm needs to be supported in the DSP 6803 return GetAudioEffectOffloadFlag(); 6804 } 6805 ConstructMchAudioModuleInfo(DeviceType deviceType)6806 AudioModuleInfo AudioPolicyService::ConstructMchAudioModuleInfo(DeviceType deviceType) 6807 { 6808 AudioModuleInfo audioModuleInfo = {}; 6809 audioModuleInfo.lib = "libmodule-hdi-sink.z.so"; 6810 audioModuleInfo.format = "s32le"; // 32bit little endian 6811 audioModuleInfo.fixedLatency = "1"; // here we need to set latency fixed for a fixed buffer size. 6812 6813 // used as "sink_name" in hdi_sink.c, hope we could use name to find target sink. 6814 audioModuleInfo.name = MCH_PRIMARY_SPEAKER; 6815 6816 std::stringstream typeValue; 6817 typeValue << static_cast<int32_t>(deviceType); 6818 audioModuleInfo.deviceType = typeValue.str(); 6819 6820 audioModuleInfo.adapterName = "primary"; 6821 audioModuleInfo.className = "multichannel"; // used in renderer_sink_adapter.c 6822 audioModuleInfo.fileName = "mch_dump_file"; 6823 6824 audioModuleInfo.channels = "6"; 6825 audioModuleInfo.rate = "48000"; 6826 audioModuleInfo.bufferSize = "7680"; 6827 6828 return audioModuleInfo; 6829 } 6830 LoadMchModule()6831 int32_t AudioPolicyService::LoadMchModule() 6832 { 6833 AUDIO_INFO_LOG("load multichannel mode"); 6834 DeviceType deviceType = DEVICE_TYPE_SPEAKER; 6835 AudioModuleInfo moduleInfo = ConstructMchAudioModuleInfo(deviceType); 6836 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 6837 return SUCCESS; 6838 } 6839 UnloadMchModule()6840 int32_t AudioPolicyService::UnloadMchModule() 6841 { 6842 AUDIO_INFO_LOG("unload multichannel module"); 6843 return ClosePortAndEraseIOHandle(MCH_PRIMARY_SPEAKER); 6844 } 6845 CheckStreamMode(const int64_t activateSessionId)6846 void AudioPolicyService::CheckStreamMode(const int64_t activateSessionId) 6847 { 6848 if (CheckStreamMultichannelMode(activateSessionId)) { 6849 AudioPipeType pipeMultiChannel = PIPE_TYPE_MULTICHANNEL; 6850 int32_t ret = ActivateAudioConcurrency(pipeMultiChannel); 6851 CHECK_AND_RETURN_LOG(ret == SUCCESS, "concede incoming multichannel"); 6852 MoveToNewPipeInner(activateSessionId, PIPE_TYPE_MULTICHANNEL); 6853 } 6854 } 6855 MoveToNewPipe(uint32_t sessionId,AudioPipeType pipeType)6856 int32_t AudioPolicyService::MoveToNewPipe(uint32_t sessionId, AudioPipeType pipeType) 6857 { 6858 // Check if the stream exists 6859 int32_t defaultUid = -1; 6860 if (defaultUid == streamCollector_.GetUid(sessionId)) { 6861 AUDIO_ERR_LOG("The audio stream information [%{public}d] is illegal", sessionId); 6862 return ERROR; 6863 } 6864 // move the stream to new pipe 6865 return MoveToNewPipeInner(sessionId, pipeType); 6866 } 6867 DynamicUnloadModule(const AudioPipeType pipeType)6868 int32_t AudioPolicyService::DynamicUnloadModule(const AudioPipeType pipeType) 6869 { 6870 switch (pipeType) { 6871 case PIPE_TYPE_OFFLOAD: 6872 if (isOffloadOpened_.load()) { 6873 isOffloadOpened_.store(false); 6874 auto unloadFirOffloadThrd = [this] { this->UnloadOffloadModule(); }; 6875 std::thread unloadOffloadThrd(unloadFirOffloadThrd); 6876 unloadOffloadThrd.detach(); 6877 } 6878 break; 6879 case PIPE_TYPE_MULTICHANNEL: 6880 return UnloadMchModule(); 6881 default: 6882 AUDIO_WARNING_LOG("not supported for pipe type %{public}d", pipeType); 6883 break; 6884 } 6885 return SUCCESS; 6886 } 6887 MoveToNewPipeInner(uint32_t sessionId,AudioPipeType pipeType)6888 int32_t AudioPolicyService::MoveToNewPipeInner(uint32_t sessionId, AudioPipeType pipeType) 6889 { 6890 AudioPipeType oldPipeType; 6891 streamCollector_.GetPipeType(sessionId, oldPipeType); 6892 if (oldPipeType == pipeType) { 6893 AUDIO_ERR_LOG("the same type [%{public}d],no need to move", pipeType); 6894 return SUCCESS; 6895 } 6896 Trace trace("AudioPolicyService::MoveToNewPipeInner"); 6897 AUDIO_INFO_LOG("start move stream into new pipe %{public}d", pipeType); 6898 int32_t ret = ERROR; 6899 std::string portName = PORT_NONE; 6900 AudioStreamType streamType = streamCollector_.GetStreamType(sessionId); 6901 DeviceType deviceType = GetActiveOutputDevice(); 6902 switch (pipeType) { 6903 case PIPE_TYPE_OFFLOAD: { 6904 if (!CheckStreamOffloadMode(sessionId, streamType)) { 6905 return ERROR; 6906 } 6907 if (LoadOffloadModule() != SUCCESS) { 6908 return ERROR; 6909 } 6910 portName = GetSinkPortName(deviceType, pipeType); 6911 ret = MoveToOutputDevice(sessionId, portName); 6912 break; 6913 } 6914 case PIPE_TYPE_MULTICHANNEL: { 6915 if (!CheckStreamMultichannelMode(sessionId)) { 6916 return ERROR; 6917 } 6918 if (IOHandles_.find(MCH_PRIMARY_SPEAKER) == IOHandles_.end()) { 6919 // load moudle and move into new sink 6920 LoadMchModule(); 6921 } 6922 portName = GetSinkPortName(deviceType, pipeType); 6923 ret = MoveToOutputDevice(sessionId, portName); 6924 break; 6925 } 6926 case PIPE_TYPE_NORMAL_OUT: { 6927 portName = GetSinkPortName(deviceType, pipeType); 6928 ret = MoveToOutputDevice(sessionId, portName); 6929 break; 6930 } 6931 default: 6932 AUDIO_WARNING_LOG("not supported for pipe type %{public}d", pipeType); 6933 break; 6934 } 6935 if (ret == SUCCESS) { 6936 streamCollector_.UpdateRendererPipeInfo(sessionId, pipeType); 6937 } 6938 return ret; 6939 } 6940 GetMaxRendererInstances()6941 int32_t AudioPolicyService::GetMaxRendererInstances() 6942 { 6943 for (auto &configInfo : globalConfigs_.outputConfigInfos_) { 6944 if (configInfo.name_ == "normal" && configInfo.value_ != "") { 6945 AUDIO_INFO_LOG("Max output normal instance is %{public}s", configInfo.value_.c_str()); 6946 return (int32_t)std::stoi(configInfo.value_); 6947 } 6948 } 6949 return DEFAULT_MAX_OUTPUT_NORMAL_INSTANCES; 6950 } 6951 CheckMaxRendererInstances()6952 int32_t AudioPolicyService::CheckMaxRendererInstances() 6953 { 6954 std::vector<std::unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos; 6955 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos); 6956 AUDIO_INFO_LOG("Audio current renderer change infos size: %{public}zu", audioRendererChangeInfos.size()); 6957 int32_t maxRendererInstances = GetMaxRendererInstances(); 6958 if (audioRendererChangeInfos.size() >= static_cast<size_t>(maxRendererInstances)) { 6959 std::map<int32_t, int32_t> appUseNumMap; 6960 int32_t mostAppUid = INVALID_APP_UID; 6961 int32_t mostAppNum = INVALID_APP_CREATED_AUDIO_STREAM_NUM; 6962 for (auto it = audioRendererChangeInfos.begin(); it != audioRendererChangeInfos.end(); it++) { 6963 auto appUseNum = appUseNumMap.find((*it)->clientUID); 6964 if (appUseNum != appUseNumMap.end()) { 6965 appUseNumMap[(*it)->clientUID] = ++appUseNum->second; 6966 } else { 6967 appUseNumMap.emplace((*it)->clientUID, INITIAL_VALUE); 6968 } 6969 } 6970 for (auto iter = appUseNumMap.begin(); iter != appUseNumMap.end(); iter++) { 6971 if (iter->second > mostAppNum) { 6972 mostAppNum = iter->second; 6973 mostAppUid = iter->first; 6974 } 6975 } 6976 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 6977 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_STREAM_EXHAUSTED_STATS, 6978 Media::MediaMonitor::EventType::FREQUENCY_AGGREGATION_EVENT); 6979 bean->Add("CLIENT_UID", mostAppUid); 6980 bean->Add("STREAM_NUM", mostAppNum); 6981 AUDIO_INFO_LOG("mostAppUid: %{public}d, mostAppNum: %{public}d", mostAppUid, mostAppNum); 6982 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 6983 } 6984 6985 CHECK_AND_RETURN_RET_LOG(audioRendererChangeInfos.size() < static_cast<size_t>(maxRendererInstances), ERR_OVERFLOW, 6986 "The current number of audio renderer streams is greater than the maximum number of configured instances"); 6987 6988 return SUCCESS; 6989 } 6990 6991 #ifdef BLUETOOTH_ENABLE RegisterBluetoothDeathCallback()6992 const sptr<IStandardAudioService> RegisterBluetoothDeathCallback() 6993 { 6994 lock_guard<mutex> lock(g_btProxyMutex); 6995 if (g_btProxy == nullptr) { 6996 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); 6997 CHECK_AND_RETURN_RET_LOG(samgr != nullptr, nullptr, 6998 "RegisterBluetoothDeathCallback: get sa manager failed"); 6999 sptr<IRemoteObject> object = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID); 7000 CHECK_AND_RETURN_RET_LOG(object != nullptr, nullptr, 7001 "RegisterBluetoothDeathCallback: get audio service remote object failed"); 7002 g_btProxy = iface_cast<IStandardAudioService>(object); 7003 CHECK_AND_RETURN_RET_LOG(g_btProxy != nullptr, nullptr, 7004 "RegisterBluetoothDeathCallback: get audio service proxy failed"); 7005 7006 // register death recipent 7007 sptr<AudioServerDeathRecipient> asDeathRecipient = new(std::nothrow) AudioServerDeathRecipient(getpid()); 7008 if (asDeathRecipient != nullptr) { 7009 asDeathRecipient->SetNotifyCb([] (pid_t pid) { 7010 AudioPolicyService::BluetoothServiceCrashedCallback(pid); 7011 }); 7012 bool result = object->AddDeathRecipient(asDeathRecipient); 7013 if (!result) { 7014 AUDIO_ERR_LOG("RegisterBluetoothDeathCallback: failed to add deathRecipient"); 7015 } 7016 } 7017 } 7018 sptr<IStandardAudioService> gasp = g_btProxy; 7019 return gasp; 7020 } 7021 BluetoothServiceCrashedCallback(pid_t pid)7022 void AudioPolicyService::BluetoothServiceCrashedCallback(pid_t pid) 7023 { 7024 AUDIO_INFO_LOG("Bluetooth sa crashed, will restore proxy in next call"); 7025 lock_guard<mutex> lock(g_btProxyMutex); 7026 g_btProxy = nullptr; 7027 isBtListenerRegistered = false; 7028 Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSink(); 7029 Bluetooth::AudioHfpManager::DisconnectBluetoothHfpSink(); 7030 } 7031 #endif 7032 RegisterBluetoothListener()7033 void AudioPolicyService::RegisterBluetoothListener() 7034 { 7035 #ifdef BLUETOOTH_ENABLE 7036 AUDIO_INFO_LOG("Enter AudioPolicyService::RegisterBluetoothListener"); 7037 Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_); 7038 if (isBtListenerRegistered) { 7039 AUDIO_INFO_LOG("audio policy service already register bt listerer, return"); 7040 return; 7041 } 7042 Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener(); 7043 Bluetooth::AudioHfpManager::RegisterBluetoothScoListener(); 7044 isBtListenerRegistered = true; 7045 const sptr<IStandardAudioService> gsp = RegisterBluetoothDeathCallback(); 7046 isBTReconnecting_ = true; 7047 Bluetooth::AudioA2dpManager::CheckA2dpDeviceReconnect(); 7048 Bluetooth::AudioHfpManager::CheckHfpDeviceReconnect(); 7049 isBTReconnecting_ = false; 7050 #endif 7051 } 7052 UnregisterBluetoothListener()7053 void AudioPolicyService::UnregisterBluetoothListener() 7054 { 7055 #ifdef BLUETOOTH_ENABLE 7056 AUDIO_INFO_LOG("Enter AudioPolicyService::UnregisterBluetoothListener"); 7057 Bluetooth::UnregisterDeviceObserver(); 7058 Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener(); 7059 Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener(); 7060 isBtListenerRegistered = false; 7061 #endif 7062 } 7063 SubscribeAccessibilityConfigObserver()7064 void AudioPolicyService::SubscribeAccessibilityConfigObserver() 7065 { 7066 #ifdef ACCESSIBILITY_ENABLE 7067 accessibilityConfigListener_->SubscribeObserver(); 7068 AUDIO_INFO_LOG("Subscribe accessibility config observer successfully"); 7069 #endif 7070 } 7071 GetMinStreamVolume()7072 float AudioPolicyService::GetMinStreamVolume() 7073 { 7074 return audioPolicyManager_.GetMinStreamVolume(); 7075 } 7076 GetMaxStreamVolume()7077 float AudioPolicyService::GetMaxStreamVolume() 7078 { 7079 return audioPolicyManager_.GetMaxStreamVolume(); 7080 } 7081 IsVolumeUnadjustable()7082 bool AudioPolicyService::IsVolumeUnadjustable() 7083 { 7084 return audioPolicyManager_.IsVolumeUnadjustable(); 7085 } 7086 GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfoMap)7087 void AudioPolicyService::GetStreamVolumeInfoMap(StreamVolumeInfoMap &streamVolumeInfoMap) 7088 { 7089 return audioPolicyManager_.GetStreamVolumeInfoMap(streamVolumeInfoMap); 7090 } 7091 GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType) const7092 float AudioPolicyService::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, 7093 DeviceType deviceType) const 7094 { 7095 return audioPolicyManager_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType); 7096 } 7097 QueryEffectManagerSceneMode(SupportedEffectConfig & supportedEffectConfig)7098 int32_t AudioPolicyService::QueryEffectManagerSceneMode(SupportedEffectConfig& supportedEffectConfig) 7099 { 7100 int32_t ret = audioEffectManager_.QueryEffectManagerSceneMode(supportedEffectConfig); 7101 return ret; 7102 } 7103 RegisterDataObserver()7104 void AudioPolicyService::RegisterDataObserver() 7105 { 7106 std::string devicesName = ""; 7107 int32_t ret = GetDeviceNameFromDataShareHelper(devicesName); 7108 CHECK_AND_RETURN_LOG(ret == SUCCESS, "RegisterDataObserver get devicesName failed"); 7109 SetDisplayName(devicesName, true); 7110 RegisterNameMonitorHelper(); 7111 } 7112 SetPlaybackCapturerFilterInfos(const AudioPlaybackCaptureConfig & config)7113 int32_t AudioPolicyService::SetPlaybackCapturerFilterInfos(const AudioPlaybackCaptureConfig &config) 7114 { 7115 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 7116 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, 7117 "SetPlaybackCapturerFilterInfos, Audio Server Proxy is null"); 7118 7119 std::string identity = IPCSkeleton::ResetCallingIdentity(); 7120 int32_t ret = gsp->SetCaptureSilentState(config.silentCapture); 7121 IPCSkeleton::SetCallingIdentity(identity); 7122 CHECK_AND_RETURN_RET_LOG(!ret, ERR_OPERATION_FAILED, "SetCaptureSilentState failed"); 7123 7124 std::vector<int32_t> targetUsages; 7125 AUDIO_INFO_LOG("SetPlaybackCapturerFilterInfos"); 7126 for (size_t i = 0; i < config.filterOptions.usages.size(); i++) { 7127 if (count(targetUsages.begin(), targetUsages.end(), config.filterOptions.usages[i]) == 0) { 7128 targetUsages.emplace_back(config.filterOptions.usages[i]); // deduplicate 7129 } 7130 } 7131 7132 identity = IPCSkeleton::ResetCallingIdentity(); 7133 int32_t res = gsp->SetSupportStreamUsage(targetUsages); 7134 IPCSkeleton::SetCallingIdentity(identity); 7135 return res; 7136 } 7137 SetCaptureSilentState(bool state)7138 int32_t AudioPolicyService::SetCaptureSilentState(bool state) 7139 { 7140 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 7141 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, ERR_OPERATION_FAILED, "SetCaptureSilentState, Audio server Proxy is null"); 7142 7143 std::string identity = IPCSkeleton::ResetCallingIdentity(); 7144 int32_t res = gsp->SetCaptureSilentState(state); 7145 IPCSkeleton::SetCallingIdentity(identity); 7146 return res; 7147 } 7148 IsConnectedOutputDevice(const sptr<AudioDeviceDescriptor> & desc)7149 bool AudioPolicyService::IsConnectedOutputDevice(const sptr<AudioDeviceDescriptor> &desc) 7150 { 7151 DeviceType deviceType = desc->deviceType_; 7152 7153 CHECK_AND_RETURN_RET_LOG(desc->deviceRole_ == DeviceRole::OUTPUT_DEVICE, false, 7154 "Not output device!"); 7155 7156 auto isPresent = [&deviceType] (const sptr<AudioDeviceDescriptor> &desc) { 7157 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor"); 7158 if (deviceType == DEVICE_TYPE_FILE_SINK) { 7159 return false; 7160 } 7161 return ((deviceType == desc->deviceType_) && (desc->deviceRole_ == DeviceRole::OUTPUT_DEVICE)); 7162 }; 7163 7164 auto itr = std::find_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent); 7165 CHECK_AND_RETURN_RET_LOG(itr != connectedDevices_.end(), false, "Device not available"); 7166 7167 return true; 7168 } 7169 GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> & desc)7170 int32_t AudioPolicyService::GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> &desc) 7171 { 7172 int32_t rate = 48000; 7173 7174 CHECK_AND_RETURN_RET_LOG(desc != nullptr, -1, "desc is null!"); 7175 7176 bool ret = IsConnectedOutputDevice(desc); 7177 CHECK_AND_RETURN_RET(ret, -1); 7178 7179 DeviceType clientDevType = desc->deviceType_; 7180 for (const auto &device : deviceClassInfo_) { 7181 auto moduleInfoList = device.second; 7182 for (auto &moduleInfo : moduleInfoList) { 7183 auto serverDevType = GetDeviceType(moduleInfo.name); 7184 if (clientDevType == serverDevType) { 7185 rate = atoi(moduleInfo.rate.c_str()); 7186 return rate; 7187 } 7188 } 7189 } 7190 7191 return rate; 7192 } 7193 AddMicrophoneDescriptor(sptr<AudioDeviceDescriptor> & deviceDescriptor)7194 void AudioPolicyService::AddMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor) 7195 { 7196 if (deviceDescriptor->deviceRole_ == INPUT_DEVICE && 7197 deviceDescriptor->deviceType_ != DEVICE_TYPE_FILE_SOURCE) { 7198 auto isPresent = [&deviceDescriptor](const sptr<MicrophoneDescriptor> &desc) { 7199 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor"); 7200 return desc->deviceType_ == deviceDescriptor->deviceType_; 7201 }; 7202 7203 auto iter = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent); 7204 if (iter == connectedMicrophones_.end()) { 7205 sptr<MicrophoneDescriptor> micDesc = new (std::nothrow) MicrophoneDescriptor(startMicrophoneId++, 7206 deviceDescriptor->deviceType_); 7207 CHECK_AND_RETURN_LOG(micDesc != nullptr, "new MicrophoneDescriptor failed"); 7208 connectedMicrophones_.push_back(micDesc); 7209 } 7210 } 7211 } 7212 RemoveMicrophoneDescriptor(sptr<AudioDeviceDescriptor> & deviceDescriptor)7213 void AudioPolicyService::RemoveMicrophoneDescriptor(sptr<AudioDeviceDescriptor> &deviceDescriptor) 7214 { 7215 auto isPresent = [&deviceDescriptor](const sptr<MicrophoneDescriptor> &desc) { 7216 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor"); 7217 return desc->deviceType_ == deviceDescriptor->deviceType_; 7218 }; 7219 7220 auto iter = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent); 7221 if (iter != connectedMicrophones_.end()) { 7222 connectedMicrophones_.erase(iter); 7223 } 7224 } 7225 AddAudioCapturerMicrophoneDescriptor(int32_t sessionId,DeviceType devType)7226 void AudioPolicyService::AddAudioCapturerMicrophoneDescriptor(int32_t sessionId, DeviceType devType) 7227 { 7228 if (devType == DEVICE_TYPE_NONE) { 7229 audioCaptureMicrophoneDescriptor_[sessionId] = new MicrophoneDescriptor(0, DEVICE_TYPE_INVALID); 7230 return; 7231 } 7232 auto isPresent = [&devType] (const sptr<MicrophoneDescriptor> &desc) { 7233 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid microphone descriptor"); 7234 return (devType == desc->deviceType_); 7235 }; 7236 7237 auto itr = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent); 7238 if (itr != connectedMicrophones_.end()) { 7239 audioCaptureMicrophoneDescriptor_[sessionId] = *itr; 7240 } 7241 } 7242 GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)7243 vector<sptr<MicrophoneDescriptor>> AudioPolicyService::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId) 7244 { 7245 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 7246 7247 vector<sptr<MicrophoneDescriptor>> descList = {}; 7248 const auto desc = audioCaptureMicrophoneDescriptor_.find(sessionId); 7249 if (desc != audioCaptureMicrophoneDescriptor_.end()) { 7250 sptr<MicrophoneDescriptor> micDesc = new (std::nothrow) MicrophoneDescriptor(desc->second); 7251 if (micDesc == nullptr) { 7252 AUDIO_ERR_LOG("Create microphone device descriptor failed"); 7253 return descList; 7254 } 7255 descList.push_back(micDesc); 7256 } 7257 return descList; 7258 } 7259 GetAvailableMicrophones()7260 vector<sptr<MicrophoneDescriptor>> AudioPolicyService::GetAvailableMicrophones() 7261 { 7262 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 7263 return connectedMicrophones_; 7264 } 7265 UpdateAudioCapturerMicrophoneDescriptor(DeviceType devType)7266 void AudioPolicyService::UpdateAudioCapturerMicrophoneDescriptor(DeviceType devType) 7267 { 7268 auto isPresent = [&devType] (const sptr<MicrophoneDescriptor> &desc) { 7269 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid microphone descriptor"); 7270 return (devType == desc->deviceType_); 7271 }; 7272 7273 auto itr = std::find_if(connectedMicrophones_.begin(), connectedMicrophones_.end(), isPresent); 7274 if (itr != connectedMicrophones_.end()) { 7275 for (auto& desc : audioCaptureMicrophoneDescriptor_) { 7276 if (desc.second->deviceType_ != devType) { 7277 desc.second = *itr; 7278 } 7279 } 7280 } 7281 } 7282 RemoveAudioCapturerMicrophoneDescriptor(int32_t uid)7283 void AudioPolicyService::RemoveAudioCapturerMicrophoneDescriptor(int32_t uid) 7284 { 7285 vector<unique_ptr<AudioCapturerChangeInfo>> audioCapturerChangeInfos; 7286 streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos); 7287 7288 for (auto &info : audioCapturerChangeInfos) { 7289 if (info->clientUID != uid && info->createrUID != uid) { 7290 continue; 7291 } 7292 audioCaptureMicrophoneDescriptor_.erase(info->sessionId); 7293 } 7294 } 7295 FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo,StreamPropInfo & targetInfo,SourceType & targetSourceType)7296 int32_t AudioPolicyService::FetchTargetInfoForSessionAdd(const SessionInfo sessionInfo, StreamPropInfo &targetInfo, 7297 SourceType &targetSourceType) 7298 { 7299 const PipeInfo *pipeInfoPtr = nullptr; 7300 if (adapterInfoMap_.count(AdaptersType::TYPE_PRIMARY) > 0) { 7301 pipeInfoPtr = adapterInfoMap_.at(AdaptersType::TYPE_PRIMARY).GetPipeByName(PIPE_PRIMARY_INPUT); 7302 } 7303 CHECK_AND_RETURN_RET_LOG(pipeInfoPtr != nullptr, ERROR, "pipeInfoPtr is null"); 7304 7305 const auto &streamPropInfoList = pipeInfoPtr->streamPropInfos_; 7306 7307 if (streamPropInfoList.empty()) { 7308 AUDIO_ERR_LOG("supportedRate or supportedChannels is empty"); 7309 return ERROR; 7310 } 7311 StreamPropInfo targetStreamPropInfo = *streamPropInfoList.begin(); 7312 if (sessionInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION 7313 || sessionInfo.sourceType == SOURCE_TYPE_VOICE_RECOGNITION) { 7314 targetSourceType = sessionInfo.sourceType; 7315 for (const auto &streamPropInfo : streamPropInfoList) { 7316 if (sessionInfo.channels == streamPropInfo.channelLayout_ 7317 && sessionInfo.rate == streamPropInfo.sampleRate_) { 7318 targetStreamPropInfo = streamPropInfo; 7319 break; 7320 } 7321 } 7322 } else if (sessionInfo.sourceType == SOURCE_TYPE_VOICE_CALL) { 7323 targetSourceType = SOURCE_TYPE_VOICE_CALL; 7324 } else if (sessionInfo.sourceType == SOURCE_TYPE_CAMCORDER) { 7325 targetSourceType = SOURCE_TYPE_CAMCORDER; 7326 } else { 7327 // For normal sourcetype, continue to use the default value 7328 targetSourceType = SOURCE_TYPE_MIC; 7329 } 7330 targetInfo = targetStreamPropInfo; 7331 return SUCCESS; 7332 } 7333 OnCapturerSessionRemoved(uint64_t sessionID)7334 void AudioPolicyService::OnCapturerSessionRemoved(uint64_t sessionID) 7335 { 7336 if (sessionWithSpecialSourceType_.count(sessionID) > 0) { 7337 if (sessionWithSpecialSourceType_[sessionID].sourceType == SOURCE_TYPE_REMOTE_CAST) { 7338 HandleRemoteCastDevice(false); 7339 } 7340 sessionWithSpecialSourceType_.erase(sessionID); 7341 return; 7342 } 7343 7344 if (sessionWithNormalSourceType_.count(sessionID) > 0) { 7345 sessionWithNormalSourceType_.erase(sessionID); 7346 if (!sessionWithNormalSourceType_.empty()) { 7347 return; 7348 } 7349 ClosePortAndEraseIOHandle(PRIMARY_MIC); 7350 return; 7351 } 7352 7353 AUDIO_INFO_LOG("Sessionid:%{public}" PRIu64 " not added, directly placed into sessionIdisRemovedSet_", sessionID); 7354 sessionIdisRemovedSet_.insert(sessionID); 7355 } 7356 OnCapturerSessionAdded(uint64_t sessionID,SessionInfo sessionInfo,AudioStreamInfo streamInfo)7357 int32_t AudioPolicyService::OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo, 7358 AudioStreamInfo streamInfo) 7359 { 7360 CHECK_AND_RETURN_RET_LOG(isPolicyConfigParsered_ && isPrimaryMicModuleInfoLoaded_, ERROR, 7361 "policyConfig not loaded"); 7362 if (sessionIdisRemovedSet_.count(sessionID) > 0) { 7363 sessionIdisRemovedSet_.erase(sessionID); 7364 AUDIO_INFO_LOG("sessionID: %{public}" PRIu64 " had already been removed earlier", sessionID); 7365 return SUCCESS; 7366 } 7367 if (specialSourceTypeSet_.count(sessionInfo.sourceType) == 0) { 7368 StreamPropInfo targetInfo; 7369 SourceType sourcetype; 7370 int32_t res = FetchTargetInfoForSessionAdd(sessionInfo, targetInfo, sourcetype); 7371 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, res, 7372 "FetchTargetInfoForSessionAdd error, maybe device not support recorder"); 7373 bool isSourceLoaded = !sessionWithNormalSourceType_.empty(); 7374 if (!isSourceLoaded) { 7375 auto moduleInfo = primaryMicModuleInfo_; 7376 // current layout represents the number of channel. This will need to be modify in the future. 7377 moduleInfo.channels = std::to_string(targetInfo.channelLayout_); 7378 moduleInfo.rate = std::to_string(targetInfo.sampleRate_); 7379 moduleInfo.bufferSize = std::to_string(targetInfo.bufferSize_); 7380 moduleInfo.format = targetInfo.format_; 7381 moduleInfo.sourceType = std::to_string(sourcetype); 7382 AUDIO_INFO_LOG("rate:%{public}s, channels:%{public}s, bufferSize:%{public}s format:%{public}s, " 7383 "sourcetype: %{public}s", 7384 moduleInfo.rate.c_str(), moduleInfo.channels.c_str(), moduleInfo.bufferSize.c_str(), 7385 moduleInfo.format.c_str(), moduleInfo.sourceType.c_str()); 7386 OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo); 7387 audioPolicyManager_.SetDeviceActive(GetCurrentInputDeviceType(), 7388 moduleInfo.name, true, INPUT_DEVICES_FLAG); 7389 } 7390 sessionWithNormalSourceType_[sessionID] = sessionInfo; 7391 } else if (sessionInfo.sourceType == SOURCE_TYPE_REMOTE_CAST) { 7392 HandleRemoteCastDevice(true, streamInfo); 7393 sessionWithSpecialSourceType_[sessionID] = sessionInfo; 7394 } else { 7395 sessionWithSpecialSourceType_[sessionID] = sessionInfo; 7396 } 7397 AUDIO_INFO_LOG("sessionID: %{public}" PRIu64 " OnCapturerSessionAdded end", sessionID); 7398 return SUCCESS; 7399 } 7400 RectifyModuleInfo(AudioModuleInfo & moduleInfo,std::list<AudioModuleInfo> & moduleInfoList,SourceInfo & targetInfo)7401 void AudioPolicyService::RectifyModuleInfo(AudioModuleInfo &moduleInfo, std::list<AudioModuleInfo> &moduleInfoList, 7402 SourceInfo &targetInfo) 7403 { 7404 auto [targetSourceType, targetRate, targetChannels] = targetInfo; 7405 for (auto &adapterModuleInfo : moduleInfoList) { 7406 if (moduleInfo.role == adapterModuleInfo.role && 7407 adapterModuleInfo.name.find(MODULE_SINK_OFFLOAD) == std::string::npos) { 7408 CHECK_AND_CONTINUE_LOG(adapterModuleInfo.supportedRate_.count(targetRate) > 0, "rate unmatch."); 7409 CHECK_AND_CONTINUE_LOG(adapterModuleInfo.supportedChannels_.count(targetChannels) > 0, "channels unmatch."); 7410 moduleInfo.rate = std::to_string(targetRate); 7411 moduleInfo.channels = std::to_string(targetChannels); 7412 uint32_t sampleFormatBits = PcmFormatToBits(static_cast<AudioSampleFormat>( 7413 formatFromParserStrToEnum[moduleInfo.format])); 7414 uint32_t bufferSize = (targetRate * targetChannels * sampleFormatBits / BUFFER_CALC_1000MS) 7415 * BUFFER_CALC_20MS; 7416 moduleInfo.bufferSize = std::to_string(bufferSize); 7417 AUDIO_INFO_LOG("match success. rate:%{public}s, channels:%{public}s, bufferSize:%{public}s", 7418 moduleInfo.rate.c_str(), moduleInfo.channels.c_str(), moduleInfo.bufferSize.c_str()); 7419 } 7420 } 7421 moduleInfo.sourceType = std::to_string(targetSourceType); 7422 currentRate = targetRate; 7423 currentSourceType = targetSourceType; 7424 } 7425 DeviceFilterByUsageInner(AudioDeviceUsage usage,const std::vector<sptr<AudioDeviceDescriptor>> & descs)7426 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::DeviceFilterByUsageInner(AudioDeviceUsage usage, 7427 const std::vector<sptr<AudioDeviceDescriptor>>& descs) 7428 { 7429 std::vector<unique_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors; 7430 7431 unordered_map<AudioDevicePrivacyType, list<DevicePrivacyInfo>> devicePrivacyMaps = 7432 audioDeviceManager_.GetDevicePrivacyMaps(); 7433 for (const auto &dev : descs) { 7434 for (const auto &devicePrivacy : devicePrivacyMaps) { 7435 list<DevicePrivacyInfo> deviceInfos = devicePrivacy.second; 7436 audioDeviceManager_.GetAvailableDevicesWithUsage(usage, deviceInfos, dev, audioDeviceDescriptors); 7437 } 7438 } 7439 std::vector<sptr<AudioDeviceDescriptor>> deviceDescriptors; 7440 for (const auto &dec : audioDeviceDescriptors) { 7441 sptr<AudioDeviceDescriptor> tempDec = new(std::nothrow) AudioDeviceDescriptor(*dec); 7442 deviceDescriptors.push_back(move(tempDec)); 7443 } 7444 return deviceDescriptors; 7445 } 7446 TriggerAvailableDeviceChangedCallback(const vector<sptr<AudioDeviceDescriptor>> & desc,bool isConnected)7447 void AudioPolicyService::TriggerAvailableDeviceChangedCallback( 7448 const vector<sptr<AudioDeviceDescriptor>> &desc, bool isConnected) 7449 { 7450 Trace trace("AudioPolicyService::TriggerAvailableDeviceChangedCallback"); 7451 7452 WriteDeviceChangedSysEvents(desc, isConnected); 7453 7454 if (audioPolicyServerHandler_ != nullptr) { 7455 audioPolicyServerHandler_->SendAvailableDeviceChange(desc, isConnected); 7456 } 7457 } 7458 GetAvailableDevices(AudioDeviceUsage usage)7459 std::vector<unique_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetAvailableDevices(AudioDeviceUsage usage) 7460 { 7461 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 7462 7463 return GetAvailableDevicesInner(usage); 7464 } 7465 GetAvailableDevicesInner(AudioDeviceUsage usage)7466 std::vector<unique_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetAvailableDevicesInner(AudioDeviceUsage usage) 7467 { 7468 std::vector<unique_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors; 7469 7470 audioDeviceDescriptors = audioDeviceManager_.GetAvailableDevicesByUsage(usage); 7471 7472 AUDIO_INFO_LOG("audioDeviceDescriptors size:%{public}zu", audioDeviceDescriptors.size()); 7473 return audioDeviceDescriptors; 7474 } 7475 OffloadStartPlaying(const std::vector<int32_t> & sessionIds)7476 int32_t AudioPolicyService::OffloadStartPlaying(const std::vector<int32_t> &sessionIds) 7477 { 7478 #ifdef BLUETOOTH_ENABLE 7479 AUDIO_INFO_LOG("OffloadStartPlaying, a2dpOffloadFlag_: %{public}d, sessionIds: %{public}zu", 7480 a2dpOffloadFlag_, sessionIds.size()); 7481 if (a2dpOffloadFlag_ != A2DP_OFFLOAD || sessionIds.size() == 0) { 7482 return SUCCESS; 7483 } 7484 int32_t ret = Bluetooth::AudioA2dpManager::OffloadStartPlaying(sessionIds); 7485 if (audioA2dpOffloadManager_ != nullptr) { 7486 A2dpOffloadConnectionState state = audioA2dpOffloadManager_->GetA2dOffloadConnectionState(); 7487 if (ret == SUCCESS && (state != CONNECTION_STATUS_CONNECTED)) { 7488 audioA2dpOffloadManager_->ConnectA2dpOffload( 7489 Bluetooth::AudioA2dpManager::GetActiveA2dpDevice(), sessionIds); 7490 } 7491 } 7492 return ret; 7493 #else 7494 return SUCCESS; 7495 #endif 7496 } 7497 OffloadStopPlaying(const std::vector<int32_t> & sessionIds)7498 int32_t AudioPolicyService::OffloadStopPlaying(const std::vector<int32_t> &sessionIds) 7499 { 7500 #ifdef BLUETOOTH_ENABLE 7501 AUDIO_PRERELEASE_LOGI("OffloadStopPlaying, a2dpOffloadFlag_: %{public}d, sessionIds: %{public}zu", 7502 a2dpOffloadFlag_, sessionIds.size()); 7503 if (a2dpOffloadFlag_ != A2DP_OFFLOAD || sessionIds.size() == 0) { 7504 return SUCCESS; 7505 } 7506 return Bluetooth::AudioA2dpManager::OffloadStopPlaying(sessionIds); 7507 #else 7508 return SUCCESS; 7509 #endif 7510 } 7511 OffloadGetRenderPosition(uint32_t & delayValue,uint64_t & sendDataSize,uint32_t & timeStamp)7512 int32_t AudioPolicyService::OffloadGetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp) 7513 { 7514 Trace trace("AudioPolicyService::OffloadGetRenderPosition"); 7515 #ifdef BLUETOOTH_ENABLE 7516 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 7517 AUDIO_DEBUG_LOG("GetRenderPosition, deviceType: %{public}d, a2dpOffloadFlag_: %{public}d", 7518 a2dpOffloadFlag_, curOutputDeviceType); 7519 int32_t ret = SUCCESS; 7520 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP && 7521 GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID && a2dpOffloadFlag_ == A2DP_OFFLOAD) { 7522 ret = Bluetooth::AudioA2dpManager::GetRenderPosition(delayValue, sendDataSize, timeStamp); 7523 } else { 7524 delayValue = 0; 7525 sendDataSize = 0; 7526 timeStamp = 0; 7527 } 7528 return ret; 7529 #else 7530 return SUCCESS; 7531 #endif 7532 } 7533 GetAndSaveClientType(uint32_t uid,const std::string & bundleName)7534 int32_t AudioPolicyService::GetAndSaveClientType(uint32_t uid, const std::string &bundleName) 7535 { 7536 #ifdef FEATURE_APPGALLERY 7537 ClientTypeManager::GetInstance()->GetAndSaveClientType(uid, bundleName); 7538 #endif 7539 return SUCCESS; 7540 } 7541 GetA2dpOffloadCodecAndSendToDsp()7542 void AudioPolicyService::GetA2dpOffloadCodecAndSendToDsp() 7543 { 7544 #ifdef BLUETOOTH_ENABLE 7545 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_BLUETOOTH_A2DP) { 7546 return; 7547 } 7548 Bluetooth::BluetoothRemoteDevice bluetoothRemoteDevice_ = Bluetooth::AudioA2dpManager::GetCurrentActiveA2dpDevice(); 7549 Bluetooth::A2dpOffloadCodecStatus offloadCodeStatus = Bluetooth::A2dpSource::GetProfile()-> 7550 GetOffloadCodecStatus(bluetoothRemoteDevice_); 7551 std::string key = "AUDIO_EXT_PARAM_KEY_A2DP_OFFLOAD_CONFIG"; 7552 std::string value = std::to_string(offloadCodeStatus.offloadInfo.mediaPacketHeader) + "," 7553 + std::to_string(offloadCodeStatus.offloadInfo.mPt) + "," 7554 + std::to_string(offloadCodeStatus.offloadInfo.ssrc) + "," 7555 + std::to_string(offloadCodeStatus.offloadInfo.boundaryFlag) + "," 7556 + std::to_string(offloadCodeStatus.offloadInfo.broadcastFlag) + "," 7557 + std::to_string(offloadCodeStatus.offloadInfo.codecType) + "," 7558 + std::to_string(offloadCodeStatus.offloadInfo.maxLatency) + "," 7559 + std::to_string(offloadCodeStatus.offloadInfo.scmsTEnable) + "," 7560 + std::to_string(offloadCodeStatus.offloadInfo.sampleRate) + "," 7561 + std::to_string(offloadCodeStatus.offloadInfo.encodedAudioBitrate) + "," 7562 + std::to_string(offloadCodeStatus.offloadInfo.bitsPerSample) + "," 7563 + std::to_string(offloadCodeStatus.offloadInfo.chMode) + "," 7564 + std::to_string(offloadCodeStatus.offloadInfo.aclHdl) + "," 7565 + std::to_string(offloadCodeStatus.offloadInfo.l2cRcid) + "," 7566 + std::to_string(offloadCodeStatus.offloadInfo.mtu) + "," 7567 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific0) + "," 7568 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific1) + "," 7569 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific2) + "," 7570 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific3) + "," 7571 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific4) + "," 7572 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific5) + "," 7573 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific6) + "," 7574 + std::to_string(offloadCodeStatus.offloadInfo.codecSpecific7) + ";"; 7575 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 7576 std::string identity = IPCSkeleton::ResetCallingIdentity(); 7577 gsp->SetAudioParameter(key, value); 7578 IPCSkeleton::SetCallingIdentity(identity); 7579 AUDIO_DEBUG_LOG("update offloadcodec[%{public}s]", value.c_str()); 7580 #endif 7581 } 7582 7583 #ifdef BLUETOOTH_ENABLE UpdateA2dpOffloadFlag(const std::vector<Bluetooth::A2dpStreamInfo> & allActiveSessions,DeviceType deviceType)7584 void AudioPolicyService::UpdateA2dpOffloadFlag(const std::vector<Bluetooth::A2dpStreamInfo> &allActiveSessions, 7585 DeviceType deviceType) 7586 { 7587 if (allActiveSessions.size() == 0) { 7588 AUDIO_PRERELEASE_LOGI("no active sessions"); 7589 return; 7590 } 7591 auto receiveOffloadFlag = NO_A2DP_DEVICE; 7592 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) { 7593 receiveOffloadFlag = static_cast<BluetoothOffloadState>(Bluetooth::AudioA2dpManager::A2dpOffloadSessionRequest( 7594 allActiveSessions)); 7595 } else if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_A2DP && 7596 GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID && deviceType == DEVICE_TYPE_NONE) { 7597 receiveOffloadFlag = static_cast<BluetoothOffloadState>(Bluetooth::AudioA2dpManager::A2dpOffloadSessionRequest( 7598 allActiveSessions)); 7599 } 7600 7601 std::lock_guard<std::mutex> lock(switchA2dpOffloadMutex_); 7602 AUDIO_PRERELEASE_LOGI("deviceType: %{public}d, currentActiveDevice_: %{public}d, allActiveSessions: %{public}zu, " 7603 "a2dpOffloadFlag_: %{public}d, receiveOffloadFlag: %{public}d", 7604 deviceType, GetCurrentOutputDeviceType(), allActiveSessions.size(), a2dpOffloadFlag_, 7605 receiveOffloadFlag); 7606 7607 if (receiveOffloadFlag == NO_A2DP_DEVICE) { 7608 UpdateOffloadWhenActiveDeviceSwitchFromA2dp(); 7609 } else if (receiveOffloadFlag != a2dpOffloadFlag_) { 7610 if (a2dpOffloadFlag_ == A2DP_OFFLOAD) { 7611 HandleA2dpDeviceOutOffload(receiveOffloadFlag); 7612 } else if (receiveOffloadFlag == A2DP_OFFLOAD) { 7613 HandleA2dpDeviceInOffload(receiveOffloadFlag); 7614 } else { 7615 AUDIO_INFO_LOG("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_, 7616 receiveOffloadFlag); 7617 a2dpOffloadFlag_ = receiveOffloadFlag; 7618 } 7619 } else if (a2dpOffloadFlag_ == A2DP_OFFLOAD) { 7620 std::vector<int32_t> allSessions; 7621 GetAllRunningStreamSession(allSessions); 7622 OffloadStartPlaying(allSessions); 7623 UpdateEffectBtOffloadSupported(true); 7624 ResetOffloadModeOnSpatializationChanged(allSessions); 7625 GetA2dpOffloadCodecAndSendToDsp(); 7626 std::string activePort = BLUETOOTH_SPEAKER; 7627 audioPolicyManager_.SuspendAudioDevice(activePort, true); 7628 } 7629 } 7630 ResetOffloadModeOnSpatializationChanged(std::vector<int32_t> & allSessions)7631 void AudioPolicyService::ResetOffloadModeOnSpatializationChanged(std::vector<int32_t> &allSessions) 7632 { 7633 AudioSpatializationState spatialState = 7634 AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState(); 7635 bool effectOffloadFlag = GetAudioEffectOffloadFlag(); 7636 AUDIO_INFO_LOG("spatialization: %{public}d, headTracking: %{public}d, effectOffloadFlag: %{public}d", 7637 spatialState.spatializationEnabled, spatialState.headTrackingEnabled, effectOffloadFlag); 7638 if (spatialState.spatializationEnabled) { 7639 if (effectOffloadFlag) { 7640 for (auto it = allSessions.begin(); it != allSessions.end(); it++) { 7641 OffloadStreamSetCheck(*it); 7642 } 7643 } else { 7644 OffloadStreamReleaseCheck(*offloadSessionID_); 7645 } 7646 } 7647 } 7648 #endif 7649 HandleA2dpDeviceOutOffload(BluetoothOffloadState a2dpOffloadFlag)7650 int32_t AudioPolicyService::HandleA2dpDeviceOutOffload(BluetoothOffloadState a2dpOffloadFlag) 7651 { 7652 #ifdef BLUETOOTH_ENABLE 7653 AUDIO_INFO_LOG("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_, a2dpOffloadFlag); 7654 std::vector<int32_t> allSessions; 7655 GetAllRunningStreamSession(allSessions); 7656 OffloadStopPlaying(allSessions); 7657 a2dpOffloadFlag_ = a2dpOffloadFlag; 7658 7659 DeviceType dev = GetActiveOutputDevice(); 7660 UpdateEffectDefaultSink(dev); 7661 AUDIO_INFO_LOG("Handle A2dpDevice Out Offload"); 7662 7663 FetchStreamForA2dpOffload(true); 7664 7665 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_A2DP) { 7666 return HandleActiveDevice(DEVICE_TYPE_BLUETOOTH_A2DP); 7667 } else { 7668 return SUCCESS; 7669 } 7670 #else 7671 return ERROR; 7672 #endif 7673 } 7674 HandleA2dpDeviceInOffload(BluetoothOffloadState a2dpOffloadFlag)7675 int32_t AudioPolicyService::HandleA2dpDeviceInOffload(BluetoothOffloadState a2dpOffloadFlag) 7676 { 7677 #ifdef BLUETOOTH_ENABLE 7678 AUDIO_INFO_LOG("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_, a2dpOffloadFlag); 7679 a2dpOffloadFlag_ = a2dpOffloadFlag; 7680 GetA2dpOffloadCodecAndSendToDsp(); 7681 std::vector<int32_t> allSessions; 7682 GetAllRunningStreamSession(allSessions); 7683 OffloadStartPlaying(allSessions); 7684 7685 DeviceType dev = GetActiveOutputDevice(); 7686 UpdateEffectDefaultSink(dev); 7687 AUDIO_INFO_LOG("Handle A2dpDevice In Offload"); 7688 UpdateEffectBtOffloadSupported(true); 7689 7690 if (IsA2dpOffloadConnected()) { 7691 AUDIO_INFO_LOG("A2dpOffload has been connected, Fetch stream"); 7692 FetchStreamForA2dpOffload(true); 7693 } 7694 7695 std::string activePort = BLUETOOTH_SPEAKER; 7696 audioPolicyManager_.SuspendAudioDevice(activePort, true); 7697 return SUCCESS; 7698 #else 7699 return ERROR; 7700 #endif 7701 } 7702 GetAllRunningStreamSession(std::vector<int32_t> & allSessions,bool doStop)7703 void AudioPolicyService::GetAllRunningStreamSession(std::vector<int32_t> &allSessions, bool doStop) 7704 { 7705 #ifdef BLUETOOTH_ENABLE 7706 vector<unique_ptr<AudioRendererChangeInfo>> rendererChangeInfos; 7707 streamCollector_.GetCurrentRendererChangeInfos(rendererChangeInfos); 7708 std::vector<int32_t> stopPlayingStream(0); 7709 for (auto &changeInfo : rendererChangeInfos) { 7710 if (changeInfo->rendererState != RENDERER_RUNNING) { 7711 if (doStop) { 7712 stopPlayingStream.push_back(changeInfo->sessionId); 7713 } 7714 continue; 7715 } 7716 allSessions.push_back(changeInfo->sessionId); 7717 } 7718 if (doStop && stopPlayingStream.size() > 0) { 7719 OffloadStopPlaying(stopPlayingStream); 7720 } 7721 #endif 7722 } 7723 UpdateAllUserSelectDevice(vector<unique_ptr<AudioDeviceDescriptor>> & userSelectDeviceMap,AudioDeviceDescriptor & desc,const sptr<AudioDeviceDescriptor> & selectDesc)7724 void AudioPolicyService::UpdateAllUserSelectDevice(vector<unique_ptr<AudioDeviceDescriptor>> &userSelectDeviceMap, 7725 AudioDeviceDescriptor &desc, const sptr<AudioDeviceDescriptor> &selectDesc) 7726 { 7727 if (userSelectDeviceMap[MEDIA_RENDER_ID]->deviceType_ == desc.deviceType_ && 7728 userSelectDeviceMap[MEDIA_RENDER_ID]->macAddress_ == desc.macAddress_) { 7729 if (userSelectDeviceMap[MEDIA_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) { 7730 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor(selectDesc)); 7731 } else { 7732 audioStateManager_.UpdatePreferredMediaRenderDeviceConnectState(desc.connectState_); 7733 } 7734 } 7735 if (userSelectDeviceMap[CALL_RENDER_ID]->deviceType_ == desc.deviceType_ && 7736 userSelectDeviceMap[CALL_RENDER_ID]->macAddress_ == desc.macAddress_) { 7737 if (userSelectDeviceMap[CALL_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) { 7738 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor(selectDesc)); 7739 } else { 7740 audioStateManager_.UpdatePreferredCallRenderDeviceConnectState(desc.connectState_); 7741 } 7742 } 7743 if (userSelectDeviceMap[CALL_CAPTURE_ID]->deviceType_ == desc.deviceType_ && 7744 userSelectDeviceMap[CALL_CAPTURE_ID]->macAddress_ == desc.macAddress_) { 7745 if (userSelectDeviceMap[CALL_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) { 7746 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor(selectDesc)); 7747 } else { 7748 audioStateManager_.UpdatePreferredCallCaptureDeviceConnectState(desc.connectState_); 7749 } 7750 } 7751 if (userSelectDeviceMap[RECORD_CAPTURE_ID]->deviceType_ == desc.deviceType_ && 7752 userSelectDeviceMap[RECORD_CAPTURE_ID]->macAddress_ == desc.macAddress_) { 7753 if (userSelectDeviceMap[RECORD_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) { 7754 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor(selectDesc)); 7755 } else { 7756 audioStateManager_.UpdatePreferredRecordCaptureDeviceConnectState(desc.connectState_); 7757 } 7758 } 7759 } 7760 OnPreferredStateUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand updateCommand,AudioStreamDeviceChangeReasonExt & reason)7761 void AudioPolicyService::OnPreferredStateUpdated(AudioDeviceDescriptor &desc, 7762 const DeviceInfoUpdateCommand updateCommand, AudioStreamDeviceChangeReasonExt &reason) 7763 { 7764 AudioStateManager& stateManager = AudioStateManager::GetAudioStateManager(); 7765 unique_ptr<AudioDeviceDescriptor> userSelectMediaRenderDevice = stateManager.GetPreferredMediaRenderDevice(); 7766 unique_ptr<AudioDeviceDescriptor> userSelectCallRenderDevice = stateManager.GetPreferredCallRenderDevice(); 7767 unique_ptr<AudioDeviceDescriptor> userSelectCallCaptureDevice = stateManager.GetPreferredCallCaptureDevice(); 7768 unique_ptr<AudioDeviceDescriptor> userSelectRecordCaptureDevice = stateManager.GetPreferredRecordCaptureDevice(); 7769 vector<unique_ptr<AudioDeviceDescriptor>> userSelectDeviceMap; 7770 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectMediaRenderDevice)); 7771 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectCallRenderDevice)); 7772 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectCallCaptureDevice)); 7773 userSelectDeviceMap.push_back(make_unique<AudioDeviceDescriptor>(*userSelectRecordCaptureDevice)); 7774 if (updateCommand == CATEGORY_UPDATE) { 7775 if (desc.deviceCategory_ == BT_UNWEAR_HEADPHONE) { 7776 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; 7777 UpdateAllUserSelectDevice(userSelectDeviceMap, desc, new(std::nothrow) AudioDeviceDescriptor()); 7778 #ifdef BLUETOOTH_ENABLE 7779 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && 7780 desc.macAddress_ == GetCurrentOutputDeviceMacAddr()) { 7781 Bluetooth::AudioA2dpManager::SetActiveA2dpDevice(""); 7782 } else if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && 7783 desc.macAddress_ == GetCurrentOutputDeviceMacAddr()) { 7784 Bluetooth::AudioHfpManager::DisconnectSco(); 7785 } 7786 #endif 7787 } else { 7788 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE; 7789 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) { 7790 SetPreferredDevice(AUDIO_MEDIA_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 7791 SetPreferredDevice(AUDIO_RECORD_CAPTURE, new(std::nothrow) AudioDeviceDescriptor()); 7792 } else { 7793 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 7794 SetPreferredDevice(AUDIO_CALL_CAPTURE, new(std::nothrow) AudioDeviceDescriptor()); 7795 ClearScoDeviceSuspendState(desc.macAddress_); 7796 #ifdef BLUETOOTH_ENABLE 7797 CheckAndActiveHfpDevice(desc); 7798 #endif 7799 } 7800 } 7801 } else if (updateCommand == ENABLE_UPDATE) { 7802 UpdateAllUserSelectDevice(userSelectDeviceMap, desc, new(std::nothrow) AudioDeviceDescriptor(desc)); 7803 reason = desc.isEnable_ ? AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE : 7804 AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE; 7805 } 7806 } 7807 7808 #ifdef BLUETOOTH_ENABLE CheckAndActiveHfpDevice(AudioDeviceDescriptor & desc)7809 void AudioPolicyService::CheckAndActiveHfpDevice(AudioDeviceDescriptor &desc) 7810 { 7811 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 7812 AudioRendererInfo rendererInfo = {}; 7813 rendererInfo.streamUsage = STREAM_USAGE_VOICE_COMMUNICATION; 7814 std::vector<sptr<AudioDeviceDescriptor>> preferredDeviceList = 7815 GetPreferredOutputDeviceDescInner(rendererInfo); 7816 if (preferredDeviceList.size() > 0 && 7817 preferredDeviceList[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 7818 Bluetooth::AudioHfpManager::SetActiveHfpDevice(preferredDeviceList[0]->macAddress_); 7819 } 7820 } 7821 } 7822 #endif 7823 OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)7824 void AudioPolicyService::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command) 7825 { 7826 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 7827 7828 AUDIO_WARNING_LOG("[%{public}s] type[%{public}d] command: %{public}d category[%{public}d] " \ 7829 "connectState[%{public}d] isEnable[%{public}d]", GetEncryptAddr(desc.macAddress_).c_str(), 7830 desc.deviceType_, command, desc.deviceCategory_, desc.connectState_, desc.isEnable_); 7831 DeviceUpdateClearRecongnitionStatus(desc); 7832 if (command == ENABLE_UPDATE && desc.isEnable_ == true) { 7833 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 7834 ClearScoDeviceSuspendState(desc.macAddress_); 7835 } 7836 unique_ptr<AudioDeviceDescriptor> userSelectMediaDevice = 7837 AudioStateManager::GetAudioStateManager().GetPreferredMediaRenderDevice(); 7838 unique_ptr<AudioDeviceDescriptor> userSelectCallDevice = 7839 AudioStateManager::GetAudioStateManager().GetPreferredCallRenderDevice(); 7840 if ((userSelectMediaDevice->deviceType_ == desc.deviceType_ && 7841 userSelectMediaDevice->macAddress_ == desc.macAddress_ && 7842 userSelectMediaDevice->isEnable_ == desc.isEnable_) || 7843 (userSelectCallDevice->deviceType_ == desc.deviceType_ && 7844 userSelectCallDevice->macAddress_ == desc.macAddress_ && 7845 userSelectCallDevice->isEnable_ == desc.isEnable_)) { 7846 AUDIO_INFO_LOG("Current enable state has been set true during user selection, no need to be set again."); 7847 return; 7848 } 7849 } else if (command == ENABLE_UPDATE && !desc.isEnable_ && desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && 7850 GetCurrentOutputDeviceMacAddr() == desc.macAddress_) { 7851 UnloadA2dpModule(); 7852 } 7853 sptr<AudioDeviceDescriptor> audioDescriptor = new(std::nothrow) AudioDeviceDescriptor(desc); 7854 audioDeviceManager_.UpdateDevicesListInfo(audioDescriptor, command); 7855 CheckForA2dpSuspend(desc); 7856 7857 // VGS feature 7858 if ((desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) && (desc.connectState_ == ConnectState::CONNECTED)) { 7859 // 鎶婃槸鍚︽敮鎸乂GS淇濆瓨鍒伴煶棰戝唴閮? 7860 audioPolicyManager_.SetVgsVolumeSupported(desc.isVgsSupported_); 7861 if (desc.isVgsSupported_) { 7862 int currentVolume = GetSystemVolumeLevel(STREAM_VOICE_CALL); 7863 AUDIO_INFO_LOG("currentVolume: %{public}d", currentVolume); 7864 SetSystemVolumeLevel(STREAM_VOICE_CALL, currentVolume); 7865 } 7866 } else { 7867 audioPolicyManager_.SetVgsVolumeSupported(false); 7868 } 7869 7870 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN; 7871 OnPreferredStateUpdated(desc, command, reason); 7872 FetchDevice(true, reason); 7873 FetchDevice(false); 7874 UpdateA2dpOffloadFlagForAllStream(); 7875 } 7876 DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor & desc)7877 void AudioPolicyService::DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor &desc) 7878 { 7879 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && (desc.deviceCategory_ == BT_UNWEAR_HEADPHONE || 7880 desc.connectState_ == DEACTIVE_CONNECTED || desc.connectState_ == SUSPEND_CONNECTED || !desc.isEnable_)) { 7881 BluetoothScoDisconectForRecongnition(); 7882 Bluetooth::AudioHfpManager::ClearRecongnitionStatus(); 7883 } 7884 } 7885 CheckForA2dpSuspend(AudioDeviceDescriptor & desc)7886 void AudioPolicyService::CheckForA2dpSuspend(AudioDeviceDescriptor &desc) 7887 { 7888 if (desc.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) { 7889 return; 7890 } 7891 7892 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 7893 CHECK_AND_RETURN_LOG(gsp != nullptr, "Service proxy unavailable"); 7894 7895 std::string identity = IPCSkeleton::ResetCallingIdentity(); 7896 if (audioDeviceManager_.GetScoState()) { 7897 gsp->SuspendRenderSink("a2dp"); 7898 } else { 7899 gsp->RestoreRenderSink("a2dp"); 7900 } 7901 IPCSkeleton::SetCallingIdentity(identity); 7902 } 7903 UpdateOffloadWhenActiveDeviceSwitchFromA2dp()7904 void AudioPolicyService::UpdateOffloadWhenActiveDeviceSwitchFromA2dp() 7905 { 7906 AUDIO_PRERELEASE_LOGI("a2dpOffloadFlag_ change from %{public}d to %{public}d", a2dpOffloadFlag_, NO_A2DP_DEVICE); 7907 std::vector<int32_t> allSessions; 7908 GetAllRunningStreamSession(allSessions); 7909 OffloadStopPlaying(allSessions); 7910 a2dpOffloadFlag_ = NO_A2DP_DEVICE; 7911 for (auto it = allSessions.begin(); it != allSessions.end(); ++it) { 7912 ResetOffloadMode(*it); 7913 } 7914 } 7915 SetCallDeviceActive(InternalDeviceType deviceType,bool active,std::string address)7916 int32_t AudioPolicyService::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address) 7917 { 7918 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 7919 7920 AUDIO_WARNING_LOG("Device type[%{public}d] flag[%{public}d] address[%{public}s]", 7921 deviceType, active, GetEncryptAddr(address).c_str()); 7922 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device"); 7923 7924 // Activate new device if its already connected 7925 auto isPresent = [&deviceType, &address] (const unique_ptr<AudioDeviceDescriptor> &desc) { 7926 CHECK_AND_RETURN_RET_LOG(desc != nullptr, false, "Invalid device descriptor"); 7927 return ((deviceType == desc->deviceType_) && (address == desc->macAddress_)); 7928 }; 7929 7930 vector<unique_ptr<AudioDeviceDescriptor>> callDevices = GetAvailableDevicesInner(CALL_OUTPUT_DEVICES); 7931 7932 auto itr = std::find_if(callDevices.begin(), callDevices.end(), isPresent); 7933 CHECK_AND_RETURN_RET_LOG(itr != callDevices.end(), ERR_OPERATION_FAILED, 7934 "Requested device not available %{public}d ", deviceType); 7935 if (active) { 7936 if (deviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 7937 (*itr)->isEnable_ = true; 7938 audioDeviceManager_.UpdateDevicesListInfo(new(std::nothrow) AudioDeviceDescriptor(**itr), ENABLE_UPDATE); 7939 ClearScoDeviceSuspendState(address); 7940 } 7941 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor(**itr)); 7942 #ifdef BLUETOOTH_ENABLE 7943 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO && 7944 deviceType != DEVICE_TYPE_BLUETOOTH_SCO) { 7945 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO, 7946 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT); 7947 Bluetooth::AudioHfpManager::DisconnectSco(); 7948 } 7949 if (GetCurrentOutputDeviceType() != DEVICE_TYPE_BLUETOOTH_SCO && 7950 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 7951 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO, 7952 (*itr)->macAddress_, USER_SELECT_BT); 7953 } 7954 #endif 7955 } else { 7956 SetPreferredDevice(AUDIO_CALL_RENDER, new(std::nothrow) AudioDeviceDescriptor()); 7957 #ifdef BLUETOOTH_ENABLE 7958 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_BLUETOOTH_SCO && 7959 deviceType == DEVICE_TYPE_BLUETOOTH_SCO) { 7960 Bluetooth::SendUserSelectionEvent(DEVICE_TYPE_BLUETOOTH_SCO, 7961 GetCurrentOutputDeviceMacAddr(), USER_NOT_SELECT_BT); 7962 Bluetooth::AudioHfpManager::DisconnectSco(); 7963 } 7964 #endif 7965 } 7966 FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE); 7967 return SUCCESS; 7968 } 7969 GetActiveBluetoothDevice()7970 std::unique_ptr<AudioDeviceDescriptor> AudioPolicyService::GetActiveBluetoothDevice() 7971 { 7972 std::shared_lock deviceLock(deviceStatusUpdateSharedMutex_); 7973 7974 unique_ptr<AudioDeviceDescriptor> preferredDesc = audioStateManager_.GetPreferredCallRenderDevice(); 7975 if (preferredDesc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) { 7976 return preferredDesc; 7977 } 7978 7979 std::vector<unique_ptr<AudioDeviceDescriptor>> audioPrivacyDeviceDescriptors = 7980 audioDeviceManager_.GetCommRenderPrivacyDevices(); 7981 std::vector<unique_ptr<AudioDeviceDescriptor>> activeDeviceDescriptors; 7982 7983 for (auto &desc : audioPrivacyDeviceDescriptors) { 7984 if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && desc->isEnable_) { 7985 activeDeviceDescriptors.push_back(make_unique<AudioDeviceDescriptor>(*desc)); 7986 } 7987 } 7988 7989 uint32_t btDeviceSize = activeDeviceDescriptors.size(); 7990 if (btDeviceSize == 0) { 7991 activeDeviceDescriptors = audioDeviceManager_.GetCommRenderBTCarDevices(); 7992 } 7993 btDeviceSize = activeDeviceDescriptors.size(); 7994 if (btDeviceSize == 0) { 7995 return make_unique<AudioDeviceDescriptor>(); 7996 } else if (btDeviceSize == 1) { 7997 unique_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[0]); 7998 return res; 7999 } 8000 8001 uint32_t index = 0; 8002 for (uint32_t i = 1; i < btDeviceSize; ++i) { 8003 if (activeDeviceDescriptors[i]->connectTimeStamp_ > 8004 activeDeviceDescriptors[index]->connectTimeStamp_) { 8005 index = i; 8006 } 8007 } 8008 unique_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[index]); 8009 return res; 8010 } 8011 GetConverterConfig()8012 ConverterConfig AudioPolicyService::GetConverterConfig() 8013 { 8014 AudioConverterParser &converterParser = AudioConverterParser::GetInstance(); 8015 return converterParser.LoadConfig(); 8016 } 8017 ClearScoDeviceSuspendState(string macAddress)8018 void AudioPolicyService::ClearScoDeviceSuspendState(string macAddress) 8019 { 8020 AUDIO_DEBUG_LOG("Clear sco suspend state %{public}s", GetEncryptAddr(macAddress).c_str()); 8021 vector<shared_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetDevicesByFilter( 8022 DEVICE_TYPE_BLUETOOTH_SCO, DEVICE_ROLE_NONE, macAddress, "", SUSPEND_CONNECTED); 8023 for (auto &desc : descs) { 8024 desc->connectState_ = DEACTIVE_CONNECTED; 8025 } 8026 } 8027 GetMaxAmplitude(const int32_t deviceId)8028 float AudioPolicyService::GetMaxAmplitude(const int32_t deviceId) 8029 { 8030 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 8031 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, 0, "Service proxy unavailable"); 8032 8033 if (deviceId == GetCurrentOutputDevice().deviceId_) { 8034 std::string identity = IPCSkeleton::ResetCallingIdentity(); 8035 float outputMaxAmplitude = gsp->GetMaxAmplitude(true, GetCurrentOutputDeviceType()); 8036 IPCSkeleton::SetCallingIdentity(identity); 8037 return outputMaxAmplitude; 8038 } 8039 8040 if (deviceId == GetCurrentInputDevice().deviceId_) { 8041 std::string identity = IPCSkeleton::ResetCallingIdentity(); 8042 float inputMaxAmplitude = gsp->GetMaxAmplitude(false, GetCurrentInputDeviceType()); 8043 IPCSkeleton::SetCallingIdentity(identity); 8044 return inputMaxAmplitude; 8045 } 8046 8047 return 0; 8048 } 8049 OpenPortAndInsertIOHandle(const std::string & moduleName,const AudioModuleInfo & moduleInfo)8050 int32_t AudioPolicyService::OpenPortAndInsertIOHandle(const std::string &moduleName, 8051 const AudioModuleInfo &moduleInfo) 8052 { 8053 AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo); 8054 CHECK_AND_RETURN_RET_LOG(ioHandle != OPEN_PORT_FAILURE, ERR_INVALID_HANDLE, "OpenAudioPort failed %{public}d", 8055 ioHandle); 8056 8057 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 8058 IOHandles_[moduleName] = ioHandle; 8059 8060 return SUCCESS; 8061 } 8062 ClosePortAndEraseIOHandle(const std::string & moduleName)8063 int32_t AudioPolicyService::ClosePortAndEraseIOHandle(const std::string &moduleName) 8064 { 8065 AudioIOHandle ioHandle; 8066 { 8067 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 8068 auto ioHandleIter = IOHandles_.find(moduleName); 8069 CHECK_AND_RETURN_RET_LOG(ioHandleIter != IOHandles_.end(), ERROR, 8070 "can not find %{public}s in io map", moduleName.c_str()); 8071 ioHandle = ioHandleIter->second; 8072 IOHandles_.erase(moduleName); 8073 } 8074 AUDIO_INFO_LOG("[close-module] %{public}s,id:%{public}d", moduleName.c_str(), ioHandle); 8075 int32_t result = audioPolicyManager_.CloseAudioPort(ioHandle); 8076 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "CloseAudioPort failed %{public}d", result); 8077 return SUCCESS; 8078 } 8079 GetDeviceUsage(const AudioDeviceDescriptor & desc)8080 DeviceUsage AudioPolicyService::GetDeviceUsage(const AudioDeviceDescriptor &desc) 8081 { 8082 return audioDeviceManager_.GetDeviceUsage(desc); 8083 } 8084 HandleRemoteCastDevice(bool isConnected,AudioStreamInfo streamInfo)8085 void AudioPolicyService::HandleRemoteCastDevice(bool isConnected, AudioStreamInfo streamInfo) 8086 { 8087 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 8088 8089 AudioDeviceDescriptor updatedDesc = AudioDeviceDescriptor(DEVICE_TYPE_REMOTE_CAST, 8090 GetDeviceRole(DEVICE_TYPE_REMOTE_CAST)); 8091 std::vector<sptr<AudioDeviceDescriptor>> descForCb = {}; 8092 auto isPresent = [&updatedDesc] (const sptr<AudioDeviceDescriptor> &descriptor) { 8093 return descriptor->deviceType_ == updatedDesc.deviceType_ && 8094 descriptor->macAddress_ == updatedDesc.macAddress_ && 8095 descriptor->networkId_ == updatedDesc.networkId_; 8096 }; 8097 if (isConnected) { 8098 // If device already in list, remove it else do not modify the list 8099 connectedDevices_.erase(std::remove_if(connectedDevices_.begin(), connectedDevices_.end(), isPresent), 8100 connectedDevices_.end()); 8101 UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb); 8102 LoadInnerCapturerSink(REMOTE_CAST_INNER_CAPTURER_SINK_NAME, streamInfo); 8103 audioPolicyManager_.ResetRemoteCastDeviceVolume(); 8104 } else { 8105 UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb); 8106 FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::OLD_DEVICE_UNAVALIABLE_EXT); 8107 UnloadInnerCapturerSink(REMOTE_CAST_INNER_CAPTURER_SINK_NAME); 8108 } 8109 FetchDevice(true); 8110 FetchDevice(false); 8111 8112 // update a2dp offload 8113 UpdateA2dpOffloadFlagForAllStream(); 8114 } 8115 TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)8116 int32_t AudioPolicyService::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason) 8117 { 8118 std::lock_guard<std::shared_mutex> deviceLock(deviceStatusUpdateSharedMutex_); 8119 FetchDevice(true, reason); 8120 FetchDevice(false, reason); 8121 8122 // update a2dp offload 8123 UpdateA2dpOffloadFlagForAllStream(); 8124 return SUCCESS; 8125 } 8126 SetDeviceSafeVolumeStatus()8127 void AudioPolicyService::SetDeviceSafeVolumeStatus() 8128 { 8129 if (!userSelect_) { 8130 return; 8131 } 8132 8133 DeviceType curOutputDeviceType = GetCurrentOutputDeviceType(); 8134 switch (curOutputDeviceType) { 8135 case DEVICE_TYPE_BLUETOOTH_A2DP: 8136 case DEVICE_TYPE_BLUETOOTH_SCO: 8137 safeStatusBt_ = SAFE_INACTIVE; 8138 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_); 8139 CreateCheckMusicActiveThread(); 8140 break; 8141 case DEVICE_TYPE_WIRED_HEADSET: 8142 case DEVICE_TYPE_WIRED_HEADPHONES: 8143 case DEVICE_TYPE_USB_HEADSET: 8144 case DEVICE_TYPE_USB_ARM_HEADSET: 8145 case DEVICE_TYPE_DP: 8146 safeStatus_ = SAFE_INACTIVE; 8147 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_); 8148 CreateCheckMusicActiveThread(); 8149 break; 8150 default: 8151 AUDIO_INFO_LOG("safeVolume unsupported device:%{public}d", curOutputDeviceType); 8152 break; 8153 } 8154 } 8155 DisableSafeMediaVolume()8156 int32_t AudioPolicyService::DisableSafeMediaVolume() 8157 { 8158 AUDIO_INFO_LOG("Enter"); 8159 std::lock_guard<std::mutex> lock(dialogMutex_); 8160 userSelect_ = true; 8161 isDialogSelectDestroy_.store(true); 8162 dialogSelectCondition_.notify_all(); 8163 SetDeviceSafeVolumeStatus(); 8164 return SUCCESS; 8165 } 8166 SafeVolumeDialogDisapper()8167 int32_t AudioPolicyService::SafeVolumeDialogDisapper() 8168 { 8169 AUDIO_INFO_LOG("Enter"); 8170 std::lock_guard<std::mutex> lock(dialogMutex_); 8171 isSafeVolumeDialogShowing_.store(false); 8172 dialogSelectCondition_.notify_all(); 8173 SetDeviceSafeVolumeStatus(); 8174 return SUCCESS; 8175 } 8176 GetSafeVolumeDump(std::string & dumpString)8177 void AudioPolicyService::GetSafeVolumeDump(std::string &dumpString) 8178 { 8179 audioPolicyManager_.SafeVolumeDump(dumpString); 8180 } 8181 DevicesInfoDump(std::string & dumpString)8182 void AudioPolicyService::DevicesInfoDump(std::string &dumpString) 8183 { 8184 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors; 8185 8186 dumpString += "\nInput local Devices:\n"; 8187 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, INPUT_DEVICES_FLAG); 8188 AppendFormat(dumpString, "- %zu Input Devices (s) available\n", audioDeviceDescriptors.size()); 8189 8190 dumpString += "\nOutput local Devices:\n"; 8191 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, OUTPUT_DEVICES_FLAG); 8192 AppendFormat(dumpString, "- %zu output Devices (s) available\n", audioDeviceDescriptors.size()); 8193 8194 dumpString += "\nInput distributed Devices:\n"; 8195 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, DISTRIBUTED_INPUT_DEVICES_FLAG); 8196 AppendFormat(dumpString, "- %zu output Devices (s) available\n", audioDeviceDescriptors.size()); 8197 8198 dumpString += "\nOutput distributed Devices:\n"; 8199 audioDeviceDescriptors = GetDumpDeviceInfo(dumpString, DISTRIBUTED_OUTPUT_DEVICES_FLAG); 8200 AppendFormat(dumpString, "- %zu output Devices (s) available\n", audioDeviceDescriptors.size()); 8201 8202 priorityOutputDevice_ = GetActiveOutputDevice(); 8203 priorityInputDevice_ = GetActiveInputDevice(); 8204 AppendFormat(dumpString, "\nHighest priority output device: %s", 8205 AudioInfoDumpUtils::GetDeviceTypeName(priorityOutputDevice_).c_str()); 8206 AppendFormat(dumpString, "\nHighest priority input device: %s \n", 8207 AudioInfoDumpUtils::GetDeviceTypeName(priorityInputDevice_).c_str()); 8208 8209 GetMicrophoneDescriptorsDump(dumpString); 8210 GetOffloadStatusDump(dumpString); 8211 } 8212 GetDumpDeviceInfo(std::string & dumpString,DeviceFlag deviceFlag)8213 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDumpDeviceInfo(std::string &dumpString, 8214 DeviceFlag deviceFlag) 8215 { 8216 std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = GetDumpDevices(deviceFlag); 8217 8218 for (auto &desc : deviceDescs) { 8219 sptr<AudioDeviceDescriptor> devDesc = new(std::nothrow) AudioDeviceDescriptor(*desc); 8220 dumpString += "\n"; 8221 AppendFormat(dumpString, " - device name:%s\n", 8222 AudioInfoDumpUtils::GetDeviceTypeName(devDesc->deviceType_).c_str()); 8223 AppendFormat(dumpString, " - device type:%d\n", devDesc->deviceType_); 8224 AppendFormat(dumpString, " - device id:%d\n", devDesc->deviceId_); 8225 AppendFormat(dumpString, " - device role:%d\n", devDesc->deviceRole_); 8226 AppendFormat(dumpString, " - device name:%s\n", devDesc->deviceName_.c_str()); 8227 AppendFormat(dumpString, " - device mac:%s\n", GetEncryptAddr(devDesc->macAddress_).c_str()); 8228 AppendFormat(dumpString, " - device network:%s\n", devDesc->networkId_.c_str()); 8229 if (deviceFlag == DeviceFlag::INPUT_DEVICES_FLAG || deviceFlag == DeviceFlag::OUTPUT_DEVICES_FLAG) { 8230 conneceType_ = CONNECT_TYPE_LOCAL; 8231 } else if (deviceFlag == DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG || 8232 deviceFlag == DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG) { 8233 conneceType_ = CONNECT_TYPE_DISTRIBUTED; 8234 } 8235 AppendFormat(dumpString, " - connect type:%s\n", AudioInfoDumpUtils::GetConnectTypeName(conneceType_).c_str()); 8236 for (auto &samplingRate : devDesc->audioStreamInfo_.samplingRate) { 8237 AppendFormat(dumpString, " - device sampleRates:%d\n", samplingRate); 8238 } 8239 for (auto &channel : devDesc->audioStreamInfo_.channels) { 8240 AppendFormat(dumpString, " - device channels:%d\n", channel); 8241 } 8242 AppendFormat(dumpString, " - device format:%d\n", devDesc->audioStreamInfo_.format); 8243 } 8244 return deviceDescs; 8245 } 8246 GetDumpDevices(DeviceFlag deviceFlag)8247 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyService::GetDumpDevices(DeviceFlag deviceFlag) 8248 { 8249 bool hasSystemPermission = PermissionUtil::VerifySystemPermission(); 8250 switch (deviceFlag) { 8251 case NONE_DEVICES_FLAG: 8252 case DISTRIBUTED_OUTPUT_DEVICES_FLAG: 8253 case DISTRIBUTED_INPUT_DEVICES_FLAG: 8254 case ALL_DISTRIBUTED_DEVICES_FLAG: 8255 case ALL_L_D_DEVICES_FLAG: 8256 if (!hasSystemPermission) { 8257 AUDIO_ERR_LOG("GetDevices: No system permission"); 8258 std::vector<sptr<AudioDeviceDescriptor>> info = {}; 8259 return info; 8260 } 8261 break; 8262 default: 8263 break; 8264 } 8265 8266 std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = GetDevices(deviceFlag); 8267 8268 if (!hasSystemPermission) { 8269 for (sptr<AudioDeviceDescriptor> desc : deviceDescs) { 8270 desc->networkId_ = ""; 8271 desc->interruptGroupId_ = GROUP_ID_NONE; 8272 desc->volumeGroupId_ = GROUP_ID_NONE; 8273 } 8274 } 8275 return deviceDescs; 8276 } 8277 AudioModeDump(std::string & dumpString)8278 void AudioPolicyService::AudioModeDump(std::string &dumpString) 8279 { 8280 GetCallStatusDump(dumpString); 8281 GetRingerModeDump(dumpString); 8282 } 8283 GetCallStatusDump(std::string & dumpString)8284 void AudioPolicyService::GetCallStatusDump(std::string &dumpString) 8285 { 8286 dumpString += "\nAudio Scene:"; 8287 bool hasSystemPermission = PermissionUtil::VerifySystemPermission(); 8288 AudioScene callStatus = GetAudioScene(hasSystemPermission); 8289 switch (callStatus) { 8290 case AUDIO_SCENE_DEFAULT: 8291 dumpString += "DEFAULT"; 8292 break; 8293 case AUDIO_SCENE_RINGING: 8294 dumpString += "RINGING"; 8295 break; 8296 case AUDIO_SCENE_PHONE_CALL: 8297 dumpString += "PHONE_CALL"; 8298 break; 8299 case AUDIO_SCENE_PHONE_CHAT: 8300 dumpString += "PHONE_CHAT"; 8301 break; 8302 default: 8303 dumpString += "UNKNOWN"; 8304 } 8305 dumpString += "\n"; 8306 } 8307 GetRingerModeDump(std::string & dumpString)8308 void AudioPolicyService::GetRingerModeDump(std::string &dumpString) 8309 { 8310 dumpString += "Ringer Mode:"; 8311 AudioRingerMode ringerMode = GetRingerMode(); 8312 switch (ringerMode) { 8313 case RINGER_MODE_NORMAL: 8314 dumpString += "NORMAL"; 8315 break; 8316 case RINGER_MODE_SILENT: 8317 dumpString += "SILENT"; 8318 break; 8319 case RINGER_MODE_VIBRATE: 8320 dumpString += "VIBRATE"; 8321 break; 8322 default: 8323 dumpString += "UNKNOWN"; 8324 } 8325 dumpString += "\n\n"; 8326 } 8327 GetMicrophoneDescriptorsDump(std::string & dumpString)8328 void AudioPolicyService::GetMicrophoneDescriptorsDump(std::string &dumpString) 8329 { 8330 dumpString += "\nAvailable MicrophoneDescriptors:\n"; 8331 8332 std::vector<sptr<MicrophoneDescriptor>> micDescs = GetAvailableMicrophones(); 8333 for (auto it = micDescs.begin(); 8334 it != micDescs.end(); ++it) { 8335 AppendFormat(dumpString, " - id:%d \n", (*it)->micId_); 8336 AppendFormat(dumpString, " - device type:%d \n", (*it)->deviceType_); 8337 AppendFormat(dumpString, " - group id:%d \n", (*it)->groupId_); 8338 AppendFormat(dumpString, " - sensitivity:%d \n", (*it)->sensitivity_); 8339 AppendFormat(dumpString, " - position:%f %f %f (x, y, z)\n", 8340 (*it)->position_.x, (*it)->position_.y, (*it)->position_.z); 8341 AppendFormat(dumpString, " - orientation:%f %f %f (x, y, z)\n", 8342 (*it)->orientation_.x, (*it)->orientation_.y, (*it)->orientation_.z); 8343 } 8344 } 8345 AudioPolicyParserDump(std::string & dumpString)8346 void AudioPolicyService::AudioPolicyParserDump(std::string &dumpString) 8347 { 8348 dumpString += "\nAudioPolicyParser:\n"; 8349 GetAudioAdapterInfos(adapterInfoMap_); 8350 GetVolumeGroupData(volumeGroupData_); 8351 GetInterruptGroupData(interruptGroupData_); 8352 GetGlobalConfigs(globalConfigs_); 8353 for (auto &[adapterType, adapterInfo] : adapterInfoMap_) { 8354 AppendFormat(dumpString, " - adapter : %s -- adapterType:%u\n", adapterInfo.adapterName_.c_str(), adapterType); 8355 for (auto &deviceInfo : adapterInfo.deviceInfos_) { 8356 AppendFormat(dumpString, " - device -- name:%s, pin:%s, type:%s, role:%s\n", deviceInfo.name_.c_str(), 8357 deviceInfo.pin_.c_str(), deviceInfo.type_.c_str(), deviceInfo.role_.c_str()); 8358 } 8359 for (auto &pipeInfo : adapterInfo.pipeInfos_) { 8360 AppendFormat(dumpString, " - module : -- name:%s, pipeRole:%s, pipeFlags:%s, lib:%s, paPropRole:%s, " 8361 "fixedLatency:%s, renderInIdleState:%s\n", pipeInfo.name_.c_str(), 8362 pipeInfo.pipeRole_.c_str(), pipeInfo.pipeFlags_.c_str(), pipeInfo.lib_.c_str(), 8363 pipeInfo.paPropRole_.c_str(), pipeInfo.fixedLatency_.c_str(), pipeInfo.renderInIdleState_.c_str()); 8364 8365 for (auto &configInfo : pipeInfo.configInfos_) { 8366 AppendFormat(dumpString, " - config : -- name:%s, value:%s\n", configInfo.name_.c_str(), 8367 configInfo.value_.c_str()); 8368 } 8369 } 8370 } 8371 for (auto& volume : volumeGroupData_) { 8372 AppendFormat(dumpString, " - volumeGroupMap_ first:%s, second:%s\n\n", volume.first.c_str(), 8373 volume.second.c_str()); 8374 } 8375 for (auto& interrupt : interruptGroupData_) { 8376 AppendFormat(dumpString, " - interruptGroupMap_ first:%s, second:%s\n", interrupt.first.c_str(), 8377 interrupt.second.c_str()); 8378 } 8379 AppendFormat(dumpString, " - globalConfig adapter:%s, pipe:%s, device:%s, updateRouteSupport:%d, " 8380 "audioLatency:%s, sinkLatency:%s\n", globalConfigs_.adapter_.c_str(), 8381 globalConfigs_.pipe_.c_str(), globalConfigs_.device_.c_str(), 8382 globalConfigs_.updateRouteSupport_, 8383 globalConfigs_.globalPaConfigs_.audioLatency_.c_str(), 8384 globalConfigs_.globalPaConfigs_.sinkLatency_.c_str()); 8385 for (auto &outputConfig : globalConfigs_.outputConfigInfos_) { 8386 AppendFormat(dumpString, " - output config name:%s, type:%s, value:%s\n", outputConfig.name_.c_str(), 8387 outputConfig.type_.c_str(), outputConfig.value_.c_str()); 8388 } 8389 for (auto &inputConfig : globalConfigs_.inputConfigInfos_) { 8390 AppendFormat(dumpString, " - input config name:%s, type_%s, value:%s\n\n", inputConfig.name_.c_str(), 8391 inputConfig.type_.c_str(), inputConfig.value_.c_str()); 8392 } 8393 AppendFormat(dumpString, " - module curActiveCount:%d\n\n", GetCurActivateCount()); 8394 } 8395 XmlParsedDataMapDump(std::string & dumpString)8396 void AudioPolicyService::XmlParsedDataMapDump(std::string &dumpString) 8397 { 8398 dumpString += "\nXmlParsedDataParser:\n"; 8399 8400 GetDeviceClassInfo(deviceClassInfo_); 8401 8402 for (auto &[adapterType, deviceClassInfos] : deviceClassInfo_) { 8403 AppendFormat(dumpString, " - DeviceClassInfo type %d\n", adapterType); 8404 for (auto &deviceClassInfo : deviceClassInfos) { 8405 AppendFormat(dumpString, " - Data : className:%s, name:%s, adapter:%s, id:%s, lib:%s, role:%s, rate:%s\n", 8406 deviceClassInfo.className.c_str(), deviceClassInfo.name.c_str(), 8407 deviceClassInfo.adapterName.c_str(), deviceClassInfo.id.c_str(), 8408 deviceClassInfo.lib.c_str(), deviceClassInfo.role.c_str(), deviceClassInfo.rate.c_str()); 8409 8410 for (auto rate : deviceClassInfo.supportedRate_) { 8411 AppendFormat(dumpString, " - rate:%u\n", rate); 8412 } 8413 8414 for (auto supportedChannel : deviceClassInfo.supportedChannels_) { 8415 AppendFormat(dumpString, " - supportedChannel:%u\n", supportedChannel); 8416 } 8417 8418 AppendFormat(dumpString, " -DeviceClassInfo : format:%s, channels:%s, bufferSize:%s, fixedLatency:%s, " 8419 " sinkLatency:%s, renderInIdleState:%s, OpenMicSpeaker:%s, fileName:%s, networkId:%s, " 8420 "deviceType:%s, sceneName:%s, sourceType:%s, offloadEnable:%s\n", 8421 deviceClassInfo.format.c_str(), deviceClassInfo.channels.c_str(), deviceClassInfo.bufferSize.c_str(), 8422 deviceClassInfo.fixedLatency.c_str(), deviceClassInfo.sinkLatency.c_str(), 8423 deviceClassInfo.renderInIdleState.c_str(), deviceClassInfo.OpenMicSpeaker.c_str(), 8424 deviceClassInfo.fileName.c_str(), deviceClassInfo.networkId.c_str(), deviceClassInfo.deviceType.c_str(), 8425 deviceClassInfo.sceneName.c_str(), deviceClassInfo.sourceType.c_str(), 8426 deviceClassInfo.offloadEnable.c_str()); 8427 } 8428 AppendFormat(dumpString, "-----EndOfXmlParsedDataMap-----\n"); 8429 } 8430 } 8431 StreamEffectSceneInfoDump(string & dumpString,const ProcessNew & processNew,const string processType)8432 static void StreamEffectSceneInfoDump(string &dumpString, const ProcessNew &processNew, const string processType) 8433 { 8434 int32_t count; 8435 AppendFormat(dumpString, "- %zu %s supported :\n", processNew.stream.size(), processType.c_str()); 8436 8437 for (Stream x : processNew.stream) { 8438 AppendFormat(dumpString, " %s stream scene = %s \n", processType.c_str(), x.scene.c_str()); 8439 count = 0; 8440 for (StreamEffectMode mode : x.streamEffectMode) { 8441 count++; 8442 AppendFormat(dumpString, " - modeName%d = %s \n", count, mode.mode.c_str()); 8443 int32_t n = 0; 8444 for (Device deviceInfo : mode.devicePort) { 8445 n++; 8446 AppendFormat(dumpString, " - device%d type = %s \n", n, deviceInfo.type.c_str()); 8447 AppendFormat(dumpString, " - device%d chain = %s \n", n, deviceInfo.chain.c_str()); 8448 } 8449 } 8450 dumpString += "\n"; 8451 } 8452 } 8453 EffectManagerInfoDump(string & dumpString)8454 void AudioPolicyService::EffectManagerInfoDump(string &dumpString) 8455 { 8456 int32_t count = 0; 8457 GetEffectManagerInfo(); 8458 GetAudioAdapterInfos(adapterInfoMap_); 8459 8460 dumpString += "==== Audio Effect Manager INFO ====\n"; 8461 8462 // effectChain info 8463 count = 0; 8464 AppendFormat(dumpString, "- system support %d effectChain(s):\n", 8465 supportedEffectConfig_.effectChains.size()); 8466 for (EffectChain x : supportedEffectConfig_.effectChains) { 8467 count++; 8468 AppendFormat(dumpString, " effectChain%d :\n", count); 8469 AppendFormat(dumpString, " - effectChain name = %s \n", x.name.c_str()); 8470 int32_t countEffect = 0; 8471 for (string effectUnit : x.apply) { 8472 countEffect++; 8473 AppendFormat(dumpString, " - effectUnit%d = %s \n", countEffect, effectUnit.c_str()); 8474 } 8475 dumpString += "\n"; 8476 } 8477 8478 // converter info 8479 AppendFormat(dumpString, "- system support audio converter for special streams:\n"); 8480 AppendFormat(dumpString, " - converter name: %s\n", converterConfig_.library.name.c_str()); 8481 AppendFormat(dumpString, " - converter out channel layout: %" PRId64 "\n", 8482 converterConfig_.outChannelLayout); 8483 dumpString += "\n"; 8484 8485 // preProcess info 8486 StreamEffectSceneInfoDump(dumpString, supportedEffectConfig_.preProcessNew, "preProcess"); 8487 dumpString += "\n"; 8488 // postProcess info 8489 StreamEffectSceneInfoDump(dumpString, supportedEffectConfig_.postProcessNew, "postProcess"); 8490 8491 // postProcess scene maping 8492 AppendFormat(dumpString, "- postProcess scene maping config:\n"); 8493 for (SceneMappingItem it: supportedEffectConfig_.postProcessSceneMap) { 8494 AppendFormat(dumpString, " - streamUsage: %s = %s \n", it.name.c_str(), it.sceneType.c_str()); 8495 } 8496 dumpString += "\n"; 8497 } 8498 MicrophoneMuteInfoDump(string & dumpString)8499 void AudioPolicyService::MicrophoneMuteInfoDump(string &dumpString) 8500 { 8501 dumpString += "==== Microphone Mute INFO ====\n"; 8502 // non-persistent microphone mute info 8503 AppendFormat(dumpString, " - non-persistent microphone isMuted: %d \n", isMicrophoneMuteTemporary_); 8504 // persistent microphone mute info 8505 AppendFormat(dumpString, " - persistent microphone isMuted: %d \n", isMicrophoneMutePersistent_); 8506 dumpString += "\n"; 8507 } 8508 GetGroupInfoDump(std::string & dumpString)8509 void AudioPolicyService::GetGroupInfoDump(std::string &dumpString) 8510 { 8511 dumpString += "\nVolume GroupInfo:\n"; 8512 // Get group info 8513 std::vector<sptr<VolumeGroupInfo>> groupInfos = GetVolumeGroupInfos(); 8514 AppendFormat(dumpString, "- %zu Group Infos (s) available :\n", groupInfos.size()); 8515 8516 for (auto it = groupInfos.begin(); it != groupInfos.end(); it++) { 8517 AppendFormat(dumpString, " Group Infos %d\n", it - groupInfos.begin() + 1); 8518 AppendFormat(dumpString, " - ConnectType(0 for Local, 1 for Remote): %d\n", (*it)->connectType_); 8519 AppendFormat(dumpString, " - Name: %s\n", (*it)->groupName_.c_str()); 8520 AppendFormat(dumpString, " - Id: %d\n", (*it)->volumeGroupId_); 8521 } 8522 dumpString += "\n"; 8523 } 8524 StreamVolumesDump(std::string & dumpString)8525 void AudioPolicyService::StreamVolumesDump(std::string &dumpString) 8526 { 8527 dumpString += "\nStream Volumes:\n"; 8528 // Get stream volumes 8529 std::map<AudioStreamType, int32_t> streamVolumes_; 8530 for (int stream = AudioStreamType::STREAM_VOICE_CALL; stream <= AudioStreamType::STREAM_TYPE_MAX; stream++) { 8531 AudioStreamType streamType = (AudioStreamType)stream; 8532 8533 if (IsStreamSupported(streamType)) { 8534 if (streamType == STREAM_ALL) { 8535 streamType = STREAM_MUSIC; 8536 AUDIO_DEBUG_LOG("GetVolume of STREAM_ALL for streamType = %{public}d ", streamType); 8537 } 8538 int32_t volume = GetSystemVolumeLevel(streamType); 8539 streamVolumes_.insert({ streamType, volume }); 8540 } 8541 } 8542 AppendFormat(dumpString, " [StreamName]: [Volume]\n"); 8543 for (auto it = streamVolumes_.cbegin(); it != streamVolumes_.cend(); 8544 ++it) { 8545 AppendFormat(dumpString, " - %s: %d\n", AudioInfoDumpUtils::GetStreamName(it->first).c_str(), it->second); 8546 } 8547 GetVolumeConfigDump(dumpString); 8548 GetGroupInfoDump(dumpString); 8549 GetSafeVolumeDump(dumpString); 8550 } 8551 IsStreamSupported(AudioStreamType streamType)8552 bool AudioPolicyService::IsStreamSupported(AudioStreamType streamType) 8553 { 8554 switch (streamType) { 8555 case STREAM_MUSIC: 8556 case STREAM_RING: 8557 case STREAM_VOICE_CALL: 8558 case STREAM_VOICE_COMMUNICATION: 8559 case STREAM_VOICE_ASSISTANT: 8560 case STREAM_WAKEUP: 8561 case STREAM_CAMCORDER: 8562 return true; 8563 default: 8564 return false; 8565 } 8566 } 8567 GetVolumeConfigDump(std::string & dumpString)8568 void AudioPolicyService::GetVolumeConfigDump(std::string &dumpString) 8569 { 8570 dumpString += "\nVolume config of streams:\n"; 8571 8572 StreamVolumeInfoMap streamVolumeInfos; 8573 GetStreamVolumeInfoMap(streamVolumeInfos); 8574 for (auto it = streamVolumeInfos.cbegin(); 8575 it != streamVolumeInfos.cend(); ++it) { 8576 auto streamType = it->first; 8577 AppendFormat(dumpString, " %s: ", AudioInfoDumpUtils::GetStreamName(streamType).c_str()); 8578 if (streamType == STREAM_ALL) { 8579 streamType = STREAM_MUSIC; 8580 AUDIO_INFO_LOG("GetStreamMute of STREAM_ALL for streamType = %{public}d ", streamType); 8581 } 8582 AppendFormat(dumpString, "mute = %d ", GetStreamMute(streamType)); 8583 auto streamVolumeInfo = it->second; 8584 AppendFormat(dumpString, "minLevel = %d ", streamVolumeInfo->minLevel); 8585 AppendFormat(dumpString, "maxLevel = %d ", streamVolumeInfo->maxLevel); 8586 AppendFormat(dumpString, "defaultLevel = %d\n", streamVolumeInfo->defaultLevel); 8587 DeviceVolumeInfosDump(dumpString, streamVolumeInfo->deviceVolumeInfos); 8588 } 8589 } 8590 DeviceVolumeInfosDump(std::string & dumpString,DeviceVolumeInfoMap & deviceVolumeInfos)8591 void AudioPolicyService::DeviceVolumeInfosDump(std::string &dumpString, DeviceVolumeInfoMap &deviceVolumeInfos) 8592 { 8593 for (auto iter = deviceVolumeInfos.cbegin(); iter != deviceVolumeInfos.cend(); ++iter) { 8594 AppendFormat(dumpString, " %s : {", AudioInfoDumpUtils::GetDeviceVolumeTypeName(iter->first).c_str()); 8595 auto volumePoints = iter->second->volumePoints; 8596 for (auto volPoint = volumePoints.cbegin(); volPoint != volumePoints.cend(); ++volPoint) { 8597 AppendFormat(dumpString, "[%u, %d]", volPoint->index, volPoint->dbValue); 8598 if (volPoint + 1 != volumePoints.cend()) { 8599 dumpString += ", "; 8600 } 8601 } 8602 dumpString += "}\n"; 8603 } 8604 } 8605 AudioStreamDump(std::string & dumpString)8606 void AudioPolicyService::AudioStreamDump(std::string &dumpString) 8607 { 8608 dumpString += "\nAudioRenderer stream:\n"; 8609 vector<unique_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos; 8610 streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos); 8611 8612 AppendFormat(dumpString, " - audiorenderer stream size : %zu\n", audioRendererChangeInfos.size()); 8613 for (auto it = audioRendererChangeInfos.begin(); it != audioRendererChangeInfos.end(); it++) { 8614 if ((*it)->rendererInfo.rendererFlags == STREAM_FLAG_NORMAL) { 8615 AppendFormat(dumpString, " - normal audiorenderer stream:\n"); 8616 } else if ((*it)->rendererInfo.rendererFlags == STREAM_FLAG_FAST) { 8617 AppendFormat(dumpString, " - fast audiorenderer stream:\n"); 8618 } 8619 AppendFormat(dumpString, " - clientUID : %d\n", (*it)->clientUID); 8620 AppendFormat(dumpString, " - streamId : %d\n", (*it)->sessionId); 8621 AppendFormat(dumpString, " - deviceType : %d\n", (*it)->outputDeviceInfo.deviceType); 8622 AppendFormat(dumpString, " - contentType : %d\n", (*it)->rendererInfo.contentType); 8623 AppendFormat(dumpString, " - streamUsage : %d\n", (*it)->rendererInfo.streamUsage); 8624 AppendFormat(dumpString, " - samplingRate : %d\n", (*it)->rendererInfo.samplingRate); 8625 AudioStreamType streamType = GetStreamType((*it)->sessionId); 8626 AppendFormat(dumpString, " - volume : %f\n", GetSystemVolumeDb(streamType)); 8627 AppendFormat(dumpString, " - pipeType : %d\n", (*it)->rendererInfo.pipeType); 8628 } 8629 GetCapturerStreamDump(dumpString); 8630 } 8631 GetCapturerStreamDump(std::string & dumpString)8632 void AudioPolicyService::GetCapturerStreamDump(std::string &dumpString) 8633 { 8634 dumpString += "\nAudioCapturer stream:\n"; 8635 vector<unique_ptr<AudioCapturerChangeInfo>> audioCapturerChangeInfos; 8636 streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos); 8637 AppendFormat(dumpString, " - audiocapturer stream size : %zu\n", audioCapturerChangeInfos.size()); 8638 for (auto it = audioCapturerChangeInfos.begin(); it != audioCapturerChangeInfos.end(); it++) { 8639 if ((*it)->capturerInfo.capturerFlags == STREAM_FLAG_NORMAL) { 8640 AppendFormat(dumpString, " - normal audiocapturer stream:\n"); 8641 } else if ((*it)->capturerInfo.capturerFlags == STREAM_FLAG_FAST) { 8642 AppendFormat(dumpString, " - fast audiocapturer stream:\n"); 8643 } 8644 AppendFormat(dumpString, " - clientUID : %d\n", (*it)->clientUID); 8645 AppendFormat(dumpString, " - streamId : %d\n", (*it)->sessionId); 8646 AppendFormat(dumpString, " - is muted : %s\n", (*it)->muted ? "true" : "false"); 8647 AppendFormat(dumpString, " - deviceType : %d\n", (*it)->inputDeviceInfo.deviceType); 8648 AppendFormat(dumpString, " - samplingRate : %d\n", (*it)->capturerInfo.samplingRate); 8649 AppendFormat(dumpString, " - pipeType : %d\n", (*it)->capturerInfo.pipeType); 8650 } 8651 } 8652 GetOffloadStatusDump(std::string & dumpString)8653 void AudioPolicyService::GetOffloadStatusDump(std::string &dumpString) 8654 { 8655 dumpString += "\nOffload status:"; 8656 DeviceType dev = GetActiveOutputDevice(); 8657 if (dev != DEVICE_TYPE_SPEAKER && dev != DEVICE_TYPE_USB_HEADSET && dev != DEVICE_TYPE_BLUETOOTH_A2DP) { 8658 AppendFormat(dumpString, " - current device do not supportted offload: %d\n", dev); 8659 } 8660 dumpString += "\nPrimary Offload\n"; 8661 if (dev == DEVICE_TYPE_SPEAKER || dev == DEVICE_TYPE_USB_HEADSET) { 8662 AppendFormat(dumpString, " - primary deviceType : %d\n", dev); 8663 AppendFormat(dumpString, " - primary offloadEnable : %d\n", GetOffloadAvailableFromXml()); 8664 } else { 8665 AppendFormat(dumpString, " - current device is not primary\n"); 8666 } 8667 dumpString += "\nA2DP offload\n"; 8668 if (dev == DEVICE_TYPE_BLUETOOTH_A2DP) { 8669 AppendFormat(dumpString, " - A2DP deviceType: %d\n", dev); 8670 AppendFormat(dumpString, " - A2DP offloadstatus : %d\n", a2dpOffloadFlag_); 8671 } else { 8672 AppendFormat(dumpString, " - current device is not A2DP\n"); 8673 } 8674 AppendFormat(dumpString, "\n"); 8675 } 8676 GetCurActivateCount()8677 int32_t AudioPolicyService::GetCurActivateCount() 8678 { 8679 return audioPolicyManager_.GetCurActivateCount(); 8680 } 8681 NotifyAccountsChanged(const int & id)8682 void AudioPolicyService::NotifyAccountsChanged(const int &id) 8683 { 8684 audioPolicyManager_.NotifyAccountsChanged(id); 8685 } 8686 WriteServiceStartupError(string reason)8687 void AudioPolicyService::WriteServiceStartupError(string reason) 8688 { 8689 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 8690 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_SERVICE_STARTUP_ERROR, 8691 Media::MediaMonitor::EventType::FAULT_EVENT); 8692 bean->Add("SERVICE_ID", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVICE_ID)); 8693 bean->Add("ERROR_CODE", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVER)); 8694 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 8695 } 8696 LoadToneDtmfConfig()8697 bool AudioPolicyService::LoadToneDtmfConfig() 8698 { 8699 AUDIO_INFO_LOG("Enter"); 8700 std::unique_ptr<AudioToneParser> audioToneParser = make_unique<AudioToneParser>(); 8701 if (audioToneParser == nullptr) { 8702 WriteServiceStartupError("Audio Tone Load Configuration failed"); 8703 } 8704 CHECK_AND_RETURN_RET_LOG(audioToneParser != nullptr, false, "Failed to create AudioToneParser"); 8705 std::string AUDIO_TONE_CONFIG_FILE = "system/etc/audio/audio_tone_dtmf_config.xml"; 8706 8707 if (audioToneParser->LoadConfig(toneDescriptorMap)) { 8708 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>( 8709 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::LOAD_CONFIG_ERROR, 8710 Media::MediaMonitor::EventType::FAULT_EVENT); 8711 bean->Add("CATEGORY", Media::MediaMonitor::AUDIO_TONE_DTMF_CONFIG); 8712 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean); 8713 WriteServiceStartupError("Audio Tone Load Configuration failed"); 8714 AUDIO_ERR_LOG("Audio Tone Load Configuration failed"); 8715 return false; 8716 } 8717 AUDIO_INFO_LOG("Done"); 8718 return true; 8719 } 8720 SetAudioConcurrencyCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)8721 int32_t AudioPolicyService::SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object) 8722 { 8723 return streamCollector_.SetAudioConcurrencyCallback(sessionID, object); 8724 } 8725 UnsetAudioConcurrencyCallback(const uint32_t sessionID)8726 int32_t AudioPolicyService::UnsetAudioConcurrencyCallback(const uint32_t sessionID) 8727 { 8728 return streamCollector_.UnsetAudioConcurrencyCallback(sessionID); 8729 } 8730 ActivateAudioConcurrency(const AudioPipeType & pipeType)8731 int32_t AudioPolicyService::ActivateAudioConcurrency(const AudioPipeType &pipeType) 8732 { 8733 return streamCollector_.ActivateAudioConcurrency(pipeType); 8734 } 8735 OnReceiveBluetoothEvent(const std::string macAddress,const std::string deviceName)8736 void AudioPolicyService::OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName) 8737 { 8738 std::lock_guard<std::shared_mutex> lock(deviceStatusUpdateSharedMutex_); 8739 audioDeviceManager_.OnReceiveBluetoothEvent(macAddress, deviceName); 8740 for (auto device : connectedDevices_) { 8741 if (device->macAddress_ == macAddress) { 8742 device->deviceName_ = deviceName; 8743 int32_t bluetoothId_ = device->deviceId_; 8744 std::string name_ = device->deviceName_; 8745 AUDIO_INFO_LOG("bluetoothId %{public}d alias name changing to %{public}s", bluetoothId_, name_.c_str()); 8746 } 8747 } 8748 } 8749 UpdateRoute(unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices)8750 void AudioPolicyService::UpdateRoute(unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, 8751 vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices) 8752 { 8753 StreamUsage streamUsage = rendererChangeInfo->rendererInfo.streamUsage; 8754 InternalDeviceType deviceType = outputDevices.front()->deviceType_; 8755 AUDIO_INFO_LOG("update route, streamUsage:%{public}d, 1st devicetype:%{public}d", streamUsage, deviceType); 8756 if (Util::IsRingerOrAlarmerStreamUsage(streamUsage) && IsRingerOrAlarmerDualDevicesRange(deviceType)) { 8757 if (!SelectRingerOrAlarmDevices(outputDevices, rendererChangeInfo)) { 8758 UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG); 8759 } 8760 8761 AudioRingerMode ringerMode = audioPolicyManager_.GetRingerMode(); 8762 if (ringerMode != RINGER_MODE_NORMAL && IsRingerOrAlarmerDualDevicesRange(outputDevices.front()->getType()) && 8763 outputDevices.front()->getType() != DEVICE_TYPE_SPEAKER) { 8764 audioPolicyManager_.SetStreamMute(STREAM_RING, false, streamUsage); 8765 ringerModeMute_.store(false); 8766 if (audioPolicyManager_.GetSystemVolumeLevel(STREAM_RING) < 8767 audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE) { 8768 audioPolicyManager_.SetDoubleRingVolumeDb(STREAM_RING, 8769 audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE); 8770 } 8771 } else { 8772 ringerModeMute_.store(true); 8773 } 8774 shouldUpdateDeviceDueToDualTone_ = true; 8775 } else { 8776 if (enableDualHalToneState_) { 8777 AUDIO_INFO_LOG("disable dual hal tone for not ringer/alarm."); 8778 UpdateDualToneState(false, enableDualHalToneSessionId_); 8779 } 8780 ringerModeMute_.store(true); 8781 UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG); 8782 shouldUpdateDeviceDueToDualTone_ = false; 8783 } 8784 } 8785 IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType & deviceType)8786 bool AudioPolicyService::IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType &deviceType) 8787 { 8788 switch (deviceType) { 8789 case DEVICE_TYPE_SPEAKER: 8790 case DEVICE_TYPE_WIRED_HEADSET: 8791 case DEVICE_TYPE_WIRED_HEADPHONES: 8792 case DEVICE_TYPE_BLUETOOTH_SCO: 8793 case DEVICE_TYPE_BLUETOOTH_A2DP: 8794 case DEVICE_TYPE_USB_HEADSET: 8795 case DEVICE_TYPE_USB_ARM_HEADSET: 8796 return true; 8797 default: 8798 return false; 8799 } 8800 } 8801 IsA2dpOrArmUsbDevice(const InternalDeviceType & deviceType)8802 bool AudioPolicyService::IsA2dpOrArmUsbDevice(const InternalDeviceType &deviceType) 8803 { 8804 switch (deviceType) { 8805 case DEVICE_TYPE_BLUETOOTH_A2DP: 8806 case DEVICE_TYPE_USB_ARM_HEADSET: 8807 return true; 8808 default: { 8809 return false; 8810 } 8811 } 8812 } 8813 SelectRingerOrAlarmDevices(const vector<std::unique_ptr<AudioDeviceDescriptor>> & descs,const unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo)8814 bool AudioPolicyService::SelectRingerOrAlarmDevices(const vector<std::unique_ptr<AudioDeviceDescriptor>> &descs, 8815 const unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo) 8816 { 8817 CHECK_AND_RETURN_RET_LOG(descs.size() > 0 && descs.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT, false, 8818 "audio devices not in range for ringer or alarmer."); 8819 const int32_t sessionId = rendererChangeInfo->sessionId; 8820 const StreamUsage streamUsage = rendererChangeInfo->rendererInfo.streamUsage; 8821 bool allDevicesInDualDevicesRange = true; 8822 std::vector<std::pair<InternalDeviceType, DeviceFlag>> activeDevices; 8823 for (size_t i = 0; i < descs.size(); i++) { 8824 if (IsRingerOrAlarmerDualDevicesRange(descs[i]->deviceType_)) { 8825 activeDevices.push_back(make_pair(descs[i]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG)); 8826 AUDIO_INFO_LOG("select ringer/alarm devices devicetype[%{public}zu]:%{public}d", i, descs[i]->deviceType_); 8827 } else { 8828 allDevicesInDualDevicesRange = false; 8829 break; 8830 } 8831 } 8832 8833 AUDIO_INFO_LOG("select ringer/alarm sessionId:%{public}d, streamUsage:%{public}d", sessionId, streamUsage); 8834 if (!descs.empty() && allDevicesInDualDevicesRange) { 8835 if (descs.size() == AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT && 8836 GetSinkName(*descs.front(), sessionId) != GetSinkName(*descs.back(), sessionId)) { 8837 AUDIO_INFO_LOG("set dual hal tone, reset primary sink to default before."); 8838 UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG); 8839 if (enableDualHalToneState_ && enableDualHalToneSessionId_ != sessionId) { 8840 AUDIO_INFO_LOG("sesion changed, disable old dual hal tone."); 8841 UpdateDualToneState(false, enableDualHalToneSessionId_); 8842 } 8843 8844 if ((GetRingerMode() != RINGER_MODE_NORMAL) && (streamUsage != STREAM_USAGE_ALARM)) { 8845 AUDIO_INFO_LOG("no normal ringer mode and no alarm, dont dual hal tone."); 8846 return false; 8847 } 8848 UpdateDualToneState(true, sessionId); 8849 } else { 8850 UpdateActiveDevicesRoute(activeDevices); 8851 } 8852 return true; 8853 } 8854 return false; 8855 } 8856 DealAudioSceneOutputDevices(const AudioScene & audioScene,std::vector<DeviceType> & activeOutputDevices,bool & haveArmUsbDevice)8857 void AudioPolicyService::DealAudioSceneOutputDevices(const AudioScene &audioScene, 8858 std::vector<DeviceType> &activeOutputDevices, bool &haveArmUsbDevice) 8859 { 8860 vector<std::unique_ptr<AudioDeviceDescriptor>> descs {}; 8861 switch (audioScene) { 8862 case AUDIO_SCENE_RINGING: 8863 descs = audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_RINGTONE, -1); 8864 if (!descs.empty()) { 8865 SetCurrentOutputDeviceType(descs.front()->getType()); 8866 } 8867 break; 8868 case AUDIO_SCENE_VOICE_RINGING: 8869 descs = audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_RINGTONE, -1); 8870 if (!descs.empty()) { 8871 SetCurrentOutputDeviceType(descs.front()->getType()); 8872 } 8873 break; 8874 default: 8875 AUDIO_INFO_LOG("No ringing scene:%{public}d", audioScene); 8876 break; 8877 } 8878 8879 if (!descs.empty()) { 8880 for (size_t i = 0; i < descs.size(); i++) { 8881 if (descs[i]->getType() == DEVICE_TYPE_USB_ARM_HEADSET) { 8882 AUDIO_INFO_LOG("usb headset is arm device."); 8883 activeOutputDevices.push_back(DEVICE_TYPE_USB_ARM_HEADSET); 8884 haveArmUsbDevice = true; 8885 } else { 8886 activeOutputDevices.push_back(descs[i]->getType()); 8887 } 8888 } 8889 } else { 8890 if (GetCurrentOutputDeviceType() == DEVICE_TYPE_USB_ARM_HEADSET) { 8891 activeOutputDevices.push_back(DEVICE_TYPE_USB_ARM_HEADSET); 8892 haveArmUsbDevice = true; 8893 } else { 8894 activeOutputDevices.push_back(GetCurrentOutputDeviceType()); 8895 } 8896 } 8897 } 8898 ResetRingerModeMute()8899 int32_t AudioPolicyService::ResetRingerModeMute() 8900 { 8901 if (!ringerModeMute_.load()) { 8902 std::unique_lock<std::mutex> lock(ringerModeMuteMutex_); 8903 bool resetWaiting = ringerModeMuteCondition_.wait_for(lock, 8904 std::chrono::milliseconds(WAIT_RINGER_MODE_MUTE_RESET_TIME_MS), 8905 [this] { return !ringerModeMute_.load(); } 8906 ); 8907 if (!resetWaiting || audioScene_ == AUDIO_SCENE_DEFAULT) { 8908 AUDIO_INFO_LOG("reset ringer mode mute"); 8909 if (audioPolicyManager_.SetStreamMute(STREAM_RING, true) == SUCCESS) { 8910 ringerModeMute_.store(true); 8911 } 8912 } 8913 } 8914 return SUCCESS; 8915 } 8916 IsRingerModeMute()8917 bool AudioPolicyService::IsRingerModeMute() 8918 { 8919 return ringerModeMute_.load(); 8920 } 8921 LoadHdiEffectModel()8922 void AudioPolicyService::LoadHdiEffectModel() 8923 { 8924 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 8925 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null"); 8926 8927 std::string identity = IPCSkeleton::ResetCallingIdentity(); 8928 gsp->LoadHdiEffectModel(); 8929 IPCSkeleton::SetCallingIdentity(identity); 8930 } 8931 UpdateEffectBtOffloadSupported(const bool & isSupported)8932 void AudioPolicyService::UpdateEffectBtOffloadSupported(const bool &isSupported) 8933 { 8934 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 8935 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null"); 8936 8937 std::string identity = IPCSkeleton::ResetCallingIdentity(); 8938 gsp->UpdateEffectBtOffloadSupported(isSupported); 8939 IPCSkeleton::SetCallingIdentity(identity); 8940 return; 8941 } 8942 ScoInputDeviceFetchedForRecongnition(bool handleFlag,const std::string & address,ConnectState connectState)8943 int32_t AudioPolicyService::ScoInputDeviceFetchedForRecongnition(bool handleFlag, const std::string &address, 8944 ConnectState connectState) 8945 { 8946 Bluetooth::BluetoothRemoteDevice device = Bluetooth::BluetoothRemoteDevice(address); 8947 if (handleFlag && connectState != DEACTIVE_CONNECTED) { 8948 return SUCCESS; 8949 } 8950 return Bluetooth::AudioHfpManager::HandleScoWithRecongnition(handleFlag, device); 8951 } 8952 SetRotationToEffect(const uint32_t rotate)8953 void AudioPolicyService::SetRotationToEffect(const uint32_t rotate) 8954 { 8955 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 8956 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null"); 8957 8958 std::string identity = IPCSkeleton::ResetCallingIdentity(); 8959 gsp->SetRotationToEffect(rotate); 8960 IPCSkeleton::SetCallingIdentity(identity); 8961 } 8962 IsA2dpOffloadConnected()8963 bool AudioPolicyService::IsA2dpOffloadConnected() 8964 { 8965 if (audioA2dpOffloadManager_ == nullptr) { 8966 AUDIO_WARNING_LOG("Null audioA2dpOffloadManager"); 8967 return true; 8968 } 8969 A2dpOffloadConnectionState state = audioA2dpOffloadManager_->GetA2dOffloadConnectionState(); 8970 return state == CONNECTION_STATUS_CONNECTED; 8971 } 8972 UpdateSessionConnectionState(const int32_t & sessionID,const int32_t & state)8973 void AudioPolicyService::UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state) 8974 { 8975 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 8976 CHECK_AND_RETURN_LOG(gsp != nullptr, "Audio Server Proxy is null"); 8977 8978 std::string identity = IPCSkeleton::ResetCallingIdentity(); 8979 gsp->UpdateSessionConnectionState(sessionID, state); 8980 IPCSkeleton::SetCallingIdentity(identity); 8981 } 8982 LoadSplitModule(const std::string & splitArgs,const std::string & networkId)8983 int32_t AudioPolicyService::LoadSplitModule(const std::string &splitArgs, const std::string &networkId) 8984 { 8985 AUDIO_INFO_LOG("start audio stream split, the split args is %{public}s", splitArgs.c_str()); 8986 if (splitArgs.empty() || networkId.empty()) { 8987 std::string anonymousNetworkId = networkId.empty() ? "" : networkId.substr(0, 2) + "***"; 8988 AUDIO_ERR_LOG("LoadSplitModule, invalid param, splitArgs:'%{public}s', networkId:'%{public}s'", 8989 splitArgs.c_str(), anonymousNetworkId.c_str()); 8990 return ERR_INVALID_PARAM; 8991 } 8992 std::string moduleName = GetRemoteModuleName(networkId, OUTPUT_DEVICE); 8993 8994 ClosePortAndEraseIOHandle(moduleName); 8995 8996 AudioModuleInfo moudleInfo = ConstructRemoteAudioModuleInfo(networkId, OUTPUT_DEVICE, DEVICE_TYPE_SPEAKER); 8997 moudleInfo.lib = "libmodule-split-stream-sink.z.so"; 8998 moudleInfo.extra = splitArgs; 8999 9000 int32_t openRet = OpenPortAndInsertIOHandle(moduleName, moudleInfo); 9001 if (openRet != 0) { 9002 AUDIO_ERR_LOG("open fail, OpenPortAndInsertIOHandle ret: %{public}d", openRet); 9003 } 9004 return openRet; 9005 } 9006 SetDefaultOutputDevice(const DeviceType deviceType,const uint32_t sessionID,const StreamUsage streamUsage,bool isRunning)9007 int32_t AudioPolicyService::SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID, 9008 const StreamUsage streamUsage, bool isRunning) 9009 { 9010 CHECK_AND_RETURN_RET_LOG(hasEarpiece_, ERR_NOT_SUPPORTED, "the device has no earpiece"); 9011 int32_t ret = audioDeviceManager_.SetDefaultOutputDevice(deviceType, sessionID, streamUsage, isRunning); 9012 if (ret == NEED_TO_FETCH) { 9013 FetchDevice(true); 9014 return SUCCESS; 9015 } 9016 return ret; 9017 } 9018 UpdateDefaultOutputDeviceWhenStopping(int32_t uid)9019 void AudioPolicyService::UpdateDefaultOutputDeviceWhenStopping(int32_t uid) 9020 { 9021 std::vector<uint32_t> sessionIDSet = streamCollector_.GetAllRendererSessionIDForUID(uid); 9022 for (const auto &sessionID : sessionIDSet) { 9023 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(sessionID); 9024 audioDeviceManager_.RemoveSelectedDefaultOutputDevice(sessionID); 9025 } 9026 FetchDevice(true); 9027 } 9028 SetPreferredDevice(const PreferredType preferredType,const sptr<AudioDeviceDescriptor> & desc)9029 int32_t AudioPolicyService::SetPreferredDevice(const PreferredType preferredType, 9030 const sptr<AudioDeviceDescriptor> &desc) 9031 { 9032 int32_t ret = SUCCESS; 9033 switch (preferredType) { 9034 case AUDIO_MEDIA_RENDER: 9035 audioStateManager_.SetPreferredMediaRenderDevice(desc); 9036 break; 9037 case AUDIO_CALL_RENDER: 9038 audioStateManager_.SetPreferredCallRenderDevice(desc); 9039 break; 9040 case AUDIO_CALL_CAPTURE: 9041 audioStateManager_.SetPreferredCallCaptureDevice(desc); 9042 break; 9043 case AUDIO_RECORD_CAPTURE: 9044 audioStateManager_.SetPreferredRecordCaptureDevice(desc); 9045 break; 9046 case AUDIO_RING_RENDER: 9047 case AUDIO_TONE_RENDER: 9048 AUDIO_WARNING_LOG("preferredType:%{public}d, not supported", preferredType); 9049 ret = ERR_INVALID_PARAM; 9050 break; 9051 default: 9052 AUDIO_ERR_LOG("invalid preferredType: %{public}d", preferredType); 9053 ret = ERR_INVALID_PARAM; 9054 break; 9055 } 9056 if (desc == nullptr || desc->deviceType_ == DEVICE_TYPE_NONE) { 9057 ErasePreferredDeviceByType(preferredType); 9058 } 9059 if (ret != SUCCESS) { 9060 AUDIO_ERR_LOG("Set preferredType %{public}d failed, ret: %{public}d", preferredType, ret); 9061 } 9062 return ret; 9063 } 9064 ErasePreferredDeviceByType(const PreferredType preferredType)9065 int32_t AudioPolicyService::ErasePreferredDeviceByType(const PreferredType preferredType) 9066 { 9067 if (isBTReconnecting_) { 9068 return SUCCESS; 9069 } 9070 auto type = static_cast<Media::MediaMonitor::PerferredType>(preferredType); 9071 int32_t ret = Media::MediaMonitor::MediaMonitorManager::GetInstance().ErasePreferredDeviceByType(type); 9072 if (ret != SUCCESS) { 9073 AUDIO_ERR_LOG("Erase preferredType %{public}d failed, ret: %{public}d", preferredType, ret); 9074 return ERROR; 9075 } 9076 return SUCCESS; 9077 } 9078 OnA2dpPlayingStateChanged(const std::string & deviceAddress,int32_t playingState)9079 void AudioA2dpOffloadManager::OnA2dpPlayingStateChanged(const std::string &deviceAddress, int32_t playingState) 9080 { 9081 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged current A2dpOffload MacAddr:%{public}s, incoming MacAddr:%{public}s, " 9082 "currentStatus:%{public}d, incommingState:%{public}d", GetEncryptAddr(a2dpOffloadDeviceAddress_).c_str(), 9083 GetEncryptAddr(deviceAddress).c_str(), currentOffloadConnectionState_, playingState); 9084 if (deviceAddress != a2dpOffloadDeviceAddress_) { 9085 if (playingState == A2DP_STOPPED && currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTED) { 9086 return; 9087 } 9088 // below is A2dp(not offload scenario) 9089 currentOffloadConnectionState_ = CONNECTION_STATUS_DISCONNECTED; 9090 return; 9091 } 9092 9093 // deviceAddress matched 9094 if (playingState == A2DP_PLAYING) { 9095 if (currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTING) { 9096 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged currentOffloadConnectionState_ change " 9097 "from %{public}d to %{public}d", currentOffloadConnectionState_, CONNECTION_STATUS_CONNECTED); 9098 9099 for (int32_t sessionId : connectionTriggerSessionIds_) { 9100 audioPolicyService_->UpdateSessionConnectionState(sessionId, DATA_LINK_CONNECTED); 9101 } 9102 std::vector<int32_t>().swap(connectionTriggerSessionIds_); 9103 connectionCV_.notify_all(); 9104 } 9105 currentOffloadConnectionState_ = CONNECTION_STATUS_CONNECTED; 9106 } else if (playingState == A2DP_STOPPED) { 9107 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged currentOffloadConnectionState_ change " 9108 "from %{public}d to %{public}d", currentOffloadConnectionState_, CONNECTION_STATUS_DISCONNECTED); 9109 9110 currentOffloadConnectionState_ = CONNECTION_STATUS_DISCONNECTED; 9111 a2dpOffloadDeviceAddress_ = ""; 9112 std::vector<int32_t>().swap(connectionTriggerSessionIds_); 9113 } else { 9114 // at the current moment, we only handle the PLAYING and STOPPED state, 9115 // will handle other state in the future 9116 AUDIO_INFO_LOG("OnA2dpPlayingStateChanged currentOffloadConnectionState_: %{public}d, " 9117 "received unexpected state:%{public}d", currentOffloadConnectionState_, playingState); 9118 } 9119 } 9120 ConnectA2dpOffload(const std::string & deviceAddress,const vector<int32_t> & sessionIds)9121 void AudioA2dpOffloadManager::ConnectA2dpOffload(const std::string &deviceAddress, const vector<int32_t> &sessionIds) 9122 { 9123 AUDIO_INFO_LOG("start connecting a2dpOffload for MacAddr:%{public}s.", GetEncryptAddr(deviceAddress).c_str()); 9124 a2dpOffloadDeviceAddress_ = deviceAddress; 9125 connectionTriggerSessionIds_.assign(sessionIds.begin(), sessionIds.end()); 9126 9127 for (int32_t sessionId : connectionTriggerSessionIds_) { 9128 audioPolicyService_->UpdateSessionConnectionState(sessionId, DATA_LINK_CONNECTING); 9129 } 9130 9131 if (currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTED || 9132 currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTING) { 9133 AUDIO_INFO_LOG("currentOffloadConnectionState_ already in %{public}d, " 9134 "status, no need to trigger another waiting", currentOffloadConnectionState_); 9135 return; 9136 } 9137 9138 std::thread switchThread(&AudioA2dpOffloadManager::WaitForConnectionCompleted, this); 9139 switchThread.detach(); 9140 AUDIO_INFO_LOG("currentOffloadConnectionState_ change from %{public}d to %{public}d", 9141 currentOffloadConnectionState_, CONNECTION_STATUS_CONNECTING); 9142 currentOffloadConnectionState_ = CONNECTION_STATUS_CONNECTING; 9143 } 9144 WaitForConnectionCompleted()9145 void AudioA2dpOffloadManager::WaitForConnectionCompleted() 9146 { 9147 std::unique_lock<std::mutex> waitLock(connectionMutex_); 9148 bool connectionCompleted = connectionCV_.wait_for(waitLock, 9149 std::chrono::milliseconds(AudioA2dpOffloadManager::CONNECTION_TIMEOUT_IN_MS), [this] { 9150 return currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTED; 9151 }); 9152 // a2dp connection timeout, anyway we should notify client dataLink OK in order to allow the data flow begin 9153 AUDIO_INFO_LOG("WaitForConnectionCompleted unblocked, connectionCompleted is %{public}d", connectionCompleted); 9154 9155 if (!connectionCompleted) { 9156 AUDIO_INFO_LOG("currentOffloadConnectionState_ change from %{public}d to %{public}d", 9157 currentOffloadConnectionState_, CONNECTION_STATUS_TIMEOUT); 9158 currentOffloadConnectionState_ = CONNECTION_STATUS_CONNECTED; 9159 for (int32_t sessionId : connectionTriggerSessionIds_) { 9160 audioPolicyService_->UpdateSessionConnectionState(sessionId, DATA_LINK_CONNECTED); 9161 } 9162 std::vector<int32_t>().swap(connectionTriggerSessionIds_); 9163 } 9164 waitLock.unlock(); 9165 audioPolicyService_->FetchStreamForA2dpOffload(false); 9166 return; 9167 } 9168 IsA2dpOffloadConnecting(int32_t sessionId)9169 bool AudioA2dpOffloadManager::IsA2dpOffloadConnecting(int32_t sessionId) 9170 { 9171 if (currentOffloadConnectionState_ == CONNECTION_STATUS_CONNECTING) { 9172 if (std::find(connectionTriggerSessionIds_.begin(), connectionTriggerSessionIds_.end(), sessionId) != 9173 connectionTriggerSessionIds_.end()) { 9174 return true; 9175 } 9176 } 9177 return false; 9178 } 9179 GetAudioEffectOffloadFlag()9180 bool AudioPolicyService::GetAudioEffectOffloadFlag() 9181 { 9182 // check if audio effect offload 9183 const sptr<IStandardAudioService> gsp = GetAudioServerProxy(); 9184 CHECK_AND_RETURN_RET_LOG(gsp != nullptr, false, "gsp null"); 9185 9186 std::string identity = IPCSkeleton::ResetCallingIdentity(); 9187 bool effectOffloadFlag = gsp->GetEffectOffloadEnabled(); 9188 IPCSkeleton::SetCallingIdentity(identity); 9189 return effectOffloadFlag; 9190 } 9191 CheckSpatializationAndEffectState()9192 bool AudioPolicyService::CheckSpatializationAndEffectState() 9193 { 9194 AudioSpatializationState spatialState = 9195 AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState(); 9196 bool effectOffloadFlag = GetAudioEffectOffloadFlag(); 9197 return spatialState.spatializationEnabled && !effectOffloadFlag; 9198 } 9199 JudgeIfLoadMchModule()9200 void AudioPolicyService::JudgeIfLoadMchModule() 9201 { 9202 bool isNeedLoadMchModule = false; 9203 { 9204 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 9205 if (IOHandles_.find(MCH_PRIMARY_SPEAKER) == IOHandles_.end()) { 9206 isNeedLoadMchModule = true; 9207 } 9208 } 9209 if (isNeedLoadMchModule) { 9210 LoadMchModule(); 9211 } 9212 } 9213 FetchStreamForSpkMchStream(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & descs)9214 void AudioPolicyService::FetchStreamForSpkMchStream(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, 9215 vector<std::unique_ptr<AudioDeviceDescriptor>> &descs) 9216 { 9217 if (CheckStreamMultichannelMode(rendererChangeInfo->sessionId)) { 9218 JudgeIfLoadMchModule(); 9219 std::string oldSinkName = GetSinkName(rendererChangeInfo->outputDeviceInfo, rendererChangeInfo->sessionId); 9220 std::string newSinkName = GetSinkPortName(descs.front()->deviceType_, PIPE_TYPE_MULTICHANNEL); 9221 AUDIO_INFO_LOG("mute sink old:[%{public}s] new:[%{public}s]", oldSinkName.c_str(), newSinkName.c_str()); 9222 MuteSinkPort(oldSinkName, newSinkName, AudioStreamDeviceChangeReason::OVERRODE); 9223 int32_t ret = MoveToOutputDevice(rendererChangeInfo->sessionId, newSinkName); 9224 if (ret == SUCCESS) { 9225 streamCollector_.UpdateRendererPipeInfo(rendererChangeInfo->sessionId, PIPE_TYPE_MULTICHANNEL); 9226 } 9227 } else { 9228 AudioPipeType pipeType = PIPE_TYPE_UNKNOWN; 9229 streamCollector_.GetPipeType(rendererChangeInfo->sessionId, pipeType); 9230 if (pipeType == PIPE_TYPE_MULTICHANNEL) { 9231 std::lock_guard<std::mutex> ioHandleLock(ioHandlesMutex_); 9232 { 9233 AUDIO_INFO_LOG("unload multichannel module"); 9234 std::string currentActivePort = MCH_PRIMARY_SPEAKER; 9235 auto ioHandleIter = IOHandles_.find(currentActivePort); 9236 CHECK_AND_RETURN_LOG(ioHandleIter != IOHandles_.end(), "Can not find port MCH_PRIMARY_SPEAKER in io map"); 9237 AudioIOHandle activateDeviceIOHandle = ioHandleIter->second; 9238 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true); 9239 audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle); 9240 IOHandles_.erase(currentActivePort); 9241 } 9242 } 9243 ResetOffloadMode(rendererChangeInfo->sessionId); 9244 } 9245 } 9246 ResetOffloadAndMchMode(std::unique_ptr<AudioRendererChangeInfo> & rendererChangeInfo,vector<std::unique_ptr<AudioDeviceDescriptor>> & outputDevices)9247 void AudioPolicyService::ResetOffloadAndMchMode(std::unique_ptr<AudioRendererChangeInfo> &rendererChangeInfo, 9248 vector<std::unique_ptr<AudioDeviceDescriptor>> &outputDevices) 9249 { 9250 if (outputDevices.front()->networkId_ != LOCAL_NETWORK_ID 9251 || outputDevices.front()->deviceType_ == DEVICE_TYPE_REMOTE_CAST) { 9252 RemoteOffloadStreamRelease(rendererChangeInfo->sessionId); 9253 } else { 9254 FetchStreamForSpkMchStream(rendererChangeInfo, outputDevices); 9255 } 9256 } 9257 ActivateConcurrencyFromServer(AudioPipeType incomingPipe)9258 int32_t AudioPolicyService::ActivateConcurrencyFromServer(AudioPipeType incomingPipe) 9259 { 9260 std::lock_guard<std::mutex> lock(offloadMutex_); 9261 CHECK_AND_RETURN_RET_LOG(!offloadSessionID_.has_value(), 9262 ERR_ILLEGAL_STATE, "Offload stream existing, concede incoming lowlatency stream"); 9263 return SUCCESS; 9264 } 9265 IsVoiceCallRelatedScene()9266 bool AudioPolicyService::IsVoiceCallRelatedScene() 9267 { 9268 return audioScene_ == AUDIO_SCENE_RINGING || 9269 audioScene_ == AUDIO_SCENE_PHONE_CALL || 9270 audioScene_ == AUDIO_SCENE_PHONE_CHAT || 9271 audioScene_ == AUDIO_SCENE_VOICE_RINGING; 9272 } 9273 } // namespace AudioStandard 9274 } // namespace OHOS 9275