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_event_utils.h"
32 #include "audio_server_proxy.h"
33 #include "audio_core_service.h"
34 #include "audio_utils_c.h"
35 #include "sle_audio_device_manager.h"
36 #include "audio_zone_service.h"
37
38 namespace OHOS {
39 namespace AudioStandard {
40 const int MEDIA_RENDER_ID = 0;
41 const int CALL_RENDER_ID = 1;
42 const int CALL_CAPTURE_ID = 2;
43 const int RECORD_CAPTURE_ID = 3;
44 const uint32_t REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS = 30000;
45 const std::string DEFAULT_BUFFER_SIZE_8000 = "320";
46
47 const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50;
48
GetEncryptAddr(const std::string & addr)49 static std::string GetEncryptAddr(const std::string &addr)
50 {
51 const int32_t START_POS = 6;
52 const int32_t END_POS = 13;
53 const int32_t ADDRESS_STR_LEN = 17;
54 if (addr.empty() || addr.length() != ADDRESS_STR_LEN) {
55 return std::string("");
56 }
57 std::string tmp = "**:**:**:**:**:**";
58 std::string out = addr;
59 for (int i = START_POS; i <= END_POS; i++) {
60 out[i] = tmp[i];
61 }
62 return out;
63 }
64
GetField(const std::string & src,const char * field,const char sep)65 static std::string GetField(const std::string &src, const char* field, const char sep)
66 {
67 auto str = std::string(field) + '=';
68 auto pos = src.find(str);
69 CHECK_AND_RETURN_RET(pos != std::string::npos, "");
70 pos += str.length();
71 auto end = src.find(sep, pos);
72 return end == std::string::npos ? src.substr(pos) : src.substr(pos, end - pos);
73 }
74
GetDPModuleInfo(AudioModuleInfo & moduleInfo,string deviceInfo)75 static void GetDPModuleInfo(AudioModuleInfo &moduleInfo, string deviceInfo)
76 {
77 auto rate_begin = deviceInfo.find("rate=");
78 auto rate_end = deviceInfo.find_first_of(" ", rate_begin);
79 if (rate_end > rate_begin) {
80 moduleInfo.rate = deviceInfo.substr(rate_begin + std::strlen("rate="),
81 rate_end - rate_begin - std::strlen("rate="));
82 }
83 if (moduleInfo.role == "sink") {
84 auto sinkFormat_begin = deviceInfo.find("format=");
85 auto sinkFormat_end = deviceInfo.find_first_of(" ", sinkFormat_begin);
86 string format = deviceInfo.substr(sinkFormat_begin + std::strlen("format="),
87 sinkFormat_end - sinkFormat_begin - std::strlen("format="));
88 if (!format.empty()) moduleInfo.format = format;
89
90 auto sinkChannel_begin = deviceInfo.find("channels=");
91 auto sinkChannel_end = deviceInfo.find_first_of(" ", sinkChannel_begin);
92 string channel = deviceInfo.substr(sinkChannel_begin + std::strlen("channels="),
93 sinkChannel_end - sinkChannel_begin - std::strlen("channels="));
94 moduleInfo.channels = channel;
95
96 auto sinkBSize_begin = deviceInfo.find("buffer_size=");
97 auto sinkBSize_end = deviceInfo.find_first_of(" ", sinkBSize_begin);
98 string bufferSize = deviceInfo.substr(sinkBSize_begin + std::strlen("buffer_size="),
99 sinkBSize_end - sinkBSize_begin - std::strlen("buffer_size="));
100 moduleInfo.bufferSize = bufferSize;
101 }
102 }
103
Init(std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager,std::shared_ptr<AudioPolicyServerHandler> handler)104 void AudioDeviceStatus::Init(std::shared_ptr<AudioA2dpOffloadManager> audioA2dpOffloadManager,
105 std::shared_ptr<AudioPolicyServerHandler> handler)
106 {
107 audioA2dpOffloadManager_ = audioA2dpOffloadManager;
108 audioPolicyServerHandler_ = handler;
109 }
110
DeInit()111 void AudioDeviceStatus::DeInit()
112 {
113 audioA2dpOffloadManager_ = nullptr;
114 audioPolicyServerHandler_ = nullptr;
115 }
116
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo,DeviceRole role,bool hasPair)117 void AudioDeviceStatus::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
118 const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair)
119 {
120 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN;
121 // fill device change action for callback
122 std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
123
124 int32_t result = HandleSpecialDeviceType(devType, isConnected, macAddress, role);
125 CheckAndWriteDeviceChangeExceptionEvent(result == SUCCESS, reason, devType, role, result,
126 "handle special deviceType failed.");
127 CHECK_AND_RETURN_LOG(result == SUCCESS, "handle special deviceType failed.");
128
129 AUDIO_WARNING_LOG("[ADeviceEvent] device[%{public}d] address[%{public}s] role[%{public}d] connect[%{public}d]",
130 devType, GetEncryptStr(macAddress).c_str(), role, isConnected);
131
132 AudioDeviceDescriptor updatedDesc(devType, role == DEVICE_ROLE_NONE ?
133 AudioPolicyUtils::GetInstance().GetDeviceRole(devType) : role);
134 updatedDesc.hasPair_ = hasPair;
135 UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc);
136
137 if (isConnected) {
138 // If device already in list, remove it else do not modify the list
139 audioConnectedDevice_.DelConnectedDevice(updatedDesc.networkId_, updatedDesc.deviceType_,
140 updatedDesc.macAddress_, updatedDesc.deviceRole_);
141 // If the pnp device fails to load, it will not connect
142 result = HandleLocalDeviceConnected(updatedDesc);
143 CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed.");
144 audioDeviceCommon_.UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb);
145
146 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
147 #ifdef BLUETOOTH_ENABLE
148 if (updatedDesc.connectState_ == CONNECTED &&
149 updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
150 AudioRendererInfo rendererInfo = {};
151 rendererInfo.streamUsage = STREAM_USAGE_VOICE_COMMUNICATION;
152 std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
153 audioDeviceCommon_.GetPreferredOutputDeviceDescInner(rendererInfo);
154 if (preferredDeviceList.size() > 0 &&
155 preferredDeviceList[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
156 Bluetooth::AudioHfpManager::SetActiveHfpDevice(preferredDeviceList[0]->macAddress_);
157 }
158 }
159 #endif
160 } else {
161 audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb);
162 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
163 }
164
165 TriggerDeviceChangedCallback(descForCb, isConnected);
166 TriggerAvailableDeviceChangedCallback(descForCb, isConnected);
167
168 // fetch input&output device
169 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("OnDeviceStatusUpdated_2", reason);
170 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("OnDeviceStatusUpdated_2");
171
172 if (!isConnected) {
173 result = HandleLocalDeviceDisconnected(updatedDesc);
174 CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed.");
175 }
176
177 // update a2dp offload
178 audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
179 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
180 audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 5 param");
181 }
182
WriteOutputDeviceChangedSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & deviceDescriptor,const SinkInput & sinkInput)183 void AudioDeviceStatus::WriteOutputDeviceChangedSysEvents(
184 const std::shared_ptr<AudioDeviceDescriptor> &deviceDescriptor, const SinkInput &sinkInput)
185 {
186 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
187 Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE,
188 Media::MediaMonitor::BEHAVIOR_EVENT);
189 bean->Add("ISOUTPUT", 1);
190 bean->Add("STREAMID", sinkInput.streamId);
191 bean->Add("STREAMTYPE", sinkInput.streamType);
192 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_);
193 bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_));
194 bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_));
195 bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_);
196 bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_);
197 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
198 AUTO_CTRACE("SYSEVENT BEHAVIOR EVENT DEVICE_CHANGE, ISOUTPUT: 1, STREAMID: %d, STREAMTYPE: %d, DEVICETYPE: %d, "
199 "NETWORKID: %s, ADDRESS: %s, DEVICE_NAME: %s, BT_TYPE: %d", sinkInput.streamId, sinkInput.streamType,
200 deviceDescriptor->deviceType_, ConvertNetworkId(deviceDescriptor->networkId_).c_str(),
201 GetEncryptAddr(deviceDescriptor->macAddress_).c_str(),
202 deviceDescriptor->deviceName_.c_str(), deviceDescriptor->deviceCategory_);
203 }
204
WriteInputDeviceChangedSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & deviceDescriptor,const SourceOutput & sourceOutput)205 void AudioDeviceStatus::WriteInputDeviceChangedSysEvents(
206 const std::shared_ptr<AudioDeviceDescriptor> &deviceDescriptor, const SourceOutput &sourceOutput)
207 {
208 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
209 Media::MediaMonitor::AUDIO, Media::MediaMonitor::DEVICE_CHANGE,
210 Media::MediaMonitor::BEHAVIOR_EVENT);
211 bean->Add("ISOUTPUT", 0);
212 bean->Add("STREAMID", sourceOutput.streamId);
213 bean->Add("STREAMTYPE", sourceOutput.streamType);
214 bean->Add("DEVICETYPE", deviceDescriptor->deviceType_);
215 bean->Add("NETWORKID", ConvertNetworkId(deviceDescriptor->networkId_));
216 bean->Add("ADDRESS", GetEncryptAddr(deviceDescriptor->macAddress_));
217 bean->Add("DEVICE_NAME", deviceDescriptor->deviceName_);
218 bean->Add("BT_TYPE", deviceDescriptor->deviceCategory_);
219 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
220 AUTO_CTRACE("SYSEVENT BEHAVIOR EVENT DEVICE_CHANGE, ISOUTPUT: 0, STREAMID: %d, STREAMTYPE: %d, DEVICETYPE: %d, "
221 "NETWORKID: %s, ADDRESS: %s, DEVICE_NAME: %s, BT_TYPE: %d", sourceOutput.streamId, sourceOutput.streamType,
222 deviceDescriptor->deviceType_, ConvertNetworkId(deviceDescriptor->networkId_).c_str(),
223 GetEncryptAddr(deviceDescriptor->macAddress_).c_str(),
224 deviceDescriptor->deviceName_.c_str(), deviceDescriptor->deviceCategory_);
225 }
226
227
WriteHeadsetSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & desc,bool isConnected)228 void AudioDeviceStatus::WriteHeadsetSysEvents(const std::shared_ptr<AudioDeviceDescriptor> &desc, bool isConnected)
229 {
230 CHECK_AND_RETURN_LOG(desc != nullptr, "desc is null");
231 if ((desc->deviceType_ == DEVICE_TYPE_WIRED_HEADSET) ||
232 (desc->deviceType_ == DEVICE_TYPE_USB_HEADSET) ||
233 (desc->deviceType_ == DEVICE_TYPE_WIRED_HEADPHONES)) {
234 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
235 Media::MediaMonitor::AUDIO, Media::MediaMonitor::HEADSET_CHANGE,
236 Media::MediaMonitor::BEHAVIOR_EVENT);
237 bean->Add("HASMIC", 1);
238 bean->Add("ISCONNECT", isConnected ? 1 : 0);
239 bean->Add("DEVICETYPE", desc->deviceType_);
240 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
241 }
242 }
243
WriteDeviceChangeSysEvents(const std::shared_ptr<AudioDeviceDescriptor> & desc)244 void AudioDeviceStatus::WriteDeviceChangeSysEvents(const std::shared_ptr<AudioDeviceDescriptor> &desc)
245 {
246 CHECK_AND_RETURN_LOG(desc != nullptr, "desc is null");
247 if (desc->deviceRole_ == OUTPUT_DEVICE) {
248 std::vector<SinkInput> sinkInputs;
249 audioPolicyManager_.GetAllSinkInputs(sinkInputs);
250 for (SinkInput sinkInput : sinkInputs) {
251 WriteOutputDeviceChangedSysEvents(desc, sinkInput);
252 }
253 } else if (desc->deviceRole_ == INPUT_DEVICE) {
254 std::vector<SourceOutput> sourceOutputs = audioDeviceCommon_.GetSourceOutputs();
255 for (SourceOutput sourceOutput : sourceOutputs) {
256 WriteInputDeviceChangedSysEvents(desc, sourceOutput);
257 }
258 }
259 }
260
WriteAllDeviceSysEvents(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,bool isConnected)261 void AudioDeviceStatus::WriteAllDeviceSysEvents(
262 const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc, bool isConnected)
263 {
264 Trace trace("AudioDeviceStatus::WriteAllDeviceSysEvents");
265 for (auto deviceDescriptor : desc) {
266 WriteHeadsetSysEvents(deviceDescriptor, isConnected);
267 if (!isConnected) {
268 continue;
269 }
270 WriteDeviceChangeSysEvents(deviceDescriptor);
271 }
272 }
273
TriggerAvailableDeviceChangedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,bool isConnected)274 void AudioDeviceStatus::TriggerAvailableDeviceChangedCallback(
275 const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc, bool isConnected)
276 {
277 Trace trace("AudioDeviceStatus::TriggerAvailableDeviceChangedCallback");
278
279 WriteAllDeviceSysEvents(desc, isConnected);
280
281 if (audioPolicyServerHandler_ != nullptr) {
282 audioPolicyServerHandler_->SendAvailableDeviceChange(desc, isConnected);
283 }
284 }
285
TriggerDeviceChangedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,bool isConnected)286 void AudioDeviceStatus::TriggerDeviceChangedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc,
287 bool isConnected)
288 {
289 Trace trace("AudioDeviceStatus::TriggerDeviceChangedCallback");
290 WriteAllDeviceSysEvents(desc, isConnected);
291 if (audioPolicyServerHandler_ != nullptr) {
292 audioPolicyServerHandler_->SendDeviceChangedCallback(desc, isConnected);
293 }
294 }
295
UpdateLocalGroupInfo(bool isConnected,const std::string & macAddress,const std::string & deviceName,const DeviceStreamInfo & streamInfo,AudioDeviceDescriptor & deviceDesc)296 void AudioDeviceStatus::UpdateLocalGroupInfo(bool isConnected, const std::string& macAddress,
297 const std::string& deviceName, const DeviceStreamInfo& streamInfo, AudioDeviceDescriptor& deviceDesc)
298 {
299 deviceDesc.SetDeviceInfo(deviceName, macAddress);
300 deviceDesc.SetDeviceCapability({ streamInfo }, 0);
301 audioVolumeManager_.UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, LOCAL_NETWORK_ID,
302 isConnected, NO_REMOTE_ID);
303 audioVolumeManager_.UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_,
304 LOCAL_NETWORK_ID, isConnected, NO_REMOTE_ID);
305 deviceDesc.networkId_ = LOCAL_NETWORK_ID;
306 }
307
RehandlePnpDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)308 int32_t AudioDeviceStatus::RehandlePnpDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address)
309 {
310 Trace trace("AudioDeviceStatus::RehandlePnpDevice");
311
312 // Maximum number of attempts, preventing situations where hal has not yet finished coming online.
313 int32_t maxRetries = 3;
314 int32_t retryCount = 0;
315 bool isConnected = true;
316 while (retryCount < maxRetries) {
317 retryCount++;
318 AUDIO_INFO_LOG("rehandle device[%{public}d], retry count[%{public}d]", deviceType, retryCount);
319
320 int32_t ret = HandleSpecialDeviceType(deviceType, isConnected, address, deviceRole);
321 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Rehandle special device type failed");
322 if (deviceType == DEVICE_TYPE_USB_HEADSET) {
323 AUDIO_INFO_LOG("Hifi device, don't load module");
324 return ret;
325 }
326 if (deviceType == DEVICE_TYPE_USB_ARM_HEADSET) {
327 if (HandleArmUsbDevice(deviceType, deviceRole, address) == SUCCESS) {
328 return SUCCESS;
329 }
330 } else if (deviceType == DEVICE_TYPE_DP) {
331 if (HandleDpDevice(deviceType, address) == SUCCESS) {
332 return SUCCESS;
333 }
334 } else if (deviceType == DEVICE_TYPE_ACCESSORY) {
335 if (HandleAccessoryDevice(deviceType, address) == SUCCESS) {
336 return SUCCESS;
337 }
338 }
339 usleep(REHANDLE_DEVICE_RETRY_INTERVAL_IN_MICROSECONDS);
340 }
341
342 AUDIO_ERR_LOG("rehandle device[%{public}d] failed", deviceType);
343 return ERROR;
344 }
345
HandleDpDevice(DeviceType deviceType,const std::string & address)346 int32_t AudioDeviceStatus::HandleDpDevice(DeviceType deviceType, const std::string &address)
347 {
348 Trace trace("AudioDeviceStatus::HandleDpDevice");
349 if (deviceType == DEVICE_TYPE_DP) {
350 std::string defaulyDPInfo = "";
351 std::string getDPInfo = "";
352 GetModuleInfo(ClassType::TYPE_DP, defaulyDPInfo);
353 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
354
355 getDPInfo = AudioServerProxy::GetInstance().GetAudioParameterProxy(LOCAL_NETWORK_ID, GET_DP_DEVICE_INFO,
356 defaulyDPInfo + " address=" + address + " ");
357 AUDIO_DEBUG_LOG("device info from dp hal is \n defaulyDPInfo:%{public}s", defaulyDPInfo.c_str());
358
359 getDPInfo = getDPInfo.empty() ? defaulyDPInfo : getDPInfo;
360 int32_t ret = LoadDpModule(getDPInfo);
361 if (ret != SUCCESS) {
362 AUDIO_ERR_LOG ("load dp module failed");
363 return ERR_OPERATION_FAILED;
364 }
365 std::string activePort = AudioPolicyUtils::GetInstance().GetSinkPortName(DEVICE_TYPE_DP);
366 AUDIO_INFO_LOG("port %{public}s, active dp device", activePort.c_str());
367 } else if (audioActiveDevice_.GetCurrentOutputDeviceType() == DEVICE_TYPE_DP) {
368 std::string activePort = AudioPolicyUtils::GetInstance().GetSinkPortName(DEVICE_TYPE_DP);
369 audioPolicyManager_.SuspendAudioDevice(activePort, true);
370 }
371
372 return SUCCESS;
373 }
374
HandleAccessoryDevice(DeviceType deviceType,const std::string & address)375 int32_t AudioDeviceStatus::HandleAccessoryDevice(DeviceType deviceType, const std::string &address)
376 {
377 Trace trace("AudioDeviceStatus::HandleAccessoryDevice");
378 std::string defaulyAccessoryInfo = "";
379 auto res = GetModuleInfo(ClassType::TYPE_ACCESSORY, defaulyAccessoryInfo);
380 CHECK_AND_RETURN_RET_LOG(res == SUCCESS, ERR_OPERATION_FAILED, "get module info failed");
381 CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
382 char sampleRate[10] = {0};
383 // default samplerate of accessory is 16000
384 GetParameter("hw.pencil.samplerate", "16000", sampleRate, sizeof(sampleRate));
385
386 auto rate_begin = defaulyAccessoryInfo.find("rate=");
387 auto rate_end = defaulyAccessoryInfo.find_first_of(" ", rate_begin);
388 CHECK_AND_RETURN_RET_LOG(rate_end > rate_begin, ERR_OPERATION_FAILED, "get rate failed");
389 defaulyAccessoryInfo.replace(rate_begin + std::strlen("rate="),
390 rate_end - rate_begin - std::strlen("rate="), sampleRate);
391 if (strncmp(sampleRate, "8000", sizeof("8000")) == 0) { // when double connect samplerate of accessory is 8000
392 auto size_begin = defaulyAccessoryInfo.find("buffer_size=");
393 auto size_end = defaulyAccessoryInfo.find_first_of(" ", size_begin);
394 CHECK_AND_RETURN_RET_LOG(size_end > size_begin, ERR_OPERATION_FAILED, "get size failed");
395 defaulyAccessoryInfo.replace(size_begin + std::strlen("buffer_size="),
396 size_end - size_begin - std::strlen("buffer_size="), DEFAULT_BUFFER_SIZE_8000);
397 }
398
399 AUDIO_INFO_LOG("device info from accessory hal is defaulyAccessoryInfo: %{public}s",
400 defaulyAccessoryInfo.c_str());
401
402 int32_t ret = LoadAccessoryModule(defaulyAccessoryInfo);
403 if (ret != SUCCESS) {
404 AUDIO_ERR_LOG ("load accessory module failed");
405 return ERR_OPERATION_FAILED;
406 }
407 std::string activePort = AudioPolicyUtils::GetInstance().GetSinkPortName(deviceType);
408 AUDIO_INFO_LOG("port %{public}s, active accessory device", activePort.c_str());
409 return SUCCESS;
410 }
411
HandleLocalDeviceConnected(AudioDeviceDescriptor & updatedDesc)412 int32_t AudioDeviceStatus::HandleLocalDeviceConnected(AudioDeviceDescriptor &updatedDesc)
413 {
414 DeviceStreamInfo audioStreamInfo = updatedDesc.GetDeviceStreamInfo();
415 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
416 A2dpDeviceConfigInfo configInfo = {audioStreamInfo, false};
417 audioA2dpDevice_.AddA2dpDevice(updatedDesc.macAddress_, configInfo);
418 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP_IN) {
419 A2dpDeviceConfigInfo configInfo = {audioStreamInfo, false};
420 audioA2dpDevice_.AddA2dpInDevice(updatedDesc.macAddress_, configInfo);
421 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {
422 int32_t result = HandleDpDevice(updatedDesc.deviceType_, updatedDesc.macAddress_);
423 if (result != SUCCESS) {
424 result = RehandlePnpDevice(updatedDesc.deviceType_, OUTPUT_DEVICE, updatedDesc.macAddress_);
425 }
426 CheckAndWriteDeviceChangeExceptionEvent(result == SUCCESS,
427 AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE,
428 updatedDesc.deviceType_, updatedDesc.deviceRole_, result, "Load dp failed.");
429 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Load dp failed.");
430 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_HEADSET ||
431 updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
432 AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "usb");
433 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_ACCESSORY) {
434 int32_t result = HandleAccessoryDevice(updatedDesc.deviceType_, updatedDesc.macAddress_);
435 CheckAndWriteDeviceChangeExceptionEvent(result == SUCCESS,
436 AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE,
437 updatedDesc.deviceType_, updatedDesc.deviceRole_, result, "Load accessory failed.");
438 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Load accessory failed.");
439 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_NEARLINK) {
440 SleAudioDeviceManager::GetInstance().AddNearlinkDevice(updatedDesc);
441 audioVolumeManager_.SetNearlinkDeviceVolume(updatedDesc.macAddress_, STREAM_MUSIC,
442 SleAudioDeviceManager::GetInstance().GetVolumeLevelByVolumeType(STREAM_MUSIC, updatedDesc));
443 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_HEARING_AID) {
444 A2dpDeviceConfigInfo configInfo = {audioStreamInfo, false};
445 audioA2dpDevice_.AddHearingAidDevice(updatedDesc.macAddress_, configInfo);
446 }
447 return SUCCESS;
448 }
449
UpdateActiveA2dpDeviceWhenDisconnecting(const std::string & macAddress)450 void AudioDeviceStatus::UpdateActiveA2dpDeviceWhenDisconnecting(const std::string& macAddress)
451 {
452 AUDIO_INFO_LOG("In");
453 if (audioA2dpDevice_.DelA2dpDevice(macAddress) == 0) {
454 audioActiveDevice_.SetActiveBtDeviceMac("");
455 audioIOHandleMap_.ClosePortAndEraseIOHandle(BLUETOOTH_SPEAKER);
456 audioPolicyManager_.SetAbsVolumeScene(false);
457 audioVolumeManager_.SetSharedAbsVolumeScene(false);
458 #ifdef BLUETOOTH_ENABLE
459 Bluetooth::AudioA2dpManager::SetActiveA2dpDevice("");
460 AudioServerProxy::GetInstance().SetBtHdiInvalidState();
461 AudioServerProxy::GetInstance().UnloadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_BLUETOOTH, "bt_a2dp", true);
462 AudioServerProxy::GetInstance().UnloadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_BLUETOOTH, "bt_a2dp_fast", true);
463 AudioServerProxy::GetInstance().UnloadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_BLUETOOTH, "bt_hdap", true);
464 #endif
465 return;
466 }
467 }
468
HandleLocalDeviceDisconnected(const AudioDeviceDescriptor & updatedDesc)469 int32_t AudioDeviceStatus::HandleLocalDeviceDisconnected(const AudioDeviceDescriptor &updatedDesc)
470 {
471 if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
472 UpdateActiveA2dpDeviceWhenDisconnecting(updatedDesc.macAddress_);
473 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP_IN) {
474 if (audioA2dpDevice_.DelA2dpInDevice(updatedDesc.macAddress_) == 0) {
475 audioActiveDevice_.SetActiveBtInDeviceMac("");
476 audioIOHandleMap_.ClosePortAndEraseIOHandle(BLUETOOTH_MIC);
477 }
478 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {
479 audioIOHandleMap_.ClosePortAndEraseIOHandle(GetModuleNameByType(TYPE_DP));
480 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
481 audioEcManager_.CloseUsbArmDevice(updatedDesc);
482 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_ACCESSORY) {
483 audioIOHandleMap_.ClosePortAndEraseIOHandle(ACCESSORY_SOURCE);
484 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_HEARING_AID) {
485 if (audioA2dpDevice_.DelHearingAidDevice(updatedDesc.macAddress_) == 0) {
486 audioIOHandleMap_.ClosePortAndEraseIOHandle(HEARING_AID_SPEAKER);
487 }
488 }
489 SleAudioDeviceManager::GetInstance().RemoveNearlinkDevice(updatedDesc);
490
491 AudioServerProxy::GetInstance().ResetRouteForDisconnectProxy(updatedDesc.deviceType_);
492 if (updatedDesc.deviceType_ == DEVICE_TYPE_DP) {
493 AudioServerProxy::GetInstance().UnloadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "dp", false);
494 } else if (updatedDesc.deviceType_ == DEVICE_TYPE_USB_HEADSET ||
495 updatedDesc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
496 AudioServerProxy::GetInstance().UnloadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "usb", false);
497 }
498 return SUCCESS;
499 }
500
HandleArmUsbDevice(DeviceType deviceType,DeviceRole deviceRole,const std::string & address)501 int32_t AudioDeviceStatus::HandleArmUsbDevice(DeviceType deviceType, DeviceRole deviceRole, const std::string &address)
502 {
503 Trace trace("AudioPolicyService::HandleArmUsbDevice");
504 if (deviceType != DEVICE_TYPE_USB_ARM_HEADSET &&
505 audioActiveDevice_.GetCurrentOutputDeviceType() == DEVICE_TYPE_USB_HEADSET) {
506 std::string activePort = AudioPolicyUtils::GetInstance().GetSinkPortName(DEVICE_TYPE_USB_ARM_HEADSET);
507 audioPolicyManager_.SuspendAudioDevice(activePort, true);
508 }
509
510 return SUCCESS;
511 }
512
GetModuleInfo(ClassType classType,std::string & moduleInfoStr)513 int32_t AudioDeviceStatus::GetModuleInfo(ClassType classType, std::string &moduleInfoStr)
514 {
515 std::list<AudioModuleInfo> moduleInfoList;
516 {
517 bool ret = audioConfigManager_.GetModuleListByType(classType, moduleInfoList);
518 CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED,
519 "find %{public}d type failed", classType);
520 }
521 moduleInfoStr = audioPolicyManager_.GetModuleArgs(*moduleInfoList.begin());
522 return SUCCESS;
523 }
524
LoadDpModule(std::string deviceInfo)525 int32_t AudioDeviceStatus::LoadDpModule(std::string deviceInfo)
526 {
527 AUDIO_INFO_LOG("LoadDpModule");
528 std::list<AudioModuleInfo> moduleInfoList;
529 {
530 bool ret = audioConfigManager_.GetModuleListByType(ClassType::TYPE_DP, moduleInfoList);
531 CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED,
532 "dp module is not exist in the configuration file");
533 }
534 AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "dp");
535 for (auto &moduleInfo : moduleInfoList) {
536 AUDIO_INFO_LOG("[module_load]::load module[%{public}s]", moduleInfo.name.c_str());
537 if (audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name) == false) {
538 GetDPModuleInfo(moduleInfo, deviceInfo);
539 if (moduleInfo.role == ROLE_SINK) {
540 AUDIO_INFO_LOG("save dp sink module info for cust param");
541 audioEcManager_.SetDpSinkModuleInfo(moduleInfo);
542 }
543 return audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
544 }
545 }
546
547 return SUCCESS;
548 }
549
LoadAccessoryModule(std::string deviceInfo)550 int32_t AudioDeviceStatus::LoadAccessoryModule(std::string deviceInfo)
551 {
552 AUDIO_INFO_LOG("LoadAccessoryModule");
553 std::list<AudioModuleInfo> moduleInfoList;
554 {
555 bool ret = audioConfigManager_.GetModuleListByType(ClassType::TYPE_ACCESSORY, moduleInfoList);
556 CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED,
557 "accessory module is not exist in the configuration file");
558 }
559 AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "accessory");
560 for (auto &moduleInfo : moduleInfoList) {
561 if (audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name) == false) {
562 AUDIO_INFO_LOG("[module_load]::load module[%{public}s]", moduleInfo.name.c_str());
563 GetDPModuleInfo(moduleInfo, deviceInfo);
564 moduleInfo.deviceType = std::to_string(static_cast<int32_t>(DEVICE_TYPE_ACCESSORY));
565 auto size_begin = deviceInfo.find("buffer_size=");
566 auto size_end = deviceInfo.find_first_of(" ", size_begin);
567 CHECK_AND_RETURN_RET_LOG(size_end > size_begin, ERR_OPERATION_FAILED, "get size failed");
568 string bufferSize = deviceInfo.substr(size_begin + std::strlen("buffer_size="),
569 size_end - size_begin - std::strlen("buffer_size"));
570 moduleInfo.bufferSize = bufferSize;
571 return audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
572 }
573 }
574 return SUCCESS;
575 }
576
NoNeedChangeUsbDevice(const string & address)577 bool AudioDeviceStatus::NoNeedChangeUsbDevice(const string &address)
578 {
579 auto key = string("need_change_usb_device#C") + GetField(address, "card", ';') + "D0";
580 auto ret = AudioServerProxy::GetInstance().GetAudioParameterProxy(key);
581 AUDIO_INFO_LOG("key=%{public}s, ret=%{public}s", key.c_str(), ret.c_str());
582 return ret == "false";
583 }
584
HandleSpecialDeviceType(DeviceType & devType,bool & isConnected,const std::string & address,DeviceRole role)585 int32_t AudioDeviceStatus::HandleSpecialDeviceType(DeviceType &devType, bool &isConnected,
586 const std::string &address, DeviceRole role)
587 {
588 if (devType == DEVICE_TYPE_USB_HEADSET || devType == DEVICE_TYPE_USB_ARM_HEADSET) {
589 CHECK_AND_RETURN_RET(!address.empty() && role != DEVICE_ROLE_NONE, ERROR);
590 AUDIO_INFO_LOG("Entry. Addr:%{public}s, Role:%{public}d, HasHifi:%{public}d, HasArm:%{public}d",
591 GetEncryptAddr(address).c_str(), role,
592 audioConnectedDevice_.HasHifi(role), audioConnectedDevice_.HasArm(role));
593 if (isConnected) {
594 // Usb-c maybe reported repeatedly, the devType remains unchanged
595 auto exists = audioConnectedDevice_.GetUsbDeviceDescriptor(address, role);
596 if (exists) {
597 devType = exists->deviceType_;
598 return SUCCESS;
599 }
600 if (audioConnectedDevice_.HasHifi(role) || NoNeedChangeUsbDevice(address)) {
601 devType = DEVICE_TYPE_USB_ARM_HEADSET;
602 }
603 } else if (audioConnectedDevice_.IsArmDevice(address, role)) {
604 devType = DEVICE_TYPE_USB_ARM_HEADSET;
605 // Temporary resolution to avoid pcm driver problem
606 string condition = string("address=") + address + " role=" + to_string(DEVICE_ROLE_NONE);
607 string deviceInfo = AudioServerProxy::GetInstance().GetAudioParameterProxy(LOCAL_NETWORK_ID, USB_DEVICE,
608 condition);
609 }
610 } else if (devType == DEVICE_TYPE_EXTERN_CABLE) {
611 CheckAndWriteDeviceChangeExceptionEvent(isConnected,
612 AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE,
613 devType, role, ERROR, "Extern cable disconnected, do nothing");
614 CHECK_AND_RETURN_RET_LOG(isConnected, ERROR, "Extern cable disconnected, do nothing");
615 DeviceType connectedHeadsetType = audioConnectedDevice_.FindConnectedHeadset();
616 if (connectedHeadsetType == DEVICE_TYPE_NONE) {
617 AUDIO_INFO_LOG("Extern cable connect without headset connected before, do nothing");
618 return ERROR;
619 }
620 devType = connectedHeadsetType;
621 isConnected = false;
622 }
623
624 return SUCCESS;
625 }
626
OnPnpDeviceStatusUpdated(AudioDeviceDescriptor & desc,bool isConnected)627 void AudioDeviceStatus::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected)
628 {
629 CHECK_AND_RETURN_LOG(desc.deviceType_ != DEVICE_TYPE_NONE, "devType is none type");
630 if (!hasModulesLoaded) {
631 AUDIO_WARNING_LOG("modules has not loaded");
632 AudioDeviceDescriptor pnpDesc = desc;
633 pnpDeviceList_.push_back({pnpDesc, isConnected});
634 return;
635 }
636 if (desc.deviceType_ == DEVICE_TYPE_DP) {
637 if (isConnected) {
638 auto exists = audioDeviceManager_.ExistsByType(DEVICE_TYPE_DP);
639 CHECK_AND_RETURN_LOG(!exists, "DP device already exists, ignore this one.");
640 } else {
641 auto exists = audioDeviceManager_.ExistsByTypeAndAddress(DEVICE_TYPE_DP, desc.macAddress_);
642 CHECK_AND_RETURN_LOG(exists, "DP device does not exist, can not disconnect.");
643 }
644 }
645 AudioStreamInfo streamInfo = {};
646 OnDeviceStatusUpdated(desc.deviceType_, isConnected, desc.macAddress_, desc.deviceName_, streamInfo);
647 }
648
OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)649 void AudioDeviceStatus::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status)
650 {
651 CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
652 OnBlockedStatusUpdated(devType, status);
653 }
654
OnBlockedStatusUpdated(DeviceType devType,DeviceBlockStatus status)655 void AudioDeviceStatus::OnBlockedStatusUpdated(DeviceType devType, DeviceBlockStatus status)
656 {
657 std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
658 std::shared_ptr<AudioDeviceDescriptor> audioDescriptor =
659 std::make_shared<AudioDeviceDescriptor>(devType, AudioPolicyUtils::GetInstance().GetDeviceRole(devType));
660 descForCb.push_back(audioDescriptor);
661
662 vector<shared_ptr<AudioCapturerChangeInfo>> audioChangeInfos;
663 streamCollector_.GetCurrentCapturerChangeInfos(audioChangeInfos);
664 for (auto it = audioChangeInfos.begin(); it != audioChangeInfos.end(); it++) {
665 if ((*it)->capturerState == CAPTURER_RUNNING) {
666 AUDIO_INFO_LOG("record running");
667 TriggerMicrophoneBlockedCallback(descForCb, status);
668 }
669 }
670 }
671
TriggerMicrophoneBlockedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc,DeviceBlockStatus status)672 void AudioDeviceStatus::TriggerMicrophoneBlockedCallback(const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc,
673 DeviceBlockStatus status)
674 {
675 Trace trace("AudioDeviceStatus::TriggerMicrophoneBlockedCallback");
676 if (audioPolicyServerHandler_ != nullptr) {
677 audioPolicyServerHandler_->SendMicrophoneBlockedCallback(desc, status);
678 }
679 }
680
ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)681 void AudioDeviceStatus::ReloadA2dpOffloadOnDeviceChanged(DeviceType deviceType, const std::string &macAddress,
682 const std::string &deviceName, const AudioStreamInfo &streamInfo)
683 {
684 uint32_t bufferSize = streamInfo.samplingRate *
685 AudioPolicyUtils::GetInstance().PcmFormatToBytes(streamInfo.format) *
686 streamInfo.channels / BT_BUFFER_ADJUSTMENT_FACTOR;
687 AUDIO_INFO_LOG("Updated buffer size: %{public}d", bufferSize);
688
689 std::list<AudioModuleInfo> moduleInfoList;
690 bool ret = audioConfigManager_.GetModuleListByType(ClassType::TYPE_A2DP, moduleInfoList);
691 CHECK_AND_RETURN_LOG(ret, "GetModuleListByType failed");
692 for (auto &moduleInfo : moduleInfoList) {
693 CHECK_AND_CONTINUE_LOG(audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name),
694 "Cannot find module %{public}s", moduleInfo.name.c_str());
695 moduleInfo.channels = to_string(streamInfo.channels);
696 moduleInfo.rate = to_string(streamInfo.samplingRate);
697 moduleInfo.format = AudioPolicyUtils::GetInstance().ConvertToHDIAudioFormat(streamInfo.format);
698 moduleInfo.bufferSize = to_string(bufferSize);
699 moduleInfo.renderInIdleState = "1";
700 moduleInfo.sinkLatency = "0";
701
702 // First unload the existing bt sink
703 AUDIO_DEBUG_LOG("UnLoad existing a2dp module");
704 std::string currentActivePort
705 = AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType());
706 AudioIOHandle activateDeviceIOHandle;
707 audioIOHandleMap_.GetModuleIdByKey(BLUETOOTH_SPEAKER, activateDeviceIOHandle);
708 audioIOHandleMap_.MuteDefaultSinkPort(audioActiveDevice_.GetCurrentOutputDeviceNetworkId(),
709 AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType()));
710 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
711 std::shared_ptr<AudioPipeManager> pipeManager = AudioPipeManager::GetPipeManager();
712 uint32_t curPaIndex = pipeManager->GetPaIndexByIoHandle(activateDeviceIOHandle);
713 std::vector<std::shared_ptr<AudioStreamDescriptor>> streamDescs =
714 pipeManager->GetStreamDescsByIoHandle(activateDeviceIOHandle);
715 AUDIO_INFO_LOG("IoHandleId: %{public}u, paIndex: %{public}u, stream count: %{public}zu",
716 activateDeviceIOHandle, curPaIndex, streamDescs.size());
717 pipeManager->RemoveAudioPipeInfo(activateDeviceIOHandle);
718 int32_t engineFlag = GetEngineFlag();
719 if (engineFlag != 1) {
720 audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle, curPaIndex);
721 }
722
723 CHECK_AND_RETURN(RestoreNewA2dpPort(streamDescs, moduleInfo, currentActivePort) == SUCCESS);
724 std::string portName = AudioPolicyUtils::GetInstance().GetSinkPortName(deviceType);
725 if (!audioSceneManager_.IsVoiceCallRelatedScene()) {
726 audioPolicyManager_.SetDeviceActive(deviceType, portName, true);
727 }
728 audioPolicyManager_.SuspendAudioDevice(portName, false);
729 audioPolicyManager_.SuspendAudioDevice(currentActivePort, false);
730 audioConnectedDevice_.UpdateConnectDevice(deviceType, macAddress, deviceName, streamInfo);
731 break;
732 }
733 }
734
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)735 void AudioDeviceStatus::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
736 const std::string &deviceName, const AudioStreamInfo &streamInfo)
737 {
738 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
739 AUDIO_INFO_LOG("[ADeviceEvent] device[%{public}d] currentOutputDevice[%{public}d] "
740 "macAddress:[%{public}s], activeBTDevice:[%{public}s]",
741 deviceType, audioActiveDevice_.GetCurrentOutputDeviceType(),
742 GetEncryptAddr(macAddress).c_str(), GetEncryptAddr(btDevice).c_str());
743 // only for the active a2dp device.
744 if ((deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) && !macAddress.compare(btDevice)) {
745 int32_t activeSessionsSize = 0;
746 BluetoothOffloadState state = NO_A2DP_DEVICE;
747 if (audioA2dpOffloadManager_) {
748 activeSessionsSize = audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
749 state = audioA2dpOffloadManager_->GetA2dpOffloadFlag();
750 }
751 AUDIO_DEBUG_LOG("streamInfo.sampleRate: %{public}d, a2dpOffloadFlag: %{public}d",
752 streamInfo.samplingRate, state);
753 if (!IsConfigurationUpdated(deviceType, streamInfo) ||
754 (activeSessionsSize > 0 && state == A2DP_OFFLOAD)) {
755 AUDIO_DEBUG_LOG("Audio configuration same");
756 return;
757 }
758 audioA2dpDevice_.SetA2dpDeviceStreamInfo(macAddress, streamInfo);
759 ReloadA2dpOffloadOnDeviceChanged(deviceType, macAddress, deviceName, streamInfo);
760 } else if (audioA2dpDevice_.CheckA2dpDeviceExist(macAddress)) {
761 AUDIO_DEBUG_LOG("Audio configuration update, macAddress:[%{public}s], streamInfo.sampleRate: %{public}d",
762 GetEncryptAddr(macAddress).c_str(), streamInfo.samplingRate);
763 audioA2dpDevice_.SetA2dpDeviceStreamInfo(macAddress, streamInfo);
764 }
765 }
766
IsConfigurationUpdated(DeviceType deviceType,const AudioStreamInfo & streamInfo)767 bool AudioDeviceStatus::IsConfigurationUpdated(DeviceType deviceType, const AudioStreamInfo &streamInfo)
768 {
769 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
770 AudioStreamInfo audioStreamInfo = {};
771 if (audioActiveDevice_.GetActiveA2dpDeviceStreamInfo(deviceType, audioStreamInfo)) {
772 AUDIO_DEBUG_LOG("Device configurations current rate: %{public}d, format: %{public}d, channel: %{public}d",
773 audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
774 AUDIO_DEBUG_LOG("Device configurations updated rate: %{public}d, format: %{public}d, channel: %{public}d",
775 streamInfo.samplingRate, streamInfo.format, streamInfo.channels);
776 if ((audioStreamInfo.samplingRate != streamInfo.samplingRate)
777 || (audioStreamInfo.channels != streamInfo.channels)
778 || (audioStreamInfo.format != streamInfo.format)) {
779 return true;
780 }
781 }
782 }
783
784 return false;
785 }
786
GetDeviceTypeFromPin(AudioPin hdiPin)787 DeviceType AudioDeviceStatus::GetDeviceTypeFromPin(AudioPin hdiPin)
788 {
789 AUDIO_INFO_LOG("Pin: %{public}d", hdiPin);
790 switch (hdiPin) {
791 case OHOS::AudioStandard::AUDIO_PIN_NONE:
792 break;
793 case OHOS::AudioStandard::AUDIO_PIN_OUT_SPEAKER:
794 case OHOS::AudioStandard::AUDIO_PIN_OUT_DAUDIO_DEFAULT:
795 return DeviceType::DEVICE_TYPE_SPEAKER;
796 case OHOS::AudioStandard::AUDIO_PIN_OUT_HEADSET:
797 break;
798 case OHOS::AudioStandard::AUDIO_PIN_OUT_LINEOUT:
799 break;
800 case OHOS::AudioStandard::AUDIO_PIN_OUT_HDMI:
801 break;
802 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB:
803 break;
804 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_EXT:
805 break;
806 case OHOS::AudioStandard::AUDIO_PIN_OUT_USB_HEADSET:
807 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_HEADSET:
808 return DeviceType::DEVICE_TYPE_USB_ARM_HEADSET;
809 case OHOS::AudioStandard::AUDIO_PIN_IN_MIC:
810 case OHOS::AudioStandard::AUDIO_PIN_IN_DAUDIO_DEFAULT:
811 return DeviceType::DEVICE_TYPE_MIC;
812 case OHOS::AudioStandard::AUDIO_PIN_IN_PENCIL:
813 case OHOS::AudioStandard::AUDIO_PIN_IN_UWB:
814 return DeviceType::DEVICE_TYPE_ACCESSORY;
815 case OHOS::AudioStandard::AUDIO_PIN_IN_HS_MIC:
816 break;
817 case OHOS::AudioStandard::AUDIO_PIN_IN_LINEIN:
818 break;
819 case OHOS::AudioStandard::AUDIO_PIN_IN_USB_EXT:
820 break;
821 default:
822 break;
823 }
824 return DeviceType::DEVICE_TYPE_DEFAULT;
825 }
826
GetModuleNameByType(ClassType type)827 string AudioDeviceStatus::GetModuleNameByType(ClassType type)
828 {
829 list<AudioModuleInfo> moduleList;
830 bool ret = audioConfigManager_.GetModuleListByType(type, moduleList);
831 CHECK_AND_RETURN_RET_LOG(ret && !moduleList.empty(), "", "Get module info of type[%{public}d] failed", type);
832 return moduleList.front().name;
833 }
834
GetDeviceByStatusInfo(const DStatusInfo & statusInfo)835 std::shared_ptr<AudioDeviceDescriptor> AudioDeviceStatus::GetDeviceByStatusInfo(const DStatusInfo &statusInfo)
836 {
837 DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
838 AudioDeviceDescriptor deviceDesc(devType, AudioPolicyUtils::GetInstance().GetDeviceRole(devType));
839 deviceDesc.SetDeviceInfo(statusInfo.deviceName, statusInfo.macAddress);
840 DeviceStreamInfo streamInfo = {};
841 std::list<DeviceStreamInfo> streamInfoList = statusInfo.streamInfo.empty() ?
842 std::list<DeviceStreamInfo>{ streamInfo } : statusInfo.streamInfo;
843 deviceDesc.SetDeviceCapability(streamInfoList, 0);
844 deviceDesc.networkId_ = statusInfo.networkId;
845 return std::make_shared<AudioDeviceDescriptor>(deviceDesc);
846 }
847
OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)848 void AudioDeviceStatus::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop)
849 {
850 AUDIO_WARNING_LOG("[ADeviceEvent] remote HDI_PIN[%{public}d] connet[%{public}d] "
851 "networkId[%{public}s]", statusInfo.hdiPin, statusInfo.isConnected,
852 GetEncryptStr(statusInfo.networkId).c_str());
853 if (isStop) {
854 std::shared_ptr<AudioDeviceDescriptor> device = GetDeviceByStatusInfo(statusInfo);
855 AudioZoneService::GetInstance().MoveDeviceToGlobalFromZones(device);
856
857 HandleOfflineDistributedDevice();
858 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
859 audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 2.1 param");
860 return;
861 }
862 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN;
863 std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
864 int32_t ret = HandleDistributedDeviceUpdate(statusInfo, descForCb, reason);
865 CHECK_AND_RETURN_LOG(ret == SUCCESS, "HandleDistributedDeviceUpdate return directly.");
866
867 TriggerDeviceChangedCallback(descForCb, statusInfo.isConnected);
868 TriggerAvailableDeviceChangedCallback(descForCb, statusInfo.isConnected);
869
870 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("OnDeviceStatusUpdated_3", reason);
871 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("OnDeviceStatusUpdated_3");
872 DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
873 DeviceRole deviceRole = AudioPolicyUtils::GetInstance().GetDeviceRole(devType);
874 if (!statusInfo.isConnected) {
875 std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(statusInfo.networkId, deviceRole);
876 audioIOHandleMap_.ClosePortAndEraseIOHandle(moduleName);
877 }
878 if (deviceRole == DeviceRole::INPUT_DEVICE) {
879 remoteCapturerSwitch_ = true;
880 }
881
882 // update a2dp offload
883 if (audioA2dpOffloadManager_) {
884 audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
885 }
886 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
887 audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 2.2 param");
888 }
889
ActivateNewDevice(std::string networkId,DeviceType deviceType,bool isRemote)890 int32_t AudioDeviceStatus::ActivateNewDevice(std::string networkId, DeviceType deviceType, bool isRemote)
891 {
892 if (isRemote) {
893 AudioModuleInfo moduleInfo = AudioPolicyUtils::GetInstance().ConstructRemoteAudioModuleInfo(networkId,
894 AudioPolicyUtils::GetInstance().GetDeviceRole(deviceType), deviceType);
895 std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId,
896 AudioPolicyUtils::GetInstance().GetDeviceRole(deviceType));
897 AUDIO_INFO_LOG("Module name: %{public}s, adapter name: %{public}s",
898 moduleName.c_str(), moduleInfo.adapterName.c_str());
899 uint32_t paIndex = 0;
900 AudioIOHandle ioHandle = AudioPolicyManagerFactory::GetAudioPolicyManager().OpenAudioPort(moduleInfo, paIndex);
901 CHECK_AND_RETURN_RET_LOG(ioHandle != HDI_INVALID_ID, ERR_INVALID_HANDLE,
902 "OpenAudioPort failed ioHandle[%{public}u]", ioHandle);
903 CHECK_AND_RETURN_RET_LOG(paIndex != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
904 "OpenAudioPort failed paId[%{public}u]", paIndex);
905 std::shared_ptr<AudioPipeInfo> pipeInfo = std::make_shared<AudioPipeInfo>();
906 pipeInfo->id_ = ioHandle;
907 pipeInfo->paIndex_ = paIndex;
908 if (moduleInfo.role == "sink") {
909 pipeInfo->name_ = "distributed_output";
910 pipeInfo->pipeRole_ = PIPE_ROLE_OUTPUT;
911 pipeInfo->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL;
912 } else {
913 pipeInfo->name_ = "distributed_input";
914 pipeInfo->pipeRole_ = PIPE_ROLE_INPUT;
915 pipeInfo->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL;
916 }
917 pipeInfo->adapterName_ = moduleInfo.adapterName;
918 pipeInfo->moduleInfo_ = moduleInfo;
919 pipeInfo->pipeAction_ = PIPE_ACTION_DEFAULT;
920 pipeInfo->InitAudioStreamInfo();
921 AudioPipeManager::GetPipeManager()->AddAudioPipeInfo(pipeInfo);
922 audioIOHandleMap_.AddIOHandleInfo(moduleName, ioHandle);
923 }
924 return SUCCESS;
925 }
926
HandleDistributedDeviceUpdate(DStatusInfo & statusInfo,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descForCb,AudioStreamDeviceChangeReasonExt & reason)927 int32_t AudioDeviceStatus::HandleDistributedDeviceUpdate(DStatusInfo &statusInfo,
928 std::vector<std::shared_ptr<AudioDeviceDescriptor>> &descForCb, AudioStreamDeviceChangeReasonExt &reason)
929 {
930 DeviceType devType = GetDeviceTypeFromPin(statusInfo.hdiPin);
931 DeviceRole devRole = AudioPolicyUtils::GetInstance().GetDeviceRole(devType);
932 const std::string networkId = statusInfo.networkId;
933 AudioDeviceDescriptor deviceDesc(devType, devRole);
934 deviceDesc.SetDeviceInfo(statusInfo.deviceName, statusInfo.macAddress);
935 DeviceStreamInfo streamInfo = {};
936 std::list<DeviceStreamInfo> streamInfoList = statusInfo.streamInfo.empty() ?
937 std::list<DeviceStreamInfo>{ streamInfo } : statusInfo.streamInfo;
938 deviceDesc.SetDeviceCapability(streamInfoList, 0);
939 deviceDesc.networkId_ = networkId;
940 audioVolumeManager_.UpdateGroupInfo(VOLUME_TYPE, GROUP_NAME_DEFAULT, deviceDesc.volumeGroupId_, networkId,
941 statusInfo.isConnected, statusInfo.mappingVolumeId);
942 audioVolumeManager_.UpdateGroupInfo(INTERRUPT_TYPE, GROUP_NAME_DEFAULT, deviceDesc.interruptGroupId_, networkId,
943 statusInfo.isConnected, statusInfo.mappingInterruptId);
944 if (statusInfo.isConnected) {
945 if (audioConnectedDevice_.GetConnectedDeviceByType(networkId, devType) != nullptr) {
946 return ERROR;
947 }
948 int32_t ret = ActivateNewDevice(statusInfo.networkId, devType,
949 statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED);
950 CheckAndWriteDeviceChangeExceptionEvent(ret == SUCCESS,
951 AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE, devType, devRole, ret,
952 "DEVICE online but open audio device failed.");
953 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "DEVICE online but open audio device failed.");
954 audioDeviceCommon_.UpdateConnectedDevicesWhenConnecting(deviceDesc, descForCb);
955
956 if (statusInfo.connectType == ConnectType::CONNECT_TYPE_DISTRIBUTED) {
957 AudioServerProxy::GetInstance().NotifyDeviceInfoProxy(networkId, true);
958 }
959 } else {
960 std::shared_ptr<AudioDeviceDescriptor> device = GetDeviceByStatusInfo(statusInfo);
961 AudioZoneService::GetInstance().MoveDeviceToGlobalFromZones(device);
962 audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(deviceDesc, descForCb);
963 reason = AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE_UNAVAILABLE;
964 std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId,
965 AudioPolicyUtils::GetInstance().GetDeviceRole(devType));
966 std::string currentActivePort = REMOTE_CLASS;
967 audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
968 audioRouteMap_.RemoveDeviceInRouterMap(moduleName);
969 audioRouteMap_.RemoveDeviceInFastRouterMap(networkId);
970 }
971 return SUCCESS;
972 }
973
AddEarpiece()974 void AudioDeviceStatus::AddEarpiece()
975 {
976 if (!audioConfigManager_.GetHasEarpiece()) {
977 return;
978 }
979 std::shared_ptr<AudioDeviceDescriptor> audioDescriptor =
980 std::make_shared<AudioDeviceDescriptor>(DEVICE_TYPE_EARPIECE, OUTPUT_DEVICE);
981 CHECK_AND_RETURN_LOG(audioDescriptor != nullptr, "Create earpiect device descriptor failed");
982
983 // Use speaker streaminfo for earpiece cap
984 auto itr = audioConnectedDevice_.GetConnectedDeviceByType(DEVICE_TYPE_SPEAKER);
985 if (itr != nullptr) {
986 audioDescriptor->SetDeviceCapability(itr->audioStreamInfo_, 0);
987 }
988 audioDescriptor->deviceId_ = AudioPolicyUtils::startDeviceId++;
989 AudioPolicyUtils::GetInstance().UpdateDisplayName(audioDescriptor);
990 audioDeviceManager_.AddNewDevice(audioDescriptor);
991 audioConnectedDevice_.AddConnectedDevice(audioDescriptor);
992 AUDIO_INFO_LOG("Add earpiece to device list");
993 }
994
OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo & moduleInfo)995 bool AudioDeviceStatus::OpenPortAndAddDeviceOnServiceConnected(AudioModuleInfo &moduleInfo)
996 {
997 auto devType = AudioPolicyUtils::GetInstance().GetDeviceType(moduleInfo.name);
998 if (devType != DEVICE_TYPE_MIC) {
999 audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
1000
1001 if (devType == DEVICE_TYPE_SPEAKER) {
1002 auto result = audioPolicyManager_.SetDeviceActive(devType, moduleInfo.name, true);
1003 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, false, "[module_load]::Device failed %{public}d", devType);
1004 }
1005 }
1006
1007 if (devType == DEVICE_TYPE_MIC) {
1008 audioEcManager_.SetPrimaryMicModuleInfo(moduleInfo);
1009 }
1010
1011 if (devType == DEVICE_TYPE_SPEAKER || devType == DEVICE_TYPE_MIC) {
1012 AddAudioDevice(moduleInfo, devType);
1013 }
1014
1015 audioVolumeManager_.NotifyVolumeGroup();
1016
1017 return true;
1018 }
1019
AddAudioDevice(AudioModuleInfo & moduleInfo,DeviceType devType)1020 void AudioDeviceStatus::AddAudioDevice(AudioModuleInfo& moduleInfo, DeviceType devType)
1021 {
1022 // add new device into active device list
1023 std::string volumeGroupName = audioConfigManager_.GetGroupName(moduleInfo.name, VOLUME_TYPE);
1024 std::string interruptGroupName = audioConfigManager_.GetGroupName(moduleInfo.name, INTERRUPT_TYPE);
1025 int32_t volumeGroupId = GROUP_ID_NONE;
1026 int32_t interruptGroupId = GROUP_ID_NONE;
1027 audioVolumeManager_.UpdateGroupInfo(GroupType::VOLUME_TYPE, volumeGroupName, volumeGroupId, LOCAL_NETWORK_ID, true,
1028 NO_REMOTE_ID);
1029 audioVolumeManager_.UpdateGroupInfo(GroupType::INTERRUPT_TYPE, interruptGroupName, interruptGroupId,
1030 LOCAL_NETWORK_ID, true, NO_REMOTE_ID);
1031
1032 std::shared_ptr<AudioDeviceDescriptor> audioDescriptor = std::make_shared<AudioDeviceDescriptor>(devType,
1033 AudioPolicyUtils::GetInstance().GetDeviceRole(moduleInfo.role), volumeGroupId, interruptGroupId,
1034 LOCAL_NETWORK_ID);
1035 CHECK_AND_RETURN_LOG(audioDescriptor != nullptr, "audioDescriptor is nullptr.");
1036 if (!moduleInfo.supportedRate_.empty() && !moduleInfo.supportedChannelLayout_.empty()) {
1037 DeviceStreamInfo streamInfo = {};
1038 for (auto supportedRate : moduleInfo.supportedRate_) {
1039 streamInfo.samplingRate.insert(static_cast<AudioSamplingRate>(supportedRate));
1040 }
1041 for (auto supportedChannelLayout : moduleInfo.supportedChannelLayout_) {
1042 streamInfo.channelLayout.insert(static_cast<AudioChannelLayout>(supportedChannelLayout));
1043 }
1044 audioDescriptor->SetDeviceCapability({ streamInfo }, 0);
1045 }
1046
1047 audioDescriptor->deviceId_ = AudioPolicyUtils::startDeviceId++;
1048 AudioPolicyUtils::GetInstance().UpdateDisplayName(audioDescriptor);
1049 audioDeviceManager_.AddNewDevice(audioDescriptor);
1050 audioConnectedDevice_.AddConnectedDevice(audioDescriptor);
1051 audioMicrophoneDescriptor_.AddMicrophoneDescriptor(audioDescriptor);
1052 }
1053
OnServiceConnected(AudioServiceIndex serviceIndex)1054 int32_t AudioDeviceStatus::OnServiceConnected(AudioServiceIndex serviceIndex)
1055 {
1056 int32_t result = ERROR;
1057 AUDIO_DEBUG_LOG("[module_load]::HDI and AUDIO SERVICE is READY. Loading default modules");
1058 std::unordered_map<ClassType, std::list<AudioModuleInfo>> deviceClassInfo = {};
1059 audioConfigManager_.GetDeviceClassInfo(deviceClassInfo);
1060 for (const auto &device : deviceClassInfo) {
1061 if (device.first != ClassType::TYPE_PRIMARY && device.first != ClassType::TYPE_FILE_IO) {
1062 continue;
1063 }
1064 if (device.first == ClassType::TYPE_PRIMARY) {
1065 AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_LOCAL, "primary");
1066 }
1067 auto moduleInfoList = device.second;
1068 for (auto &moduleInfo : moduleInfoList) {
1069 AUDIO_INFO_LOG("[module_load]::Load module[%{public}s]", moduleInfo.name.c_str());
1070 uint32_t sinkLatencyInMsec = audioConfigManager_.GetSinkLatencyFromXml();
1071 moduleInfo.sinkLatency = sinkLatencyInMsec != 0 ? to_string(sinkLatencyInMsec) : "";
1072 if (OpenPortAndAddDeviceOnServiceConnected(moduleInfo)) {
1073 result = SUCCESS;
1074 }
1075 audioOffloadStream_.SetOffloadAvailableFromXML(moduleInfo);
1076 }
1077 }
1078
1079 if (result == SUCCESS) {
1080 AUDIO_INFO_LOG("[module_load]::Setting speaker as active device on bootup");
1081 hasModulesLoaded = true;
1082 shared_ptr<AudioDeviceDescriptor> outDevice = audioDeviceManager_.GetRenderDefaultDevice();
1083 audioActiveDevice_.SetCurrentOutputDevice(*outDevice);
1084 shared_ptr<AudioDeviceDescriptor> inDevice = audioDeviceManager_.GetCaptureDefaultDevice();
1085 audioActiveDevice_.SetCurrentInputDevice(*inDevice);
1086 AudioDeviceDescriptor curDevice = audioActiveDevice_.GetCurrentOutputDevice();
1087 audioVolumeManager_.SetVolumeForSwitchDevice(curDevice);
1088 OnPreferredDeviceUpdated(audioActiveDevice_.GetCurrentOutputDevice(),
1089 audioActiveDevice_.GetCurrentInputDeviceType());
1090 AddEarpiece();
1091 for (auto it = pnpDeviceList_.begin(); it != pnpDeviceList_.end(); ++it) {
1092 OnPnpDeviceStatusUpdated((*it).first, (*it).second);
1093 }
1094 }
1095 return result;
1096 }
1097
OnPreferredDeviceUpdated(const AudioDeviceDescriptor & activeOutputDevice,DeviceType activeInputDevice)1098 void AudioDeviceStatus::OnPreferredDeviceUpdated(const AudioDeviceDescriptor& activeOutputDevice,
1099 DeviceType activeInputDevice)
1100 {
1101 audioDeviceCommon_.OnPreferredOutputDeviceUpdated(activeOutputDevice,
1102 AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE);
1103 audioDeviceCommon_.OnPreferredInputDeviceUpdated(activeInputDevice, LOCAL_NETWORK_ID);
1104 }
1105
OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)1106 void AudioDeviceStatus::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress)
1107 {
1108 if (macAddress.empty()) {
1109 AUDIO_ERR_LOG("failed as the macAddress is empty!");
1110 return;
1111 }
1112 AUDIO_INFO_LOG("[ADeviceEvent] bt select device type[%{public}d] address[%{public}s]",
1113 devType, GetEncryptAddr(macAddress).c_str());
1114 std::vector<shared_ptr<AudioDeviceDescriptor>> bluetoothDevices =
1115 audioDeviceManager_.GetAvailableBluetoothDevice(devType, macAddress);
1116 std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
1117 for (const auto &dec : bluetoothDevices) {
1118 if (dec->deviceRole_ == DeviceRole::OUTPUT_DEVICE) {
1119 std::shared_ptr<AudioDeviceDescriptor> tempDec = std::make_shared<AudioDeviceDescriptor>(*dec);
1120 audioDeviceDescriptors.push_back(move(tempDec));
1121 }
1122 }
1123 int32_t res = audioDeviceCommon_.DeviceParamsCheck(DeviceRole::OUTPUT_DEVICE, audioDeviceDescriptors);
1124 CHECK_AND_RETURN_LOG(res == SUCCESS, "DeviceParamsCheck no success");
1125 audioDeviceDescriptors[0]->isEnable_ = true;
1126 audioDeviceManager_.UpdateDevicesListInfo(audioDeviceDescriptors[0], ENABLE_UPDATE);
1127 if (devType == DEVICE_TYPE_BLUETOOTH_SCO) {
1128 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_RENDER, audioDeviceDescriptors[0], SYSTEM_UID,
1129 "OnForcedDeviceSelected");
1130 AudioPolicyUtils::GetInstance().ClearScoDeviceSuspendState(audioDeviceDescriptors[0]->macAddress_);
1131 } else {
1132 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER, audioDeviceDescriptors[0]);
1133 }
1134 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("OnForcedDeviceSelected",
1135 AudioStreamDeviceChangeReason::OVERRODE);
1136 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
1137 audioActiveDevice_.GetCurrentOutputDevice(), "OnForcedDeviceSelected");
1138 }
1139
OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,DeviceType devType,std::string macAddress,std::string deviceName,bool isActualConnection,AudioStreamInfo streamInfo,bool isConnected)1140 void AudioDeviceStatus::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, DeviceType devType,
1141 std::string macAddress, std::string deviceName, bool isActualConnection, AudioStreamInfo streamInfo,
1142 bool isConnected)
1143 {
1144 AUDIO_WARNING_LOG("[ADeviceEvent] bt device[%{public}d] mac[%{public}s] connect[%{public}d]",
1145 devType, GetEncryptStr(macAddress).c_str(), isConnected);
1146
1147 auto devDesc = make_shared<AudioDeviceDescriptor>(updatedDesc);
1148 if (!isActualConnection && audioDeviceManager_.IsConnectedDevices(devDesc)) {
1149 audioDeviceManager_.UpdateVirtualDevices(devDesc, isConnected);
1150 return;
1151 }
1152
1153 AudioServerProxy::GetInstance().SetDmDeviceTypeProxy(isConnected ? updatedDesc.dmDeviceType_ : 0,
1154 updatedDesc.deviceType_);
1155
1156 UpdateLocalGroupInfo(isConnected, macAddress, deviceName, streamInfo, updatedDesc);
1157 // fill device change action for callback
1158 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN;
1159 std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
1160 updatedDesc.spatializationSupported_ = (updatedDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP)
1161 && AudioSpatializationService::GetAudioSpatializationService().
1162 IsSpatializationSupportedForDevice(updatedDesc.macAddress_)
1163 && AudioSpatializationService::GetAudioSpatializationService().IsSpatializationSupported();
1164 UpdateDeviceList(updatedDesc, isConnected, descForCb, reason);
1165
1166 TriggerDeviceChangedCallback(descForCb, isConnected);
1167 TriggerAvailableDeviceChangedCallback(descForCb, isConnected);
1168
1169 if (!isActualConnection) {
1170 return;
1171 }
1172 // fetch input&output device
1173 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("OnDeviceStatusUpdated_4", reason);
1174 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("OnDeviceStatusUpdated_4");
1175 // update a2dp offload
1176 if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && audioA2dpOffloadManager_) {
1177 audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
1178 }
1179 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
1180 audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceStatusUpdated 2 param");
1181 }
1182
UpdateDeviceList(AudioDeviceDescriptor & updatedDesc,bool isConnected,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descForCb,AudioStreamDeviceChangeReasonExt & reason)1183 void AudioDeviceStatus::UpdateDeviceList(AudioDeviceDescriptor &updatedDesc, bool isConnected,
1184 std::vector<std::shared_ptr<AudioDeviceDescriptor>> &descForCb,
1185 AudioStreamDeviceChangeReasonExt &reason)
1186 {
1187 if (isConnected) {
1188 // deduplicate
1189 audioConnectedDevice_.DelConnectedDevice(updatedDesc.networkId_, updatedDesc.deviceType_,
1190 updatedDesc.macAddress_, updatedDesc.deviceRole_);
1191 audioDeviceCommon_.UpdateConnectedDevicesWhenConnecting(updatedDesc, descForCb);
1192 int32_t result = HandleLocalDeviceConnected(updatedDesc);
1193 CHECK_AND_RETURN_LOG(result == SUCCESS, "Connect local device failed.");
1194 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
1195 } else {
1196 audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(updatedDesc, descForCb);
1197 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
1198 CheckForA2dpSuspend(updatedDesc);
1199 // fix pop, fetch device before unload module
1200 if (IsOutputDevice(updatedDesc.deviceType_, updatedDesc.deviceRole_)) {
1201 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("UpdateDeviceList", reason);
1202 }
1203 if (IsInputDevice(updatedDesc.deviceType_, updatedDesc.deviceRole_)) {
1204 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("UpdateDeviceList");
1205 }
1206 int32_t result = HandleLocalDeviceDisconnected(updatedDesc);
1207 CHECK_AND_RETURN_LOG(result == SUCCESS, "Disconnect local device failed.");
1208 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
1209 }
1210 AUDIO_INFO_LOG("Device: %{public}d, isConnected: %{public}d", updatedDesc.deviceType_, isConnected);
1211 }
1212
1213 #ifdef BLUETOOTH_ENABLE
CheckAndActiveHfpDevice(AudioDeviceDescriptor & desc)1214 void AudioDeviceStatus::CheckAndActiveHfpDevice(AudioDeviceDescriptor &desc)
1215 {
1216 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && !audioDeviceManager_.GetScoState()) {
1217 Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc.macAddress_);
1218 }
1219 }
1220 #endif
1221
OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)1222 void AudioDeviceStatus::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command)
1223 {
1224 AUDIO_WARNING_LOG("[ADeviceEvent] bt [%{public}s] type[%{public}d] command: %{public}d category[%{public}d] " \
1225 "connectState[%{public}d] isEnable[%{public}d] deviceUsage[%{public}d]",
1226 GetEncryptAddr(desc.macAddress_).c_str(), desc.deviceType_, command, desc.deviceCategory_,
1227 desc.connectState_, desc.isEnable_, desc.deviceUsage_);
1228 std::string portNeedClose = "";
1229 uint32_t oldPaIndex = OPEN_PORT_FAILURE;
1230 if (command == ENABLE_UPDATE && desc.isEnable_ == true) {
1231 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
1232 AudioPolicyUtils::GetInstance().ClearScoDeviceSuspendState(desc.macAddress_);
1233 }
1234 shared_ptr<AudioDeviceDescriptor> userSelectMediaDevice =
1235 AudioStateManager::GetAudioStateManager().GetPreferredMediaRenderDevice();
1236 shared_ptr<AudioDeviceDescriptor> userSelectCallDevice =
1237 AudioStateManager::GetAudioStateManager().GetPreferredCallRenderDevice();
1238 if ((userSelectMediaDevice->deviceType_ == desc.deviceType_ &&
1239 userSelectMediaDevice->macAddress_ == desc.macAddress_ &&
1240 userSelectMediaDevice->isEnable_ == desc.isEnable_) ||
1241 (userSelectCallDevice->deviceType_ == desc.deviceType_ &&
1242 userSelectCallDevice->macAddress_ == desc.macAddress_ &&
1243 userSelectCallDevice->isEnable_ == desc.isEnable_)) {
1244 AUDIO_INFO_LOG("Current enable state has been set true during user selection, no need to be set again.");
1245 return;
1246 }
1247 } else if (command == ENABLE_UPDATE && !desc.isEnable_ && desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
1248 audioActiveDevice_.GetCurrentOutputDeviceMacAddr() == desc.macAddress_) {
1249 audioIOHandleMap_.MuteDefaultSinkPort(audioActiveDevice_.GetCurrentOutputDeviceNetworkId(),
1250 AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType()));
1251 portNeedClose = BLUETOOTH_SPEAKER;
1252 oldPaIndex = GetPaIndexByPortName(portNeedClose);
1253 }
1254 AudioStreamDeviceChangeReasonExt reason = AudioStreamDeviceChangeReason::UNKNOWN;
1255 std::shared_ptr<AudioDeviceDescriptor> audioDescriptor = std::make_shared<AudioDeviceDescriptor>(desc);
1256 reason = audioDeviceManager_.UpdateDevicesListInfo(audioDescriptor, command);
1257 CheckForA2dpSuspend(desc);
1258
1259 OnPreferredStateUpdated(desc, command, reason);
1260 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("OnDeviceInfoUpdated", reason);
1261 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("OnDeviceInfoUpdated");
1262 if (portNeedClose != "" && oldPaIndex == GetPaIndexByPortName(portNeedClose)) {
1263 audioIOHandleMap_.ClosePortAndEraseIOHandle(portNeedClose);
1264 }
1265 if (audioA2dpOffloadManager_) {
1266 audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
1267 }
1268 audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
1269 audioActiveDevice_.GetCurrentOutputDevice(), "OnDeviceInfoUpdated");
1270 }
1271
CheckForA2dpSuspend(AudioDeviceDescriptor & desc)1272 void AudioDeviceStatus::CheckForA2dpSuspend(AudioDeviceDescriptor &desc)
1273 {
1274 if (desc.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) {
1275 return;
1276 }
1277 if (audioDeviceManager_.GetScoState()) {
1278 AudioServerProxy::GetInstance().SuspendRenderSinkProxy("a2dp");
1279 } else {
1280 AudioServerProxy::GetInstance().RestoreRenderSinkProxy("a2dp");
1281 }
1282 }
1283
UserSelectDeviceMapInit()1284 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioDeviceStatus::UserSelectDeviceMapInit()
1285 {
1286 AudioStateManager& stateManager = AudioStateManager::GetAudioStateManager();
1287 shared_ptr<AudioDeviceDescriptor> userSelectMediaRenderDevice = stateManager.GetPreferredMediaRenderDevice();
1288 shared_ptr<AudioDeviceDescriptor> userSelectCallRenderDevice = stateManager.GetPreferredCallRenderDevice();
1289 shared_ptr<AudioDeviceDescriptor> userSelectCallCaptureDevice = stateManager.GetPreferredCallCaptureDevice();
1290 shared_ptr<AudioDeviceDescriptor> userSelectRecordCaptureDevice = stateManager.GetPreferredRecordCaptureDevice();
1291 vector<shared_ptr<AudioDeviceDescriptor>> userSelectDeviceMap;
1292 userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectMediaRenderDevice));
1293 userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectCallRenderDevice));
1294 userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectCallCaptureDevice));
1295 userSelectDeviceMap.push_back(make_shared<AudioDeviceDescriptor>(*userSelectRecordCaptureDevice));
1296 return userSelectDeviceMap;
1297 }
1298
DeactivateNearlinkDevice(AudioDeviceDescriptor & desc)1299 void AudioDeviceStatus::DeactivateNearlinkDevice(AudioDeviceDescriptor &desc)
1300 {
1301 if (desc.deviceType_ == DEVICE_TYPE_NEARLINK || desc.deviceType_ == DEVICE_TYPE_NEARLINK_IN) {
1302 if (desc.macAddress_ == audioActiveDevice_.GetCurrentOutputDeviceMacAddr()) {
1303 SleAudioDeviceManager::GetInstance().SetActiveDevice(desc, STREAM_USAGE_INVALID);
1304 }
1305 }
1306 }
1307
OnPreferredStateUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand updateCommand,AudioStreamDeviceChangeReasonExt & reason)1308 void AudioDeviceStatus::OnPreferredStateUpdated(AudioDeviceDescriptor &desc,
1309 const DeviceInfoUpdateCommand updateCommand, AudioStreamDeviceChangeReasonExt &reason)
1310 {
1311 vector<shared_ptr<AudioDeviceDescriptor>> userSelectDeviceMap = UserSelectDeviceMapInit();
1312 if (updateCommand == CATEGORY_UPDATE) {
1313 if (desc.deviceCategory_ == BT_UNWEAR_HEADPHONE) {
1314 reason = AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
1315 UpdateAllUserSelectDevice(userSelectDeviceMap, desc, std::make_shared<AudioDeviceDescriptor>());
1316 #ifdef BLUETOOTH_ENABLE
1317 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
1318 desc.macAddress_ == audioActiveDevice_.GetCurrentOutputDeviceMacAddr()) {
1319 Bluetooth::AudioA2dpManager::SetActiveA2dpDevice("");
1320 }
1321 #endif
1322 // Handle Nearlink Device
1323 DeactivateNearlinkDevice(desc);
1324 } else {
1325 reason = AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE;
1326 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP || desc.deviceType_ == DEVICE_TYPE_NEARLINK) {
1327 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER,
1328 std::make_shared<AudioDeviceDescriptor>());
1329 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_RECORD_CAPTURE,
1330 std::make_shared<AudioDeviceDescriptor>());
1331 }
1332 if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO || desc.deviceType_ == DEVICE_TYPE_NEARLINK) {
1333 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_RENDER,
1334 std::make_shared<AudioDeviceDescriptor>(), CLEAR_UID, "OnPreferredStateUpdated");
1335 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_CAPTURE,
1336 std::make_shared<AudioDeviceDescriptor>());
1337 AudioPolicyUtils::GetInstance().ClearScoDeviceSuspendState(desc.macAddress_);
1338 #ifdef BLUETOOTH_ENABLE
1339 CheckAndActiveHfpDevice(desc);
1340 #endif
1341 }
1342 }
1343 } else if (updateCommand == ENABLE_UPDATE) {
1344 UpdateAllUserSelectDevice(userSelectDeviceMap, desc, std::make_shared<AudioDeviceDescriptor>(desc));
1345 reason = desc.isEnable_ ? AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE :
1346 AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE;
1347 } else if (updateCommand == USAGE_UPDATE) {
1348 UpdateAllUserSelectDevice(userSelectDeviceMap, desc, std::make_shared<AudioDeviceDescriptor>(desc));
1349 }
1350 }
1351
UpdateAllUserSelectDevice(std::vector<std::shared_ptr<AudioDeviceDescriptor>> & userSelectDeviceMap,AudioDeviceDescriptor & desc,const std::shared_ptr<AudioDeviceDescriptor> & selectDesc)1352 void AudioDeviceStatus::UpdateAllUserSelectDevice(
1353 std::vector<std::shared_ptr<AudioDeviceDescriptor>> &userSelectDeviceMap,
1354 AudioDeviceDescriptor &desc, const std::shared_ptr<AudioDeviceDescriptor> &selectDesc)
1355 {
1356 if (userSelectDeviceMap[MEDIA_RENDER_ID]->deviceType_ == desc.deviceType_ &&
1357 userSelectDeviceMap[MEDIA_RENDER_ID]->macAddress_ == desc.macAddress_) {
1358 if (userSelectDeviceMap[MEDIA_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) {
1359 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_MEDIA_RENDER, selectDesc);
1360 } else {
1361 audioStateManager_.UpdatePreferredMediaRenderDeviceConnectState(desc.connectState_);
1362 }
1363 }
1364 if (userSelectDeviceMap[CALL_RENDER_ID]->deviceType_ == desc.deviceType_ &&
1365 userSelectDeviceMap[CALL_RENDER_ID]->macAddress_ == desc.macAddress_) {
1366 if (userSelectDeviceMap[CALL_RENDER_ID]->connectState_ != VIRTUAL_CONNECTED) {
1367 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_RENDER,
1368 selectDesc, SYSTEM_UID, "UpdateAllUserSelectDevice");
1369 } else {
1370 audioStateManager_.UpdatePreferredCallRenderDeviceConnectState(desc.connectState_);
1371 }
1372 }
1373 if (userSelectDeviceMap[CALL_CAPTURE_ID]->deviceType_ == desc.deviceType_ &&
1374 userSelectDeviceMap[CALL_CAPTURE_ID]->macAddress_ == desc.macAddress_) {
1375 if (userSelectDeviceMap[CALL_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) {
1376 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_CAPTURE, selectDesc);
1377 } else {
1378 audioStateManager_.UpdatePreferredCallCaptureDeviceConnectState(desc.connectState_);
1379 }
1380 }
1381 if (userSelectDeviceMap[RECORD_CAPTURE_ID]->deviceType_ == desc.deviceType_ &&
1382 userSelectDeviceMap[RECORD_CAPTURE_ID]->macAddress_ == desc.macAddress_) {
1383 if (userSelectDeviceMap[RECORD_CAPTURE_ID]->connectState_ != VIRTUAL_CONNECTED) {
1384 AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_RECORD_CAPTURE, selectDesc);
1385 } else {
1386 audioStateManager_.UpdatePreferredRecordCaptureDeviceConnectState(desc.connectState_);
1387 }
1388 }
1389 }
1390
RemoveDeviceFromGlobalOnly(std::shared_ptr<AudioDeviceDescriptor> desc)1391 void AudioDeviceStatus::RemoveDeviceFromGlobalOnly(std::shared_ptr<AudioDeviceDescriptor> desc)
1392 {
1393 CHECK_AND_RETURN_LOG(desc != nullptr, "desc is nullptr");
1394 AUDIO_INFO_LOG("remove device from global list only");
1395 std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
1396 audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(desc, descForCb);
1397 TriggerDeviceChangedCallback(descForCb, false);
1398 TriggerAvailableDeviceChangedCallback(descForCb, false);
1399 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("RemoveDeviceFromGlobalOnly");
1400 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("RemoveDeviceFromGlobalOnly");
1401 }
1402
AddDeviceBackToGlobalOnly(std::shared_ptr<AudioDeviceDescriptor> desc)1403 void AudioDeviceStatus::AddDeviceBackToGlobalOnly(std::shared_ptr<AudioDeviceDescriptor> desc)
1404 {
1405 CHECK_AND_RETURN_LOG(desc != nullptr, "desc is nullptr");
1406 AUDIO_INFO_LOG("add device back to global list only");
1407 std::vector<std::shared_ptr<AudioDeviceDescriptor>> descForCb = {};
1408 audioDeviceCommon_.UpdateConnectedDevicesWhenConnecting(desc, descForCb);
1409 TriggerDeviceChangedCallback(descForCb, true);
1410 TriggerAvailableDeviceChangedCallback(descForCb, true);
1411 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("AddDeviceBackToGlobalOnly");
1412 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("AddDeviceBackToGlobalOnly");
1413 }
1414
HandleOfflineDistributedDevice()1415 void AudioDeviceStatus::HandleOfflineDistributedDevice()
1416 {
1417 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceChangeDescriptor = {};
1418
1419 std::vector<std::shared_ptr<AudioDeviceDescriptor>> connectedDevices = audioConnectedDevice_.GetCopy();
1420 std::vector<std::string> modulesNeedClose = {};
1421 for (auto deviceDesc : connectedDevices) {
1422 if (deviceDesc != nullptr && deviceDesc->networkId_ != LOCAL_NETWORK_ID) {
1423 const std::string networkId = deviceDesc->networkId_;
1424 audioDeviceCommon_.UpdateConnectedDevicesWhenDisconnecting(deviceDesc, deviceChangeDescriptor);
1425 std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId,
1426 AudioPolicyUtils::GetInstance().GetDeviceRole(deviceDesc->deviceType_));
1427 audioIOHandleMap_.MuteDefaultSinkPort(audioActiveDevice_.GetCurrentOutputDeviceNetworkId(),
1428 AudioPolicyUtils::GetInstance().GetSinkPortName(audioActiveDevice_.GetCurrentOutputDeviceType()));
1429 modulesNeedClose.push_back(moduleName);
1430 audioRouteMap_.RemoveDeviceInRouterMap(moduleName);
1431 audioRouteMap_.RemoveDeviceInFastRouterMap(networkId);
1432 if (AudioPolicyUtils::GetInstance().GetDeviceRole(deviceDesc->deviceType_) == DeviceRole::INPUT_DEVICE) {
1433 remoteCapturerSwitch_ = true;
1434 }
1435 }
1436 }
1437
1438 TriggerDeviceChangedCallback(deviceChangeDescriptor, false);
1439 TriggerAvailableDeviceChangedCallback(deviceChangeDescriptor, false);
1440 AUDIO_INFO_LOG("onDeviceStatusUpdated reson:%{public}d",
1441 AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE_UNAVAILABLE);
1442 AudioCoreService::GetCoreService()->FetchOutputDeviceAndRoute("HandleOfflineDistributedDevice",
1443 AudioStreamDeviceChangeReasonExt::ExtEnum::DISTRIBUTED_DEVICE_UNAVAILABLE);
1444 AudioCoreService::GetCoreService()->FetchInputDeviceAndRoute("HandleOfflineDistributedDevice");
1445 for (auto &moduleName : modulesNeedClose) {
1446 audioIOHandleMap_.ClosePortAndEraseIOHandle(moduleName);
1447 }
1448 }
1449
GetDmDeviceType()1450 uint16_t AudioDeviceStatus::GetDmDeviceType()
1451 {
1452 return dmDeviceType_;
1453 }
1454
RestoreNewA2dpPort(std::vector<std::shared_ptr<AudioStreamDescriptor>> & streamDescs,AudioModuleInfo & moduleInfo,std::string & currentActivePort)1455 int32_t AudioDeviceStatus::RestoreNewA2dpPort(std::vector<std::shared_ptr<AudioStreamDescriptor>> &streamDescs,
1456 AudioModuleInfo &moduleInfo, std::string ¤tActivePort)
1457 {
1458 // Load bt sink module again with new configuration
1459 AUDIO_INFO_LOG("Reload a2dp module [%{public}s]", moduleInfo.name.c_str());
1460 uint32_t paIndex;
1461 AudioIOHandle ioHandle;
1462 int32_t engineFlag = GetEngineFlag();
1463 if (engineFlag == 1) {
1464 ioHandle = audioPolicyManager_.ReloadAudioPort(moduleInfo, paIndex);
1465 } else {
1466 ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex);
1467 }
1468 if (ioHandle == HDI_INVALID_ID || paIndex == OPEN_PORT_FAILURE) {
1469 audioPolicyManager_.SuspendAudioDevice(currentActivePort, false);
1470 AUDIO_ERR_LOG("AudioPort failed, ioHandle: %{public}u, paIndex: %{public}u", ioHandle, paIndex);
1471 return ERROR;
1472 }
1473 audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle);
1474
1475 std::shared_ptr<AudioPipeInfo> pipeInfo = std::make_shared<AudioPipeInfo>();
1476 pipeInfo->id_ = ioHandle;
1477 pipeInfo->paIndex_ = paIndex;
1478 if (moduleInfo.role == "sink") {
1479 pipeInfo->name_ = "a2dp_output";
1480 pipeInfo->pipeRole_ = PIPE_ROLE_OUTPUT;
1481 pipeInfo->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL;
1482 } else {
1483 pipeInfo->name_ = "a2dp_input";
1484 pipeInfo->pipeRole_ = PIPE_ROLE_INPUT;
1485 pipeInfo->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL;
1486 }
1487 pipeInfo->adapterName_ = "a2dp";
1488 pipeInfo->moduleInfo_ = moduleInfo;
1489 pipeInfo->pipeAction_ = PIPE_ACTION_DEFAULT;
1490 pipeInfo->InitAudioStreamInfo();
1491 pipeInfo->streamDescriptors_.insert(pipeInfo->streamDescriptors_.end(), streamDescs.begin(), streamDescs.end());
1492 AudioPipeManager::GetPipeManager()->AddAudioPipeInfo(pipeInfo);
1493 return SUCCESS;
1494 }
1495
GetPaIndexByPortName(std::string & portName)1496 uint32_t AudioDeviceStatus::GetPaIndexByPortName(std::string &portName)
1497 {
1498 AudioIOHandle ioHandle;
1499 CHECK_AND_RETURN_RET_LOG(audioIOHandleMap_.GetModuleIdByKey(portName, ioHandle), OPEN_PORT_FAILURE,
1500 "can not find %{public}s in io map", portName.c_str());
1501 std::shared_ptr<AudioPipeManager> pipeManager = AudioPipeManager::GetPipeManager();
1502 uint32_t paIndex = pipeManager->GetPaIndexByIoHandle(ioHandle);
1503 AUDIO_INFO_LOG("Port %{public}s, paIndex: %{public}u", portName.c_str(), paIndex);
1504 return paIndex;
1505 }
1506 }
1507 }
1508