• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /*
3  * Copyright (c) 2024-2025 Huawei Device Co., Ltd.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #ifndef LOG_TAG
17 #define LOG_TAG "AudioDeviceStatus"
18 #endif
19 
20 #include "audio_device_status.h"
21 #include <ability_manager_client.h>
22 #include "iservice_registry.h"
23 #include "parameter.h"
24 #include "parameters.h"
25 #include "audio_policy_log.h"
26 #include "audio_inner_call.h"
27 #include "media_monitor_manager.h"
28 #include "common/hdi_adapter_info.h"
29 
30 #include "audio_policy_utils.h"
31 #include "audio_server_proxy.h"
32 
33 namespace OHOS {
34 namespace AudioStandard {
35 const int MEDIA_RENDER_ID = 0;
36 const int CALL_RENDER_ID = 1;
37 const int CALL_CAPTURE_ID = 2;
38 const int RECORD_CAPTURE_ID = 3;
39 const uint32_t REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS = 30000;
40 
41 const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50;
42 
GetEncryptAddr(const std::string & addr)43 static std::string GetEncryptAddr(const std::string &addr)
44 {
45     const int32_t START_POS = 6;
46     const int32_t END_POS = 13;
47     const int32_t ADDRESS_STR_LEN = 17;
48     if (addr.empty() || addr.length() != ADDRESS_STR_LEN) {
49         return std::string("");
50     }
51     std::string tmp = "**:**:**:**:**:**";
52     std::string out = addr;
53     for (int i = START_POS; i <= END_POS; i++) {
54         out[i] = tmp[i];
55     }
56     return out;
57 }
58 
GetField(const std::string & src,const char * field,const char sep)59 static std::string GetField(const std::string &src, const char* field, const char sep)
60 {
61     auto str = std::string(field) + '=';
62     auto pos = src.find(str);
63     CHECK_AND_RETURN_RET(pos != std::string::npos, "");
64     pos += str.length();
65     auto end = src.find(sep, pos);
66     return end == std::string::npos ? src.substr(pos) : src.substr(pos, end - pos);
67 }
68 
GetDPModuleInfo(AudioModuleInfo & moduleInfo,string deviceInfo)69 static void GetDPModuleInfo(AudioModuleInfo &moduleInfo, string deviceInfo)
70 {
71     if (moduleInfo.role == "sink") {
72         auto sinkRate_begin = deviceInfo.find("rate=");
73         auto sinkRate_end = deviceInfo.find_first_of(" ", sinkRate_begin);
74         moduleInfo.rate = deviceInfo.substr(sinkRate_begin + std::strlen("rate="),
75             sinkRate_end - sinkRate_begin - std::strlen("rate="));
76 
77         auto sinkFormat_begin = deviceInfo.find("format=");
78         auto sinkFormat_end = deviceInfo.find_first_of(" ", sinkFormat_begin);
79         string format = deviceInfo.substr(sinkFormat_begin + std::strlen("format="),
80             sinkFormat_end - sinkFormat_begin - std::strlen("format="));
81         if (!format.empty()) moduleInfo.format = format;
82 
83         auto sinkChannel_begin = deviceInfo.find("channels=");
84         auto sinkChannel_end = deviceInfo.find_first_of(" ", sinkChannel_begin);
85         string channel = deviceInfo.substr(sinkChannel_begin + std::strlen("channels="),
86             sinkChannel_end - sinkChannel_begin - std::strlen("channels="));
87         moduleInfo.channels = channel;
88 
89         auto sinkBSize_begin = deviceInfo.find("buffer_size=");
90         auto sinkBSize_end = deviceInfo.find_first_of(" ", sinkBSize_begin);
91         string bufferSize = deviceInfo.substr(sinkBSize_begin + std::strlen("buffer_size="),
92             sinkBSize_end - sinkBSize_begin - std::strlen("buffer_size="));
93         moduleInfo.bufferSize = bufferSize;
94     }
95 }
96 
Init(std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager,std::shared_ptr<AudioPolicyServerHandler> handler)97 void AudioDeviceStatus::Init(std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager,
98     std::shared_ptr<AudioPolicyServerHandler> handler)
99 {
100     audioA2dpOffloadManager_ = audioA2dpOffloadManager;
101     audioPolicyServerHandler_ = handler;
102 }
103 
DeInit()104 void AudioDeviceStatus::DeInit()
105 {
106     audioA2dpOffloadManager_ = nullptr;
107     audioPolicyServerHandler_ = nullptr;
108 }
109 
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo,DeviceRole role,bool hasPair)110 void AudioDeviceStatus::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
111     const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair)
112 {
113     AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN;
114     // fill device change action for callback
115     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
116 
117     int32_t result = HandleSpecialDeviceType(devType, isConnected, macAddress, role);
118     CHECK_AND_RETURN_LOG(result == SUCCESS, "handle special deviceType failed.");
119 
120     AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], address[%{public}s]",
121         devType, isConnected, GetEncryptStr(macAddress).c_str());
122 
123     AudioDeviceDescriptor updatedDesc(devType, role == DEVICE_ROLE_NONE ?
124         AudioPolicyUtils::GetInstance().GetDeviceRole(devType) : role);
125     updatedDesc.hasPair_ = hasPair;
126     UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc);
127 
128     if (isConnected) {
129         // If device already in list, remove it else do not modify the list
130         audioConnectedDevice_.DelConnectedDevice(updatedDesc.networkId_, updatedDesc.deviceType_,
131             updatedDesc.macAddress_, updatedDesc.deviceRole_);
132         // If the pnp device fails to load, it will not connect
133         result = HandleLocalDeviceConnected(updatedDesc);
134         CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed.");
135         audioDeviceCommon_.UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb);
136 
137         reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
138 #ifdef BLUETOOTH_ENABLE
139     if (updatedDesc.connectState_ == CONNECTED &&
140         updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
141         AudioRendererInfo rendererInfo = {};
142         rendererInfo.streamUsage = STREAM_USAGE_VOICE_COMMUNICATION;
143         std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
144             audioDeviceCommon_.GetPreferredOutputDeviceDescInner(rendererInfo);
145         if (preferredDeviceList.size() > 0 &&
146             preferredDeviceList[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
147             Bluetooth::AudioHfpManager::SetActiveHfpDevice(preferredDeviceList[0]->macAddress_);
148         }
149     }
150 #endif
151     } else {
152         audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb);
153         reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
154         result = HandleLocalDeviceDisconnected(updatedDesc);
155         CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed.");
156     }
157 
158     TriggerDeviceChangedCallback(descForCb, isConnected);
159     TriggerAvailableDeviceChangedCallback(descForCb, isConnected);
160 
161     // fetch input&output device
162     audioDeviceCommon_.FetchDevice(true, reason);
163     audioDeviceCommon_.FetchDevice(false);
164 
165     // update a2dp offload
166     audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
167     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
168         audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 5 param");
169 }
170 
WriteOutputDeviceChangedSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & deviceDescriptor,const SinkInput & sinkInput)171 void AudioDeviceStatus::WriteOutputDeviceChangedSysEvents(
172     const std::shared_ptr<AudioDeviceDescriptor> &deviceDescriptor, const SinkInput &sinkInput)
173 {
174     std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
175         Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE,
176         Media::MediaMonitor::BEHAVIOR_EVENT);
177     bean->Add("ISOUTPUT", 1);
178     bean->Add("STREAMID", sinkInput.streamId);
179     bean->Add("STREAMTYPE", sinkInput.streamType);
180     bean->Add("DEVICETYPE", deviceDescriptor->deviceType_);
181     bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_));
182     bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_));
183     bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_);
184     bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_);
185     Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
186 }
187 
WriteInputDeviceChangedSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & deviceDescriptor,const SourceOutput & sourceOutput)188 void AudioDeviceStatus::WriteInputDeviceChangedSysEvents(
189     const std::shared_ptr<AudioDeviceDescriptor> &deviceDescriptor, const SourceOutput &sourceOutput)
190 {
191     std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
192         Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE,
193         Media::MediaMonitor::BEHAVIOR_EVENT);
194     bean->Add("ISOUTPUT", 0);
195     bean->Add("STREAMID", sourceOutput.streamId);
196     bean->Add("STREAMTYPE", sourceOutput.streamType);
197     bean->Add("DEVICETYPE", deviceDescriptor->deviceType_);
198     bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_));
199     bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_));
200     bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_);
201     bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_);
202     Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
203 }
204 
205 
WriteHeadsetSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & desc,bool isConnected)206 void AudioDeviceStatus::WriteHeadsetSysEvents(const std::shared_ptr<AudioDeviceDescriptor> &desc, bool isConnected)
207 {
208     CHECK_AND_RETURN_LOG(desc != nullptr, "desc is null");
209     if ((desc->deviceType_ == DEVICE_TYPE_WIRED_HEADSET) ||
210         (desc->deviceType_ == DEVICE_TYPE_USB_HEADSET) ||
211         (desc->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES)) {
212         std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
213             Media::MediaMonitor::AUDIO, Media::MediaMonitor::HEADSET_CHANGE,
214             Media::MediaMonitor::BEHAVIOR_EVENT);
215         bean->Add("HASMIC", 1);
216         bean->Add("ISCONNECT", isConnected ? 1 : 0);
217         bean->Add("DEVICETYPE", desc->deviceType_);
218         Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
219     }
220 }
221 
WriteDeviceChangeSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & desc)222 void AudioDeviceStatus::WriteDeviceChangeSysEvents(const std::shared_ptr<AudioDeviceDescriptor> &desc)
223 {
224     CHECK_AND_RETURN_LOG(desc != nullptr, "desc is null");
225     if (desc->deviceRole_ == OUTPUT_DEVICE) {
226         std::vector<SinkInput> sinkInputs;
227         audioPolicyManager_.GetAllSinkInputs(sinkInputs);
228         for (SinkInput sinkInput : sinkInputs) {
229             WriteOutputDeviceChangedSysEvents(desc, sinkInput);
230         }
231     } else if (desc->deviceRole_ == INPUT_DEVICE) {
232         std::vector<SourceOutput> sourceOutputs = audioDeviceCommon_.GetSourceOutputs();
233         for (SourceOutput sourceOutput : sourceOutputs) {
234             WriteInputDeviceChangedSysEvents(desc, sourceOutput);
235         }
236     }
237 }
238 
WriteAllDeviceSysEvents(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,bool isConnected)239 void AudioDeviceStatus::WriteAllDeviceSysEvents(
240     const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc, bool isConnected)
241 {
242     Trace trace("AudioDeviceStatus::WriteAllDeviceSysEvents");
243     for (auto deviceDescriptor : desc) {
244         WriteHeadsetSysEvents(deviceDescriptor, isConnected);
245         if (!isConnected) {
246             continue;
247         }
248         WriteDeviceChangeSysEvents(deviceDescriptor);
249     }
250 }
251 
TriggerAvailableDeviceChangedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,bool isConnected)252 void AudioDeviceStatus::TriggerAvailableDeviceChangedCallback(
253     const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc, bool isConnected)
254 {
255     Trace trace("AudioDeviceStatus::TriggerAvailableDeviceChangedCallback");
256 
257     WriteAllDeviceSysEvents(desc, isConnected);
258 
259     if (audioPolicyServerHandler_ != nullptr) {
260         audioPolicyServerHandler_->SendAvailableDeviceChange(desc, isConnected);
261     }
262 }
263 
TriggerDeviceChangedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,bool isConnected)264 void AudioDeviceStatus::TriggerDeviceChangedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc,
265     bool isConnected)
266 {
267     Trace trace("AudioDeviceStatus::TriggerDeviceChangedCallback");
268     WriteAllDeviceSysEvents(desc, isConnected);
269     if (audioPolicyServerHandler_ != nullptr) {
270         audioPolicyServerHandler_->SendDeviceChangedCallback(desc, isConnected);
271     }
272 }
273 
UpdateLocalGroupInfo(bool isConnected,const std::string & macAddress,const std::string & deviceName,const DeviceStreamInfo & streamInfo,AudioDeviceDescriptor & deviceDesc)274 void AudioDeviceStatus::UpdateLocalGroupInfo(bool isConnected, const std::string& macAddress,
275     const std::string& deviceName, const DeviceStreamInfo& streamInfo, AudioDeviceDescriptor& deviceDesc)
276 {
277     deviceDesc.SetDeviceInfo(deviceName, macAddress);
278     deviceDesc.SetDeviceCapability(streamInfo, 0);
279     audioVolumeManager_.UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, LOCAL_NETWORK_ID,
280         isConnected, NO_REMOTE_ID);
281     audioVolumeManager_.UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_,
282         LOCAL_NETWORK_ID, isConnected, NO_REMOTE_ID);
283     deviceDesc.networkId_ = LOCAL_NETWORK_ID;
284 }
285 
RehandlePnpDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)286 int32_t AudioDeviceStatus::RehandlePnpDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address)
287 {
288     Trace trace("AudioDeviceStatus::RehandlePnpDevice");
289 
290     // Maximum number of attempts, preventing situations where hal has not yet finished coming online.
291     int32_t maxRetries = 3;
292     int32_t retryCount = 0;
293     bool isConnected = true;
294     while (retryCount < maxRetries) {
295         retryCount++;
296         AUDIO_INFO_LOG("rehandle device[%{public}d], retry count[%{public}d]", deviceType, retryCount);
297 
298         int32_t ret = HandleSpecialDeviceType(deviceType, isConnected, address, deviceRole);
299         CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Rehandle special device type failed");
300         if (deviceType == DEVICE_TYPE_USB_HEADSET) {
301             AUDIO_INFO_LOG("Hifi device, don't load module");
302             return ret;
303         }
304         if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
305             if (HandleArmUsbDevice(deviceType, deviceRole, address) == SUCCESS) {
306                 return SUCCESS;
307             }
308         } else if (deviceType == DEVICE_TYPE_DP) {
309             if (HandleDpDevice(deviceType, address)  == SUCCESS) {
310                 return SUCCESS;
311             }
312         }
313         usleep(REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS);
314     }
315 
316     AUDIO_ERR_LOG("rehandle device[%{public}d] failed", deviceType);
317     return ERROR;
318 }
319 
HandleDpDevice(DeviceType deviceType,const std::string & address)320 int32_t AudioDeviceStatus::HandleDpDevice(DeviceType deviceType, const std::string &address)
321 {
322     Trace trace("AudioDeviceStatus::HandleDpDevice");
323     if (deviceType == DEVICE_TYPE_DP) {
324         std::string defaulyDPInfo = "";
325         std::string getDPInfo = "";
326         GetModuleInfo(ClassType::TYPE_DP, defaulyDPInfo);
327         CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
328 
329         getDPInfo = AudioServerProxy::GetInstance().GetAudioParameterProxy(LOCAL_NETWORK_ID, GET_DP_DEVICE_INFO,
330             defaulyDPInfo + " address=" + address + " ");
331         AUDIO_DEBUG_LOG("device info from dp hal is \n defaulyDPInfo:%{public}s", defaulyDPInfo.c_str());
332 
333         getDPInfo = getDPInfo.empty() ? defaulyDPInfo : getDPInfo;
334         int32_t ret = LoadDpModule(getDPInfo);
335         if (ret != SUCCESS) {
336             AUDIO_ERR_LOG ("load dp module failed");
337             return ERR_OPERATION_FAILED;
338         }
339         std::string activePort = AudioPolicyUtils::GetInstance().GetSinkPortName(DEVICE_TYPE_DP);
340         AUDIO_INFO_LOG("port %{public}s, active dp device", activePort.c_str());
341     } else if (audioActiveDevice_.GetCurrentOutputDeviceType() == DEVICE_TYPE_DP) {
342         std::string activePort = AudioPolicyUtils::GetInstance().GetSinkPortName(DEVICE_TYPE_DP);
343         audioPolicyManager_.SuspendAudioDevice(activePort, true);
344     }
345 
346     return SUCCESS;
347 }
348 
HandleLocalDeviceConnected(AudioDeviceDescriptor & updatedDesc)349 int32_t AudioDeviceStatus::HandleLocalDeviceConnected(AudioDeviceDescriptor &updatedDesc)
350 {
351     if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
352         A2dpDeviceConfigInfo configInfo = {updatedDesc.audioStreamInfo_, false};
353         audioA2dpDevice_.AddA2dpDevice(updatedDesc.macAddress_, configInfo);
354     } else if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP_IN) {
355         A2dpDeviceConfigInfo configInfo = {updatedDesc.audioStreamInfo_, false};
356         audioA2dpDevice_.AddA2dpInDevice(updatedDesc.macAddress_, configInfo);
357     } else if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {               // DP device only for output.
358         CHECK_AND_RETURN_RET_LOG(!audioDeviceCommon_.GetHasDpFlag(), ERROR,
359             "DP device already exists, ignore this one.");
360         int32_t result = HandleDpDevice(updatedDesc.deviceType_, updatedDesc.macAddress_);
361         if (result != SUCCESS) {
362             result = RehandlePnpDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_);
363         }
364         CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Load dp failed.");
365         audioDeviceCommon_.SetHasDpFlag(true);
366     } else if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_HEADSET ||
367         updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
368         AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "usb");
369     }
370     return SUCCESS;
371 }
372 
UpdateActiveA2dpDeviceWhenDisconnecting(const std::string & macAddress)373 void AudioDeviceStatus::UpdateActiveA2dpDeviceWhenDisconnecting(const std::string& macAddress)
374 {
375     if (audioA2dpDevice_.DelA2dpDevice(macAddress) == 0) {
376         audioActiveDevice_.SetActiveBtDeviceMac("");
377         audioIOHandleMap_.ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER);
378         audioPolicyManager_.SetAbsVolumeScene(false);
379         audioVolumeManager_.SetSharedAbsVolumeScene(false);
380 #ifdef BLUETOOTH_ENABLE
381         Bluetooth::AudioA2dpManager::SetActiveA2dpDevice("");
382 #endif
383         return;
384     }
385 }
386 
HandleLocalDeviceDisconnected(const AudioDeviceDescriptor & updatedDesc)387 int32_t AudioDeviceStatus::HandleLocalDeviceDisconnected(const AudioDeviceDescriptor &updatedDesc)
388 {
389     if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
390         UpdateActiveA2dpDeviceWhenDisconnecting(updatedDesc.macAddress_);
391     } else if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP_IN) {
392         if (audioA2dpDevice_.DelA2dpInDevice(updatedDesc.macAddress_) == 0) {
393             audioActiveDevice_.SetActiveBtInDeviceMac("");
394             audioIOHandleMap_.ClosePortAndEraseIOHandle(BLUETOOTH_MIC);
395         }
396     } else if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {
397         audioIOHandleMap_.ClosePortAndEraseIOHandle(DP_SINK);
398     } else if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
399         audioEcManager_.CloseUsbArmDevice(updatedDesc);
400     }
401 
402     AudioServerProxy::GetInstance().ResetRouteForDisconnectProxy(updatedDesc.deviceType_);
403     if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {
404         AudioServerProxy::GetInstance().UnloadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "dp", false);
405     } else if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_HEADSET ||
406         updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
407         AudioServerProxy::GetInstance().UnloadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "usb", false);
408     }
409     return SUCCESS;
410 }
411 
HandleArmUsbDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)412 int32_t AudioDeviceStatus::HandleArmUsbDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address)
413 {
414     Trace trace("AudioPolicyService::HandleArmUsbDevice");
415     if (deviceType != DEVICE_TYPE_USB_ARM_HEADSET &&
416         audioActiveDevice_.GetCurrentOutputDeviceType() == DEVICE_TYPE_USB_HEADSET) {
417         std::string activePort = AudioPolicyUtils::GetInstance().GetSinkPortName(DEVICE_TYPE_USB_ARM_HEADSET);
418         audioPolicyManager_.SuspendAudioDevice(activePort, true);
419     }
420 
421     return SUCCESS;
422 }
423 
GetModuleInfo(ClassType classType,std::string & moduleInfoStr)424 int32_t AudioDeviceStatus::GetModuleInfo(ClassType classType, std::string &moduleInfoStr)
425 {
426     std::list<AudioModuleInfo> moduleInfoList;
427     {
428         bool ret = audioConfigManager_.GetModuleListByType(classType, moduleInfoList);
429         CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED,
430             "find %{public}d type failed", classType);
431     }
432     moduleInfoStr = audioPolicyManager_.GetModuleArgs(*moduleInfoList.begin());
433     return SUCCESS;
434 }
435 
LoadDpModule(std::string deviceInfo)436 int32_t AudioDeviceStatus::LoadDpModule(std::string deviceInfo)
437 {
438     AUDIO_INFO_LOG("LoadDpModule");
439     std::list<AudioModuleInfo> moduleInfoList;
440     {
441         bool ret = audioConfigManager_.GetModuleListByType(ClassType::TYPE_DP, moduleInfoList);
442         CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED,
443             "dp module is not exist in the configuration file");
444     }
445     AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "dp");
446     for (auto &moduleInfo : moduleInfoList) {
447         AUDIO_INFO_LOG("[module_load]::load module[%{public}s]", moduleInfo.name.c_str());
448         if (audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name) == false) {
449             GetDPModuleInfo(moduleInfo, deviceInfo);
450             if (moduleInfo.role == ROLE_SINK) {
451                 AUDIO_INFO_LOG("save dp sink module info for cust param");
452                 audioEcManager_.SetDpSinkModuleInfo(moduleInfo);
453             }
454             return audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
455         }
456     }
457 
458     return SUCCESS;
459 }
460 
NoNeedChangeUsbDevice(const string & address)461 bool AudioDeviceStatus::NoNeedChangeUsbDevice(const string &address)
462 {
463     auto key = string("need_change_usb_device#C") + GetField(address, "card", ';') + "D0";
464     auto ret = AudioServerProxy::GetInstance().GetAudioParameterProxy(key);
465     AUDIO_INFO_LOG("key=%{public}s, ret=%{public}s", key.c_str(), ret.c_str());
466     return ret == "false";
467 }
468 
HandleSpecialDeviceType(DeviceType & devType,bool & isConnected,const std::string & address,DeviceRole role)469 int32_t AudioDeviceStatus::HandleSpecialDeviceType(DeviceType &devType, bool &isConnected,
470     const std::string &address, DeviceRole role)
471 {
472     if (devType == DEVICE_TYPE_USB_HEADSET || devType == DEVICE_TYPE_USB_ARM_HEADSET) {
473         CHECK_AND_RETURN_RET(!address.empty() && role != DEVICE_ROLE_NONE, ERROR);
474         AUDIO_INFO_LOG("Entry. Addr:%{public}s, Role:%{public}d, HasHifi:%{public}d, HasArm:%{public}d",
475             GetEncryptAddr(address).c_str(), role,
476             audioConnectedDevice_.HasHifi(role), audioConnectedDevice_.HasArm(role));
477         if (isConnected) {
478             // Usb-c maybe reported repeatedly, the devType remains unchanged
479             auto exists = audioConnectedDevice_.GetUsbDeviceDescriptor(address, role);
480             if (exists) {
481                 devType = exists->deviceType_;
482                 return SUCCESS;
483             }
484             if (audioConnectedDevice_.HasHifi(role) || NoNeedChangeUsbDevice(address)) {
485                 devType = DEVICE_TYPE_USB_ARM_HEADSET;
486             }
487         } else if (audioConnectedDevice_.IsArmDevice(address, role)) {
488             devType = DEVICE_TYPE_USB_ARM_HEADSET;
489             // Temporary resolution to avoid pcm driver problem
490             string condition = string("address=") + address + " role=" + to_string(DEVICE_ROLE_NONE);
491             string deviceInfo = AudioServerProxy::GetInstance().GetAudioParameterProxy(LOCAL_NETWORK_ID, USB_DEVICE,
492                 condition);
493         }
494     } else if (devType == DEVICE_TYPE_EXTERN_CABLE) {
495         CHECK_AND_RETURN_RET_LOG(isConnected, ERROR, "Extern cable disconnected, do nothing");
496         DeviceType connectedHeadsetType = audioConnectedDevice_.FindConnectedHeadset();
497         if (connectedHeadsetType == DEVICE_TYPE_NONE) {
498             AUDIO_INFO_LOG("Extern cable connect without headset connected before, do nothing");
499             return ERROR;
500         }
501         devType = connectedHeadsetType;
502         isConnected = false;
503     }
504 
505     return SUCCESS;
506 }
507 
OnPnpDeviceStatusUpdated(AudioDeviceDescriptor & desc,bool isConnected)508 void AudioDeviceStatus::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected)
509 {
510     CHECK_AND_RETURN_LOG(desc.deviceType_ != DEVICE_TYPE_NONE, "devType is none type");
511     if (!hasModulesLoaded) {
512         AUDIO_WARNING_LOG("modules has not loaded");
513         AudioDeviceDescriptor pnpDesc = desc;
514         pnpDeviceList_.push_back({pnpDesc, isConnected});
515         return;
516     }
517     AudioStreamInfo streamInfo = {};
518     OnDeviceStatusUpdated(desc.deviceType_, isConnected, desc.macAddress_, desc.deviceName_, streamInfo);
519 }
520 
OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)521 void AudioDeviceStatus::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status)
522 {
523     CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
524     OnBlockedStatusUpdated(devType, status);
525 }
526 
OnBlockedStatusUpdated(DeviceType devType,DeviceBlockStatus status)527 void AudioDeviceStatus::OnBlockedStatusUpdated(DeviceType devType, DeviceBlockStatus status)
528 {
529     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
530     std::shared_ptr<AudioDeviceDescriptor> audioDescriptor =
531         std::make_shared<AudioDeviceDescriptor>(devType, AudioPolicyUtils::GetInstance().GetDeviceRole(devType));
532     descForCb.push_back(audioDescriptor);
533 
534     vector<shared_ptr<AudioCapturerChangeInfo>> audioChangeInfos;
535     streamCollector_.GetCurrentCapturerChangeInfos(audioChangeInfos);
536     for (auto it = audioChangeInfos.begin(); it != audioChangeInfos.end(); it++) {
537         if ((*it)->capturerState == CAPTURER_RUNNING) {
538             AUDIO_INFO_LOG("record running");
539             TriggerMicrophoneBlockedCallback(descForCb, status);
540         }
541     }
542 }
543 
TriggerMicrophoneBlockedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,DeviceBlockStatus status)544 void AudioDeviceStatus::TriggerMicrophoneBlockedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc,
545     DeviceBlockStatus status)
546 {
547     Trace trace("AudioDeviceStatus::TriggerMicrophoneBlockedCallback");
548     if (audioPolicyServerHandler_ != nullptr) {
549         audioPolicyServerHandler_->SendMicrophoneBlockedCallback(desc, status);
550     }
551 }
552 
ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)553 void AudioDeviceStatus::ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, const std::string &macAddress,
554     const std::string &deviceName, const AudioStreamInfo &streamInfo)
555 {
556     uint32_t bufferSize = streamInfo.samplingRate *
557         AudioPolicyUtils::GetInstance().PcmFormatToBytes(streamInfo.format) *
558         streamInfo.channels / BT_BUFFER_ADJUSTMENT_FACTOR;
559     AUDIO_DEBUG_LOG("Updated buffer size: %{public}d", bufferSize);
560 
561     std::list<AudioModuleInfo> moduleInfoList;
562     bool ret = audioConfigManager_.GetModuleListByType(ClassType::TYPE_A2DP, moduleInfoList);
563     CHECK_AND_RETURN_LOG(ret, "GetModuleListByType failed");
564     for (auto &moduleInfo : moduleInfoList) {
565         CHECK_AND_CONTINUE_LOG(audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name),
566             "Cannot find module %{public}s", moduleInfo.name.c_str());
567         moduleInfo.channels = to_string(streamInfo.channels);
568         moduleInfo.rate = to_string(streamInfo.samplingRate);
569         moduleInfo.format = AudioPolicyUtils::GetInstance().ConvertToHDIAudioFormat(streamInfo.format);
570         moduleInfo.bufferSize = to_string(bufferSize);
571         moduleInfo.renderInIdleState = "1";
572         moduleInfo.sinkLatency = "0";
573 
574         // First unload the existing bt sink
575         AUDIO_DEBUG_LOG("UnLoad existing a2dp module");
576         std::string currentActivePort
577             = AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType());
578         AudioIOHandle activateDeviceIOHandle;
579         audioIOHandleMap_.GetModuleIdByKey(BLUETOOTH_SPEAKER, activateDeviceIOHandle);
580         audioIOHandleMap_.MuteDefaultSinkPort(audioActiveDevice_.GetCurrentOutputDeviceNetworkId(),
581             AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType()));
582         audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
583         audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle);
584 
585         // Load bt sink module again with new configuration
586         AUDIO_DEBUG_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str());
587         AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo);
588         if (ioHandle == OPEN_PORT_FAILURE) {
589             audioPolicyManager_.SuspendAudioDevice(currentActivePort, false);
590             AUDIO_ERR_LOG("OpenAudioPort failed %{public}d", ioHandle);
591             return;
592         }
593         audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle);
594         std::string portName = AudioPolicyUtils::GetInstance().GetSinkPortName(deviceType);
595         if (!audioSceneManager_.IsVoiceCallRelatedScene()) {
596             audioPolicyManager_.SetDeviceActive(deviceType, portName, true);
597         }
598         audioPolicyManager_.SuspendAudioDevice(portName, false);
599         audioPolicyManager_.SuspendAudioDevice(currentActivePort, false);
600         audioConnectedDevice_.UpdateConnectDevice(deviceType, macAddress, deviceName, streamInfo);
601         break;
602     }
603 }
604 
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)605 void AudioDeviceStatus::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
606     const std::string &deviceName, const AudioStreamInfo &streamInfo)
607 {
608     std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
609     AUDIO_INFO_LOG("OnDeviceConfigurationChanged start, deviceType: %{public}d, currentActiveDevice_: %{public}d, "
610         "macAddress:[%{public}s], activeBTDevice:[%{public}s]", deviceType,
611         audioActiveDevice_.GetCurrentOutputDeviceType(),
612         GetEncryptAddr(macAddress).c_str(), GetEncryptAddr(btDevice).c_str());
613     // only for the active a2dp device.
614     if ((deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) && !macAddress.compare(btDevice)) {
615         int32_t activeSessionsSize = 0;
616         BluetoothOffloadState state = NO_A2DP_DEVICE;
617         if (audioA2dpOffloadManager_) {
618             activeSessionsSize = audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
619             state = audioA2dpOffloadManager_->GetA2dpOffloadFlag();
620         }
621         AUDIO_DEBUG_LOG("streamInfo.sampleRate: %{public}d, a2dpOffloadFlag: %{public}d",
622             streamInfo.samplingRate, state);
623         if (!IsConfigurationUpdated(deviceType, streamInfo) ||
624             (activeSessionsSize > 0 && state == A2DP_OFFLOAD)) {
625             AUDIO_DEBUG_LOG("Audio configuration same");
626             return;
627         }
628         audioA2dpDevice_.SetA2dpDeviceStreamInfo(macAddress, streamInfo);
629         ReloadA2dpOffloadOnDeviceChanged(deviceType, macAddress, deviceName, streamInfo);
630     } else if (audioA2dpDevice_.CheckA2dpDeviceExist(macAddress)) {
631         AUDIO_DEBUG_LOG("Audio configuration update, macAddress:[%{public}s], streamInfo.sampleRate: %{public}d",
632             GetEncryptAddr(macAddress).c_str(), streamInfo.samplingRate);
633         audioA2dpDevice_.SetA2dpDeviceStreamInfo(macAddress, streamInfo);
634     }
635 }
636 
IsConfigurationUpdated(DeviceType deviceType,const AudioStreamInfo & streamInfo)637 bool AudioDeviceStatus::IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo)
638 {
639     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
640         AudioStreamInfo audioStreamInfo = {};
641         if (audioActiveDevice_.GetActiveA2dpDeviceStreamInfo(deviceType, audioStreamInfo)) {
642             AUDIO_DEBUG_LOG("Device configurations current rate: %{public}d, format: %{public}d, channel: %{public}d",
643                 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
644             AUDIO_DEBUG_LOG("Device configurations updated rate: %{public}d, format: %{public}d, channel: %{public}d",
645                 streamInfo.samplingRate, streamInfo.format, streamInfo.channels);
646             if ((audioStreamInfo.samplingRate != streamInfo.samplingRate)
647                 || (audioStreamInfo.channels != streamInfo.channels)
648                 || (audioStreamInfo.format != streamInfo.format)) {
649                 return true;
650             }
651         }
652     }
653 
654     return false;
655 }
656 
GetDeviceTypeFromPin(AudioPin hdiPin)657 DeviceType AudioDeviceStatus::GetDeviceTypeFromPin(AudioPin hdiPin)
658 {
659     switch (hdiPin) {
660         case OHOS::AudioStandard::AUDIO_PIN_NONE:
661             break;
662         case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
663         case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
664             return DeviceType::DEVICE_TYPE_SPEAKER;
665         case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
666             break;
667         case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
668             break;
669         case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
670             break;
671         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
672             break;
673         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
674             break;
675         case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_HEADSET:
676         case OHOS::AudioStandard::AUDIO_PIN_IN_USB_HEADSET:
677             return DeviceType::DEVICE_TYPE_USB_ARM_HEADSET;
678         case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
679         case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
680             return DeviceType::DEVICE_TYPE_MIC;
681         case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
682             break;
683         case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
684             break;
685         case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
686             break;
687         default:
688             break;
689     }
690     return DeviceType::DEVICE_TYPE_DEFAULT;
691 }
692 
OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)693 void AudioDeviceStatus::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop)
694 {
695     AUDIO_WARNING_LOG("Device connection updated | HDI_PIN[%{public}d] CONNECT_STATUS[%{public}d]"
696         " NETWORKID[%{public}s]", statusInfo.hdiPin, statusInfo.isConnected,
697         GetEncryptStr(statusInfo.networkId).c_str());
698     if (isStop) {
699         HandleOfflineDistributedDevice();
700         audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
701             audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 2.1 param");
702         return;
703     }
704     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
705     int32_t ret = HandleDistributedDeviceUpdate(statusInfo, descForCb);
706     CHECK_AND_RETURN_LOG(ret == SUCCESS, "HandleDistributedDeviceUpdate return directly.");
707 
708     TriggerDeviceChangedCallback(descForCb, statusInfo.isConnected);
709     TriggerAvailableDeviceChangedCallback(descForCb, statusInfo.isConnected);
710 
711     audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE);
712     audioDeviceCommon_.FetchDevice(false);
713 
714     DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
715     if (AudioPolicyUtils::GetInstance().GetDeviceRole(devType) == DeviceRole::INPUT_DEVICE) {
716         remoteCapturerSwitch_ = true;
717     }
718 
719     // update a2dp offload
720     if (audioA2dpOffloadManager_) {
721         audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
722     }
723     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
724         audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 2.2 param");
725 }
726 
ActivateNewDevice(std::string networkId,DeviceType deviceType,bool isRemote)727 int32_t AudioDeviceStatus::ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote)
728 {
729     if (isRemote) {
730         AudioModuleInfo moduleInfo = AudioPolicyUtils::GetInstance().ConstructRemoteAudioModuleInfo(networkId,
731             AudioPolicyUtils::GetInstance().GetDeviceRole(deviceType), deviceType);
732         std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId,
733             AudioPolicyUtils::GetInstance().GetDeviceRole(deviceType));
734         audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleName, moduleInfo);
735     }
736     return SUCCESS;
737 }
738 
HandleDistributedDeviceUpdate(DStatusInfo & statusInfo,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descForCb)739 int32_t AudioDeviceStatus::HandleDistributedDeviceUpdate(DStatusInfo &statusInfo,
740     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &descForCb)
741 {
742     DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
743     const std::string networkId = statusInfo.networkId;
744     AudioDeviceDescriptor deviceDesc(devType, AudioPolicyUtils::GetInstance().GetDeviceRole(devType));
745     // need fix to detect dmDeviceType and displayName
746     if (devType == DEVICE_TYPE_SPEAKER && networkId != LOCAL_NETWORK_ID) {
747         deviceDesc.dmDeviceType_ = 0x0B8;
748         statusInfo.deviceName = "HiCar";
749     }
750     deviceDesc.SetDeviceInfo(statusInfo.deviceName, statusInfo.macAddress);
751     deviceDesc.SetDeviceCapability(statusInfo.streamInfo, 0);
752     deviceDesc.networkId_ = networkId;
753     audioVolumeManager_.UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, networkId,
754         statusInfo.isConnected, statusInfo.mappingVolumeId);
755     audioVolumeManager_.UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, networkId,
756         statusInfo.isConnected, statusInfo.mappingInterruptId);
757     if (statusInfo.isConnected) {
758         if (audioConnectedDevice_.GetConnectedDeviceByType(networkId, devType) != nullptr) {
759             return ERROR;
760         }
761         int32_t ret = ActivateNewDevice(statusInfo.networkId, devType,
762             statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED);
763         CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "DEVICE online but open audio device failed.");
764         audioDeviceCommon_.UpdateConnectedDevicesWhenConnecting(deviceDesc, descForCb);
765 
766         if (statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED) {
767             AudioServerProxy::GetInstance().NotifyDeviceInfoProxy(networkId, true);
768         }
769     } else {
770         audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(deviceDesc, descForCb);
771         std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId,
772             AudioPolicyUtils::GetInstance().GetDeviceRole(devType));
773         std::string currentActivePort = REMOTE_CLASS;
774         audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
775         audioIOHandleMap_.ClosePortAndEraseIOHandle(moduleName);
776         audioRouteMap_.RemoveDeviceInRouterMap(moduleName);
777         audioRouteMap_.RemoveDeviceInFastRouterMap(networkId);
778     }
779     return SUCCESS;
780 }
781 
AddEarpiece()782 void AudioDeviceStatus::AddEarpiece()
783 {
784     if (!audioConfigManager_.GetHasEarpiece()) {
785         return;
786     }
787     std::shared_ptr<AudioDeviceDescriptor> audioDescriptor =
788         std::make_shared<AudioDeviceDescriptor>(DEVICE_TYPE_EARPIECE, OUTPUT_DEVICE);
789     CHECK_AND_RETURN_LOG(audioDescriptor != nullptr, "Create earpiect device descriptor failed");
790 
791     // Use speaker streaminfo for earpiece cap
792     auto itr = audioConnectedDevice_.GetConnectedDeviceByType(DEVICE_TYPE_SPEAKER);
793     if (itr != nullptr) {
794         audioDescriptor->SetDeviceCapability(itr->audioStreamInfo_, 0);
795     }
796     audioDescriptor->deviceId_ = AudioPolicyUtils::startDeviceId++;
797     AudioPolicyUtils::GetInstance().UpdateDisplayName(audioDescriptor);
798     audioDeviceManager_.AddNewDevice(audioDescriptor);
799     audioConnectedDevice_.AddConnectedDevice(audioDescriptor);
800     AUDIO_INFO_LOG("Add earpiece to device list");
801 }
802 
OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo & moduleInfo)803 bool AudioDeviceStatus::OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo &moduleInfo)
804 {
805     auto devType = AudioPolicyUtils::GetInstance().GetDeviceType(moduleInfo.name);
806     if (devType != DEVICE_TYPE_MIC) {
807         audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
808 
809         if (devType == DEVICE_TYPE_SPEAKER) {
810             auto result = audioPolicyManager_.SetDeviceActive(devType, moduleInfo.name, true);
811             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, false, "[module_load]::Device failed %{public}d", devType);
812         }
813     }
814 
815     if (devType == DEVICE_TYPE_MIC) {
816         audioEcManager_.SetPrimaryMicModuleInfo(moduleInfo);
817     }
818 
819     if (devType == DEVICE_TYPE_SPEAKER || devType == DEVICE_TYPE_MIC) {
820         AddAudioDevice(moduleInfo, devType);
821     }
822 
823     audioVolumeManager_.NotifyVolumeGroup();
824 
825     return true;
826 }
827 
AddAudioDevice(AudioModuleInfo & moduleInfo,DeviceType devType)828 void AudioDeviceStatus::AddAudioDevice(AudioModuleInfo& moduleInfo, DeviceType devType)
829 {
830     // add new device into active device list
831     std::string volumeGroupName = audioConfigManager_.GetGroupName(moduleInfo.name, VOLUME_TYPE);
832     std::string interruptGroupName = audioConfigManager_.GetGroupName(moduleInfo.name, INTERRUPT_TYPE);
833     int32_t volumeGroupId = GROUP_ID_NONE;
834     int32_t interruptGroupId = GROUP_ID_NONE;
835     audioVolumeManager_.UpdateGroupInfo(GroupType::VOLUME_TYPE, volumeGroupName, volumeGroupId, LOCAL_NETWORK_ID, true,
836         NO_REMOTE_ID);
837     audioVolumeManager_.UpdateGroupInfo(GroupType::INTERRUPT_TYPE, interruptGroupName, interruptGroupId,
838         LOCAL_NETWORK_ID, true, NO_REMOTE_ID);
839 
840     std::shared_ptr<AudioDeviceDescriptor> audioDescriptor = std::make_shared<AudioDeviceDescriptor>(devType,
841         AudioPolicyUtils::GetInstance().GetDeviceRole(moduleInfo.role), volumeGroupId, interruptGroupId,
842         LOCAL_NETWORK_ID);
843     if (!moduleInfo.supportedRate_.empty() && !moduleInfo.supportedChannels_.empty()) {
844         DeviceStreamInfo streamInfo = {};
845         for (auto supportedRate : moduleInfo.supportedRate_) {
846             streamInfo.samplingRate.insert(static_cast<AudioSamplingRate>(supportedRate));
847         }
848         for (auto supportedChannels : moduleInfo.supportedChannels_) {
849             streamInfo.channels.insert(static_cast<AudioChannel>(supportedChannels));
850         }
851         audioDescriptor->SetDeviceCapability(streamInfo, 0);
852     }
853 
854     audioDescriptor->deviceId_ = AudioPolicyUtils::startDeviceId++;
855     AudioPolicyUtils::GetInstance().UpdateDisplayName(audioDescriptor);
856     audioDeviceManager_.AddNewDevice(audioDescriptor);
857     audioConnectedDevice_.AddConnectedDevice(audioDescriptor);
858     audioMicrophoneDescriptor_.AddMicrophoneDescriptor(audioDescriptor);
859 }
860 
OnServiceConnected(AudioServiceIndex serviceIndex)861 int32_t AudioDeviceStatus::OnServiceConnected(AudioServiceIndex serviceIndex)
862 {
863     int32_t result = ERROR;
864     AUDIO_DEBUG_LOG("[module_load]::HDI and AUDIO SERVICE is READY. Loading default modules");
865     std::unordered_map<ClassType, std::list<AudioModuleInfo>> deviceClassInfo = {};
866     audioConfigManager_.GetDeviceClassInfo(deviceClassInfo);
867     for (const auto &device : deviceClassInfo) {
868         if (device.first != ClassType::TYPE_PRIMARY && device.first != ClassType::TYPE_FILE_IO) {
869             continue;
870         }
871         if (device.first == ClassType::TYPE_PRIMARY) {
872             AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "primary");
873         }
874         auto moduleInfoList = device.second;
875         for (auto &moduleInfo : moduleInfoList) {
876             AUDIO_INFO_LOG("[module_load]::Load module[%{public}s]", moduleInfo.name.c_str());
877             uint32_t sinkLatencyInMsec = audioConfigManager_.GetSinkLatencyFromXml();
878             moduleInfo.sinkLatency = sinkLatencyInMsec != 0 ? to_string(sinkLatencyInMsec) : "";
879             if (OpenPortAndAddDeviceOnServiceConnected(moduleInfo)) {
880                 result = SUCCESS;
881             }
882             audioOffloadStream_.SetOffloadAvailableFromXML(moduleInfo);
883         }
884     }
885 
886     if (result == SUCCESS) {
887         AUDIO_INFO_LOG("[module_load]::Setting speaker as active device on bootup");
888         hasModulesLoaded = true;
889         shared_ptr<AudioDeviceDescriptor> outDevice = audioDeviceManager_.GetRenderDefaultDevice();
890         audioActiveDevice_.SetCurrentOutputDevice(*outDevice);
891         shared_ptr<AudioDeviceDescriptor> inDevice = audioDeviceManager_.GetCaptureDefaultDevice();
892         audioActiveDevice_.SetCurrentInputDevice(*inDevice);
893         audioVolumeManager_.SetVolumeForSwitchDevice(audioActiveDevice_.GetCurrentOutputDeviceType());
894         OnPreferredDeviceUpdated(audioActiveDevice_.GetCurrentOutputDevice(),
895             audioActiveDevice_.GetCurrentInputDeviceType());
896         AddEarpiece();
897         for (auto it = pnpDeviceList_.begin(); it != pnpDeviceList_.end(); ++it) {
898             OnPnpDeviceStatusUpdated((*it).first, (*it).second);
899         }
900     }
901     return result;
902 }
903 
OnPreferredDeviceUpdated(const AudioDeviceDescriptor & activeOutputDevice,DeviceType activeInputDevice)904 void AudioDeviceStatus::OnPreferredDeviceUpdated(const AudioDeviceDescriptor& activeOutputDevice,
905     DeviceType activeInputDevice)
906 {
907     audioDeviceCommon_.OnPreferredOutputDeviceUpdated(activeOutputDevice);
908     audioDeviceCommon_.OnPreferredInputDeviceUpdated(activeInputDevice, LOCAL_NETWORK_ID);
909 }
910 
OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)911 void AudioDeviceStatus::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress)
912 {
913     if (macAddress.empty()) {
914         AUDIO_ERR_LOG("failed as the macAddress is empty!");
915         return;
916     }
917     AUDIO_INFO_LOG("bt select device type[%{public}d] address[%{public}s]",
918         devType, GetEncryptAddr(macAddress).c_str());
919     std::vector<shared_ptr<AudioDeviceDescriptor>> bluetoothDevices =
920         audioDeviceManager_.GetAvailableBluetoothDevice(devType, macAddress);
921     std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
922     for (const auto &dec : bluetoothDevices) {
923         if (dec->deviceRole_ == DeviceRole::OUTPUT_DEVICE) {
924             std::shared_ptr<AudioDeviceDescriptor> tempDec = std::make_shared<AudioDeviceDescriptor>(*dec);
925             audioDeviceDescriptors.push_back(move(tempDec));
926         }
927     }
928     int32_t res = audioDeviceCommon_.DeviceParamsCheck(DeviceRole::OUTPUT_DEVICE, audioDeviceDescriptors);
929     CHECK_AND_RETURN_LOG(res == SUCCESS, "DeviceParamsCheck no success");
930     audioDeviceDescriptors[0]->isEnable_ = true;
931     audioDeviceManager_.UpdateDevicesListInfo(audioDeviceDescriptors[0], ENABLE_UPDATE);
932     if (devType == DEVICE_TYPE_BLUETOOTH_SCO) {
933         AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_RENDER, audioDeviceDescriptors[0], SYSTEM_UID,
934             "OnForcedDeviceSelected");
935         AudioPolicyUtils::GetInstance().ClearScoDeviceSuspendState(audioDeviceDescriptors[0]->macAddress_);
936     } else {
937         AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER, audioDeviceDescriptors[0]);
938     }
939     audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
940     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
941         audioActiveDevice_.GetCurrentOutputDevice(), "OnForcedDeviceSelected");
942 }
943 
OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,DeviceType devType,std::string macAddress,std::string deviceName,bool isActualConnection,AudioStreamInfo streamInfo,bool isConnected)944 void AudioDeviceStatus::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, DeviceType devType,
945     std::string macAddress, std::string deviceName, bool isActualConnection, AudioStreamInfo streamInfo,
946     bool isConnected)
947 {
948     AUDIO_WARNING_LOG("Device connection state updated | TYPE[%{public}d] STATUS[%{public}d], mac[%{public}s]",
949         devType, isConnected, GetEncryptStr(macAddress).c_str());
950 
951     auto devDesc = make_shared<AudioDeviceDescriptor>(updatedDesc);
952     if (!isActualConnection && audioDeviceManager_.IsConnectedDevices(devDesc)) {
953         audioDeviceManager_.UpdateVirtualDevices(devDesc, isConnected);
954         return;
955     }
956 
957     UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc);
958     // fill device change action for callback
959     AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN;
960     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
961     updatedDesc.spatializationSupported_ = (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP)
962         && AudioSpatializationService::GetAudioSpatializationService().
963         IsSpatializationSupportedForDevice(updatedDesc.macAddress_)
964         && AudioSpatializationService::GetAudioSpatializationService().IsSpatializationSupported();
965     UpdateDeviceList(updatedDesc, isConnected, descForCb, reason);
966 
967     TriggerDeviceChangedCallback(descForCb, isConnected);
968     TriggerAvailableDeviceChangedCallback(descForCb, isConnected);
969 
970     if (!isActualConnection) {
971         return;
972     }
973     // fetch input&output device
974     audioDeviceCommon_.FetchDevice(true, reason);
975     audioDeviceCommon_.FetchDevice(false);
976     // update a2dp offload
977     if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && audioA2dpOffloadManager_) {
978         audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
979     }
980     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
981         audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 2 param");
982 }
983 
UpdateDeviceList(AudioDeviceDescriptor & updatedDesc,bool isConnected,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descForCb,AudioStreamDeviceChangeReasonExt & reason)984 void AudioDeviceStatus::UpdateDeviceList(AudioDeviceDescriptor &updatedDesc,  bool isConnected,
985     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &descForCb,
986     AudioStreamDeviceChangeReasonExt &reason)
987 {
988     if (isConnected) {
989         // deduplicate
990         audioConnectedDevice_.DelConnectedDevice(updatedDesc.networkId_, updatedDesc.deviceType_,
991             updatedDesc.macAddress_, updatedDesc.deviceRole_);
992         audioDeviceCommon_.UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb);
993         int32_t result = HandleLocalDeviceConnected(updatedDesc);
994         CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed.");
995         reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
996     } else {
997         audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb);
998         reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
999         CheckForA2dpSuspend(updatedDesc);
1000         audioDeviceCommon_.FetchDevice(true, reason); //  fix pop, fetch device before unload module
1001         int32_t result = HandleLocalDeviceDisconnected(updatedDesc);
1002         CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed.");
1003         reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
1004     }
1005 }
1006 
1007 #ifdef BLUETOOTH_ENABLE
CheckAndActiveHfpDevice(AudioDeviceDescriptor & desc)1008 void AudioDeviceStatus::CheckAndActiveHfpDevice(AudioDeviceDescriptor &desc)
1009 {
1010     if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && !audioDeviceManager_.GetScoState()) {
1011         Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc.macAddress_);
1012     }
1013 }
1014 #endif
1015 
OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)1016 void AudioDeviceStatus::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command)
1017 {
1018     AUDIO_WARNING_LOG("[%{public}s] type[%{public}d] command: %{public}d category[%{public}d] " \
1019         "connectState[%{public}d] isEnable[%{public}d]", GetEncryptAddr(desc.macAddress_).c_str(),
1020         desc.deviceType_, command, desc.deviceCategory_, desc.connectState_, desc.isEnable_);
1021     DeviceUpdateClearRecongnitionStatus(desc);
1022     if (command == ENABLE_UPDATE && desc.isEnable_ == true) {
1023         if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
1024             AudioPolicyUtils::GetInstance().ClearScoDeviceSuspendState(desc.macAddress_);
1025         }
1026         shared_ptr<AudioDeviceDescriptor> userSelectMediaDevice =
1027             AudioStateManager::GetAudioStateManager().GetPreferredMediaRenderDevice();
1028         shared_ptr<AudioDeviceDescriptor> userSelectCallDevice =
1029             AudioStateManager::GetAudioStateManager().GetPreferredCallRenderDevice();
1030         if ((userSelectMediaDevice->deviceType_ == desc.deviceType_ &&
1031             userSelectMediaDevice->macAddress_ == desc.macAddress_ &&
1032             userSelectMediaDevice->isEnable_ == desc.isEnable_) ||
1033             (userSelectCallDevice->deviceType_ == desc.deviceType_ &&
1034             userSelectCallDevice->macAddress_ == desc.macAddress_ &&
1035             userSelectCallDevice->isEnable_ == desc.isEnable_)) {
1036             AUDIO_INFO_LOG("Current enable state has been set true during user selection, no need to be set again.");
1037             return;
1038         }
1039     } else if (command == ENABLE_UPDATE && !desc.isEnable_ && desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
1040         audioActiveDevice_.GetCurrentOutputDeviceMacAddr() == desc.macAddress_) {
1041         audioIOHandleMap_.MuteDefaultSinkPort(audioActiveDevice_.GetCurrentOutputDeviceNetworkId(),
1042             AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType()));
1043         audioIOHandleMap_.ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER);
1044     }
1045     std::shared_ptr<AudioDeviceDescriptor> audioDescriptor = std::make_shared<AudioDeviceDescriptor>(desc);
1046     audioDeviceManager_.UpdateDevicesListInfo(audioDescriptor, command);
1047     CheckForA2dpSuspend(desc);
1048 
1049     AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN;
1050     OnPreferredStateUpdated(desc, command, reason);
1051     audioDeviceCommon_.FetchDevice(true, reason);
1052     audioDeviceCommon_.FetchDevice(false);
1053     if (audioA2dpOffloadManager_) {
1054         audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
1055     }
1056     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
1057         audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceInfoUpdated");
1058 }
1059 
CheckForA2dpSuspend(AudioDeviceDescriptor & desc)1060 void AudioDeviceStatus::CheckForA2dpSuspend(AudioDeviceDescriptor &desc)
1061 {
1062     if (desc.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) {
1063         return;
1064     }
1065     if (audioDeviceManager_.GetScoState()) {
1066         AudioServerProxy::GetInstance().SuspendRenderSinkProxy("a2dp");
1067     } else {
1068         AudioServerProxy::GetInstance().RestoreRenderSinkProxy("a2dp");
1069     }
1070 }
1071 
UserSelectDeviceMapInit()1072 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioDeviceStatus::UserSelectDeviceMapInit()
1073 {
1074     AudioStateManager& stateManager = AudioStateManager::GetAudioStateManager();
1075     shared_ptr<AudioDeviceDescriptor> userSelectMediaRenderDevice = stateManager.GetPreferredMediaRenderDevice();
1076     shared_ptr<AudioDeviceDescriptor> userSelectCallRenderDevice = stateManager.GetPreferredCallRenderDevice();
1077     shared_ptr<AudioDeviceDescriptor> userSelectCallCaptureDevice = stateManager.GetPreferredCallCaptureDevice();
1078     shared_ptr<AudioDeviceDescriptor> userSelectRecordCaptureDevice = stateManager.GetPreferredRecordCaptureDevice();
1079     vector<shared_ptr<AudioDeviceDescriptor>> userSelectDeviceMap;
1080     userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectMediaRenderDevice));
1081     userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectCallRenderDevice));
1082     userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectCallCaptureDevice));
1083     userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectRecordCaptureDevice));
1084     return userSelectDeviceMap;
1085 }
1086 
OnPreferredStateUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand updateCommand,AudioStreamDeviceChangeReasonExt & reason)1087 void AudioDeviceStatus::OnPreferredStateUpdated(AudioDeviceDescriptor &desc,
1088     const DeviceInfoUpdateCommand updateCommand, AudioStreamDeviceChangeReasonExt &reason)
1089 {
1090     vector<shared_ptr<AudioDeviceDescriptor>> userSelectDeviceMap = UserSelectDeviceMapInit();
1091     if (updateCommand == CATEGORY_UPDATE) {
1092         if (desc.deviceCategory_ == BT_UNWEAR_HEADPHONE) {
1093             reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
1094             UpdateAllUserSelectDevice(userSelectDeviceMap, desc, std::make_shared<AudioDeviceDescriptor>());
1095 #ifdef BLUETOOTH_ENABLE
1096             if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
1097                 desc.macAddress_ == audioActiveDevice_.GetCurrentOutputDeviceMacAddr()) {
1098                 Bluetooth::AudioA2dpManager::SetActiveA2dpDevice("");
1099             } else if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO &&
1100                 desc.macAddress_ == audioActiveDevice_.GetCurrentOutputDeviceMacAddr()) {
1101                 Bluetooth::AudioHfpManager::DisconnectSco();
1102             }
1103 #endif
1104         } else {
1105             reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
1106             if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
1107                 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER,
1108                     std::make_shared<AudioDeviceDescriptor>());
1109                 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_RECORD_CAPTURE,
1110                     std::make_shared<AudioDeviceDescriptor>());
1111             } else {
1112                 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_RENDER,
1113                     std::make_shared<AudioDeviceDescriptor>(), CLEAR_UID, "OnPreferredStateUpdated");
1114                 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_CAPTURE,
1115                     std::make_shared<AudioDeviceDescriptor>());
1116                 AudioPolicyUtils::GetInstance().ClearScoDeviceSuspendState(desc.macAddress_);
1117 #ifdef BLUETOOTH_ENABLE
1118                 CheckAndActiveHfpDevice(desc);
1119 #endif
1120             }
1121         }
1122     } else if (updateCommand == ENABLE_UPDATE) {
1123         if (!desc.isEnable_ && desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO &&
1124             desc.IsSameDeviceDesc(audioActiveDevice_.GetCurrentOutputDevice())) {
1125             Bluetooth::AudioHfpManager::DisconnectSco();
1126         }
1127         UpdateAllUserSelectDevice(userSelectDeviceMap, desc, std::make_shared<AudioDeviceDescriptor>(desc));
1128         reason = desc.isEnable_ ? AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE :
1129             AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
1130     }
1131 }
1132 
UpdateAllUserSelectDevice(std::vector<std::shared_ptr<AudioDeviceDescriptor>> & userSelectDeviceMap,AudioDeviceDescriptor & desc,const std::shared_ptr<AudioDeviceDescriptor> & selectDesc)1133 void AudioDeviceStatus::UpdateAllUserSelectDevice(
1134     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &userSelectDeviceMap,
1135     AudioDeviceDescriptor &desc, const std::shared_ptr<AudioDeviceDescriptor> &selectDesc)
1136 {
1137     if (userSelectDeviceMap[MEDIA_RENDER_ID]->deviceType_ == desc.deviceType_ &&
1138         userSelectDeviceMap[MEDIA_RENDER_ID]->macAddress_ == desc.macAddress_) {
1139         if (userSelectDeviceMap[MEDIA_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) {
1140             AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER,
1141                 std::make_shared<AudioDeviceDescriptor>(selectDesc));
1142         } else {
1143             audioStateManager_.UpdatePreferredMediaRenderDeviceConnectState(desc.connectState_);
1144         }
1145     }
1146     if (userSelectDeviceMap[CALL_RENDER_ID]->deviceType_ == desc.deviceType_ &&
1147         userSelectDeviceMap[CALL_RENDER_ID]->macAddress_ == desc.macAddress_) {
1148         if (userSelectDeviceMap[CALL_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) {
1149             AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_RENDER,
1150                 std::make_shared<AudioDeviceDescriptor>(selectDesc), SYSTEM_UID, "UpdateAllUserSelectDevice");
1151         } else {
1152             audioStateManager_.UpdatePreferredCallRenderDeviceConnectState(desc.connectState_);
1153         }
1154     }
1155     if (userSelectDeviceMap[CALL_CAPTURE_ID]->deviceType_ == desc.deviceType_ &&
1156         userSelectDeviceMap[CALL_CAPTURE_ID]->macAddress_ == desc.macAddress_) {
1157         if (userSelectDeviceMap[CALL_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) {
1158             AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_CAPTURE,
1159                 std::make_shared<AudioDeviceDescriptor>(selectDesc));
1160         } else {
1161             audioStateManager_.UpdatePreferredCallCaptureDeviceConnectState(desc.connectState_);
1162         }
1163     }
1164     if (userSelectDeviceMap[RECORD_CAPTURE_ID]->deviceType_ == desc.deviceType_ &&
1165         userSelectDeviceMap[RECORD_CAPTURE_ID]->macAddress_ == desc.macAddress_) {
1166         if (userSelectDeviceMap[RECORD_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) {
1167             AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_RECORD_CAPTURE,
1168                 std::make_shared<AudioDeviceDescriptor>(selectDesc));
1169         } else {
1170             audioStateManager_.UpdatePreferredRecordCaptureDeviceConnectState(desc.connectState_);
1171         }
1172     }
1173 }
1174 
DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor & desc)1175 void AudioDeviceStatus::DeviceUpdateClearRecongnitionStatus(AudioDeviceDescriptor &desc)
1176 {
1177     if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && (desc.deviceCategory_ == BT_UNWEAR_HEADPHONE ||
1178         desc.connectState_ == DEACTIVE_CONNECTED || desc.connectState_ == SUSPEND_CONNECTED || !desc.isEnable_)) {
1179         audioDeviceCommon_.BluetoothScoDisconectForRecongnition();
1180         Bluetooth::AudioHfpManager::ClearRecongnitionStatus();
1181     }
1182 }
1183 
HandleOfflineDistributedDevice()1184 void AudioDeviceStatus::HandleOfflineDistributedDevice()
1185 {
1186     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {};
1187 
1188     std::vector<std::shared_ptr<AudioDeviceDescriptor>> connectedDevices = audioConnectedDevice_.GetCopy();
1189     for (auto deviceDesc : connectedDevices) {
1190         if (deviceDesc != nullptr && deviceDesc->networkId_ != LOCAL_NETWORK_ID) {
1191             const std::string networkId = deviceDesc->networkId_;
1192             audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(deviceDesc, deviceChangeDescriptor);
1193             std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId,
1194                 AudioPolicyUtils::GetInstance().GetDeviceRole(deviceDesc->deviceType_));
1195             audioIOHandleMap_.MuteDefaultSinkPort(audioActiveDevice_.GetCurrentOutputDeviceNetworkId(),
1196                 AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType()));
1197             audioIOHandleMap_.ClosePortAndEraseIOHandle(moduleName);
1198             audioRouteMap_.RemoveDeviceInRouterMap(moduleName);
1199             audioRouteMap_.RemoveDeviceInFastRouterMap(networkId);
1200             if (AudioPolicyUtils::GetInstance().GetDeviceRole(deviceDesc->deviceType_) == DeviceRole::INPUT_DEVICE) {
1201                 remoteCapturerSwitch_ = true;
1202             }
1203         }
1204     }
1205 
1206     TriggerDeviceChangedCallback(deviceChangeDescriptor, false);
1207     TriggerAvailableDeviceChangedCallback(deviceChangeDescriptor, false);
1208     AUDIO_INFO_LOG("onDeviceStatusUpdated reson:%{public}d",
1209         AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE);
1210     audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE);
1211     audioDeviceCommon_.FetchDevice(false);
1212 }
1213 
1214 }
1215 }
1216