• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef LOG_TAG
16 #define LOG_TAG "AudioCoreServicePrivate"
17 #endif
18 
19 #include "audio_core_service.h"
20 
21 #include <variant>
22 
23 #include "system_ability.h"
24 #include "app_mgr_client.h"
25 #include "hisysevent.h"
26 #include "audio_server_proxy.h"
27 #include "audio_policy_utils.h"
28 #include "iservice_registry.h"
29 #include "hdi_adapter_info.h"
30 #include "audio_usb_manager.h"
31 #include "audio_spatialization_service.h"
32 #include "audio_collaborative_service.h"
33 #include "audio_stream_id_allocator.h"
34 #include "ipc_skeleton.h"
35 #include "audio_bundle_manager.h"
36 
37 namespace OHOS {
38 namespace AudioStandard {
39 namespace {
40 static const int32_t MEDIA_SERVICE_UID = 1013;
41 const int32_t DATA_LINK_CONNECTED = 11;
42 const uint32_t FIRST_SESSIONID = 100000;
43 const uid_t MCU_UID = 7500;
44 const uid_t TV_SERVICE_UID = 7501;
45 const int32_t AUDIO_EXT_UID = 1041;
46 constexpr uint32_t MAX_VALID_SESSIONID = UINT32_MAX - FIRST_SESSIONID;
47 static const int VOLUME_LEVEL_DEFAULT_SIZE = 3;
48 static const int32_t BLUETOOTH_FETCH_RESULT_DEFAULT = 0;
49 static const int32_t BLUETOOTH_FETCH_RESULT_CONTINUE = 1;
50 static const int32_t BLUETOOTH_FETCH_RESULT_ERROR = 2;
51 static const int64_t WAIT_MODEM_CALL_SET_VOLUME_TIME_US = 120000; // 120ms
52 static const int64_t RING_DUAL_END_DELAY_US = 100000; // 100ms
53 static const int64_t OLD_DEVICE_UNAVALIABLE_MUTE_MS = 1000000; // 1s
54 static const int64_t NEW_DEVICE_AVALIABLE_MUTE_MS = 400000; // 400ms
55 static const int64_t NEW_DEVICE_AVALIABLE_OFFLOAD_MUTE_MS = 1000000; // 1s
56 static const int64_t NEW_DEVICE_REMOTE_CAST_AVALIABLE_MUTE_MS = 300000; // 300ms
57 static const int64_t SELECT_DEVICE_MUTE_MS = 200000; // 200ms
58 static const int64_t SELECT_OFFLOAD_DEVICE_MUTE_MS = 400000; // 400ms
59 static const int64_t OLD_DEVICE_UNAVALIABLE_EXT_MUTE_MS = 300000; // 300ms
60 static const int64_t DISTRIBUTED_DEVICE_UNAVALIABLE_MUTE_MS = 1500000;  // 1.5s
61 
62 static const uint32_t BASE_DEVICE_SWITCH_SLEEP_US = 80000; // 80ms
63 static const uint32_t OLD_DEVICE_UNAVAILABLE_EXTRA_SLEEP_US = 150000; // 150ms
64 static const uint32_t DISTRIBUTED_DEVICE_UNAVAILABLE_EXTRA_SLEEP_US = 350000; // 350ms
65 static const uint32_t HEADSET_TO_SPK_EP_EXTRA_SLEEP_US = 50000; // 50ms
66 static const uint32_t MEDIA_PAUSE_TO_DOUBLE_RING_DELAY_US = 120000; // 120ms
67 
68 static const uint32_t BT_BUFFER_ADJUSTMENT_FACTOR = 50;
69 static const int32_t WAIT_OFFLOAD_CLOSE_TIME_SEC = 10;
70 static const char* CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#";
71 static const std::unordered_set<SourceType> specialSourceTypeSet_ = {
72     SOURCE_TYPE_PLAYBACK_CAPTURE,
73     SOURCE_TYPE_WAKEUP,
74     SOURCE_TYPE_VIRTUAL_CAPTURE,
75     SOURCE_TYPE_REMOTE_CAST
76 };
77 static const std::unordered_set<uid_t> skipAddSessionIdUidSet_ = {
78     MCU_UID,
79     TV_SERVICE_UID
80 };
81 }
82 
83 static const std::vector<std::string> SourceNames = {
84     std::string(PRIMARY_MIC),
85     std::string(BLUETOOTH_MIC),
86     std::string(USB_MIC),
87     std::string(PRIMARY_WAKEUP),
88     std::string(FILE_SOURCE),
89     std::string(ACCESSORY_SOURCE)
90 };
91 
GetEncryptAddr(const std::string & addr)92 std::string AudioCoreService::GetEncryptAddr(const std::string &addr)
93 {
94     const int32_t START_POS = 6;
95     const int32_t END_POS = 13;
96     const int32_t ADDRESS_STR_LEN = 17;
97     if (addr.empty() || addr.length() != ADDRESS_STR_LEN) {
98         return std::string("");
99     }
100     std::string tmp = "**:**:**:**:**:**";
101     std::string out = addr;
102     for (int i = START_POS; i <= END_POS; i++) {
103         out[i] = tmp[i];
104     }
105     return out;
106 }
107 
UpdateActiveDeviceAndVolumeBeforeMoveSession(std::vector<std::shared_ptr<AudioStreamDescriptor>> & streamDescs,const AudioStreamDeviceChangeReasonExt reason)108 void AudioCoreService::UpdateActiveDeviceAndVolumeBeforeMoveSession(
109     std::vector<std::shared_ptr<AudioStreamDescriptor>> &streamDescs, const AudioStreamDeviceChangeReasonExt reason)
110 {
111     bool needUpdateActiveDevice = true;
112     bool isUpdateActiveDevice = false;
113     uint32_t sessionId = 0;
114     for (std::shared_ptr<AudioStreamDescriptor> streamDesc : streamDescs) {
115         //  if streamDesc select bluetooth or headset, active it
116         if (!HandleOutputStreamInRunning(streamDesc, reason)) {
117             continue;
118         }
119         int32_t outputRet = ActivateOutputDevice(streamDesc, reason);
120         CHECK_AND_CONTINUE_LOG(outputRet == SUCCESS, "Activate output device failed");
121 
122         // update current output device
123         if (needUpdateActiveDevice) {
124             isUpdateActiveDevice = UpdateOutputDevice(streamDesc->newDeviceDescs_.front(), GetRealUid(streamDesc),
125                 reason);
126             needUpdateActiveDevice = !isUpdateActiveDevice;
127             sessionId = streamDesc->sessionId_;
128         }
129 
130         CheckAndSleepBeforeRingDualDeviceSet(streamDesc, reason);
131 
132         // started stream need to mute when switch device
133         if (streamDesc->streamStatus_ == STREAM_STATUS_STARTED) {
134             MuteSinkPortForSwitchDevice(streamDesc, reason);
135         }
136         UpdatePlaybackStreamFlag(streamDesc, false);
137     }
138     AudioDeviceDescriptor audioDeviceDescriptor = audioActiveDevice_.GetCurrentOutputDevice();
139     std::shared_ptr<AudioDeviceDescriptor> descPtr =
140         std::make_shared<AudioDeviceDescriptor>(audioDeviceDescriptor);
141     if (isUpdateActiveDevice && audioDeviceManager_.IsDeviceConnected(descPtr)) {
142         AUDIO_INFO_LOG("active device updated, update volume for %{public}d", sessionId);
143         audioVolumeManager_.SetVolumeForSwitchDevice(audioDeviceDescriptor, "", false);
144         OnPreferredOutputDeviceUpdated(audioDeviceDescriptor, reason);
145     }
146 }
147 
UpdateOffloadState(std::shared_ptr<AudioPipeInfo> pipeInfo)148 void AudioCoreService::UpdateOffloadState(std::shared_ptr<AudioPipeInfo> pipeInfo)
149 {
150     CHECK_AND_RETURN(pipeInfo && pipeInfo->streamDescriptors_.size() > 0);
151     CHECK_AND_RETURN(pipeInfo->moduleInfo_.name == OFFLOAD_PRIMARY_SPEAKER ||
152         pipeInfo->moduleInfo_.className == "remote_offload");
153     OffloadType type = pipeInfo->moduleInfo_.className == "remote_offload" ? REMOTE_OFFLOAD : LOCAL_OFFLOAD;
154     isOffloadOpened_[type].store(true);
155     offloadCloseCondition_[type].notify_all();
156 }
157 
NotifyRouteUpdate(const std::vector<std::shared_ptr<AudioStreamDescriptor>> & streamDescs)158 void AudioCoreService::NotifyRouteUpdate(const std::vector<std::shared_ptr<AudioStreamDescriptor>> &streamDescs)
159 {
160     for (auto &streamDesc : streamDescs) {
161         CHECK_AND_CONTINUE_LOG(streamDesc != nullptr && !streamDesc->newDeviceDescs_.empty(), "invalid streamDesc");
162         std::lock_guard<std::mutex> lock(routeUpdateCallbackMutex_);
163         uint32_t sessionId = streamDesc->sessionId_;
164         CHECK_AND_CONTINUE_LOG(routeUpdateCallback_.count(sessionId) != 0, "sessionId %{public}u not registed",
165             sessionId);
166         auto callback = routeUpdateCallback_[sessionId];
167         CHECK_AND_CONTINUE_LOG(callback != nullptr, "callback is nullptr");
168         std::shared_ptr<AudioDeviceDescriptor> desc = streamDesc->newDeviceDescs_.front();
169         CHECK_AND_CONTINUE_LOG(desc != nullptr, "device desc is nullptr");
170         callback->OnRouteUpdate(streamDesc->routeFlag_, desc->networkId_);
171     }
172 }
173 
FetchRendererPipesAndExecute(std::vector<std::shared_ptr<AudioStreamDescriptor>> & streamDescs,const AudioStreamDeviceChangeReasonExt reason)174 int32_t AudioCoreService::FetchRendererPipesAndExecute(
175     std::vector<std::shared_ptr<AudioStreamDescriptor>> &streamDescs, const AudioStreamDeviceChangeReasonExt reason)
176 {
177     AUDIO_INFO_LOG("[PipeFetchStart] all %{public}zu output streams", streamDescs.size());
178     UpdateActiveDeviceAndVolumeBeforeMoveSession(streamDescs, reason);
179     std::vector<std::shared_ptr<AudioPipeInfo>> pipeInfos = audioPipeSelector_->FetchPipesAndExecute(streamDescs);
180     uint32_t audioFlag;
181     for (auto &pipeInfo : pipeInfos) {
182         CHECK_AND_CONTINUE_LOG(pipeInfo != nullptr, "pipeInfo is nullptr");
183         UpdateOffloadState(pipeInfo);
184         if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) {
185             ProcessOutputPipeUpdate(pipeInfo, audioFlag, reason);
186         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) {
187             ProcessOutputPipeNew(pipeInfo, audioFlag, reason);
188         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) {
189             // Do nothing
190         }
191     }
192     pipeManager_->UpdateRendererPipeInfos(pipeInfos);
193     RemoveUnusedPipe();
194     NotifyRouteUpdate(streamDescs);
195     return SUCCESS;
196 }
197 
FetchCapturerPipesAndExecute(std::vector<std::shared_ptr<AudioStreamDescriptor>> & streamDescs)198 int32_t AudioCoreService::FetchCapturerPipesAndExecute(
199     std::vector<std::shared_ptr<AudioStreamDescriptor>> &streamDescs)
200 {
201     AUDIO_INFO_LOG("[PipeFetchStart] all %{public}zu input streams", streamDescs.size());
202     std::vector<std::shared_ptr<AudioPipeInfo>> pipeInfos = audioPipeSelector_->FetchPipesAndExecute(streamDescs);
203 
204     AUDIO_INFO_LOG("[PipeExecStart] for all Pipes");
205     uint32_t audioFlag;
206     for (auto &pipeInfo : pipeInfos) {
207         CHECK_AND_CONTINUE_LOG(pipeInfo != nullptr, "pipeInfo is nullptr");
208         AUDIO_INFO_LOG("[PipeExecInfo] Scan Pipe adapter: %{public}s, name: %{public}s, action: %{public}d",
209             pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->name_.c_str(), pipeInfo->pipeAction_);
210         if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) {
211             ProcessInputPipeUpdate(pipeInfo, audioFlag);
212         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) {
213             ProcessInputPipeNew(pipeInfo, audioFlag);
214         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) {
215             // Do nothing
216         }
217     }
218     pipeManager_->UpdateCapturerPipeInfos(pipeInfos);
219     RemoveUnusedPipe();
220     return SUCCESS;
221 }
222 
ScoInputDeviceFetchedForRecongnition(bool handleFlag,const std::string & address,ConnectState connectState)223 int32_t AudioCoreService::ScoInputDeviceFetchedForRecongnition(bool handleFlag, const std::string &address,
224     ConnectState connectState)
225 {
226     AUDIO_INFO_LOG("handleflag %{public}d, address %{public}s, connectState %{public}d",
227         handleFlag, GetEncryptAddr(address).c_str(), connectState);
228     if (handleFlag && connectState != DEACTIVE_CONNECTED) {
229         return SUCCESS;
230     }
231     return Bluetooth::AudioHfpManager::HandleScoWithRecongnition(handleFlag);
232 }
233 
BluetoothScoFetch(std::shared_ptr<AudioStreamDescriptor> streamDesc)234 void AudioCoreService::BluetoothScoFetch(std::shared_ptr<AudioStreamDescriptor> streamDesc)
235 {
236     Trace trace("AudioCoreService::BluetoothScoFetch");
237     CHECK_AND_RETURN_LOG(streamDesc != nullptr && streamDesc->newDeviceDescs_.size() > 0 &&
238         streamDesc->newDeviceDescs_[0] != nullptr, "invalid streamDesc");
239     shared_ptr<AudioDeviceDescriptor> desc = streamDesc->newDeviceDescs_[0];
240     int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_);
241     if (ret != SUCCESS) {
242         AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch input device");
243         desc->exceptionFlag_ = true;
244         audioDeviceManager_.UpdateDevicesListInfo(
245             std::make_shared<AudioDeviceDescriptor>(*desc), EXCEPTION_FLAG_UPDATE);
246         FetchInputDeviceAndRoute("BluetoothScoFetch");
247         return;
248     }
249 
250     if (streamDesc->streamStatus_ != STREAM_STATUS_STARTED) {
251         return;
252     }
253     if (Util::IsScoSupportSource(streamDesc->capturerInfo_.sourceType)) {
254         ret = ScoInputDeviceFetchedForRecongnition(true, desc->macAddress_, desc->connectState_);
255     } else {
256         ret = Bluetooth::AudioHfpManager::UpdateAudioScene(audioSceneManager_.GetAudioScene(true), true);
257     }
258     if (ret != SUCCESS) {
259         AUDIO_ERR_LOG("sco [%{public}s] is not connected yet",
260             GetEncryptAddr(desc->macAddress_).c_str());
261     }
262 }
263 
CheckModemScene(std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descs,const AudioStreamDeviceChangeReasonExt reason)264 void AudioCoreService::CheckModemScene(std::vector<std::shared_ptr<AudioDeviceDescriptor>> &descs,
265     const AudioStreamDeviceChangeReasonExt reason)
266 {
267     if (!pipeManager_->IsModemCommunicationIdExist()) {
268         return;
269     }
270 
271     bool isModemCallRunning = audioSceneManager_.IsInPhoneCallScene();
272     if (isModemCallRunning) {
273         pipeManager_->UpdateModemStreamStatus(STREAM_STATUS_STARTED);
274     } else {
275         pipeManager_->UpdateModemStreamStatus(STREAM_STATUS_STOPPED);
276     }
277     descs = audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_MODEM_COMMUNICATION, -1, "CheckModemScene");
278     CHECK_AND_RETURN_LOG(descs.size() != 0, "Fetch output device for voice modem communication failed");
279     pipeManager_->UpdateModemStreamDevice(descs);
280     AudioDeviceDescriptor curDesc = audioActiveDevice_.GetCurrentOutputDevice();
281     AUDIO_INFO_LOG("Current output device %{public}d, update route %{public}d, reason %{public}d",
282         curDesc.deviceType_, descs.front()->deviceType_, static_cast<int32_t>(reason));
283     if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
284         auto modemCommunicationMap = pipeManager_->GetModemCommunicationMap();
285         auto modemMap = modemCommunicationMap.begin();
286         if (modemMap != modemCommunicationMap.end()) {
287             int32_t ret = HandleScoOutputDeviceFetched(modemMap->second, reason);
288             AUDIO_INFO_LOG("HandleScoOutputDeviceFetched %{public}d", ret);
289         }
290     }
291     if (descs.front()->deviceType_ == DEVICE_TYPE_HEARING_AID) {
292         SwitchActiveHearingAidDevice(std::make_shared<AudioDeviceDescriptor>(descs.front()));
293     }
294     auto ret = ActivateNearlinkDevice(pipeManager_->GetModemCommunicationMap().begin()->second);
295     // If the modem call is in progress, and the device is currently switching,
296     // and the current output device is different from the target device, then mute to avoid pop issue.
297     if (isModemCallRunning && IsDeviceSwitching(reason) && !curDesc.IsSameDeviceDesc(*descs.front())) {
298         SetVoiceCallMuteForSwitchDevice();
299     }
300     CheckAndUpdateHearingAidCall(descs.front()->deviceType_);
301 }
302 
UpdateModemRoute(std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descs)303 int32_t AudioCoreService::UpdateModemRoute(std::vector<std::shared_ptr<AudioDeviceDescriptor>> &descs)
304 {
305     if (!pipeManager_->IsModemCommunicationIdExist()) {
306         return SUCCESS;
307     }
308     CHECK_AND_RETURN_RET_LOG(descs.size() != 0, ERROR, "Update device route for voice modem communication failed");
309     CHECK_AND_RETURN_RET_LOG(descs.front() != nullptr, ERROR, "Update modem route: desc is nullptr");
310     if (audioSceneManager_.IsInPhoneCallScene()) {
311         audioActiveDevice_.UpdateActiveDeviceRoute(descs.front()->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG,
312             descs.front()->deviceName_, descs.front()->networkId_);
313         audioVolumeManager_.SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
314     }
315     AudioDeviceDescriptor desc = AudioDeviceDescriptor(descs.front());
316     std::unordered_map<uint32_t, std::shared_ptr<AudioStreamDescriptor>> modemSessionMap =
317         pipeManager_->GetModemCommunicationMap();
318     for (auto it = modemSessionMap.begin(); it != modemSessionMap.end(); ++it) {
319         streamCollector_.UpdateRendererDeviceInfo(GetRealUid(it->second), it->first, desc);
320         sleAudioDeviceManager_.UpdateSleStreamTypeCount(it->second);
321     }
322     return SUCCESS;
323 }
324 
CheckCloseHearingAidCall(const bool isModemCallRunning,const DeviceType type)325 void AudioCoreService::CheckCloseHearingAidCall(const bool isModemCallRunning, const DeviceType type)
326 {
327     if (hearingAidCallFlag_) {
328         if ((isModemCallRunning && type != DEVICE_TYPE_HEARING_AID) || !isModemCallRunning) {
329             hearingAidCallFlag_ = false;
330             AudioServerProxy::GetInstance().SetAudioParameterProxy("mute_call", "false");
331 
332             CHECK_AND_RETURN_LOG(softLink_ != nullptr, "softLink is null");
333             int32_t ret = softLink_->Stop();
334             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Stop failed");
335             ret = softLink_->Release();
336             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Release failed");
337             softLink_ = nullptr;
338 
339             std::shared_ptr<AudioPipeInfo> pipeInfo = pipeManager_->GetPipeinfoByNameAndFlag("primary",
340                 AUDIO_INPUT_FLAG_NORMAL);
341             CHECK_AND_RETURN_LOG(pipeInfo != nullptr, "pipeInfo is null");
342             pipeInfo->softLinkFlag_ = false;
343             pipeManager_->UpdateAudioPipeInfo(pipeInfo);
344 
345             if (pipeInfo->streamDescriptors_.empty()) {
346                 RemoveUnusedRecordPipe();
347             } else {
348                 audioCapturerSession_.ReloadCaptureSessionSoftLink();
349             }
350         }
351     }
352 }
353 
CheckOpenHearingAidCall(const bool isModemCallRunning,const DeviceType type)354 void AudioCoreService::CheckOpenHearingAidCall(const bool isModemCallRunning, const DeviceType type)
355 {
356     if (!hearingAidCallFlag_) {
357         if (isModemCallRunning && type == DEVICE_TYPE_HEARING_AID) {
358             hearingAidCallFlag_ = true;
359             uint32_t paIndex = 0;
360             audioActiveDevice_.UpdateActiveDeviceRoute(DeviceType::DEVICE_TYPE_SPEAKER,
361                 DeviceFlag::OUTPUT_DEVICES_FLAG);
362             AudioServerProxy::GetInstance().SetAudioParameterProxy("mute_call", "true");
363 
364             CheckModuleForHearingAid(paIndex);
365 
366             std::shared_ptr<AudioPipeInfo> pipeInfoOutput = pipeManager_->GetPipeinfoByNameAndFlag("hearing_aid",
367                 AUDIO_OUTPUT_FLAG_NORMAL);
368             CHECK_AND_RETURN_LOG(pipeInfoOutput != nullptr, "Can not find pipe hearing_aid");
369 
370             softLink_ = HPAE::IHpaeSoftLink::CreateSoftLink(pipeInfoOutput->paIndex_, paIndex,
371                 HPAE::SoftLinkMode::HEARING_AID);
372             CHECK_AND_RETURN_LOG(softLink_ != nullptr, "CreateSoftLink failed");
373             int32_t ret = softLink_->Start();
374             CHECK_AND_RETURN_LOG(ret == SUCCESS, "Start failed");
375         }
376     }
377 }
378 
CheckModuleForHearingAid(uint32_t & paIndex)379 void AudioCoreService::CheckModuleForHearingAid(uint32_t &paIndex)
380 {
381     std::list<AudioModuleInfo> moduleInfoList;
382     bool configRet = policyConfigMananger_.GetModuleListByType(ClassType::TYPE_PRIMARY, moduleInfoList);
383     CHECK_AND_RETURN_LOG(configRet, "HearingAid not exist in config");
384     for (auto &moduleInfo : moduleInfoList) {
385         if (moduleInfo.role != "source") { continue; }
386         AUDIO_INFO_LOG("hearingAidCall connects");
387         moduleInfo.networkId = "LocalDevice";
388         moduleInfo.deviceType = std::to_string(DEVICE_TYPE_MIC);
389         moduleInfo.sourceType = std::to_string(SOURCE_TYPE_VOICE_CALL);
390 
391         std::shared_ptr<AudioPipeInfo> pipeInfo = std::make_shared<AudioPipeInfo>();
392         pipeInfo->name_ = "primary_input";
393         pipeInfo->pipeRole_ = PIPE_ROLE_INPUT;
394         pipeInfo->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL;
395         pipeInfo->adapterName_ = "primary";
396         pipeInfo->moduleInfo_ = moduleInfo;
397         pipeInfo->pipeAction_ = PIPE_ACTION_NEW;
398         pipeInfo->softLinkFlag_ = true;
399         AudioIOHandle ioHandle;
400         if (!audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name)) {
401             ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex);
402             CHECK_AND_CONTINUE_LOG(ioHandle != HDI_INVALID_ID,
403                 "OpenAudioPort failed ioHandle[%{public}u]", ioHandle);
404             CHECK_AND_CONTINUE_LOG(paIndex != OPEN_PORT_FAILURE,
405                 "OpenAudioPort failed paId[%{public}u]", paIndex);
406             audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle);
407             pipeInfo->id_ = ioHandle;
408             pipeInfo->paIndex_ = paIndex;
409             pipeManager_->AddAudioPipeInfo(pipeInfo);
410             AUDIO_INFO_LOG("Add PipeInfo %{public}u in load hearingAidCall.", pipeInfo->id_);
411         } else {
412             CHECK_AND_CONTINUE_LOG(audioIOHandleMap_.GetModuleIdByKey(PRIMARY_MIC, ioHandle),
413                 "can not find primary in IOmap");
414             auto pipeInfoInput = pipeManager_->GetPipeinfoByNameAndFlag("primary",
415                 AUDIO_INPUT_FLAG_NORMAL);
416             CHECK_AND_CONTINUE_LOG(pipeInfoInput != nullptr, "can not find primary pipeInfo");
417             paIndex = pipeInfoInput->paIndex_;
418             pipeInfo->id_ = ioHandle;
419             pipeInfo->paIndex_ = paIndex;
420             pipeInfo->streamDescriptors_ = pipeInfoInput->streamDescriptors_;
421             pipeInfo->streamDescMap_ = pipeInfoInput->streamDescMap_;
422             pipeManager_->UpdateAudioPipeInfo(pipeInfo);
423             AUDIO_INFO_LOG("Update PipeInfo %{public}u in load hearingAidCall.", pipeInfo->id_);
424             audioCapturerSession_.ReloadCaptureSessionSoftLink();
425         }
426     }
427 }
428 
CheckAndUpdateHearingAidCall(const DeviceType type)429 void AudioCoreService::CheckAndUpdateHearingAidCall(const DeviceType type)
430 {
431     bool isModemCallRunning = audioSceneManager_.IsInPhoneCallScene();
432     CheckCloseHearingAidCall(isModemCallRunning, type);
433     CheckOpenHearingAidCall(isModemCallRunning, type);
434 }
435 
HandleAudioCaptureState(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)436 void AudioCoreService::HandleAudioCaptureState(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
437 {
438     if (mode == AUDIO_MODE_RECORD &&
439         (streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_RELEASED ||
440          streamChangeInfo.audioCapturerChangeInfo.capturerState == CAPTURER_STOPPED)) {
441         auto sourceType = streamChangeInfo.audioCapturerChangeInfo.capturerInfo.sourceType;
442         auto sessionId = streamChangeInfo.audioCapturerChangeInfo.sessionId;
443         sleAudioDeviceManager_.UpdateSleStreamTypeCount(pipeManager_->GetStreamDescById(sessionId));
444         if (Util::IsScoSupportSource(sourceType)) {
445             Bluetooth::AudioHfpManager::HandleScoWithRecongnition(false);
446             AudioServerProxy::GetInstance().SetDmDeviceTypeProxy(0, DEVICE_TYPE_NEARLINK_IN);
447         } else {
448             AUDIO_INFO_LOG("close capture app, try to disconnect sco");
449             bool isRecord = streamCollector_.HasRunningNormalCapturerStream(DEVICE_TYPE_BLUETOOTH_SCO);
450             Bluetooth::AudioHfpManager::UpdateAudioScene(audioSceneManager_.GetAudioScene(true), isRecord);
451         }
452         audioMicrophoneDescriptor_.RemoveAudioCapturerMicrophoneDescriptorBySessionID(sessionId);
453     }
454 }
455 
UpdateDefaultOutputDeviceWhenStopping(int32_t uid)456 void AudioCoreService::UpdateDefaultOutputDeviceWhenStopping(int32_t uid)
457 {
458     std::vector<uint32_t> sessionIDSet = streamCollector_.GetAllRendererSessionIDForUID(uid);
459     for (const auto &sessionID : sessionIDSet) {
460         audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(sessionID);
461         audioDeviceManager_.RemoveSelectedDefaultOutputDevice(sessionID);
462 	if (isRingDualToneOnPrimarySpeaker_ && (streamCollector_.GetStreamType(sessionID) == STREAM_RING ||
463             streamCollector_.GetStreamType(sessionID) == STREAM_ALARM)) {
464             AUDIO_INFO_LOG("disable primary speaker dual tone when ringer renderer died");
465             isRingDualToneOnPrimarySpeaker_ = false;
466             for (std::pair<AudioStreamType, StreamUsage> stream : streamsWhenRingDualOnPrimarySpeaker_) {
467                 audioPolicyManager_.SetInnerStreamMute(stream.first, false, stream.second);
468             }
469             streamsWhenRingDualOnPrimarySpeaker_.clear();
470             audioPolicyManager_.SetInnerStreamMute(STREAM_MUSIC, false, STREAM_USAGE_MUSIC);
471         }
472     }
473 }
474 
UpdateInputDeviceWhenStopping(int32_t uid)475 void AudioCoreService::UpdateInputDeviceWhenStopping(int32_t uid)
476 {
477     std::vector<uint32_t> sessionIDSet = streamCollector_.GetAllCapturerSessionIDForUID(uid);
478     for (const auto &sessionID : sessionIDSet) {
479         audioDeviceManager_.RemoveSelectedInputDevice(sessionID);
480     }
481     FetchInputDeviceAndRoute("UpdateInputDeviceWhenStopping");
482 }
483 
BluetoothDeviceFetchOutputHandle(shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason,std::string encryptMacAddr)484 int32_t AudioCoreService::BluetoothDeviceFetchOutputHandle(shared_ptr<AudioStreamDescriptor> &streamDesc,
485     const AudioStreamDeviceChangeReasonExt reason, std::string encryptMacAddr)
486 {
487     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, BLUETOOTH_FETCH_RESULT_ERROR, "Stream desc is nullptr");
488     std::shared_ptr<AudioDeviceDescriptor> desc = streamDesc->newDeviceDescs_.front();
489     CHECK_AND_RETURN_RET_LOG(desc != nullptr, BLUETOOTH_FETCH_RESULT_CONTINUE, "Device desc is nullptr");
490 
491     if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
492         int32_t ret = ActivateA2dpDeviceWhenDescEnabled(desc, reason);
493         if (ret != SUCCESS) {
494             AUDIO_ERR_LOG("Activate a2dp [%{public}s] failed", encryptMacAddr.c_str());
495             return BLUETOOTH_FETCH_RESULT_ERROR;
496         }
497     } else if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
498         int32_t ret = HandleScoOutputDeviceFetched(streamDesc, reason);
499         if (ret != SUCCESS) {
500             AUDIO_ERR_LOG("sco [%{public}s] is not connected yet", encryptMacAddr.c_str());
501             return BLUETOOTH_FETCH_RESULT_ERROR;
502         }
503     }
504     return BLUETOOTH_FETCH_RESULT_DEFAULT;
505 }
506 
ActivateA2dpDeviceWhenDescEnabled(shared_ptr<AudioDeviceDescriptor> desc,const AudioStreamDeviceChangeReasonExt reason)507 int32_t AudioCoreService::ActivateA2dpDeviceWhenDescEnabled(shared_ptr<AudioDeviceDescriptor> desc,
508     const AudioStreamDeviceChangeReasonExt reason)
509 {
510     CHECK_AND_RETURN_RET_LOG(desc != nullptr, ERR_NULL_POINTER, "invalid deviceDesc");
511     AUDIO_INFO_LOG("Desc isEnabled %{public}d", desc->isEnable_);
512     if (desc->isEnable_) {
513         return ActivateA2dpDevice(desc, reason);
514     }
515     return SUCCESS;
516 }
517 
518 
ActivateA2dpDevice(std::shared_ptr<AudioDeviceDescriptor> desc,const AudioStreamDeviceChangeReasonExt reason)519 int32_t AudioCoreService::ActivateA2dpDevice(std::shared_ptr<AudioDeviceDescriptor> desc,
520     const AudioStreamDeviceChangeReasonExt reason)
521 {
522     Trace trace("AudioCoreService::ActiveA2dpDevice");
523     int32_t ret = SwitchActiveA2dpDevice(desc);
524     AUDIO_INFO_LOG("ret : %{public}d", ret);
525     // In plan: re-try when failed
526     return ret;
527 }
528 
SwitchActiveA2dpDevice(std::shared_ptr<AudioDeviceDescriptor> deviceDescriptor)529 int32_t AudioCoreService::SwitchActiveA2dpDevice(std::shared_ptr<AudioDeviceDescriptor> deviceDescriptor)
530 {
531     CHECK_AND_RETURN_RET_LOG(deviceDescriptor != nullptr &&
532         audioA2dpDevice_.CheckA2dpDeviceExist(deviceDescriptor->macAddress_),
533         ERR_INVALID_PARAM, "Target A2DP device doesn't exist.");
534     int32_t result = ERROR;
535 #ifdef BLUETOOTH_ENABLE
536     std::string lastActiveA2dpDevice = audioActiveDevice_.GetActiveBtDeviceMac();
537     audioActiveDevice_.SetActiveBtDeviceMac(deviceDescriptor->macAddress_);
538     AudioDeviceDescriptor lastDevice = audioPolicyManager_.GetActiveDeviceDescriptor();
539     deviceDescriptor->deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
540 
541     if (Bluetooth::AudioA2dpManager::GetActiveA2dpDevice() == deviceDescriptor->macAddress_ &&
542         audioIOHandleMap_.CheckIOHandleExist(BLUETOOTH_SPEAKER)) {
543         AUDIO_WARNING_LOG("A2dp device [%{public}s] [%{public}s] is already active",
544             GetEncryptAddr(deviceDescriptor->macAddress_).c_str(), deviceDescriptor->deviceName_.c_str());
545         return SUCCESS;
546     }
547 
548     result = Bluetooth::AudioA2dpManager::SetActiveA2dpDevice(deviceDescriptor->macAddress_);
549     if (result != SUCCESS) {
550         audioActiveDevice_.SetActiveBtDeviceMac(lastActiveA2dpDevice);
551         AUDIO_ERR_LOG("Active [%{public}s] failed, using original [%{public}s] device",
552             GetEncryptAddr(audioActiveDevice_.GetActiveBtDeviceMac()).c_str(),
553             GetEncryptAddr(lastActiveA2dpDevice).c_str());
554         return result;
555     }
556 
557     AudioStreamInfo audioStreamInfo = {};
558     audioActiveDevice_.GetActiveA2dpDeviceStreamInfo(DEVICE_TYPE_BLUETOOTH_A2DP, audioStreamInfo);
559     std::string networkId = audioActiveDevice_.GetCurrentOutputDeviceNetworkId();
560     std::string sinkName = AudioPolicyUtils::GetInstance().GetSinkPortName(
561         audioActiveDevice_.GetCurrentOutputDeviceType());
562     result = LoadA2dpModule(DEVICE_TYPE_BLUETOOTH_A2DP, audioStreamInfo, networkId, sinkName, SOURCE_TYPE_INVALID);
563     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "LoadA2dpModule failed %{public}d", result);
564 #endif
565     return result;
566 }
567 
LoadA2dpModule(DeviceType deviceType,const AudioStreamInfo & audioStreamInfo,std::string networkId,std::string sinkName,SourceType sourceType)568 int32_t AudioCoreService::LoadA2dpModule(DeviceType deviceType, const AudioStreamInfo &audioStreamInfo,
569     std::string networkId, std::string sinkName, SourceType sourceType)
570 {
571     std::list<AudioModuleInfo> moduleInfoList;
572     bool ret = policyConfigMananger_.GetModuleListByType(ClassType::TYPE_A2DP, moduleInfoList);
573     CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED, "A2dp module is not exist in the configuration file");
574 
575     // not load bt_a2dp_fast and bt_hdap, maybe need fix
576     int32_t loadRet = AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_BLUETOOTH, "bt_a2dp");
577     if (loadRet) {
578         AUDIO_ERR_LOG("load adapter failed");
579     }
580     for (auto &moduleInfo : moduleInfoList) {
581         DeviceRole configRole = moduleInfo.role == "source" ? INPUT_DEVICE : OUTPUT_DEVICE;
582         DeviceRole deviceRole = deviceType == DEVICE_TYPE_BLUETOOTH_A2DP ? OUTPUT_DEVICE : INPUT_DEVICE;
583         AUDIO_INFO_LOG("Load a2dp module [%{public}s], role[%{public}d], config role[%{public}d]",
584             moduleInfo.name.c_str(), deviceRole, configRole);
585         if (configRole != deviceRole) {continue;}
586         if (audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name) == false) {
587             AUDIO_INFO_LOG("A2dp device connects for the first time");
588             // a2dp device connects for the first time
589             GetA2dpModuleInfo(moduleInfo, audioStreamInfo, sourceType);
590             uint32_t paIndex = 0;
591             AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex);
592             CHECK_AND_RETURN_RET_LOG(ioHandle != HDI_INVALID_ID,
593                 ERR_INVALID_HANDLE, "OpenAudioPort failed ioHandle[%{public}u]", ioHandle);
594             CHECK_AND_RETURN_RET_LOG(paIndex != OPEN_PORT_FAILURE,
595                 ERR_OPERATION_FAILED, "OpenAudioPort failed paId[%{public}u]", paIndex);
596             audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle);
597 
598             std::shared_ptr<AudioPipeInfo> pipeInfo = std::make_shared<AudioPipeInfo>();
599             pipeInfo->id_ = ioHandle;
600             pipeInfo->paIndex_ = paIndex;
601             if (moduleInfo.role == "sink") {
602                 pipeInfo->name_ = "a2dp_output";
603                 pipeInfo->pipeRole_ = PIPE_ROLE_OUTPUT;
604                 pipeInfo->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL;
605             } else {
606                 pipeInfo->name_ = "a2dp_input";
607                 pipeInfo->pipeRole_ = PIPE_ROLE_INPUT;
608                 pipeInfo->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL;
609             }
610             pipeInfo->adapterName_ = "a2dp";
611             pipeInfo->moduleInfo_ = moduleInfo;
612             pipeInfo->pipeAction_ = PIPE_ACTION_DEFAULT;
613             pipeInfo->InitAudioStreamInfo();
614             pipeManager_->AddAudioPipeInfo(pipeInfo);
615             AUDIO_INFO_LOG("Add PipeInfo %{public}u in load a2dp.", pipeInfo->id_);
616         } else {
617             // At least one a2dp device is already connected. A new a2dp device is connecting.
618             // Need to reload a2dp module when switching to a2dp device.
619             int32_t result = ReloadA2dpAudioPort(moduleInfo, deviceType, audioStreamInfo, networkId, sinkName,
620                 sourceType);
621             CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "ReloadA2dpAudioPort failed %{public}d", result);
622         }
623     }
624 
625     return SUCCESS;
626 }
627 
ReloadA2dpAudioPort(AudioModuleInfo & moduleInfo,DeviceType deviceType,const AudioStreamInfo & audioStreamInfo,std::string networkId,std::string sinkName,SourceType sourceType)628 int32_t AudioCoreService::ReloadA2dpAudioPort(AudioModuleInfo &moduleInfo, DeviceType deviceType,
629     const AudioStreamInfo &audioStreamInfo, std::string networkId, std::string sinkName,
630     SourceType sourceType)
631 {
632     AUDIO_INFO_LOG("Switch device from a2dp to another a2dp, reload a2dp module");
633     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
634         audioIOHandleMap_.MuteDefaultSinkPort(networkId, sinkName);
635     }
636 
637     // Firstly, unload the existing a2dp sink or source.
638     std::string portName = BLUETOOTH_SPEAKER;
639     if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP_IN) {
640         portName = BLUETOOTH_MIC;
641     }
642     AudioIOHandle activateDeviceIOHandle;
643     audioIOHandleMap_.GetModuleIdByKey(portName, activateDeviceIOHandle);
644     uint32_t curPaIndex = pipeManager_->GetPaIndexByIoHandle(activateDeviceIOHandle);
645     std::vector<std::shared_ptr<AudioStreamDescriptor>> streamDescs =
646         pipeManager_->GetStreamDescsByIoHandle(activateDeviceIOHandle);
647     AUDIO_INFO_LOG("IoHandleId: %{public}u, paIndex: %{public}u, stream num: %{public}zu",
648         activateDeviceIOHandle, curPaIndex, streamDescs.size());
649     int32_t engineFlag = GetEngineFlag();
650     if (engineFlag != 1) {
651         int32_t result = audioPolicyManager_.CloseAudioPort(activateDeviceIOHandle, curPaIndex);
652         CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "CloseAudioPort failed %{public}d", result);
653     }
654     pipeManager_->RemoveAudioPipeInfo(activateDeviceIOHandle);
655 
656     // Load a2dp sink or source module again with the configuration of active a2dp device.
657     GetA2dpModuleInfo(moduleInfo, audioStreamInfo, sourceType);
658     uint32_t paIndex = 0;
659     AudioIOHandle ioHandle = ReloadOrOpenAudioPort(engineFlag, moduleInfo, paIndex);
660     audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle);
661 
662     std::shared_ptr<AudioPipeInfo> pipeInfo = std::make_shared<AudioPipeInfo>();
663     pipeInfo->id_ = ioHandle;
664     pipeInfo->paIndex_ = paIndex;
665     if (moduleInfo.role == "sink") {
666         pipeInfo->name_ = "a2dp_output";
667         pipeInfo->pipeRole_ = PIPE_ROLE_OUTPUT;
668         pipeInfo->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL;
669     } else {
670         pipeInfo->name_ = "a2dp_input";
671         pipeInfo->pipeRole_ = PIPE_ROLE_INPUT;
672         pipeInfo->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL;
673     }
674     pipeInfo->adapterName_ = "a2dp";
675     pipeInfo->moduleInfo_ = moduleInfo;
676     pipeInfo->pipeAction_ = PIPE_ACTION_DEFAULT;
677     pipeInfo->InitAudioStreamInfo();
678     pipeInfo->streamDescriptors_.insert(pipeInfo->streamDescriptors_.end(), streamDescs.begin(), streamDescs.end());
679     pipeManager_->AddAudioPipeInfo(pipeInfo);
680     AUDIO_INFO_LOG("Close paIndex: %{public}u, open paIndex: %{public}u", curPaIndex, paIndex);
681     return SUCCESS;
682 }
683 
ReloadOrOpenAudioPort(int32_t engineFlag,AudioModuleInfo & moduleInfo,uint32_t & paIndex)684 AudioIOHandle AudioCoreService::ReloadOrOpenAudioPort(int32_t engineFlag, AudioModuleInfo &moduleInfo,
685     uint32_t &paIndex)
686 {
687     AudioIOHandle ioHandle;
688     if (engineFlag == 1) {
689         ioHandle = audioPolicyManager_.ReloadAudioPort(moduleInfo, paIndex);
690         CHECK_AND_RETURN_RET_LOG(ioHandle != HDI_INVALID_ID, ERR_INVALID_HANDLE,
691             "ReloadAudioPort failed ioHandle[%{public}u]", ioHandle);
692         CHECK_AND_RETURN_RET_LOG(paIndex != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
693             "ReloadAudioPort failed paId[%{public}u]", paIndex);
694     } else {
695         ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex);
696         CHECK_AND_RETURN_RET_LOG(ioHandle != HDI_INVALID_ID, ERR_INVALID_HANDLE,
697             "OpenAudioPort failed ioHandle[%{public}u]", ioHandle);
698         CHECK_AND_RETURN_RET_LOG(paIndex != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
699             "OpenAudioPort failed paId[%{public}u]", paIndex);
700     }
701     return ioHandle;
702 }
703 
GetA2dpModuleInfo(AudioModuleInfo & moduleInfo,const AudioStreamInfo & audioStreamInfo,SourceType sourceType)704 void AudioCoreService::GetA2dpModuleInfo(AudioModuleInfo &moduleInfo, const AudioStreamInfo& audioStreamInfo,
705     SourceType sourceType)
706 {
707     uint32_t bufferSize = audioStreamInfo.samplingRate *
708         AudioPolicyUtils::GetInstance().PcmFormatToBytes(audioStreamInfo.format) *
709         audioStreamInfo.channels / BT_BUFFER_ADJUSTMENT_FACTOR;
710     AUDIO_INFO_LOG("a2dp rate: %{public}d, format: %{public}d, channel: %{public}d",
711         audioStreamInfo.samplingRate, audioStreamInfo.format, audioStreamInfo.channels);
712     moduleInfo.channels = to_string(audioStreamInfo.channels);
713     moduleInfo.rate = to_string(audioStreamInfo.samplingRate);
714     moduleInfo.format = AudioPolicyUtils::GetInstance().ConvertToHDIAudioFormat(audioStreamInfo.format);
715     moduleInfo.bufferSize = to_string(bufferSize);
716     if (moduleInfo.role != "source") {
717         moduleInfo.renderInIdleState = "1";
718         moduleInfo.sinkLatency = "0";
719     }
720 }
721 
LoadSplitModule(const std::string & splitArgs,const std::string & networkId)722 int32_t AudioCoreService::LoadSplitModule(const std::string &splitArgs, const std::string &networkId)
723 {
724     AUDIO_INFO_LOG("[ADeviceEvent] Start split args: %{public}s", splitArgs.c_str());
725     if (splitArgs.empty() || networkId.empty()) {
726         std::string anonymousNetworkId = networkId.empty() ? "" : networkId.substr(0, 2) + "***";
727         AUDIO_ERR_LOG("invalid param, splitArgs:'%{public}s', networkId:'%{public}s'",
728             splitArgs.c_str(), anonymousNetworkId.c_str());
729         return ERR_INVALID_PARAM;
730     }
731     std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, OUTPUT_DEVICE);
732     std::string currentActivePort = REMOTE_CLASS;
733     audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
734     AudioIOHandle oldModuleId;
735     audioIOHandleMap_.GetModuleIdByKey(moduleName, oldModuleId);
736     CHECK_AND_RETURN_RET_LOG(pipeManager_ != nullptr, ERR_NULL_POINTER, "pipeManager_ is nullptr");
737     std::vector<std::shared_ptr<AudioStreamDescriptor>> streamDescriptors =
738         pipeManager_->GetStreamDescsByIoHandle(oldModuleId);
739     audioIOHandleMap_.ClosePortAndEraseIOHandle(moduleName);
740 
741     AudioModuleInfo moudleInfo = AudioPolicyUtils::GetInstance().ConstructRemoteAudioModuleInfo(networkId,
742         OUTPUT_DEVICE, DEVICE_TYPE_SPEAKER);
743     moudleInfo.lib = "libmodule-split-stream-sink.z.so";
744     moudleInfo.extra = splitArgs;
745     moudleInfo.needEmptyChunk = true;
746 
747     int32_t openRet = audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleName, moudleInfo);
748     if (openRet != 0) {
749         AUDIO_ERR_LOG("open fail, OpenPortAndInsertIOHandle ret: %{public}d", openRet);
750     }
751     AudioIOHandle newModuleId;
752     audioIOHandleMap_.GetModuleIdByKey(moduleName, newModuleId);
753     pipeManager_->UpdateOutputStreamDescsByIoHandle(newModuleId, streamDescriptors);
754     AudioServerProxy::GetInstance().NotifyDeviceInfoProxy(networkId, true);
755     FetchOutputDeviceAndRoute("LoadSplitModule");
756     AUDIO_INFO_LOG("fetch device after split stream and open port.");
757     return openRet;
758 }
759 
IsSameDevice(shared_ptr<AudioDeviceDescriptor> & desc,const AudioDeviceDescriptor & deviceInfo)760 bool AudioCoreService::IsSameDevice(shared_ptr<AudioDeviceDescriptor> &desc, const AudioDeviceDescriptor &deviceInfo)
761 {
762     CHECK_AND_RETURN_RET_LOG(desc != nullptr, ERR_NULL_POINTER, "invalid deviceDesc");
763     if (desc->networkId_ == deviceInfo.networkId_ && desc->deviceType_ == deviceInfo.deviceType_ &&
764         desc->macAddress_ == deviceInfo.macAddress_ && desc->connectState_ == deviceInfo.connectState_) {
765         if (deviceInfo.IsAudioDeviceDescriptor()) {
766             return true;
767         }
768         BluetoothOffloadState state = audioA2dpOffloadFlag_.GetA2dpOffloadFlag();
769         if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP &&
770             // switch to A2dp
771             ((deviceInfo.a2dpOffloadFlag_ == A2DP_OFFLOAD && state != A2DP_OFFLOAD) ||
772             // switch to A2dp offload
773             (deviceInfo.a2dpOffloadFlag_ != A2DP_OFFLOAD && state == A2DP_OFFLOAD))) {
774             return false;
775         }
776         if (IsUsb(desc->deviceType_)) {
777             return desc->deviceRole_ == deviceInfo.deviceRole_;
778         }
779         return true;
780     } else {
781         return false;
782     }
783 }
784 
FetchDeviceAndRoute(std::string caller,const AudioStreamDeviceChangeReasonExt reason)785 int32_t AudioCoreService::FetchDeviceAndRoute(std::string caller, const AudioStreamDeviceChangeReasonExt reason)
786 {
787     int32_t ret = FetchOutputDeviceAndRoute(caller + "FetchDeviceAndRoute", reason);
788     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fetch output device failed");
789     return FetchInputDeviceAndRoute(caller + "FetchDeviceAndRoute");
790 }
791 
FetchRendererPipeAndExecute(std::shared_ptr<AudioStreamDescriptor> streamDesc,uint32_t & sessionId,uint32_t & audioFlag,const AudioStreamDeviceChangeReasonExt reason)792 int32_t AudioCoreService::FetchRendererPipeAndExecute(std::shared_ptr<AudioStreamDescriptor> streamDesc,
793     uint32_t &sessionId, uint32_t &audioFlag, const AudioStreamDeviceChangeReasonExt reason)
794 {
795     AUDIO_INFO_LOG("[PipeFetchStart] for stream %{public}d", sessionId);
796     std::vector<std::shared_ptr<AudioPipeInfo>> pipeInfos = audioPipeSelector_->FetchPipeAndExecute(streamDesc);
797 
798     uint32_t sinkId = HDI_INVALID_ID;
799     for (auto &pipeInfo : pipeInfos) {
800         CHECK_AND_CONTINUE_LOG(pipeInfo != nullptr, "pipeInfo is nullptr");
801         AUDIO_INFO_LOG("[PipeExecInfo] Scan Pipe adapter: %{public}s, name: %{public}s, action: %{public}d",
802             pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->name_.c_str(), pipeInfo->pipeAction_);
803         UpdateOffloadState(pipeInfo);
804         if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) {
805             ProcessOutputPipeUpdate(pipeInfo, audioFlag, reason);
806         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) { // new
807             ProcessOutputPipeNew(pipeInfo, audioFlag, reason);
808         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) { // DEFAULT
809             // Do nothing
810         }
811     }
812     RemoveUnusedPipe();
813     return SUCCESS;
814 }
815 
ProcessOutputPipeNew(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & flag,const AudioStreamDeviceChangeReasonExt reason)816 void AudioCoreService::ProcessOutputPipeNew(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &flag,
817     const AudioStreamDeviceChangeReasonExt reason)
818 {
819     uint32_t paIndex = 0;
820     uint32_t id = OpenNewAudioPortAndRoute(pipeInfo, paIndex);
821     CHECK_AND_RETURN_LOG(id != HDI_INVALID_ID, "Invalid id: %{public}u", id);
822     CHECK_AND_RETURN_LOG(paIndex != OPEN_PORT_FAILURE, "Invalid paIndex: %{public}u", paIndex);
823     pipeInfo->id_ = id;
824     pipeInfo->paIndex_ = paIndex;
825 
826     for (auto &desc : pipeInfo->streamDescriptors_) {
827         CHECK_AND_CONTINUE_LOG(desc != nullptr, "desc is nullptr");
828         AUDIO_INFO_LOG("[StreamExecInfo] Stream: %{public}u, action: %{public}d, belong to %{public}s",
829             desc->sessionId_, desc->streamAction_, pipeInfo->name_.c_str());
830         switch (desc->streamAction_) {
831             case AUDIO_STREAM_ACTION_NEW:
832                 flag = desc->routeFlag_;
833                 break;
834             case AUDIO_STREAM_ACTION_MOVE:
835                 if (desc->streamStatus_ != STREAM_STATUS_STARTED) {
836                     MoveStreamSink(desc, pipeInfo, reason);
837                 } else {
838                     MoveToNewOutputDevice(desc, pipeInfo, reason);
839                 }
840                 break;
841             case AUDIO_STREAM_ACTION_RECREATE:
842                 TriggerRecreateRendererStreamCallback(desc, reason);
843                 break;
844             default:
845                 break;
846         }
847     }
848     pipeManager_->AddAudioPipeInfo(pipeInfo);
849 }
850 
ProcessOutputPipeUpdate(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & flag,const AudioStreamDeviceChangeReasonExt reason)851 void AudioCoreService::ProcessOutputPipeUpdate(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &flag,
852     const AudioStreamDeviceChangeReasonExt reason)
853 {
854     for (auto &desc : pipeInfo->streamDescriptors_) {
855         CHECK_AND_CONTINUE_LOG(desc != nullptr, "desc is nullptr");
856         AUDIO_INFO_LOG("[StreamExecInfo] Stream: %{public}u, action: %{public}d, belong to %{public}s",
857             desc->sessionId_, desc->streamAction_, pipeInfo->name_.c_str());
858         switch (desc->streamAction_) {
859             case AUDIO_STREAM_ACTION_NEW:
860                 flag = desc->routeFlag_;
861                 break;
862             case AUDIO_STREAM_ACTION_DEFAULT:
863             case AUDIO_STREAM_ACTION_MOVE:
864                 if (desc->streamStatus_ != STREAM_STATUS_STARTED) {
865                     MoveStreamSink(desc, pipeInfo, reason);
866                 } else {
867                     MoveToNewOutputDevice(desc, pipeInfo, reason);
868                 }
869                 break;
870             case AUDIO_STREAM_ACTION_RECREATE:
871                 TriggerRecreateRendererStreamCallback(desc, reason);
872                 break;
873             default:
874                 break;
875         }
876     }
877     pipeManager_->UpdateAudioPipeInfo(pipeInfo);
878 }
879 
FetchCapturerPipeAndExecute(std::shared_ptr<AudioStreamDescriptor> streamDesc,uint32_t & audioFlag,uint32_t & sessionId)880 int32_t AudioCoreService::FetchCapturerPipeAndExecute(std::shared_ptr<AudioStreamDescriptor> streamDesc,
881     uint32_t &audioFlag, uint32_t &sessionId)
882 {
883     if (sessionId == 0) {
884         streamDesc->sessionId_ = GenerateSessionId();
885         sessionId = streamDesc->sessionId_;
886         AUDIO_INFO_LOG("Generate sessionId: %{public}u for stream", sessionId);
887     }
888 
889     if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE) {
890         AUDIO_INFO_LOG("[PipeFetchInfo] playbackcapture, no need fetch pipe");
891         audioFlag = AUDIO_INPUT_FLAG_NORMAL;
892         return SUCCESS;
893     }
894 
895     AUDIO_INFO_LOG("[PipeFetchStart] for stream %{public}d", sessionId);
896     std::vector<std::shared_ptr<AudioPipeInfo>> pipeInfos = audioPipeSelector_->FetchPipeAndExecute(streamDesc);
897 
898     for (auto &pipeInfo : pipeInfos) {
899         AUDIO_INFO_LOG("[PipeExecInfo] Scan Pipe adapter: %{public}s, name: %{public}s, action: %{public}d",
900             pipeInfo->moduleInfo_.adapterName.c_str(), pipeInfo->name_.c_str(), pipeInfo->pipeAction_);
901         if (pipeInfo->pipeAction_ == PIPE_ACTION_UPDATE) {
902             ProcessInputPipeUpdate(pipeInfo, audioFlag);
903         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_NEW) {
904             ProcessInputPipeNew(pipeInfo, audioFlag);
905         } else if (pipeInfo->pipeAction_ == PIPE_ACTION_DEFAULT) {
906             // Do nothing
907         }
908     }
909     RemoveUnusedPipe();
910     return SUCCESS;
911 }
912 
ProcessInputPipeNew(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & flag)913 void AudioCoreService::ProcessInputPipeNew(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &flag)
914 {
915     uint32_t paIndex = 0;
916     uint32_t sourceId = OpenNewAudioPortAndRoute(pipeInfo, paIndex);
917     CHECK_AND_RETURN_LOG(sourceId != HDI_INVALID_ID, "Invalid sourceId: %{public}u", sourceId);
918     CHECK_AND_RETURN_LOG(paIndex != OPEN_PORT_FAILURE, "Invalid paIndex: %{public}u", paIndex);
919     pipeInfo->id_ = sourceId;
920     pipeInfo->paIndex_ = paIndex;
921 
922     for (auto &desc : pipeInfo->streamDescriptors_) {
923         AUDIO_INFO_LOG("[StreamExecInfo] Stream: %{public}u, action: %{public}d, belong to %{public}s",
924             desc->sessionId_, desc->streamAction_, pipeInfo->name_.c_str());
925         switch (desc->streamAction_) {
926             case AUDIO_STREAM_ACTION_NEW:
927                 flag = desc->routeFlag_;
928                 break;
929             case AUDIO_STREAM_ACTION_DEFAULT:
930             case AUDIO_STREAM_ACTION_MOVE:
931                 if (desc->streamStatus_ != STREAM_STATUS_STARTED) {
932                     MoveStreamSource(desc);
933                 } else {
934                     MoveToNewInputDevice(desc);
935                 }
936                 break;
937             case AUDIO_STREAM_ACTION_RECREATE:
938                 TriggerRecreateCapturerStreamCallback(desc);
939                 break;
940             default:
941                 break;
942         }
943     }
944     pipeManager_->AddAudioPipeInfo(pipeInfo);
945 }
946 
ProcessInputPipeUpdate(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & flag)947 void AudioCoreService::ProcessInputPipeUpdate(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &flag)
948 {
949     for (auto desc : pipeInfo->streamDescriptors_) {
950         AUDIO_INFO_LOG("[StreamExecInfo] Stream: %{public}u, action: %{public}d, belong to %{public}s",
951             desc->sessionId_, desc->streamAction_, pipeInfo->name_.c_str());
952         switch (desc->streamAction_) {
953             case AUDIO_STREAM_ACTION_NEW:
954                 flag = desc->routeFlag_;
955                 break;
956             case AUDIO_STREAM_ACTION_DEFAULT:
957             case AUDIO_STREAM_ACTION_MOVE:
958                 if (desc->streamStatus_ != STREAM_STATUS_STARTED) {
959                     MoveStreamSource(desc);
960                 } else {
961                     MoveToNewInputDevice(desc);
962                 }
963                 break;
964             case AUDIO_STREAM_ACTION_RECREATE:
965                 TriggerRecreateCapturerStreamCallback(desc);
966                 break;
967             default:
968                 break;
969         }
970     }
971     pipeManager_->UpdateAudioPipeInfo(pipeInfo);
972 }
973 
RemoveUnusedPipe()974 void AudioCoreService::RemoveUnusedPipe()
975 {
976     std::vector<std::shared_ptr<AudioPipeInfo>> pipeInfos = pipeManager_->GetUnusedPipe();
977     for (auto pipeInfo : pipeInfos) {
978         CHECK_AND_CONTINUE_LOG(pipeInfo != nullptr, "pipeInfo is nullptr");
979         AUDIO_INFO_LOG("[PipeExecInfo] Remove and close Pipe %{public}s", pipeInfo->ToString().c_str());
980         if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_LOWPOWER) {
981             OffloadType type = pipeInfo->moduleInfo_.className == "remote_offload" ? REMOTE_OFFLOAD : LOCAL_OFFLOAD;
982             if (type == REMOTE_OFFLOAD) {
983                 CHECK_AND_CONTINUE(isOffloadOpened_[type].load());
984                 isOffloadOpened_[type].store(false);
985             } else {
986                 DelayReleaseOffloadPipe(pipeInfo->id_, pipeInfo->paIndex_, type);
987                 continue;
988             }
989         }
990         audioPolicyManager_.CloseAudioPort(pipeInfo->id_, pipeInfo->paIndex_);
991         pipeManager_->RemoveAudioPipeInfo(pipeInfo);
992         audioIOHandleMap_.DelIOHandleInfo(pipeInfo->moduleInfo_.name);
993     }
994 }
995 
RemoveUnusedRecordPipe()996 void AudioCoreService::RemoveUnusedRecordPipe()
997 {
998     std::vector<std::shared_ptr<AudioPipeInfo>> pipeInfos = pipeManager_->GetUnusedRecordPipe();
999     for (auto pipeInfo : pipeInfos) {
1000         CHECK_AND_CONTINUE_LOG(pipeInfo != nullptr, "pipeInfo is nullptr");
1001         AUDIO_INFO_LOG("[PipeExecInfo] Remove and close Pipe %{public}s", pipeInfo->ToString().c_str());
1002         audioPolicyManager_.CloseAudioPort(pipeInfo->id_, pipeInfo->paIndex_);
1003         pipeManager_->RemoveAudioPipeInfo(pipeInfo);
1004         audioIOHandleMap_.DelIOHandleInfo(pipeInfo->moduleInfo_.name);
1005     }
1006 }
1007 
GetAdapterNameBySessionId(uint32_t sessionId)1008 std::string AudioCoreService::GetAdapterNameBySessionId(uint32_t sessionId)
1009 {
1010     AUDIO_INFO_LOG("SessionId %{public}u", sessionId);
1011     std::string adapterName = pipeManager_->GetAdapterNameBySessionId(sessionId);
1012     return adapterName;
1013 }
1014 
GetProcessDeviceInfoBySessionId(uint32_t sessionId,AudioDeviceDescriptor & deviceInfo,AudioStreamInfo & streamInfo)1015 int32_t AudioCoreService::GetProcessDeviceInfoBySessionId(uint32_t sessionId,
1016     AudioDeviceDescriptor &deviceInfo, AudioStreamInfo &streamInfo)
1017 {
1018     AUDIO_INFO_LOG("SessionId %{public}u", sessionId);
1019     deviceInfo = AudioDeviceDescriptor(pipeManager_->GetProcessDeviceInfoBySessionId(sessionId, streamInfo));
1020     return SUCCESS;
1021 }
1022 
GenerateSessionId()1023 uint32_t AudioCoreService::GenerateSessionId()
1024 {
1025     return AudioStreamIdAllocator::GetAudioStreamIdAllocator().GenerateStreamId();
1026 }
1027 
AddSessionId(const uint32_t sessionId)1028 void AudioCoreService::AddSessionId(const uint32_t sessionId)
1029 {
1030     uid_t callingUid = static_cast<uid_t>(IPCSkeleton::GetCallingUid());
1031     AUDIO_INFO_LOG("AddSessionId: %{public}u, callingUid: %{public}u", sessionId, callingUid);
1032     if (skipAddSessionIdUidSet_.count(callingUid)) {
1033         // There is no audio stream for the session id of MCU. So no need to save it.
1034         return;
1035     }
1036     std::lock_guard<std::mutex> lock(sessionIdMutex_);
1037     sessionIdMap_[sessionId] = callingUid;
1038 }
1039 
DeleteSessionId(const uint32_t sessionId)1040 void AudioCoreService::DeleteSessionId(const uint32_t sessionId)
1041 {
1042     AUDIO_INFO_LOG("DeleteSessionId: %{public}u", sessionId);
1043     std::lock_guard<std::mutex> lock(sessionIdMutex_);
1044     if (sessionIdMap_.count(sessionId) == 0) {
1045         AUDIO_INFO_LOG("The sessionId has been deleted from sessionIdMap_!");
1046     } else {
1047         sessionIdMap_.erase(sessionId);
1048     }
1049 }
1050 
IsStreamBelongToUid(const uid_t uid,const uint32_t sessionId)1051 bool AudioCoreService::IsStreamBelongToUid(const uid_t uid, const uint32_t sessionId)
1052 {
1053     std::lock_guard<std::mutex> lock(sessionIdMutex_);
1054     if (sessionIdMap_.count(sessionId) == 0) {
1055         AUDIO_INFO_LOG("The sessionId %{public}u is invalid!", sessionId);
1056         return false;
1057     }
1058 
1059     if (sessionIdMap_[sessionId] != uid) {
1060         AUDIO_INFO_LOG("The sessionId %{public}u does not belong to uid %{public}u!", sessionId, uid);
1061         return false;
1062     }
1063 
1064     AUDIO_DEBUG_LOG("The sessionId %{public}u belongs to uid %{public}u!", sessionId, uid);
1065     return true;
1066 }
1067 
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo,DeviceRole role,bool hasPair)1068 void AudioCoreService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
1069     const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair)
1070 {
1071     // Pnp device status update
1072     audioDeviceStatus_.OnDeviceStatusUpdated(devType, isConnected, macAddress, deviceName, streamInfo, role, hasPair);
1073 }
1074 
OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,bool isConnected)1075 void AudioCoreService::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected)
1076 {
1077     // Bluetooth device status updated
1078     DeviceType devType = updatedDesc.deviceType_;
1079     string macAddress = updatedDesc.macAddress_;
1080     string deviceName = updatedDesc.deviceName_;
1081     bool isActualConnection = (updatedDesc.connectState_ != VIRTUAL_CONNECTED);
1082     AUDIO_INFO_LOG("Device connection is actual connection: %{public}d", isActualConnection);
1083 
1084     DeviceStreamInfo audioStreamInfo = updatedDesc.GetDeviceStreamInfo();
1085     std::set<AudioChannel> channels = audioStreamInfo.GetChannels();
1086     AudioStreamInfo streamInfo = audioStreamInfo.CheckParams() ?
1087         AudioStreamInfo(*audioStreamInfo.samplingRate.rbegin(), audioStreamInfo.encoding,
1088         audioStreamInfo.format, *channels.rbegin()) : AudioStreamInfo();
1089 #ifdef BLUETOOTH_ENABLE
1090     if (devType == DEVICE_TYPE_BLUETOOTH_A2DP && isActualConnection && isConnected) {
1091         int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpDeviceStreamInfo(macAddress, streamInfo);
1092         CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp device stream info failed!");
1093     }
1094     if (devType == DEVICE_TYPE_BLUETOOTH_A2DP_IN && isActualConnection && isConnected) {
1095         int32_t ret = Bluetooth::AudioA2dpManager::GetA2dpInDeviceStreamInfo(macAddress, streamInfo);
1096         CHECK_AND_RETURN_LOG(ret == SUCCESS, "Get a2dp input device stream info failed!");
1097     }
1098     if (isConnected && isActualConnection
1099         && devType == DEVICE_TYPE_BLUETOOTH_SCO
1100         && updatedDesc.deviceCategory_ != BT_UNWEAR_HEADPHONE
1101         && !audioDeviceManager_.GetScoState()) {
1102         Bluetooth::AudioHfpManager::SetActiveHfpDevice(macAddress);
1103     }
1104 #endif
1105     audioDeviceStatus_.OnDeviceStatusUpdated(updatedDesc, devType,
1106         macAddress, deviceName, isActualConnection, streamInfo, isConnected);
1107 }
1108 
OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)1109 void AudioCoreService::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop)
1110 {
1111     // Distributed devices status update
1112     audioDeviceStatus_.OnDeviceStatusUpdated(statusInfo, isStop);
1113 }
1114 
MoveStreamSink(std::shared_ptr<AudioStreamDescriptor> streamDesc,std::shared_ptr<AudioPipeInfo> pipeInfo,const AudioStreamDeviceChangeReasonExt reason)1115 void AudioCoreService::MoveStreamSink(std::shared_ptr<AudioStreamDescriptor> streamDesc,
1116     std::shared_ptr<AudioPipeInfo> pipeInfo, const AudioStreamDeviceChangeReasonExt reason)
1117 {
1118     Trace trace("AudioCoreService::MoveStreamSink");
1119     CHECK_AND_RETURN_LOG(streamDesc != nullptr && streamDesc->newDeviceDescs_.size() > 0 &&
1120         streamDesc->newDeviceDescs_.front() != nullptr, "Invalid streamDesc");
1121 
1122     DeviceType oldDeviceType = DEVICE_TYPE_NONE;
1123     std::shared_ptr<AudioDeviceDescriptor> newDeviceDesc = streamDesc->newDeviceDescs_.front();
1124     AUDIO_INFO_LOG("[StreamExecInfo] Move stream %{public}u to [%{public}d][%{public}s], reason %{public}d",
1125         streamDesc->sessionId_, newDeviceDesc->deviceType_, GetEncryptAddr(newDeviceDesc->macAddress_).c_str(),
1126         static_cast<int32_t>(reason));
1127 
1128     std::vector<SinkInput> sinkInputs;
1129     audioPolicyManager_.GetAllSinkInputs(sinkInputs);
1130     std::vector<SinkInput> targetSinkInputs = audioOffloadStream_.FilterSinkInputs(streamDesc->sessionId_, sinkInputs);
1131 
1132     auto ret = (newDeviceDesc->networkId_ == LOCAL_NETWORK_ID)
1133         ? MoveToLocalOutputDevice(targetSinkInputs, pipeInfo, newDeviceDesc)
1134         : MoveToRemoteOutputDevice(targetSinkInputs, pipeInfo, newDeviceDesc);
1135     CHECK_AND_RETURN_LOG(ret == SUCCESS, "Move sink input %{public}d to device %{public}d failed!",
1136         streamDesc->sessionId_, newDeviceDesc->deviceType_);
1137     streamCollector_.UpdateRendererDeviceInfo(newDeviceDesc);
1138 }
1139 
IsNewDevicePlaybackSupported(std::shared_ptr<AudioStreamDescriptor> streamDesc)1140 bool AudioCoreService::IsNewDevicePlaybackSupported(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1141 {
1142     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr && !streamDesc->newDeviceDescs_.empty(), false,
1143         "invalid streamDesc");
1144     std::shared_ptr<AudioDeviceDescriptor> newDeviceDesc = streamDesc->newDeviceDescs_.front();
1145     CHECK_AND_RETURN_RET_LOG(newDeviceDesc != nullptr, false, "invalid newDeviceDesc");
1146     if (streamDesc->streamInfo_.encoding == ENCODING_EAC3 && newDeviceDesc->deviceType_ != DEVICE_TYPE_HDMI &&
1147         newDeviceDesc->deviceType_ != DEVICE_TYPE_LINE_DIGITAL && audioPolicyServerHandler_) {
1148         audioPolicyServerHandler_->SendFormatUnsupportedErrorEvent(ERROR_UNSUPPORTED_FORMAT);
1149         return false;
1150     }
1151     return true;
1152 }
1153 
MoveToNewOutputDevice(std::shared_ptr<AudioStreamDescriptor> streamDesc,std::shared_ptr<AudioPipeInfo> pipeInfo,const AudioStreamDeviceChangeReasonExt reason)1154 void AudioCoreService::MoveToNewOutputDevice(std::shared_ptr<AudioStreamDescriptor> streamDesc,
1155     std::shared_ptr<AudioPipeInfo> pipeInfo, const AudioStreamDeviceChangeReasonExt reason)
1156 {
1157     Trace trace("AudioCoreService::MoveToNewOutputDevice");
1158 
1159     DeviceType oldDeviceType = DEVICE_TYPE_NONE;
1160     bool isNeedTriggerCallback = true;
1161     std::shared_ptr<AudioDeviceDescriptor> newDeviceDesc = streamDesc->newDeviceDescs_.front();
1162     std::string oldSinkName = "";
1163     if (streamDesc->oldDeviceDescs_.size() == 0) {
1164         AUDIO_INFO_LOG("[StreamExecInfo] Move stream %{public}u to [%{public}d][%{public}s], reason %{public}d",
1165             streamDesc->sessionId_, newDeviceDesc->deviceType_,
1166             GetEncryptAddr(newDeviceDesc->macAddress_).c_str(), static_cast<int32_t>(reason));
1167     } else {
1168         PrepareMoveAttrs(streamDesc, oldDeviceType, isNeedTriggerCallback, oldSinkName, reason);
1169     }
1170 
1171     std::vector<SinkInput> sinkInputs;
1172     audioPolicyManager_.GetAllSinkInputs(sinkInputs);
1173     std::vector<SinkInput> targetSinkInputs = audioOffloadStream_.FilterSinkInputs(streamDesc->sessionId_, sinkInputs);
1174 
1175     if (isNeedTriggerCallback && audioPolicyServerHandler_) {
1176         std::shared_ptr<AudioDeviceDescriptor> callbackDesc = std::make_shared<AudioDeviceDescriptor>(*newDeviceDesc);
1177         callbackDesc->descriptorType_ = AudioDeviceDescriptor::DEVICE_INFO;
1178         audioPolicyServerHandler_->SendRendererDeviceChangeEvent(streamDesc->callerPid_,
1179             streamDesc->sessionId_, callbackDesc, reason);
1180     }
1181 
1182     // Mute(MuteSinkPortForSwitchDevice) is not effective before new port opened (OpenNewAudioPortAndRoute),
1183     // But anco application need more time(1S) to STOP after receive 'KEYCODE_MEDIA_PAUSE' event,
1184     // So, once the audio stream switches from the old sinkport to the new sinkport before the application STOP,
1185     // there will be audio leakage. So try Mute again for anco.
1186     if (streamDesc->appInfo_.appUid == AUDIO_ID) {
1187         MuteSinkPortForSwitchDevice(streamDesc, reason);
1188     }
1189 
1190     SleepForSwitchDevice(streamDesc, reason);
1191 
1192     CHECK_AND_RETURN_LOG(IsNewDevicePlaybackSupported(streamDesc), "new device not support playback");
1193 
1194     auto ret = (newDeviceDesc->networkId_ == LOCAL_NETWORK_ID)
1195         ? MoveToLocalOutputDevice(targetSinkInputs, pipeInfo, newDeviceDesc)
1196         : MoveToRemoteOutputDevice(targetSinkInputs, pipeInfo, newDeviceDesc);
1197     if (ret != SUCCESS) {
1198         AUDIO_ERR_LOG("Move sink input %{public}d to device %{public}d failed!",
1199             streamDesc->sessionId_, newDeviceDesc->deviceType_);
1200         audioIOHandleMap_.NotifyUnmutePort();
1201         return;
1202     }
1203 
1204     sleAudioDeviceManager_.UpdateSleStreamTypeCount(streamDesc);
1205     if (policyConfigMananger_.GetUpdateRouteSupport()) {
1206         UpdateOutputRoute(streamDesc);
1207     }
1208 
1209     streamCollector_.UpdateRendererDeviceInfo(newDeviceDesc);
1210     ReConfigOffloadStatus(streamDesc->sessionId_, pipeInfo, oldSinkName);
1211     audioIOHandleMap_.NotifyUnmutePort();
1212 }
1213 
OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)1214 void AudioCoreService::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status)
1215 {
1216     CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
1217     audioDeviceStatus_.OnMicrophoneBlockedUpdate(devType, status);
1218 }
1219 
OnPnpDeviceStatusUpdated(AudioDeviceDescriptor & desc,bool isConnected)1220 void AudioCoreService::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected)
1221 {
1222     audioDeviceStatus_.OnPnpDeviceStatusUpdated(desc, isConnected);
1223 }
1224 
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)1225 void AudioCoreService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
1226     const std::string &deviceName, const AudioStreamInfo &streamInfo)
1227 {
1228     audioDeviceStatus_.OnDeviceConfigurationChanged(deviceType, macAddress, deviceName, streamInfo);
1229 }
1230 
OnServiceConnected(AudioServiceIndex serviceIndex)1231 int32_t AudioCoreService::OnServiceConnected(AudioServiceIndex serviceIndex)
1232 {
1233     return audioDeviceStatus_.OnServiceConnected(serviceIndex);
1234 }
1235 
OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)1236 void AudioCoreService::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress)
1237 {
1238     audioDeviceStatus_.OnForcedDeviceSelected(devType, macAddress);
1239 }
1240 
UpdateRemoteOffloadModuleName(std::shared_ptr<AudioPipeInfo> pipeInfo,std::string & moduleName)1241 void AudioCoreService::UpdateRemoteOffloadModuleName(std::shared_ptr<AudioPipeInfo> pipeInfo, std::string &moduleName)
1242 {
1243     CHECK_AND_RETURN(pipeInfo && pipeInfo->moduleInfo_.className == "remote_offload");
1244     moduleName = pipeInfo->moduleInfo_.name;
1245     AUDIO_INFO_LOG("remote offload, set module name %{public}s", moduleName.c_str());
1246 }
1247 
MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,std::shared_ptr<AudioPipeInfo> pipeInfo,std::shared_ptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1248 int32_t AudioCoreService::MoveToRemoteOutputDevice(std::vector<SinkInput> sinkInputIds,
1249     std::shared_ptr<AudioPipeInfo> pipeInfo,
1250     std::shared_ptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
1251 {
1252     AUDIO_INFO_LOG("Start for [%{public}zu] sink-inputs", sinkInputIds.size());
1253 
1254     std::string networkId = remoteDeviceDescriptor->networkId_;
1255     DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
1256     DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
1257 
1258     // check: networkid
1259     CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION,
1260         "failed: not a remote device.");
1261 
1262     uint32_t sinkId = -1; // invalid sink id, use sink name instead.
1263     std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, deviceRole);
1264     UpdateRemoteOffloadModuleName(pipeInfo, moduleName);
1265     AUDIO_ERR_LOG("moduleName %{public}s", moduleName.c_str());
1266 
1267     AudioIOHandle moduleId;
1268     if (audioIOHandleMap_.GetModuleIdByKey(moduleName, moduleId)) {
1269         (void)moduleId; // mIOHandle is module id, not equal to sink id.
1270     } else {
1271         AUDIO_ERR_LOG("no such device.");
1272         if (!isOpenRemoteDevice) {
1273             AUDIO_INFO_LOG("directly return");
1274             return ERR_INVALID_PARAM;
1275         } else {
1276             return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
1277         }
1278     }
1279 
1280     // start move.
1281     for (size_t i = 0; i < sinkInputIds.size(); i++) {
1282         int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, moduleName);
1283         CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "move [%{public}d] failed", sinkInputIds[i].streamId);
1284         audioRouteMap_.AddRouteMapInfo(sinkInputIds[i].uid, moduleName, sinkInputIds[i].pid);
1285     }
1286 
1287     if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
1288         AUDIO_WARNING_LOG("Not defult type[%{public}d] on device:[%{public}s]",
1289             deviceType, GetEncryptStr(networkId).c_str());
1290     }
1291     isCurrentRemoteRenderer_ = true;
1292     return SUCCESS;
1293 }
1294 
MoveStreamSource(std::shared_ptr<AudioStreamDescriptor> streamDesc)1295 void AudioCoreService::MoveStreamSource(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1296 {
1297     Trace trace("AudioCoreService::MoveStreamSource");
1298     std::vector<SourceOutput> targetSourceOutputs = FilterSourceOutputs(streamDesc->sessionId_);
1299 
1300     AUDIO_INFO_LOG("[StreamExecInfo] Move stream %{public}u to [%{public}d][%{public}s]",
1301         streamDesc->sessionId_, streamDesc->newDeviceDescs_.front()->deviceType_,
1302         GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_).c_str());
1303 
1304     // MoveSourceOuputByIndexName
1305     auto ret = (streamDesc->newDeviceDescs_.front()->networkId_ == LOCAL_NETWORK_ID)
1306         ? MoveToLocalInputDevice(targetSourceOutputs, streamDesc->newDeviceDescs_.front())
1307         : MoveToRemoteInputDevice(targetSourceOutputs, streamDesc->newDeviceDescs_.front());
1308     CHECK_AND_RETURN_LOG((ret == SUCCESS), "Move source output %{public}d to device %{public}d failed!",
1309         streamDesc->sessionId_, streamDesc->newDeviceDescs_.front()->deviceType_);
1310     streamCollector_.UpdateCapturerDeviceInfo(streamDesc->newDeviceDescs_.front());
1311 }
1312 
MoveToNewInputDevice(std::shared_ptr<AudioStreamDescriptor> streamDesc)1313 void AudioCoreService::MoveToNewInputDevice(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1314 {
1315     Trace trace("AudioCoreService::MoveToNewInputDevice");
1316     std::vector<SourceOutput> targetSourceOutputs = FilterSourceOutputs(streamDesc->sessionId_);
1317 
1318     if (streamDesc->oldDeviceDescs_.size() == 0) {
1319         AUDIO_INFO_LOG("[StreamExecInfo] Move stream %{public}u to [%{public}d][%{public}s]",
1320             streamDesc->sessionId_, streamDesc->newDeviceDescs_.front()->deviceType_,
1321             GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_).c_str());
1322     } else {
1323         AUDIO_INFO_LOG("[StreamExecInfo] Move stream %{public}u [%{public}d][%{public}s] to [%{public}d][%{public}s]",
1324             streamDesc->sessionId_, streamDesc->oldDeviceDescs_.front()->deviceType_,
1325             GetEncryptAddr(streamDesc->oldDeviceDescs_.front()->macAddress_).c_str(),
1326             streamDesc->newDeviceDescs_.front()->deviceType_,
1327             GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_).c_str());
1328     }
1329 
1330     // MoveSourceOuputByIndexName
1331     auto ret = (streamDesc->newDeviceDescs_.front()->networkId_ == LOCAL_NETWORK_ID)
1332         ? MoveToLocalInputDevice(targetSourceOutputs, streamDesc->newDeviceDescs_.front())
1333         : MoveToRemoteInputDevice(targetSourceOutputs, streamDesc->newDeviceDescs_.front());
1334     CHECK_AND_RETURN_LOG((ret == SUCCESS), "Move source output %{public}d to device %{public}d failed!",
1335         streamDesc->sessionId_, streamDesc->newDeviceDescs_.front()->deviceType_);
1336 
1337     sleAudioDeviceManager_.UpdateSleStreamTypeCount(streamDesc);
1338 
1339     if (policyConfigMananger_.GetUpdateRouteSupport() &&
1340         streamDesc->newDeviceDescs_.front()->networkId_ == LOCAL_NETWORK_ID) {
1341         audioActiveDevice_.UpdateActiveDeviceRoute(streamDesc->newDeviceDescs_.front()->deviceType_,
1342             DeviceFlag::INPUT_DEVICES_FLAG, streamDesc->newDeviceDescs_.front()->deviceName_,
1343             streamDesc->newDeviceDescs_.front()->networkId_);
1344     }
1345     streamCollector_.UpdateCapturerDeviceInfo(streamDesc->newDeviceDescs_.front());
1346 }
1347 
MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputs,std::shared_ptr<AudioDeviceDescriptor> localDeviceDescriptor)1348 int32_t AudioCoreService::MoveToLocalInputDevice(std::vector<SourceOutput> sourceOutputs,
1349     std::shared_ptr<AudioDeviceDescriptor> localDeviceDescriptor)
1350 {
1351     CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_, ERR_INVALID_OPERATION,
1352         "failed: not a local device.");
1353 
1354     uint32_t sourceId = -1; // invalid source id, use source name instead.
1355     std::string sourceName = AudioPolicyUtils::GetInstance().GetSourcePortName(localDeviceDescriptor->deviceType_);
1356     for (size_t i = 0; i < sourceOutputs.size(); i++) {
1357         int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId,
1358             sourceId, sourceName);
1359         CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
1360             "move [%{public}d] to local failed", sourceOutputs[i].paStreamId);
1361     }
1362 
1363     return SUCCESS;
1364 }
1365 
MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputs,std::shared_ptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1366 int32_t AudioCoreService::MoveToRemoteInputDevice(std::vector<SourceOutput> sourceOutputs,
1367     std::shared_ptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
1368 {
1369     AUDIO_INFO_LOG("Start");
1370 
1371     std::string networkId = remoteDeviceDescriptor->networkId_;
1372     DeviceRole deviceRole = remoteDeviceDescriptor->deviceRole_;
1373     DeviceType deviceType = remoteDeviceDescriptor->deviceType_;
1374 
1375     // check: networkid
1376     CHECK_AND_RETURN_RET_LOG(networkId != LOCAL_NETWORK_ID, ERR_INVALID_OPERATION,
1377         "failed: not a remote device.");
1378 
1379     uint32_t sourceId = -1; // invalid sink id, use sink name instead.
1380     std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, deviceRole);
1381 
1382     AudioIOHandle moduleId;
1383     if (audioIOHandleMap_.GetModuleIdByKey(moduleName, moduleId)) {
1384         (void)moduleId; // mIOHandle is module id, not equal to sink id.
1385     } else {
1386         AUDIO_ERR_LOG("no such device.");
1387         if (!isOpenRemoteDevice) {
1388             return ERR_INVALID_PARAM;
1389         } else {
1390             return OpenRemoteAudioDevice(networkId, deviceRole, deviceType, remoteDeviceDescriptor);
1391         }
1392     }
1393 
1394     // start move.
1395     for (size_t i = 0; i < sourceOutputs.size(); i++) {
1396         int32_t ret = audioPolicyManager_.MoveSourceOutputByIndexOrName(sourceOutputs[i].paStreamId,
1397             sourceId, moduleName);
1398         CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
1399             "move [%{public}d] failed", sourceOutputs[i].paStreamId);
1400     }
1401 
1402     if (deviceType != DeviceType::DEVICE_TYPE_DEFAULT) {
1403         AUDIO_DEBUG_LOG("Not defult type[%{public}d] on device:[%{public}s]",
1404             deviceType, GetEncryptStr(networkId).c_str());
1405     }
1406     return SUCCESS;
1407 }
1408 
OpenRemoteAudioDevice(std::string networkId,DeviceRole deviceRole,DeviceType deviceType,std::shared_ptr<AudioDeviceDescriptor> remoteDeviceDescriptor)1409 int32_t AudioCoreService::OpenRemoteAudioDevice(std::string networkId, DeviceRole deviceRole, DeviceType deviceType,
1410     std::shared_ptr<AudioDeviceDescriptor> remoteDeviceDescriptor)
1411 {
1412     AUDIO_INFO_LOG("[PipeExecInfo] open remote pipe device %{public}d", deviceType);
1413     // open the test device. We should open it when device is online.
1414     std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, deviceRole);
1415     AudioModuleInfo remoteDeviceInfo = AudioPolicyUtils::GetInstance().ConstructRemoteAudioModuleInfo(networkId,
1416         deviceRole, deviceType);
1417 
1418     auto ret = AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_REMOTE, networkId);
1419     if (ret) {
1420         AUDIO_ERR_LOG("load adapter fail");
1421     }
1422     audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleName, remoteDeviceInfo);
1423 
1424     // If device already in list, remove it else do not modify the list.
1425     audioConnectedDevice_.DelConnectedDevice(networkId, deviceType);
1426     AudioPolicyUtils::GetInstance().UpdateDisplayName(remoteDeviceDescriptor);
1427     audioConnectedDevice_.AddConnectedDevice(remoteDeviceDescriptor);
1428     audioMicrophoneDescriptor_.AddMicrophoneDescriptor(remoteDeviceDescriptor);
1429     return SUCCESS;
1430 }
1431 
PrintSourceOutput(SourceOutput sourceOutput)1432 inline std::string PrintSourceOutput(SourceOutput sourceOutput)
1433 {
1434     std::stringstream value;
1435     value << "streamId:[" << sourceOutput.streamId << "] ";
1436     value << "streamType:[" << sourceOutput.streamType << "] ";
1437     value << "uid:[" << sourceOutput.uid << "] ";
1438     value << "pid:[" << sourceOutput.pid << "] ";
1439     value << "statusMark:[" << sourceOutput.statusMark << "] ";
1440     value << "deviceSourceId:[" << sourceOutput.deviceSourceId << "] ";
1441     value << "startTime:[" << sourceOutput.startTime << "]";
1442     return value.str();
1443 }
1444 
FilterSourceOutputs(int32_t sessionId)1445 std::vector<SourceOutput> AudioCoreService::FilterSourceOutputs(int32_t sessionId)
1446 {
1447     std::vector<SourceOutput> targetSourceOutputs = {};
1448     std::vector<SourceOutput> sourceOutputs = GetSourceOutputs();
1449 
1450     for (size_t i = 0; i < sourceOutputs.size(); i++) {
1451         AUDIO_DEBUG_LOG("sourceOutput[%{public}zu]:%{public}s", i, PrintSourceOutput(sourceOutputs[i]).c_str());
1452         if (sessionId == sourceOutputs[i].streamId) {
1453             targetSourceOutputs.push_back(sourceOutputs[i]);
1454         }
1455     }
1456     return targetSourceOutputs;
1457 }
1458 
GetSourceOutputs()1459 std::vector<SourceOutput> AudioCoreService::GetSourceOutputs()
1460 {
1461     std::vector<SourceOutput> sourceOutputs;
1462     {
1463         std::unordered_map<std::string, AudioIOHandle> mapCopy = AudioIOHandleMap::GetInstance().GetCopy();
1464         if (std::any_of(mapCopy.cbegin(), mapCopy.cend(), [](const auto &pair) {
1465                 return std::find(SourceNames.cbegin(), SourceNames.cend(), pair.first) != SourceNames.cend();
1466             })) {
1467             sourceOutputs = audioPolicyManager_.GetAllSourceOutputs();
1468         }
1469     }
1470     return sourceOutputs;
1471 }
1472 
UpdateOutputRoute(std::shared_ptr<AudioStreamDescriptor> streamDesc)1473 void AudioCoreService::UpdateOutputRoute(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1474 {
1475     CHECK_AND_RETURN_LOG(streamDesc != nullptr, "streamDesc is nullptr");
1476     StreamUsage streamUsage = streamDesc->rendererInfo_.streamUsage;
1477     InternalDeviceType deviceType = streamDesc->newDeviceDescs_.front()->deviceType_;
1478     AUDIO_INFO_LOG("[PipeExecInfo] Update route streamUsage:%{public}d, devicetype:[%{public}s]",
1479         streamUsage, streamDesc->GetNewDevicesTypeString().c_str());
1480     // for collaboration, the route should be updated
1481     UpdateRouteForCollaboration(deviceType);
1482     if (Util::IsRingerOrAlarmerStreamUsage(streamUsage) && IsRingerOrAlarmerDualDevicesRange(deviceType) &&
1483         !VolumeUtils::IsPCVolumeEnable()) {
1484         if (!SelectRingerOrAlarmDevices(streamDesc)) {
1485             audioActiveDevice_.UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG,
1486                 streamDesc->newDeviceDescs_.front()->deviceName_, streamDesc->newDeviceDescs_.front()->networkId_);
1487         }
1488 
1489         AudioRingerMode ringerMode = audioPolicyManager_.GetRingerMode();
1490         if (ringerMode != RINGER_MODE_NORMAL &&
1491             IsRingerOrAlarmerDualDevicesRange(streamDesc->newDeviceDescs_.front()->getType()) &&
1492             streamDesc->newDeviceDescs_.front()->getType() != DEVICE_TYPE_SPEAKER) {
1493             audioPolicyManager_.SetInnerStreamMute(STREAM_RING, false, streamUsage);
1494             audioVolumeManager_.SetRingerModeMute(false);
1495             if (audioPolicyManager_.GetSystemVolumeLevel(STREAM_RING) <
1496                 audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE) {
1497                 audioPolicyManager_.SetDoubleRingVolumeDb(STREAM_RING,
1498                     audioPolicyManager_.GetMaxVolumeLevel(STREAM_RING) / VOLUME_LEVEL_DEFAULT_SIZE);
1499             }
1500         } else {
1501             audioVolumeManager_.SetRingerModeMute(true);
1502         }
1503         shouldUpdateDeviceDueToDualTone_ = true;
1504     } else {
1505         audioVolumeManager_.SetRingerModeMute(true);
1506         if (isRingDualToneOnPrimarySpeaker_ && streamUsage != STREAM_USAGE_VOICE_MODEM_COMMUNICATION) {
1507             std::vector<std::pair<InternalDeviceType, DeviceFlag>> activeDevices;
1508             activeDevices.push_back(make_pair(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG));
1509             activeDevices.push_back(make_pair(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG));
1510             audioActiveDevice_.UpdateActiveDevicesRoute(activeDevices);
1511             AUDIO_INFO_LOG("Update desc [%{public}d] with speaker on session [%{public}d]",
1512                 deviceType, streamDesc->sessionId_);
1513             AudioStreamType streamType = streamCollector_.GetStreamType(streamDesc->sessionId_);
1514             if (!AudioCoreServiceUtils::IsDualStreamWhenRingDual(streamType)) {
1515                 streamsWhenRingDualOnPrimarySpeaker_.push_back(make_pair(streamType, streamUsage));
1516                 audioPolicyManager_.SetInnerStreamMute(streamType, true, streamUsage);
1517             }
1518             shouldUpdateDeviceDueToDualTone_ = true;
1519         } else {
1520             audioActiveDevice_.UpdateActiveDeviceRoute(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG,
1521                 streamDesc->newDeviceDescs_.front()->deviceName_, streamDesc->newDeviceDescs_.front()->networkId_);
1522             shouldUpdateDeviceDueToDualTone_ = false;
1523         }
1524     }
1525 }
1526 
OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor & deviceDescriptor,const AudioStreamDeviceChangeReason reason)1527 void AudioCoreService::OnPreferredOutputDeviceUpdated(const AudioDeviceDescriptor& deviceDescriptor,
1528     const AudioStreamDeviceChangeReason reason)
1529 {
1530     AUDIO_INFO_LOG("In");
1531     Trace trace("AudioCoreService::OnPreferredOutputDeviceUpdated:" + std::to_string(deviceDescriptor.deviceType_));
1532 
1533     if (audioPolicyServerHandler_ != nullptr) {
1534         audioPolicyServerHandler_->SendPreferredOutputDeviceUpdated();
1535         audioPolicyServerHandler_->SendAudioSessionDeviceChange(reason);
1536     }
1537     if (deviceDescriptor.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) {
1538         spatialDeviceMap_.insert(make_pair(deviceDescriptor.macAddress_, deviceDescriptor.deviceType_));
1539     }
1540 
1541     if (deviceDescriptor.macAddress_ !=
1542         AudioSpatializationService::GetAudioSpatializationService().GetCurrentDeviceAddress()) {
1543         AudioServerProxy::GetInstance().UpdateEffectBtOffloadSupportedProxy(false);
1544     }
1545     AudioPolicyUtils::GetInstance().UpdateEffectDefaultSink(deviceDescriptor.deviceType_);
1546     AudioSpatializationService::GetAudioSpatializationService().UpdateCurrentDevice(deviceDescriptor.macAddress_);
1547     AudioCollaborativeService::GetAudioCollaborativeService().UpdateCurrentDevice(deviceDescriptor);
1548 }
1549 
OnPreferredInputDeviceUpdated(DeviceType deviceType,std::string networkId)1550 void AudioCoreService::OnPreferredInputDeviceUpdated(DeviceType deviceType, std::string networkId)
1551 {
1552     AUDIO_INFO_LOG("OnPreferredInputDeviceUpdated Start");
1553 
1554     if (audioPolicyServerHandler_ != nullptr) {
1555         audioPolicyServerHandler_->SendPreferredInputDeviceUpdated();
1556     }
1557 }
1558 
1559 
IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType & deviceType)1560 bool AudioCoreService::IsRingerOrAlarmerDualDevicesRange(const InternalDeviceType &deviceType)
1561 {
1562     switch (deviceType) {
1563         case DEVICE_TYPE_SPEAKER:
1564         case DEVICE_TYPE_WIRED_HEADSET:
1565         case DEVICE_TYPE_WIRED_HEADPHONES:
1566         case DEVICE_TYPE_BLUETOOTH_SCO:
1567         case DEVICE_TYPE_BLUETOOTH_A2DP:
1568         case DEVICE_TYPE_USB_HEADSET:
1569         case DEVICE_TYPE_USB_ARM_HEADSET:
1570         case DEVICE_TYPE_NEARLINK:
1571         case DEVICE_TYPE_HEARING_AID:
1572             return true;
1573         default:
1574             return false;
1575     }
1576 }
1577 
ClearRingMuteWhenCallStart(bool pre,bool after)1578 void AudioCoreService::ClearRingMuteWhenCallStart(bool pre, bool after)
1579 {
1580     CHECK_AND_RETURN_LOG(pre == true && after == false, "ringdual not cancel by call");
1581     AUDIO_INFO_LOG("disable primary speaker dual tone when call start and ring not over");
1582     for (std::pair<AudioStreamType, StreamUsage> stream : streamsWhenRingDualOnPrimarySpeaker_) {
1583         audioPolicyManager_.SetInnerStreamMute(stream.first, false, stream.second);
1584     }
1585     streamsWhenRingDualOnPrimarySpeaker_.clear();
1586     audioPolicyManager_.SetInnerStreamMute(STREAM_MUSIC, false, STREAM_USAGE_MUSIC);
1587 }
1588 
SelectRingerOrAlarmDevices(std::shared_ptr<AudioStreamDescriptor> streamDesc)1589 bool AudioCoreService::SelectRingerOrAlarmDevices(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1590 {
1591     CHECK_AND_RETURN_RET_LOG(streamDesc->newDeviceDescs_.size() > 0 &&
1592         streamDesc->newDeviceDescs_.size() <= AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT, false,
1593         "audio devices not in range for ringer or alarmer.");
1594     const int32_t sessionId = static_cast<int32_t>(streamDesc->sessionId_);
1595     const StreamUsage streamUsage = streamDesc->rendererInfo_.streamUsage;
1596     bool allDevicesInDualDevicesRange = true;
1597     std::vector<std::pair<InternalDeviceType, DeviceFlag>> activeDevices;
1598     for (size_t i = 0; i < streamDesc->newDeviceDescs_.size(); i++) {
1599         if (IsRingerOrAlarmerDualDevicesRange(streamDesc->newDeviceDescs_[i]->deviceType_)) {
1600             activeDevices.push_back(make_pair(streamDesc->newDeviceDescs_[i]->deviceType_,
1601             DeviceFlag::OUTPUT_DEVICES_FLAG));
1602             AUDIO_INFO_LOG("select ringer/alarm devices devicetype[%{public}zu]:%{public}d",
1603                 i, streamDesc->newDeviceDescs_[i]->deviceType_);
1604         } else {
1605             allDevicesInDualDevicesRange = false;
1606             break;
1607         }
1608     }
1609 
1610     AUDIO_INFO_LOG("select ringer/alarm sessionId:%{public}d, streamUsage:%{public}d", sessionId, streamUsage);
1611     if (!streamDesc->newDeviceDescs_.empty() && allDevicesInDualDevicesRange) {
1612         if (streamDesc->newDeviceDescs_.size() == AUDIO_CONCURRENT_ACTIVE_DEVICES_LIMIT &&
1613             AudioPolicyUtils::GetInstance().GetSinkName(*streamDesc->newDeviceDescs_.front(), sessionId) !=
1614             AudioPolicyUtils::GetInstance().GetSinkName(*streamDesc->newDeviceDescs_.back(), sessionId)) {
1615             AUDIO_INFO_LOG("set dual hal tone, reset primary sink to default before.");
1616             audioActiveDevice_.UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG);
1617             if (enableDualHalToneState_ && enableDualHalToneSessionId_ != sessionId) {
1618                 AUDIO_INFO_LOG("sesion changed, disable old dual hal tone.");
1619                 UpdateDualToneState(false, enableDualHalToneSessionId_);
1620             }
1621             CHECK_AND_RETURN_RET_LOG(AudioCoreServiceUtils::NeedDualHalToneInStatus(
1622                 audioPolicyManager_.GetRingerMode(), streamUsage,
1623                 VolumeUtils::IsPCVolumeEnable(), audioVolumeManager_.GetStreamMute(STREAM_MUSIC)),
1624                 false, "no normal ringer mode and no alarm, dont dual hal tone.");
1625             UpdateDualToneState(true, sessionId);
1626         } else {
1627             if (enableDualHalToneState_ && enableDualHalToneSessionId_ == sessionId) {
1628                 AUDIO_INFO_LOG("device unavailable, disable dual hal tone.");
1629                 UpdateDualToneState(false, enableDualHalToneSessionId_);
1630             }
1631             bool pre = isRingDualToneOnPrimarySpeaker_;
1632             isRingDualToneOnPrimarySpeaker_ = AudioCoreServiceUtils::IsRingDualToneOnPrimarySpeaker(
1633                 streamDesc->newDeviceDescs_, sessionId);
1634             ClearRingMuteWhenCallStart(pre, isRingDualToneOnPrimarySpeaker_);
1635             audioActiveDevice_.UpdateActiveDevicesRoute(activeDevices);
1636         }
1637         return true;
1638     }
1639     return false;
1640 }
1641 
UpdateDualToneState(const bool & enable,const int32_t & sessionId)1642 void AudioCoreService::UpdateDualToneState(const bool &enable, const int32_t &sessionId)
1643 {
1644     AUDIO_INFO_LOG("Update dual tone state, enable:%{public}d, sessionId:%{public}d", enable, sessionId);
1645     enableDualHalToneState_ = enable;
1646     if (enableDualHalToneState_) {
1647         enableDualHalToneSessionId_ = sessionId;
1648     }
1649     Trace trace("AudioDeviceCommon::UpdateDualToneState sessionId:" + std::to_string(sessionId));
1650     auto ret = AudioServerProxy::GetInstance().UpdateDualToneStateProxy(enable, sessionId);
1651     CHECK_AND_RETURN_LOG(ret == SUCCESS, "Failed to update the dual tone state for sessionId:%{public}d", sessionId);
1652 }
1653 
MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,std::shared_ptr<AudioPipeInfo> pipeInfo,std::shared_ptr<AudioDeviceDescriptor> localDeviceDescriptor)1654 int32_t AudioCoreService::MoveToLocalOutputDevice(std::vector<SinkInput> sinkInputIds,
1655     std::shared_ptr<AudioPipeInfo> pipeInfo, std::shared_ptr<AudioDeviceDescriptor> localDeviceDescriptor)
1656 {
1657     // check
1658     CHECK_AND_RETURN_RET_LOG(LOCAL_NETWORK_ID == localDeviceDescriptor->networkId_,
1659         ERR_INVALID_OPERATION, "failed: not a local device.");
1660 
1661     // start move.
1662     uint32_t sinkId = -1; // invalid sink id, use sink name instead.
1663     for (size_t i = 0; i < sinkInputIds.size(); i++) {
1664         AudioPipeType pipeType = PIPE_TYPE_UNKNOWN;
1665         std::string sinkName = localDeviceDescriptor->deviceType_ == DEVICE_TYPE_REMOTE_CAST ?
1666             "RemoteCastInnerCapturer" : pipeInfo->moduleInfo_.name;
1667         AUDIO_INFO_LOG("Session %{public}d, sinkName %{public}s", sinkInputIds[i].streamId, sinkName.c_str());
1668         if (sinkName == BLUETOOTH_SPEAKER) {
1669             std::string activePort = BLUETOOTH_SPEAKER;
1670             audioPolicyManager_.SuspendAudioDevice(activePort, false);
1671         }
1672         AUDIO_INFO_LOG("move for sinkInput [%{public}d], portName %{public}s pipeType %{public}d",
1673             sinkInputIds[i].streamId, sinkName.c_str(), pipeType);
1674         int32_t ret = audioPolicyManager_.MoveSinkInputByIndexOrName(sinkInputIds[i].paStreamId, sinkId, sinkName);
1675         CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR,
1676             "move [%{public}d] to local failed", sinkInputIds[i].streamId);
1677         audioRouteMap_.AddRouteMapInfo(sinkInputIds[i].uid, LOCAL_NETWORK_ID, sinkInputIds[i].pid);
1678     }
1679 
1680     isCurrentRemoteRenderer_ = false;
1681     return SUCCESS;
1682 }
1683 
HasLowLatencyCapability(DeviceType deviceType,bool isRemote)1684 bool AudioCoreService::HasLowLatencyCapability(DeviceType deviceType, bool isRemote)
1685 {
1686     // Distributed devices are low latency devices
1687     if (isRemote) {
1688         return true;
1689     }
1690 
1691     switch (deviceType) {
1692         case DeviceType::DEVICE_TYPE_EARPIECE:
1693         case DeviceType::DEVICE_TYPE_SPEAKER:
1694         case DeviceType::DEVICE_TYPE_WIRED_HEADSET:
1695         case DeviceType::DEVICE_TYPE_WIRED_HEADPHONES:
1696         case DeviceType::DEVICE_TYPE_USB_HEADSET:
1697         case DeviceType::DEVICE_TYPE_DP:
1698             return true;
1699 
1700         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
1701         case DeviceType::DEVICE_TYPE_BLUETOOTH_A2DP:
1702             return false;
1703         default:
1704             return false;
1705     }
1706 }
1707 
TriggerRecreateRendererStreamCallback(shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)1708 void AudioCoreService::TriggerRecreateRendererStreamCallback(shared_ptr<AudioStreamDescriptor> &streamDesc,
1709     const AudioStreamDeviceChangeReasonExt reason)
1710 {
1711     Trace trace("AudioCoreService::TriggerRecreateRendererStreamCallback");
1712     CHECK_AND_RETURN_LOG(streamDesc != nullptr, "streamDesc is null");
1713     CHECK_AND_RETURN_LOG(audioPolicyServerHandler_ != nullptr, "audioPolicyServerHandler_ is null");
1714     int32_t callerPid = streamDesc->callerPid_;
1715     int32_t sessionId = streamDesc->sessionId_;
1716     uint32_t routeFlag = streamDesc->routeFlag_;
1717     AUDIO_INFO_LOG("Trigger recreate renderer stream %{public}d, pid: %{public}d, routeflag: 0x%{public}x",
1718         sessionId, callerPid, routeFlag);
1719     audioPolicyServerHandler_->SendRecreateRendererStreamEvent(callerPid, sessionId, routeFlag, reason);
1720 
1721     CHECK_AND_RETURN_LOG(streamDesc->oldDeviceDescs_.size() > 0 && streamDesc->oldDeviceDescs_.front() != nullptr,
1722         "oldDeviceDesc is invalid");
1723     CHECK_AND_RETURN_LOG(streamDesc->newDeviceDescs_.size() > 0 && streamDesc->newDeviceDescs_.front() != nullptr,
1724         "newDeviceDesc is invalid");
1725     std::shared_ptr<AudioDeviceDescriptor> oldDeviceDesc = streamDesc->oldDeviceDescs_.front();
1726     std::shared_ptr<AudioDeviceDescriptor> newDeviceDesc = streamDesc->newDeviceDescs_.front();
1727     if (!oldDeviceDesc->IsSameDeviceDesc(newDeviceDesc)) {
1728         std::shared_ptr<AudioDeviceDescriptor> callbackDesc = std::make_shared<AudioDeviceDescriptor>(newDeviceDesc);
1729         callbackDesc->descriptorType_ = AudioDeviceDescriptor::DEVICE_INFO;
1730         audioPolicyServerHandler_->SendRendererDeviceChangeEvent(callerPid, sessionId, callbackDesc, reason);
1731     }
1732 }
1733 
HandleStreamStatusToCapturerState(AudioStreamStatus status)1734 CapturerState AudioCoreService::HandleStreamStatusToCapturerState(AudioStreamStatus status)
1735 {
1736     switch (status) {
1737         case STREAM_STATUS_NEW:
1738             return CAPTURER_PREPARED;
1739         case STREAM_STATUS_STARTED:
1740             return CAPTURER_RUNNING;
1741         case STREAM_STATUS_PAUSED:
1742             return CAPTURER_PAUSED;
1743         case STREAM_STATUS_STOPPED:
1744             return CAPTURER_STOPPED;
1745         case STREAM_STATUS_RELEASED:
1746             return CAPTURER_RELEASED;
1747         default:
1748             return CAPTURER_INVALID;
1749     }
1750 }
1751 
TriggerRecreateCapturerStreamCallback(shared_ptr<AudioStreamDescriptor> & streamDesc)1752 void AudioCoreService::TriggerRecreateCapturerStreamCallback(shared_ptr<AudioStreamDescriptor> &streamDesc)
1753 {
1754     Trace trace("AudioCoreService::TriggerRecreateCapturerStreamCallback");
1755     AUDIO_INFO_LOG("Trigger recreate capturer stream %{public}d, pid: %{public}d, routeflag: 0x%{public}x",
1756         streamDesc->sessionId_, streamDesc->callerPid_, streamDesc->routeFlag_);
1757 
1758     if (audioPolicyServerHandler_ != nullptr) {
1759         audioPolicyServerHandler_->SendRecreateCapturerStreamEvent(streamDesc->appInfo_.appPid,
1760             streamDesc->sessionId_, streamDesc->routeFlag_, AudioStreamDeviceChangeReasonExt::ExtEnum::UNKNOWN);
1761     } else {
1762         AUDIO_WARNING_LOG("No audio policy server handler");
1763     }
1764 }
1765 
OpenNewAudioPortAndRoute(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & paIndex)1766 uint32_t AudioCoreService::OpenNewAudioPortAndRoute(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &paIndex)
1767 {
1768     uint32_t id = OPEN_PORT_FAILURE;
1769     CHECK_AND_RETURN_RET_LOG(pipeInfo != nullptr && pipeInfo->streamDescriptors_.size() > 0 &&
1770         pipeInfo->streamDescriptors_.front() != nullptr, OPEN_PORT_FAILURE, "pipeInfo is invalid");
1771     std::shared_ptr<AudioStreamDescriptor> streamDesc = pipeInfo->streamDescriptors_[0];
1772     CHECK_AND_RETURN_RET_LOG(streamDesc->newDeviceDescs_.size() > 0 &&
1773         streamDesc->newDeviceDescs_[0] != nullptr, OPEN_PORT_FAILURE, "invalid streamDesc");
1774     if (streamDesc->newDeviceDescs_.front()->deviceType_ == DEVICE_TYPE_REMOTE_CAST) {
1775         AUDIO_INFO_LOG("[PipeExecInfo] remote cast device do not need open pipe");
1776         id = streamDesc->sessionId_;
1777     } else {
1778         if (pipeInfo->moduleInfo_.name == BLUETOOTH_MIC &&
1779             streamDesc->newDeviceDescs_[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP_IN) {
1780             shared_ptr<AudioDeviceDescriptor> desc = streamDesc->newDeviceDescs_[0];
1781             audioActiveDevice_.SetActiveBtInDeviceMac(desc->macAddress_);
1782             bool ret = audioActiveDevice_.GetActiveA2dpDeviceStreamInfo(DEVICE_TYPE_BLUETOOTH_A2DP_IN,
1783                 streamDesc->streamInfo_);
1784             CHECK_AND_RETURN_RET_LOG(ret, OPEN_PORT_FAILURE, "invalid streamDesc");
1785             SourceType sourceType = streamDesc->capturerInfo_.sourceType;
1786             GetA2dpModuleInfo(pipeInfo->moduleInfo_, streamDesc->streamInfo_, sourceType);
1787         }
1788         HandleCommonSourceOpened(pipeInfo);
1789         id = audioPolicyManager_.OpenAudioPort(pipeInfo, paIndex);
1790 
1791         if (audioActiveDevice_.GetCurrentInputDeviceType() == DEVICE_TYPE_MIC ||
1792             audioActiveDevice_.GetCurrentInputDeviceType() == DEVICE_TYPE_ACCESSORY) {
1793             audioPolicyManager_.SetDeviceActive(audioActiveDevice_.GetCurrentInputDeviceType(),
1794                 pipeInfo->moduleInfo_.name, true, INPUT_DEVICES_FLAG);
1795         }
1796     }
1797     CHECK_AND_RETURN_RET_LOG(id != HDI_INVALID_ID, ERR_INVALID_HANDLE,
1798         "OpenAudioPort failed ioHandle[%{public}u]", id);
1799     CHECK_AND_RETURN_RET_LOG(paIndex != OPEN_PORT_FAILURE, ERR_OPERATION_FAILED,
1800         "OpenAudioPort failed paId[%{public}u]", paIndex);
1801     audioIOHandleMap_.AddIOHandleInfo(pipeInfo->moduleInfo_.name, id);
1802     AUDIO_INFO_LOG("[PipeExecInfo] Get HDI id: %{public}u, paIndex %{public}u", id, paIndex);
1803     return id;
1804 }
1805 
IsPaRoute(uint32_t routeFlag)1806 bool AudioCoreService::IsPaRoute(uint32_t routeFlag)
1807 {
1808     if ((routeFlag & AUDIO_OUTPUT_FLAG_DIRECT) ||
1809         (routeFlag & AUDIO_OUTPUT_FLAG_FAST) ||
1810         (routeFlag & AUDIO_INPUT_FLAG_FAST)) {
1811         return false;
1812     }
1813     return true;
1814 }
1815 
RecoverFetchedDescs(const std::vector<std::shared_ptr<AudioStreamDescriptor>> & streamDescs)1816 bool AudioCoreService::RecoverFetchedDescs(const std::vector<std::shared_ptr<AudioStreamDescriptor>> &streamDescs)
1817 {
1818     for (auto &streamDesc : streamDescs) {
1819         CHECK_AND_CONTINUE_LOG(streamDesc != nullptr, "Stream desc is nullptr");
1820         streamDesc->newDeviceDescs_ = streamDesc->oldDeviceDescs_;
1821     }
1822 
1823     return true;
1824 }
1825 
HandleScoOutputDeviceFetched(shared_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReasonExt reason)1826 int32_t AudioCoreService::HandleScoOutputDeviceFetched(
1827     shared_ptr<AudioDeviceDescriptor> &desc, const AudioStreamDeviceChangeReasonExt reason)
1828 {
1829     AUDIO_INFO_LOG("In");
1830     Trace trace("AudioCoreService::HandleScoOutputDeviceFetched");
1831 #ifdef BLUETOOTH_ENABLE
1832     int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_);
1833     if (ret != SUCCESS) {
1834         RecoverFetchedDescs(pipeManager_->GetAllOutputStreamDescs());
1835         AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch output device.");
1836         desc->exceptionFlag_ = true;
1837         audioDeviceManager_.UpdateDevicesListInfo(
1838             std::make_shared<AudioDeviceDescriptor>(*desc), EXCEPTION_FLAG_UPDATE);
1839         FetchOutputDeviceAndRoute("HandleScoOutputDeviceFetched_1", reason);
1840         return ERROR;
1841     }
1842     Bluetooth::AudioHfpManager::UpdateAudioScene(audioSceneManager_.GetAudioScene(true));
1843 #endif
1844     AUDIO_INFO_LOG("out");
1845     return SUCCESS;
1846 }
1847 
HandleScoOutputDeviceFetched(shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)1848 int32_t AudioCoreService::HandleScoOutputDeviceFetched(
1849     shared_ptr<AudioStreamDescriptor> &streamDesc, const AudioStreamDeviceChangeReasonExt reason)
1850 {
1851     AUDIO_INFO_LOG("In");
1852     Trace trace("AudioCoreService::HandleScoOutputDeviceFetched");
1853 #ifdef BLUETOOTH_ENABLE
1854     std::shared_ptr<AudioDeviceDescriptor> desc = streamDesc->newDeviceDescs_.front();
1855     int32_t ret = Bluetooth::AudioHfpManager::SetActiveHfpDevice(desc->macAddress_);
1856     if (ret != SUCCESS) {
1857         RecoverFetchedDescs(pipeManager_->GetAllOutputStreamDescs());
1858         AUDIO_ERR_LOG("Active hfp device failed, retrigger fetch output device.");
1859         desc->exceptionFlag_ = true;
1860         audioDeviceManager_.UpdateDevicesListInfo(
1861             std::make_shared<AudioDeviceDescriptor>(*desc), EXCEPTION_FLAG_UPDATE);
1862         FetchOutputDeviceAndRoute("HandleScoOutputDeviceFetched_2", reason);
1863         return ERROR;
1864     }
1865     if (streamDesc->streamStatus_ == STREAM_STATUS_STARTED) {
1866         Bluetooth::AudioHfpManager::UpdateAudioScene(audioSceneManager_.GetAudioScene(true));
1867     }
1868 #endif
1869     AUDIO_INFO_LOG("out");
1870     return SUCCESS;
1871 }
1872 
GetRealUid(std::shared_ptr<AudioStreamDescriptor> streamDesc)1873 int32_t AudioCoreService::GetRealUid(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1874 {
1875     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, -1, "Stream desc is nullptr");
1876     if (streamDesc->callerUid_ == MEDIA_SERVICE_UID) {
1877         return streamDesc->appInfo_.appUid;
1878     }
1879     return streamDesc->callerUid_;
1880 }
1881 
GetRealPid(std::shared_ptr<AudioStreamDescriptor> streamDesc)1882 int32_t AudioCoreService::GetRealPid(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1883 {
1884     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, -1, "Stream desc is nullptr");
1885     if (streamDesc->callerUid_ == MEDIA_SERVICE_UID) {
1886         return streamDesc->appInfo_.appPid;
1887     }
1888     return streamDesc->callerPid_;
1889 }
1890 
UpdateRendererInfoWhenNoPermission(const shared_ptr<AudioRendererChangeInfo> & audioRendererChangeInfos,bool hasSystemPermission)1891 void AudioCoreService::UpdateRendererInfoWhenNoPermission(
1892     const shared_ptr<AudioRendererChangeInfo> &audioRendererChangeInfos, bool hasSystemPermission)
1893 {
1894     if (!hasSystemPermission) {
1895         audioRendererChangeInfos->clientUID = 0;
1896         audioRendererChangeInfos->rendererState = RENDERER_INVALID;
1897     }
1898 }
1899 
UpdateCapturerInfoWhenNoPermission(const shared_ptr<AudioCapturerChangeInfo> & audioCapturerChangeInfos,bool hasSystemPermission)1900 void AudioCoreService::UpdateCapturerInfoWhenNoPermission(
1901     const shared_ptr<AudioCapturerChangeInfo> &audioCapturerChangeInfos, bool hasSystemPermission)
1902 {
1903     if (!hasSystemPermission) {
1904         audioCapturerChangeInfos->clientUID = 0;
1905         audioCapturerChangeInfos->capturerState = CAPTURER_INVALID;
1906     }
1907 }
1908 
SendA2dpConnectedWhileRunning(const RendererState & rendererState,const uint32_t & sessionId)1909 void AudioCoreService::SendA2dpConnectedWhileRunning(const RendererState &rendererState, const uint32_t &sessionId)
1910 {
1911     if ((rendererState == RENDERER_RUNNING) && (audioA2dpOffloadManager_ != nullptr) &&
1912         !audioA2dpOffloadManager_->IsA2dpOffloadConnecting(sessionId)) {
1913         AUDIO_INFO_LOG("Notify client not to block.");
1914         std::thread sendConnectedToClient(&AudioCoreService::UpdateSessionConnectionState, this, sessionId,
1915             DATA_LINK_CONNECTED);
1916         sendConnectedToClient.detach();
1917     }
1918 }
1919 
UpdateSessionConnectionState(const int32_t & sessionID,const int32_t & state)1920 void AudioCoreService::UpdateSessionConnectionState(const int32_t &sessionID, const int32_t &state)
1921 {
1922     AudioServerProxy::GetInstance().UpdateSessionConnectionStateProxy(sessionID, state);
1923 }
1924 
UpdateTrackerDeviceChange(const vector<std::shared_ptr<AudioDeviceDescriptor>> & desc)1925 void AudioCoreService::UpdateTrackerDeviceChange(const vector<std::shared_ptr<AudioDeviceDescriptor>> &desc)
1926 {
1927     AUDIO_INFO_LOG("Start");
1928 
1929     DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1930     for (std::shared_ptr<AudioDeviceDescriptor> deviceDesc : desc) {
1931         if (deviceDesc->deviceRole_ == OUTPUT_DEVICE) {
1932             DeviceType type = curOutputDeviceType;
1933             std::string macAddress = audioActiveDevice_.GetCurrentOutputDeviceMacAddr();
1934             auto itr = audioConnectedDevice_.CheckExistOutputDevice(type, macAddress);
1935             if (itr != nullptr) {
1936                 AudioDeviceDescriptor outputDevice(AudioDeviceDescriptor::DEVICE_INFO);
1937                 audioDeviceCommon_.UpdateDeviceInfo(outputDevice, itr, true, true);
1938                 streamCollector_.UpdateTracker(AUDIO_MODE_PLAYBACK, outputDevice);
1939             }
1940         }
1941         if (deviceDesc->deviceRole_ == INPUT_DEVICE) {
1942             DeviceType type = audioActiveDevice_.GetCurrentInputDeviceType();
1943             auto itr = audioConnectedDevice_.CheckExistInputDevice(type);
1944             if (itr != nullptr) {
1945                 AudioDeviceDescriptor inputDevice(AudioDeviceDescriptor::DEVICE_INFO);
1946                 audioDeviceCommon_.UpdateDeviceInfo(inputDevice, itr, true, true);
1947                 audioMicrophoneDescriptor_.UpdateAudioCapturerMicrophoneDescriptor(itr->deviceType_);
1948                 streamCollector_.UpdateTracker(AUDIO_MODE_RECORD, inputDevice);
1949             }
1950         }
1951     }
1952 }
1953 
GetFastControlParam()1954 bool AudioCoreService::GetFastControlParam()
1955 {
1956     int32_t fastControlFlag = 1; // default 1, set isFastControlled_ true
1957     GetSysPara("persist.multimedia.audioflag.fastcontrolled", fastControlFlag);
1958     if (fastControlFlag == 0) {
1959         isFastControlled_ = false;
1960     }
1961     return isFastControlled_;
1962 }
1963 
StoreDistributedRoutingRoleInfo(const std::shared_ptr<AudioDeviceDescriptor> descriptor,CastType type)1964 void AudioCoreService::StoreDistributedRoutingRoleInfo(
1965     const std::shared_ptr<AudioDeviceDescriptor> descriptor, CastType type)
1966 {
1967     distributedRoutingInfo_.descriptor = descriptor;
1968     distributedRoutingInfo_.type = type;
1969 }
1970 
GetSystemVolumeLevel(AudioStreamType streamType)1971 int32_t AudioCoreService::GetSystemVolumeLevel(AudioStreamType streamType)
1972 {
1973     return audioVolumeManager_.GetSystemVolumeLevel(streamType);
1974 }
1975 
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType) const1976 float AudioCoreService::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel,
1977     DeviceType deviceType) const
1978 {
1979     return audioPolicyManager_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType);
1980 }
1981 
IsStreamSupportLowpower(std::shared_ptr<AudioStreamDescriptor> streamDesc)1982 bool AudioCoreService::IsStreamSupportLowpower(std::shared_ptr<AudioStreamDescriptor> streamDesc)
1983 {
1984     Trace trace("IsStreamSupportLowpower");
1985     if (pipeManager_->PcmOffloadSessionCount() > 0) {
1986         AUDIO_INFO_LOG("PIPE_TYPE_OFFLOAD already exist.");
1987         return false;
1988     }
1989     if (!streamDesc->rendererInfo_.isOffloadAllowed) {
1990         AUDIO_INFO_LOG("normal stream because renderInfo not support offload.");
1991         return false;
1992     }
1993     if (GetRealUid(streamDesc) == AUDIO_EXT_UID) {
1994         AUDIO_INFO_LOG("the extra uid not support offload.");
1995         return false;
1996     }
1997     if (streamDesc->streamInfo_.channels > STEREO &&
1998         (streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_MOVIE ||
1999          streamDesc->rendererInfo_.originalFlag != AUDIO_FLAG_PCM_OFFLOAD)) {
2000         AUDIO_INFO_LOG("normal stream because channels.");
2001         return false;
2002     }
2003 
2004     if (streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_MUSIC &&
2005         streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_AUDIOBOOK &&
2006         (streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_MOVIE ||
2007          streamDesc->rendererInfo_.originalFlag != AUDIO_FLAG_PCM_OFFLOAD)) {
2008         AUDIO_INFO_LOG("normal stream because streamUsage.");
2009         return false;
2010     }
2011 
2012     if (streamDesc->rendererInfo_.playerType == PLAYER_TYPE_SOUND_POOL ||
2013         streamDesc->rendererInfo_.playerType == PLAYER_TYPE_OPENSL_ES) {
2014         AUDIO_INFO_LOG("normal stream beacuse playerType %{public}d.", streamDesc->rendererInfo_.playerType);
2015         return false;
2016     }
2017 
2018     AudioSpatializationState spatialState =
2019         AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState();
2020     bool effectOffloadFlag = AudioServerProxy::GetInstance().GetEffectOffloadEnabledProxy();
2021     if (spatialState.spatializationEnabled && !effectOffloadFlag) {
2022         AUDIO_INFO_LOG("spatialization effect in arm, Skipped.");
2023         return false;
2024     }
2025 
2026     // LowPower: Speaker, USB headset, a2dp offload, Nearlink
2027     if (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_SPEAKER &&
2028         streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_USB_HEADSET &&
2029         (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP ||
2030         streamDesc->newDeviceDescs_[0]->a2dpOffloadFlag_ != A2DP_OFFLOAD) &&
2031         streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_NEARLINK) {
2032         AUDIO_INFO_LOG("normal stream, deviceType: %{public}d", streamDesc->newDeviceDescs_[0]->deviceType_);
2033         return false;
2034     }
2035     return true;
2036 }
2037 
SetDefaultOutputDevice(const DeviceType deviceType,const uint32_t sessionID,const StreamUsage streamUsage,bool isRunning,bool skipForce)2038 int32_t AudioCoreService::SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID,
2039     const StreamUsage streamUsage, bool isRunning, bool skipForce)
2040 {
2041     CHECK_AND_RETURN_RET_LOG(policyConfigMananger_.GetHasEarpiece(), ERR_NOT_SUPPORTED, "the device has no earpiece");
2042     CHECK_AND_RETURN_RET_LOG(pipeManager_->GetStreamDescById(sessionID) != nullptr, ERR_NOT_SUPPORTED,
2043         "sessionId is not exist");
2044 
2045     if ((audioSessionService_ != nullptr) && (!audioSessionService_->IsStreamAllowedToSetDevice(sessionID))) {
2046         AUDIO_ERR_LOG("current stream is contained in a session which had set default output device");
2047         return ERR_NOT_SUPPORTED;
2048     }
2049 
2050     AUDIO_INFO_LOG("[ADeviceEvent] device %{public}d for %{public}s stream %{public}u", deviceType,
2051         isRunning ? "running" : "not running", sessionID);
2052     vector<shared_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos;
2053     streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
2054     bool forceFetch = false;
2055     for (auto &changeInfo : audioRendererChangeInfos) {
2056         if (changeInfo->sessionId == static_cast<int32_t>(sessionID)) {
2057             CHECK_AND_CONTINUE(!skipForce);
2058             AudioPolicyUtils::GetInstance().SetPreferredDevice(AUDIO_CALL_RENDER,
2059                 std::make_shared<AudioDeviceDescriptor>(), changeInfo->clientUID, "SetDefaultOutputDevice");
2060             forceFetch = true;
2061         }
2062     }
2063     int32_t ret = audioDeviceManager_.SetDefaultOutputDevice(deviceType, sessionID, streamUsage, isRunning);
2064     if (ret == NEED_TO_FETCH || forceFetch) {
2065         FetchOutputDeviceAndRoute("SetDefaultOutputDevice",
2066             AudioStreamDeviceChangeReasonExt::ExtEnum::SET_DEFAULT_OUTPUT_DEVICE);
2067         return SUCCESS;
2068     }
2069     return ret;
2070 }
2071 
HandleFetchOutputWhenNoRunningStream(const AudioStreamDeviceChangeReasonExt reason)2072 int32_t AudioCoreService::HandleFetchOutputWhenNoRunningStream(const AudioStreamDeviceChangeReasonExt reason)
2073 {
2074     vector<std::shared_ptr<AudioDeviceDescriptor>> descs =
2075         audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1, "HandleFetchOutputWhenNoRunningStream");
2076     CHECK_AND_RETURN_RET_LOG(!descs.empty(), ERROR, "descs is empty");
2077     AudioDeviceDescriptor tmpOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
2078     if (descs.front()->deviceType_ == DEVICE_TYPE_NONE || IsSameDevice(descs.front(), tmpOutputDeviceDesc)) {
2079         AUDIO_DEBUG_LOG("output device is not change");
2080         return SUCCESS;
2081     }
2082     audioActiveDevice_.SetCurrentOutputDevice(*descs.front());
2083     AUDIO_DEBUG_LOG("currentActiveDevice %{public}d", audioActiveDevice_.GetCurrentOutputDeviceType());
2084     audioVolumeManager_.SetVolumeForSwitchDevice(*descs.front());
2085     if (descs.front()->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
2086         SwitchActiveA2dpDevice(std::make_shared<AudioDeviceDescriptor>(*descs.front()));
2087     }
2088     if (descs.front()->deviceType_ == DEVICE_TYPE_HEARING_AID) {
2089         SwitchActiveHearingAidDevice(std::make_shared<AudioDeviceDescriptor>(*descs.front()));
2090     }
2091     if (audioSceneManager_.GetAudioScene(true) != AUDIO_SCENE_DEFAULT) {
2092         audioActiveDevice_.UpdateActiveDeviceRoute(descs.front()->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG,
2093             descs.front()->deviceName_, descs.front()->networkId_);
2094     }
2095     OnPreferredOutputDeviceUpdated(audioActiveDevice_.GetCurrentOutputDevice(), reason);
2096     return SUCCESS;
2097 }
2098 
HandleFetchInputWhenNoRunningStream()2099 int32_t AudioCoreService::HandleFetchInputWhenNoRunningStream()
2100 {
2101     std::shared_ptr<AudioDeviceDescriptor> desc;
2102     AudioDeviceDescriptor tempDesc = audioActiveDevice_.GetCurrentInputDevice();
2103     if (tempDesc.deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO && Bluetooth::AudioHfpManager::IsRecognitionStatus()) {
2104         desc = audioRouterCenter_.FetchInputDevice(SOURCE_TYPE_VOICE_RECOGNITION, -1);
2105     } else {
2106         desc = audioRouterCenter_.FetchInputDevice(SOURCE_TYPE_MIC, -1);
2107     }
2108     CHECK_AND_RETURN_RET_LOG(desc != nullptr, ERROR, "desc is nullptr");
2109 
2110     if (desc->deviceType_ == DEVICE_TYPE_NONE || IsSameDevice(desc, tempDesc)) {
2111         AUDIO_DEBUG_LOG("input device is not change");
2112         return SUCCESS;
2113     }
2114     audioActiveDevice_.SetCurrentInputDevice(*desc);
2115     if (desc->deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
2116         audioEcManager_.PresetArmIdleInput(desc->macAddress_);
2117     }
2118     DeviceType deviceType = audioActiveDevice_.GetCurrentInputDeviceType();
2119     AUDIO_DEBUG_LOG("currentActiveInputDevice update %{public}d", deviceType);
2120     OnPreferredInputDeviceUpdated(deviceType, ""); // networkId is not used
2121     return SUCCESS;
2122 }
2123 
UpdateOutputDevice(std::shared_ptr<AudioDeviceDescriptor> & desc,int32_t uid,const AudioStreamDeviceChangeReasonExt reason)2124 bool AudioCoreService::UpdateOutputDevice(std::shared_ptr<AudioDeviceDescriptor> &desc, int32_t uid,
2125     const AudioStreamDeviceChangeReasonExt reason)
2126 {
2127     std::shared_ptr<AudioDeviceDescriptor> preferredDesc = audioAffinityManager_.GetRendererDevice(uid);
2128     AudioDeviceDescriptor tmpOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
2129     if (((preferredDesc->deviceType_ != DEVICE_TYPE_NONE) && !desc->IsSameDeviceInfo(tmpOutputDeviceDesc)
2130         && desc->deviceType_ != preferredDesc->deviceType_)
2131         || ((preferredDesc->deviceType_ == DEVICE_TYPE_NONE) && !desc->IsSameDeviceInfo(tmpOutputDeviceDesc))) {
2132         WriteOutputRouteChangeEvent(desc, reason);
2133         audioActiveDevice_.SetCurrentOutputDevice(*desc);
2134         AUDIO_DEBUG_LOG("currentActiveDevice update %{public}d", audioActiveDevice_.GetCurrentOutputDeviceType());
2135         return true;
2136     }
2137     return false;
2138 }
2139 
UpdateInputDevice(std::shared_ptr<AudioDeviceDescriptor> & desc,int32_t uid,const AudioStreamDeviceChangeReasonExt reason)2140 bool AudioCoreService::UpdateInputDevice(std::shared_ptr<AudioDeviceDescriptor> &desc, int32_t uid,
2141     const AudioStreamDeviceChangeReasonExt reason)
2142 {
2143     std::shared_ptr<AudioDeviceDescriptor> preferredDesc = audioAffinityManager_.GetCapturerDevice(uid);
2144     if (((preferredDesc->deviceType_ != DEVICE_TYPE_NONE) &&
2145         !IsSameDevice(desc, audioActiveDevice_.GetCurrentInputDevice())
2146         && desc->deviceType_ != preferredDesc->deviceType_)
2147         || ((preferredDesc->deviceType_ == DEVICE_TYPE_NONE)
2148         && !IsSameDevice(desc, audioActiveDevice_.GetCurrentInputDevice()))) {
2149         WriteInputRouteChangeEvent(desc, reason);
2150         audioActiveDevice_.SetCurrentInputDevice(*desc);
2151         AUDIO_DEBUG_LOG("currentActiveInputDevice update %{public}d",
2152             audioActiveDevice_.GetCurrentInputDeviceType());
2153         return true;
2154     }
2155     return false;
2156 }
2157 
WriteOutputRouteChangeEvent(std::shared_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReason reason)2158 void AudioCoreService::WriteOutputRouteChangeEvent(std::shared_ptr<AudioDeviceDescriptor> &desc,
2159     const AudioStreamDeviceChangeReason reason)
2160 {
2161     int64_t timeStamp = AudioPolicyUtils::GetInstance().GetCurrentTimeMS();
2162     std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
2163         Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_ROUTE_CHANGE,
2164         Media::MediaMonitor::BEHAVIOR_EVENT);
2165     DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
2166     bean->Add("REASON", static_cast<int32_t>(reason));
2167     bean->Add("TIMESTAMP", static_cast<uint64_t>(timeStamp));
2168     bean->Add("DEVICE_TYPE_BEFORE_CHANGE", curOutputDeviceType);
2169     bean->Add("DEVICE_TYPE_AFTER_CHANGE", desc->deviceType_);
2170     bean->Add("PRE_AUDIO_SCENE", static_cast<int32_t>(audioSceneManager_.GetLastAudioScene()));
2171     bean->Add("CUR_AUDIO_SCENE", static_cast<int32_t>(audioSceneManager_.GetAudioScene(true)));
2172     bean->Add("DEVICE_LIST", audioDeviceManager_.GetConnDevicesStr());
2173     bean->Add("ROUTER_TYPE", static_cast<int32_t>(desc->routerType_));
2174     Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
2175 }
2176 
WriteInputRouteChangeEvent(std::shared_ptr<AudioDeviceDescriptor> & desc,const AudioStreamDeviceChangeReason reason)2177 void AudioCoreService::WriteInputRouteChangeEvent(std::shared_ptr<AudioDeviceDescriptor> &desc,
2178     const AudioStreamDeviceChangeReason reason)
2179 {
2180     int64_t timeStamp = AudioPolicyUtils::GetInstance().GetCurrentTimeMS();
2181     std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
2182         Media::MediaMonitor::AUDIO, Media::MediaMonitor::AUDIO_ROUTE_CHANGE,
2183         Media::MediaMonitor::BEHAVIOR_EVENT);
2184     bean->Add("REASON", static_cast<int32_t>(reason));
2185     bean->Add("TIMESTAMP", static_cast<uint64_t>(timeStamp));
2186     bean->Add("DEVICE_TYPE_BEFORE_CHANGE", audioActiveDevice_.GetCurrentInputDeviceType());
2187     bean->Add("DEVICE_TYPE_AFTER_CHANGE", desc->deviceType_);
2188     bean->Add("PRE_AUDIO_SCENE", static_cast<int32_t>(audioSceneManager_.GetLastAudioScene()));
2189     bean->Add("CUR_AUDIO_SCENE", static_cast<int32_t>(audioSceneManager_.GetAudioScene(true)));
2190     bean->Add("DEVICE_LIST", audioDeviceManager_.GetConnDevicesStr());
2191     bean->Add("ROUTER_TYPE", static_cast<int32_t>(desc->routerType_));
2192     Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
2193 }
2194 
HandleDeviceChangeForFetchOutputDevice(std::shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)2195 int32_t AudioCoreService::HandleDeviceChangeForFetchOutputDevice(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2196     const AudioStreamDeviceChangeReasonExt reason)
2197 {
2198     if (streamDesc->oldDeviceDescs_.size() == 0) {
2199         AUDIO_INFO_LOG("No old device info");
2200         return SUCCESS;
2201     }
2202     std::shared_ptr<AudioDeviceDescriptor> desc = streamDesc->newDeviceDescs_.front();
2203 
2204     if (desc->deviceType_ == DEVICE_TYPE_NONE || (IsSameDevice(desc, streamDesc->oldDeviceDescs_.front()) &&
2205         !NeedRehandleA2DPDevice(desc) && desc->connectState_ != DEACTIVE_CONNECTED &&
2206         audioSceneManager_.IsSameAudioScene() && !shouldUpdateDeviceDueToDualTone_)) {
2207         AUDIO_WARNING_LOG("stream %{public}d device not change, no need move device", streamDesc->sessionId_);
2208         AudioDeviceDescriptor tmpOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
2209         std::shared_ptr<AudioDeviceDescriptor> preferredDesc =
2210             audioAffinityManager_.GetRendererDevice(GetRealUid(streamDesc));
2211         if (((preferredDesc->deviceType_ != DEVICE_TYPE_NONE) && !IsSameDevice(desc, tmpOutputDeviceDesc)
2212             && desc->deviceType_ != preferredDesc->deviceType_)
2213             || ((preferredDesc->deviceType_ == DEVICE_TYPE_NONE) && !IsSameDevice(desc, tmpOutputDeviceDesc))) {
2214             audioActiveDevice_.SetCurrentOutputDevice(*desc);
2215             AudioDeviceDescriptor curOutputDevice = audioActiveDevice_.GetCurrentOutputDevice();
2216             audioVolumeManager_.SetVolumeForSwitchDevice(curOutputDevice);
2217             audioActiveDevice_.UpdateActiveDeviceRoute(curOutputDevice.deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG,
2218                 curOutputDevice.deviceName_, curOutputDevice.networkId_);
2219             OnPreferredOutputDeviceUpdated(audioActiveDevice_.GetCurrentOutputDevice(), reason);
2220         }
2221         return ERR_NEED_NOT_SWITCH_DEVICE;
2222     }
2223     return SUCCESS;
2224 }
2225 
HandleDeviceChangeForFetchInputDevice(std::shared_ptr<AudioStreamDescriptor> & streamDesc)2226 int32_t AudioCoreService::HandleDeviceChangeForFetchInputDevice(std::shared_ptr<AudioStreamDescriptor> &streamDesc)
2227 {
2228     if (streamDesc->oldDeviceDescs_.size() == 0) {
2229         AUDIO_INFO_LOG("No old device info");
2230         return SUCCESS;
2231     }
2232     std::shared_ptr<AudioDeviceDescriptor> desc = streamDesc->newDeviceDescs_.front();
2233     std::shared_ptr<AudioDeviceDescriptor> oldDeviceDesc = streamDesc->oldDeviceDescs_.front();
2234 
2235     if (desc->deviceType_ == DEVICE_TYPE_NONE ||
2236         (IsSameDevice(desc, oldDeviceDesc) && desc->connectState_ != DEACTIVE_CONNECTED)) {
2237         AUDIO_WARNING_LOG("stream %{public}d device not change, no need move device", streamDesc->sessionId_);
2238         AudioDeviceDescriptor tempDesc = audioActiveDevice_.GetCurrentInputDevice();
2239         std::shared_ptr<AudioDeviceDescriptor> preferredDesc =
2240             audioAffinityManager_.GetCapturerDevice(GetRealUid(streamDesc));
2241         if (((preferredDesc->deviceType_ != DEVICE_TYPE_NONE) && !IsSameDevice(desc, tempDesc) &&
2242             desc->deviceType_ != preferredDesc->deviceType_) ||
2243             IsSameDevice(desc, oldDeviceDesc)) {
2244             audioActiveDevice_.SetCurrentInputDevice(*desc);
2245             // networkId is not used.
2246             OnPreferredInputDeviceUpdated(audioActiveDevice_.GetCurrentInputDeviceType(), "");
2247             audioActiveDevice_.UpdateActiveDeviceRoute(audioActiveDevice_.GetCurrentInputDeviceType(),
2248                 DeviceFlag::INPUT_DEVICES_FLAG, audioActiveDevice_.GetCurrentInputDevice().deviceName_,
2249                 audioActiveDevice_.GetCurrentInputDevice().networkId_);
2250         }
2251         return ERR_NEED_NOT_SWITCH_DEVICE;
2252     }
2253     return SUCCESS;
2254 }
2255 
NeedRehandleA2DPDevice(std::shared_ptr<AudioDeviceDescriptor> & desc)2256 bool AudioCoreService::NeedRehandleA2DPDevice(std::shared_ptr<AudioDeviceDescriptor> &desc)
2257 {
2258     if (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP
2259         && audioIOHandleMap_.CheckIOHandleExist(BLUETOOTH_SPEAKER) == false) {
2260         AUDIO_WARNING_LOG("A2DP module is not loaded, need rehandle");
2261         return true;
2262     }
2263     return false;
2264 }
2265 
IsDeviceSwitching(const AudioStreamDeviceChangeReasonExt reason)2266 bool AudioCoreService::IsDeviceSwitching(const AudioStreamDeviceChangeReasonExt reason)
2267 {
2268     return reason.IsOverride() || reason.IsOldDeviceUnavaliable() || reason.IsNewDeviceAvailable();
2269 }
2270 
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,RendererState rendererState)2271 void AudioCoreService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
2272     RendererState rendererState)
2273 {
2274     const StreamUsage streamUsage = streamChangeInfo.audioRendererChangeInfo.rendererInfo.streamUsage;
2275 
2276     if (mode == AUDIO_MODE_PLAYBACK && (rendererState == RENDERER_STOPPED || rendererState == RENDERER_PAUSED ||
2277         rendererState == RENDERER_RELEASED)) {
2278         audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(streamChangeInfo.audioRendererChangeInfo.sessionId);
2279         if (rendererState == RENDERER_RELEASED) {
2280             audioDeviceManager_.RemoveSelectedDefaultOutputDevice(streamChangeInfo.audioRendererChangeInfo.sessionId);
2281         }
2282         bool isRemoved = true;
2283         sleAudioDeviceManager_.UpdateSleStreamTypeCount(pipeManager_->GetStreamDescById(
2284             streamChangeInfo.audioRendererChangeInfo.sessionId), isRemoved);
2285         FetchOutputDeviceAndRoute("UpdateTracker_1");
2286     }
2287 
2288     const auto &capturerState = streamChangeInfo.audioCapturerChangeInfo.capturerState;
2289     if (mode == AUDIO_MODE_RECORD && capturerState == CAPTURER_RELEASED) {
2290         AUDIO_INFO_LOG("[ADeviceEvent] fetch device for capturer stream %{public}d released",
2291             streamChangeInfo.audioCapturerChangeInfo.sessionId);
2292         audioDeviceManager_.RemoveSelectedInputDevice(streamChangeInfo.audioCapturerChangeInfo.sessionId);
2293         FetchInputDeviceAndRoute("UpdateTracker");
2294     }
2295 
2296     if (enableDualHalToneState_ && (mode == AUDIO_MODE_PLAYBACK)
2297         && (rendererState == RENDERER_STOPPED || rendererState == RENDERER_RELEASED)) {
2298         const int32_t sessionId = streamChangeInfo.audioRendererChangeInfo.sessionId;
2299         if ((sessionId == enableDualHalToneSessionId_) && Util::IsRingerOrAlarmerStreamUsage(streamUsage)) {
2300             AUDIO_INFO_LOG("disable dual hal tone when ringer/alarm renderer stop/release.");
2301             UpdateDualToneState(false, enableDualHalToneSessionId_);
2302         }
2303     }
2304 
2305     if (isRingDualToneOnPrimarySpeaker_ && AudioCoreServiceUtils::IsOverRunPlayback(mode, rendererState) &&
2306         Util::IsRingerOrAlarmerStreamUsage(streamUsage)) {
2307         CHECK_AND_RETURN_LOG(!AudioCoreServiceUtils::IsAlarmOnActive(streamUsage,
2308             streamCollector_.IsStreamActive(AudioVolumeType::STREAM_ALARM)), "alarm still on active");
2309         AUDIO_INFO_LOG("[ADeviceEvent] disable primary speaker dual tone when ringer renderer run over");
2310         isRingDualToneOnPrimarySpeaker_ = false;
2311         // Add delay between end of double ringtone and device switch.
2312         // After the ringtone ends, there may still be residual audio data in the pipeline.
2313         // Switching the device immediately can cause pop noise due the undrained buffers.
2314         usleep(RING_DUAL_END_DELAY_US);
2315         FetchOutputDeviceAndRoute("UpdateTracker_2");
2316         for (std::pair<AudioStreamType, StreamUsage> stream :  streamsWhenRingDualOnPrimarySpeaker_) {
2317             audioPolicyManager_.SetInnerStreamMute(stream.first, false, stream.second);
2318         }
2319         streamsWhenRingDualOnPrimarySpeaker_.clear();
2320         audioPolicyManager_.SetInnerStreamMute(STREAM_MUSIC, false, STREAM_USAGE_MUSIC);
2321     }
2322 }
2323 
HandleCommonSourceOpened(std::shared_ptr<AudioPipeInfo> & pipeInfo)2324 void AudioCoreService::HandleCommonSourceOpened(std::shared_ptr<AudioPipeInfo> &pipeInfo)
2325 {
2326     CHECK_AND_RETURN_LOG(pipeInfo != nullptr && pipeInfo->pipeRole_ == PIPE_ROLE_INPUT &&
2327         pipeInfo->streamDescriptors_.size() > 0 && pipeInfo->streamDescriptors_.front() != nullptr, "Invalid pipeInfo");
2328     auto streamDesc = pipeInfo->streamDescriptors_.front();
2329     CHECK_AND_RETURN_LOG(streamDesc != nullptr, "streamDesc is null");
2330     SourceType sourceType = streamDesc->capturerInfo_.sourceType;
2331     if (specialSourceTypeSet_.count(sourceType) == 0) {
2332         audioEcManager_.PrepareNormalSource(pipeInfo->moduleInfo_, streamDesc);
2333     }
2334 }
2335 
DelayReleaseOffloadPipe(AudioIOHandle id,uint32_t paIndex,OffloadType type)2336 void AudioCoreService::DelayReleaseOffloadPipe(AudioIOHandle id, uint32_t paIndex, OffloadType type)
2337 {
2338     AUDIO_INFO_LOG("In");
2339     CHECK_AND_RETURN_LOG(type < OFFLOAD_TYPE_NUM && isOffloadOpened_[type].load(), "Offload is already released");
2340     isOffloadOpened_[type].store(false);
2341     auto unloadOffloadThreadFuc = [this, id, paIndex, type] { this->ReleaseOffloadPipe(id, paIndex, type); };
2342     std::thread unloadOffloadThread(unloadOffloadThreadFuc);
2343     unloadOffloadThread.detach();
2344 }
2345 
ReleaseOffloadPipe(AudioIOHandle id,uint32_t paIndex,OffloadType type)2346 int32_t AudioCoreService::ReleaseOffloadPipe(AudioIOHandle id, uint32_t paIndex, OffloadType type)
2347 {
2348     AUDIO_INFO_LOG("unload offload module");
2349     std::unique_lock<std::mutex> lock(offloadCloseMutex_);
2350     // Try to wait 10 seconds before unloading the module, because the audio driver takes some time to process
2351     // the shutdown process..
2352     CHECK_AND_RETURN_RET_LOG(type < OFFLOAD_TYPE_NUM, ERR_INVALID_PARAM, "invalid type");
2353     offloadCloseCondition_[type].wait_for(lock, std::chrono::seconds(WAIT_OFFLOAD_CLOSE_TIME_SEC), [this, type] () {
2354         return isOffloadOpened_[type].load();
2355     });
2356 
2357     CHECK_AND_RETURN_RET_LOG(GetEventEntry(), ERR_INVALID_PARAM, "GetEventEntry() return nullptr");
2358     return GetEventEntry()->ReleaseOffloadPipe(id, paIndex, type);
2359 }
2360 
CheckOffloadStream(AudioStreamChangeInfo & streamChangeInfo)2361 void AudioCoreService::CheckOffloadStream(AudioStreamChangeInfo &streamChangeInfo)
2362 {
2363     std::string adapterName = GetAdapterNameBySessionId(streamChangeInfo.audioRendererChangeInfo.sessionId);
2364     AUDIO_INFO_LOG("session: %{public}u, adapter name: %{public}s",
2365         streamChangeInfo.audioRendererChangeInfo.sessionId, adapterName.c_str());
2366     CHECK_AND_RETURN(adapterName == OFFLOAD_PRIMARY_SPEAKER || adapterName.find("_out_offload") != std::string::npos);
2367 
2368     if (streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_PAUSED ||
2369         streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_STOPPED ||
2370         streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_RELEASED) {
2371         audioOffloadStream_.ResetOffloadStatus(streamChangeInfo.audioRendererChangeInfo.sessionId);
2372     }
2373     if (streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_RUNNING) {
2374         audioOffloadStream_.SetOffloadStatus(streamChangeInfo.audioRendererChangeInfo.sessionId);
2375     }
2376 }
2377 
ReConfigOffloadStatus(uint32_t sessionId,std::shared_ptr<AudioPipeInfo> & pipeInfo,std::string & oldSinkName)2378 void AudioCoreService::ReConfigOffloadStatus(uint32_t sessionId,
2379     std::shared_ptr<AudioPipeInfo> &pipeInfo, std::string &oldSinkName)
2380 {
2381     AUDIO_INFO_LOG("new sink: %{public}s, old sink: %{public}s, sessionId: %{public}u",
2382         pipeInfo->moduleInfo_.name.c_str(), oldSinkName.c_str(), sessionId);
2383     if (pipeInfo->moduleInfo_.name == OFFLOAD_PRIMARY_SPEAKER || pipeInfo->moduleInfo_.className == "remote_offload") {
2384         audioOffloadStream_.SetOffloadStatus(sessionId);
2385     } else if (oldSinkName == OFFLOAD_PRIMARY_SPEAKER) {
2386         audioOffloadStream_.ResetOffloadStatus(sessionId);
2387     }
2388 }
2389 
PrepareMoveAttrs(std::shared_ptr<AudioStreamDescriptor> & streamDesc,DeviceType & oldDeviceType,bool & isNeedTriggerCallback,std::string & oldSinkName,const AudioStreamDeviceChangeReasonExt reason)2390 void AudioCoreService::PrepareMoveAttrs(std::shared_ptr<AudioStreamDescriptor> &streamDesc, DeviceType &oldDeviceType,
2391     bool &isNeedTriggerCallback, std::string &oldSinkName, const AudioStreamDeviceChangeReasonExt reason)
2392 {
2393     std::shared_ptr<AudioDeviceDescriptor> newDeviceDesc = streamDesc->newDeviceDescs_.front();
2394     oldDeviceType = streamDesc->oldDeviceDescs_.front()->deviceType_;
2395     if (streamDesc->oldDeviceDescs_.front()->IsSameDeviceDesc(newDeviceDesc)) {
2396         isNeedTriggerCallback = false;
2397     }
2398     oldSinkName = AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->oldDeviceDescs_.front(),
2399         streamDesc->sessionId_);
2400 
2401     AUDIO_INFO_LOG("[StreamExecInfo] Move stream %{public}u, [%{public}d][%{public}s] to [%{public}d][%{public}s]" \
2402         " reason %{public}d",
2403         streamDesc->sessionId_, streamDesc->oldDeviceDescs_.front()->deviceType_,
2404         GetEncryptAddr(streamDesc->oldDeviceDescs_.front()->macAddress_).c_str(), newDeviceDesc->deviceType_,
2405         GetEncryptAddr(newDeviceDesc->macAddress_).c_str(), static_cast<int32_t>(reason));
2406 }
2407 
MuteSinkPortForSwitchDevice(std::shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)2408 void AudioCoreService::MuteSinkPortForSwitchDevice(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2409     const AudioStreamDeviceChangeReasonExt reason)
2410 {
2411     Trace trace("AudioCoreService::MuteSinkPortForSwitchDevice");
2412     if (streamDesc->newDeviceDescs_.front()->IsSameDeviceDesc(streamDesc->oldDeviceDescs_.front())) {
2413         return;
2414     }
2415 
2416     audioIOHandleMap_.SetMoveFinish(false);
2417 
2418     std::string oldSinkName = AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->oldDeviceDescs_.front(),
2419         streamDesc->sessionId_);
2420     std::string newSinkName = AudioPolicyUtils::GetInstance().GetSinkName(*streamDesc->newDeviceDescs_.front(),
2421         streamDesc->sessionId_);
2422     AUDIO_INFO_LOG("mute sink old:[%{public}s] new:[%{public}s]", oldSinkName.c_str(), newSinkName.c_str());
2423     MuteSinkPort(oldSinkName, newSinkName, reason);
2424 }
2425 
2426 // After media playback is interrupted by the alarm or ring,
2427 // a delay is required before switching to dual output (e.g., speaker + headset).
2428 // This ensures that the remaining audio buffer is drained,
2429 // preventing any residual media sound from leaking through the speaker.
CheckAndSleepBeforeRingDualDeviceSet(std::shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)2430 void AudioCoreService::CheckAndSleepBeforeRingDualDeviceSet(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2431     const AudioStreamDeviceChangeReasonExt reason)
2432 {
2433     CHECK_AND_RETURN_LOG(streamDesc != nullptr && !streamDesc->newDeviceDescs_.empty(), "Invalid streamDesc");
2434     bool isRingOrAlarmStream = Util::IsRingerOrAlarmerStreamUsage(streamDesc->rendererInfo_.streamUsage);
2435     DeviceType deviceType = streamDesc->newDeviceDescs_.front()->deviceType_;
2436     if (streamDesc->streamStatus_ == STREAM_STATUS_NEW && reason.IsSetAudioScene() &&
2437         streamDesc->newDeviceDescs_.size() > 1 && streamCollector_.IsMediaPlaying() &&
2438         IsRingerOrAlarmerDualDevicesRange(deviceType) && isRingOrAlarmStream) {
2439         usleep(MEDIA_PAUSE_TO_DOUBLE_RING_DELAY_US);
2440     }
2441 }
2442 
2443 /**
2444  * Sleep for a short duration after muting during device switching.
2445  * This allows the underlying audio buffer to drain residual data before switching to the new output device,
2446  * helping to avoid audio artifacts such as leakage or pop noise.
2447 */
SleepForSwitchDevice(std::shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)2448 void AudioCoreService::SleepForSwitchDevice(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2449     const AudioStreamDeviceChangeReasonExt reason)
2450 {
2451     CHECK_AND_RETURN_LOG(streamDesc != nullptr && !streamDesc->oldDeviceDescs_.empty() &&
2452         !streamDesc->newDeviceDescs_.empty(), "Invalid streamDesc");
2453     std::shared_ptr<AudioDeviceDescriptor> oldDesc = streamDesc->oldDeviceDescs_.front();
2454     std::shared_ptr<AudioDeviceDescriptor> newDesc = streamDesc->newDeviceDescs_.front();
2455     CHECK_AND_RETURN(oldDesc != nullptr && newDesc != nullptr);
2456     if (oldDesc->IsSameDeviceDesc(*newDesc)) { return; }
2457 
2458     std::string oldSinkName = AudioPolicyUtils::GetInstance().GetSinkName(oldDesc, streamDesc->sessionId_);
2459     bool isOldDeviceUnavailable = reason.IsOldDeviceUnavaliable() || reason.IsOldDeviceUnavaliableExt();
2460     bool isHeadsetToSpkOrEp = IsHeadsetToSpkOrEp(oldDesc, newDesc);
2461     bool isSleepScene = IsSceneRequireMuteAndSleep();
2462 
2463     struct SleepStrategy {
2464         std::function<bool()> condition;
2465         std::vector<uint32_t> sleepDurations;
2466     };
2467 
2468     std::vector<SleepStrategy> strategies = {
2469         {
2470             [&]() { return reason.IsOverride() || reason.IsSetDefaultOutputDevice() || reason.IsNewDeviceAvailable(); },
2471             {BASE_DEVICE_SWITCH_SLEEP_US, BASE_DEVICE_SWITCH_SLEEP_US}
2472         },
2473         {
2474             [&]() { return reason.IsDistributedDeviceUnavailable(); },
2475             {BASE_DEVICE_SWITCH_SLEEP_US, DISTRIBUTED_DEVICE_UNAVAILABLE_EXTRA_SLEEP_US}
2476         },
2477         {
2478             [&]() { return isOldDeviceUnavailable && isSleepScene && isHeadsetToSpkOrEp; },
2479             {BASE_DEVICE_SWITCH_SLEEP_US, OLD_DEVICE_UNAVAILABLE_EXTRA_SLEEP_US, HEADSET_TO_SPK_EP_EXTRA_SLEEP_US}
2480         },
2481         {
2482             [&]() { return isOldDeviceUnavailable && isSleepScene; },
2483             {BASE_DEVICE_SWITCH_SLEEP_US, OLD_DEVICE_UNAVAILABLE_EXTRA_SLEEP_US}
2484         },
2485         {
2486             [&]() { return reason.IsUnknown() || oldSinkName == REMOTE_CAST_INNER_CAPTURER_SINK_NAME; },
2487             {BASE_DEVICE_SWITCH_SLEEP_US}
2488         },
2489     };
2490 
2491     for (const auto &strategy : strategies) {
2492         if (strategy.condition()) {
2493             for (auto sleepTime : strategy.sleepDurations) {
2494                 usleep(sleepTime);
2495             }
2496             return;
2497         }
2498     }
2499 }
2500 
IsHeadsetToSpkOrEp(const std::shared_ptr<AudioDeviceDescriptor> & oldDesc,const std::shared_ptr<AudioDeviceDescriptor> & newDesc)2501 bool AudioCoreService::IsHeadsetToSpkOrEp(const std::shared_ptr<AudioDeviceDescriptor> &oldDesc,
2502     const std::shared_ptr<AudioDeviceDescriptor> &newDesc)
2503 {
2504     CHECK_AND_RETURN_RET(oldDesc != nullptr, false);
2505     CHECK_AND_RETURN_RET(newDesc != nullptr, false);
2506     DeviceType oldDeviceType = oldDesc->deviceType_;
2507     DeviceType newDeviceType = newDesc->deviceType_;
2508     return (oldDeviceType == DEVICE_TYPE_USB_HEADSET || oldDeviceType == DEVICE_TYPE_USB_ARM_HEADSET) &&
2509         (newDeviceType == DEVICE_TYPE_SPEAKER || newDeviceType == DEVICE_TYPE_EARPIECE);
2510 }
2511 
2512 /**
2513  * Check whether the current audio scene requires mute and sleep handling.
2514  * This function is only used in audio switching logic when disconnecting a device,
2515  * specifically within MuteSinkPortForSwitchDevice and SleepForSwitchDevice.
2516 */
IsSceneRequireMuteAndSleep()2517 bool AudioCoreService::IsSceneRequireMuteAndSleep()
2518 {
2519     AudioRingerMode ringerMode = audioPolicyManager_.GetRingerMode();
2520     AudioScene scene = audioSceneManager_.GetAudioScene(true);
2521     return (scene == AUDIO_SCENE_DEFAULT) || (scene == AUDIO_SCENE_PHONE_CHAT) ||
2522         ((scene == AUDIO_SCENE_RINGING || scene == AUDIO_SCENE_VOICE_RINGING) && ringerMode != RINGER_MODE_NORMAL);
2523 }
2524 
SetVoiceCallMuteForSwitchDevice()2525 void AudioCoreService::SetVoiceCallMuteForSwitchDevice()
2526 {
2527     Trace trace("AudioCoreService::SetVoiceMuteForSwitchDevice");
2528     AudioServerProxy::GetInstance().SetVoiceVolumeProxy(0);
2529 
2530     AUDIO_INFO_LOG("%{public}" PRId64" us for modem call update route", WAIT_MODEM_CALL_SET_VOLUME_TIME_US);
2531     usleep(WAIT_MODEM_CALL_SET_VOLUME_TIME_US);
2532     // Unmute in SetVolumeForSwitchDevice after update route.
2533 }
2534 
MuteSinkPort(const std::string & oldSinkName,const std::string & newSinkName,AudioStreamDeviceChangeReasonExt reason)2535 void AudioCoreService::MuteSinkPort(const std::string &oldSinkName, const std::string &newSinkName,
2536     AudioStreamDeviceChangeReasonExt reason)
2537 {
2538     if (reason.IsOverride() || reason.IsSetDefaultOutputDevice()) {
2539         int64_t muteTime = SELECT_DEVICE_MUTE_MS;
2540         if (newSinkName == OFFLOAD_PRIMARY_SPEAKER || oldSinkName == OFFLOAD_PRIMARY_SPEAKER) {
2541             muteTime = SELECT_OFFLOAD_DEVICE_MUTE_MS;
2542         }
2543         MutePrimaryOrOffloadSink(newSinkName, muteTime);
2544         audioIOHandleMap_.MuteSinkPort(newSinkName, SELECT_DEVICE_MUTE_MS, true, false);
2545         audioIOHandleMap_.MuteSinkPort(oldSinkName, muteTime, true, false);
2546     } else if (reason == AudioStreamDeviceChangeReason::NEW_DEVICE_AVAILABLE) {
2547         int64_t muteTime = NEW_DEVICE_AVALIABLE_MUTE_MS;
2548         if (newSinkName == OFFLOAD_PRIMARY_SPEAKER || oldSinkName == OFFLOAD_PRIMARY_SPEAKER) {
2549             muteTime = NEW_DEVICE_AVALIABLE_OFFLOAD_MUTE_MS;
2550         }
2551         MutePrimaryOrOffloadSink(oldSinkName, muteTime);
2552         audioIOHandleMap_.MuteSinkPort(newSinkName, NEW_DEVICE_AVALIABLE_MUTE_MS, true, false);
2553         audioIOHandleMap_.MuteSinkPort(oldSinkName, muteTime, true, false);
2554     }
2555     MuteSinkPortLogic(oldSinkName, newSinkName, reason);
2556 }
2557 
MutePrimaryOrOffloadSink(const std::string & sinkName,int64_t muteTime)2558 void AudioCoreService::MutePrimaryOrOffloadSink(const std::string &sinkName, int64_t muteTime)
2559 {
2560     // Fix sinkPort mute error caused by incorrect pipeType
2561     if (sinkName == OFFLOAD_PRIMARY_SPEAKER) {
2562         audioIOHandleMap_.MuteSinkPort(PRIMARY_SPEAKER, muteTime, true, false);
2563     } else if (sinkName == PRIMARY_SPEAKER) {
2564         audioIOHandleMap_.MuteSinkPort(OFFLOAD_PRIMARY_SPEAKER, muteTime, true, false);
2565     }
2566 }
2567 
MuteSinkPortLogic(const std::string & oldSinkName,const std::string & newSinkName,AudioStreamDeviceChangeReasonExt reason)2568 void AudioCoreService::MuteSinkPortLogic(const std::string &oldSinkName, const std::string &newSinkName,
2569     AudioStreamDeviceChangeReasonExt reason)
2570 {
2571     auto ringermode = audioPolicyManager_.GetRingerMode();
2572     AudioScene scene = audioSceneManager_.GetAudioScene(true);
2573     if (reason.IsDistributedDeviceUnavailable()) {
2574         audioIOHandleMap_.MuteSinkPort(newSinkName, DISTRIBUTED_DEVICE_UNAVALIABLE_MUTE_MS, true, false);
2575     } else if (reason.IsOldDeviceUnavaliable() && ((scene == AUDIO_SCENE_DEFAULT) ||
2576         ((scene == AUDIO_SCENE_RINGING || scene == AUDIO_SCENE_VOICE_RINGING) &&
2577         ringermode != RINGER_MODE_NORMAL) || (scene == AUDIO_SCENE_PHONE_CHAT))) {
2578         MutePrimaryOrOffloadSink(newSinkName, OLD_DEVICE_UNAVALIABLE_MUTE_MS);
2579         audioIOHandleMap_.MuteSinkPort(newSinkName, OLD_DEVICE_UNAVALIABLE_MUTE_MS, true, false);
2580     } else if (reason.IsOldDeviceUnavaliableExt() && ((scene == AUDIO_SCENE_DEFAULT) ||
2581         ((scene == AUDIO_SCENE_RINGING || scene == AUDIO_SCENE_VOICE_RINGING) &&
2582         ringermode != RINGER_MODE_NORMAL) || (scene == AUDIO_SCENE_PHONE_CHAT))) {
2583         audioIOHandleMap_.MuteSinkPort(newSinkName, OLD_DEVICE_UNAVALIABLE_EXT_MUTE_MS, true, false);
2584     } else if (reason == AudioStreamDeviceChangeReason::UNKNOWN &&
2585         oldSinkName == REMOTE_CAST_INNER_CAPTURER_SINK_NAME) {
2586         // remote cast -> earpiece 300ms fix sound leak
2587         audioIOHandleMap_.MuteSinkPort(newSinkName, NEW_DEVICE_REMOTE_CAST_AVALIABLE_MUTE_MS, true, false);
2588     }
2589 }
2590 
ActivateOutputDevice(std::shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)2591 int32_t AudioCoreService::ActivateOutputDevice(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2592     const AudioStreamDeviceChangeReasonExt reason)
2593 {
2594     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, ERR_NULL_POINTER, "Stream desc is nullptr");
2595     std::shared_ptr<AudioDeviceDescriptor> deviceDesc = streamDesc->newDeviceDescs_.front();
2596 
2597     std::string encryptMacAddr = GetEncryptAddr(deviceDesc->macAddress_);
2598     int32_t bluetoothFetchResult = BluetoothDeviceFetchOutputHandle(streamDesc, reason, encryptMacAddr);
2599     CheckAndWriteDeviceChangeExceptionEvent(bluetoothFetchResult == BLUETOOTH_FETCH_RESULT_DEFAULT, reason,
2600         deviceDesc->deviceType_, deviceDesc->deviceRole_, bluetoothFetchResult, "bluetooth fetch output device failed");
2601     CHECK_AND_RETURN_RET(bluetoothFetchResult == BLUETOOTH_FETCH_RESULT_DEFAULT, ERR_OPERATION_FAILED);
2602 
2603     int32_t nearlinkFetchResult = ActivateNearlinkDevice(streamDesc);
2604     CheckAndWriteDeviceChangeExceptionEvent(nearlinkFetchResult == SUCCESS, reason,
2605         deviceDesc->deviceType_, deviceDesc->deviceRole_, nearlinkFetchResult, "nearlink fetch output device failed");
2606     CHECK_AND_RETURN_RET_LOG(nearlinkFetchResult == SUCCESS, ERROR, "nearlink fetch output device failed");
2607 
2608     if (deviceDesc->deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
2609         audioEcManager_.ActivateArmDevice(deviceDesc->macAddress_, deviceDesc->deviceRole_);
2610     }
2611     if (deviceDesc->deviceType_ == DEVICE_TYPE_HEARING_AID) {
2612         SwitchActiveHearingAidDevice(std::make_shared<AudioDeviceDescriptor>(deviceDesc));
2613     }
2614     return SUCCESS;
2615 }
2616 
ActivateInputDevice(std::shared_ptr<AudioStreamDescriptor> & streamDesc)2617 int32_t AudioCoreService::ActivateInputDevice(std::shared_ptr<AudioStreamDescriptor> &streamDesc)
2618 {
2619     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr && streamDesc->newDeviceDescs_.size() > 0 &&
2620         streamDesc->newDeviceDescs_[0] != nullptr, ERR_INVALID_PARAM, "Invalid stream desc");
2621     if (streamDesc->newDeviceDescs_[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
2622         BluetoothScoFetch(streamDesc);
2623     }
2624 
2625     int32_t nearlinkFetchResult = ActivateNearlinkDevice(streamDesc);
2626     CHECK_AND_RETURN_RET_LOG(nearlinkFetchResult == SUCCESS, ERROR, "nearlink fetch input device failed");
2627 
2628     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr && streamDesc->newDeviceDescs_.size() > 0 &&
2629         streamDesc->newDeviceDescs_[0] != nullptr, ERR_INVALID_PARAM, "Invalid stream desc");
2630     std::shared_ptr<AudioDeviceDescriptor> deviceDesc = streamDesc->newDeviceDescs_.front();
2631     if (deviceDesc->deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) {
2632         audioEcManager_.ActivateArmDevice(deviceDesc->macAddress_, deviceDesc->deviceRole_);
2633     }
2634 
2635     return SUCCESS;
2636 }
2637 
OnAudioSceneChange(const AudioScene & audioScene)2638 void AudioCoreService::OnAudioSceneChange(const AudioScene& audioScene)
2639 {
2640     Trace trace("AudioCoreService::OnAudioSceneChange:" + std::to_string(audioScene));
2641     AUDIO_INFO_LOG("scene change to %{public}d", audioScene);
2642     CHECK_AND_RETURN_LOG(audioPolicyServerHandler_ != nullptr, "audio policy server handler is null");
2643     audioPolicyServerHandler_->SendAudioSceneChangeEvent(audioScene);
2644 }
2645 
HandleOutputStreamInRunning(std::shared_ptr<AudioStreamDescriptor> & streamDesc,AudioStreamDeviceChangeReasonExt reason)2646 bool AudioCoreService::HandleOutputStreamInRunning(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2647     AudioStreamDeviceChangeReasonExt reason)
2648 {
2649     if (streamDesc->streamStatus_ != STREAM_STATUS_STARTED) {
2650         return true;
2651     }
2652     if (HandleDeviceChangeForFetchOutputDevice(streamDesc, reason) == ERR_NEED_NOT_SWITCH_DEVICE &&
2653         !Util::IsRingerOrAlarmerStreamUsage(streamDesc->rendererInfo_.streamUsage)) {
2654         return false;
2655     }
2656     return true;
2657 }
2658 
HandleInputStreamInRunning(std::shared_ptr<AudioStreamDescriptor> & streamDesc)2659 bool AudioCoreService::HandleInputStreamInRunning(std::shared_ptr<AudioStreamDescriptor> &streamDesc)
2660 {
2661     if (streamDesc->streamStatus_ != STREAM_STATUS_STARTED) {
2662         return true;
2663     }
2664     if (HandleDeviceChangeForFetchInputDevice(streamDesc) == ERR_NEED_NOT_SWITCH_DEVICE) {
2665         return false;
2666     }
2667     return true;
2668 }
2669 
HandleDualStartClient(std::vector<std::pair<DeviceType,DeviceFlag>> & activeDevices,std::shared_ptr<AudioStreamDescriptor> & streamDesc)2670 void AudioCoreService::HandleDualStartClient(std::vector<std::pair<DeviceType, DeviceFlag>> &activeDevices,
2671     std::shared_ptr<AudioStreamDescriptor> &streamDesc)
2672 {
2673     CHECK_AND_RETURN_LOG(streamDesc != nullptr && streamDesc->newDeviceDescs_.size() > 1, "Invalid params");
2674     std::string firstSinkName =
2675         AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->newDeviceDescs_[0], streamDesc->sessionId_);
2676     std::string secondSinkName =
2677         AudioPolicyUtils::GetInstance().GetSinkName(streamDesc->newDeviceDescs_[1], streamDesc->sessionId_);
2678     AUDIO_INFO_LOG("firstSinkName %{public}s, secondSinkName %{public}s",
2679         firstSinkName.c_str(), secondSinkName.c_str());
2680     if (firstSinkName == secondSinkName) {
2681         activeDevices.push_back(
2682             make_pair(streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG));
2683         activeDevices.push_back(
2684             make_pair(streamDesc->newDeviceDescs_[1]->deviceType_, DeviceFlag::OUTPUT_DEVICES_FLAG));
2685     }
2686 }
2687 
HandlePlaybackStreamInA2dp(std::shared_ptr<AudioStreamDescriptor> & streamDesc,bool isCreateProcess)2688 void AudioCoreService::HandlePlaybackStreamInA2dp(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2689     bool isCreateProcess)
2690 {
2691 #ifdef BLUETOOTH_ENABLE
2692     CHECK_AND_RETURN_LOG(streamDesc != nullptr && streamDesc->newDeviceDescs_.size() > 0 &&
2693         streamDesc->newDeviceDescs_[0] != nullptr, "Invalid stream desc");
2694     CHECK_AND_RETURN(streamDesc->newDeviceDescs_[0]->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP); // no need log
2695     vector<Bluetooth::A2dpStreamInfo> allSessionInfos;
2696     Bluetooth::A2dpStreamInfo a2dpStreamInfo;
2697     vector<shared_ptr<AudioRendererChangeInfo>> audioRendererChangeInfos;
2698     streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
2699 
2700     for (auto &changeInfo : audioRendererChangeInfos) {
2701         a2dpStreamInfo.sessionId = changeInfo->sessionId;
2702         a2dpStreamInfo.streamType = streamCollector_.GetStreamType(changeInfo->sessionId);
2703         StreamUsage tempStreamUsage = changeInfo->rendererInfo.streamUsage;
2704         AudioSpatializationState spatialState =
2705             AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState(tempStreamUsage);
2706         a2dpStreamInfo.isSpatialAudio = spatialState.spatializationEnabled;
2707         allSessionInfos.push_back(a2dpStreamInfo);
2708     }
2709     if (isCreateProcess) {
2710         a2dpStreamInfo.sessionId = static_cast<int32_t>(streamDesc->sessionId_);
2711         StreamUsage tempStreamUsage = streamDesc->rendererInfo_.streamUsage;
2712         a2dpStreamInfo.streamType =
2713             streamCollector_.GetStreamType(streamDesc->rendererInfo_.contentType, tempStreamUsage);
2714         AudioSpatializationState spatialState =
2715             AudioSpatializationService::GetAudioSpatializationService().GetSpatializationState(tempStreamUsage);
2716         a2dpStreamInfo.isSpatialAudio = spatialState.spatializationEnabled;
2717         allSessionInfos.push_back(a2dpStreamInfo);
2718     }
2719     auto flag =
2720         static_cast<BluetoothOffloadState>(Bluetooth::AudioA2dpManager::A2dpOffloadSessionRequest(allSessionInfos));
2721     streamDesc->newDeviceDescs_[0]->a2dpOffloadFlag_ = flag;
2722     AUDIO_INFO_LOG("A2dp offload flag:%{public}d isCreate:%{public}s", flag, isCreateProcess ? "true" : "false");
2723 #endif
2724 }
2725 
GetDisableFastStreamParam()2726 bool AudioCoreService::GetDisableFastStreamParam()
2727 {
2728     int32_t disableFastStream = 1; // default 1, set disableFastStream true
2729     GetSysPara("persist.multimedia.audioflag.fastcontrolled", disableFastStream);
2730     return disableFastStream == 0 ? false : true;
2731 }
2732 
IsFastAllowed(std::string & bundleName)2733 bool AudioCoreService::IsFastAllowed(std::string &bundleName)
2734 {
2735     CHECK_AND_RETURN_RET(bundleName != "", true);
2736     std::string bundleNamePre = CHECK_FAST_BLOCK_PREFIX + bundleName;
2737     std::string result = AudioServerProxy::GetInstance().GetAudioParameterProxy(bundleNamePre);
2738     if (result == "true") { // "true" means in control
2739         AUDIO_INFO_LOG("%{public}s not in fast list", bundleName.c_str());
2740         return false;
2741     }
2742     return true;
2743 }
2744 
ResetNearlinkDeviceState(const std::shared_ptr<AudioDeviceDescriptor> & deviceDesc)2745 void AudioCoreService::ResetNearlinkDeviceState(const std::shared_ptr<AudioDeviceDescriptor> &deviceDesc)
2746 {
2747     CHECK_AND_RETURN_LOG(deviceDesc != nullptr, "deviceDesc is nullptr");
2748 
2749     auto currentOutputDevice = audioActiveDevice_.GetCurrentOutputDevice();
2750     auto currentInputDevice = audioActiveDevice_.GetCurrentInputDevice();
2751     if (deviceDesc->deviceType_ == DEVICE_TYPE_NEARLINK && currentOutputDevice.deviceType_ == DEVICE_TYPE_NEARLINK) {
2752         if (!deviceDesc->IsSameDeviceDesc(currentOutputDevice)) {
2753             AUDIO_INFO_LOG("Reset nearlink output device state, macAddress: %{public}s",
2754                 AudioPolicyUtils::GetInstance().GetEncryptAddr(currentOutputDevice.macAddress_).c_str());
2755             sleAudioDeviceManager_.ResetSleStreamTypeCount(
2756                 std::make_shared<AudioDeviceDescriptor>(currentOutputDevice));
2757         }
2758     }
2759     if (deviceDesc->deviceType_ == DEVICE_TYPE_NEARLINK_IN &&
2760         currentInputDevice.deviceType_ == DEVICE_TYPE_NEARLINK_IN) {
2761         if (!deviceDesc->IsSameDeviceDesc(currentInputDevice)) {
2762             AUDIO_INFO_LOG("Reset nearlink input device state, macAddress: %{public}s",
2763                 AudioPolicyUtils::GetInstance().GetEncryptAddr(currentInputDevice.macAddress_).c_str());
2764             sleAudioDeviceManager_.ResetSleStreamTypeCount(
2765                 std::make_shared<AudioDeviceDescriptor>(currentInputDevice));
2766         }
2767     }
2768 }
2769 
ActivateNearlinkDevice(const std::shared_ptr<AudioStreamDescriptor> & streamDesc,const AudioStreamDeviceChangeReasonExt reason)2770 int32_t AudioCoreService::ActivateNearlinkDevice(const std::shared_ptr<AudioStreamDescriptor> &streamDesc,
2771     const AudioStreamDeviceChangeReasonExt reason)
2772 {
2773     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, ERR_INVALID_PARAM, "Stream desc is nullptr");
2774     auto deviceDesc = streamDesc->newDeviceDescs_.front();
2775     CHECK_AND_RETURN_RET_LOG(deviceDesc != nullptr, ERR_INVALID_PARAM, "Device desc is nullptr");
2776 
2777     std::variant<StreamUsage, SourceType> audioStreamConfig;
2778     bool isRunning = streamDesc->streamStatus_ == STREAM_STATUS_STARTED;
2779     bool isRecognitionSource = false;
2780     if (streamDesc->audioMode_ == AUDIO_MODE_PLAYBACK) {
2781         audioStreamConfig = streamDesc->rendererInfo_.streamUsage;
2782     } else {
2783         audioStreamConfig = streamDesc->capturerInfo_.sourceType;
2784         isRecognitionSource = Util::IsScoSupportSource(streamDesc->capturerInfo_.sourceType);
2785     }
2786     if (deviceDesc->deviceType_ == DEVICE_TYPE_NEARLINK || deviceDesc->deviceType_ == DEVICE_TYPE_NEARLINK_IN) {
2787         auto runDeviceActivationFlow = [this, &deviceDesc, &isRunning](auto &&config) -> int32_t {
2788             int32_t ret = sleAudioDeviceManager_.SetActiveDevice(*deviceDesc, config);
2789             CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Activating Nearlink device fails");
2790             CHECK_AND_RETURN_RET_LOG(isRunning, ret, "Stream is not runningf, no needs start playing");
2791             return sleAudioDeviceManager_.StartPlaying(*deviceDesc, config);
2792         };
2793         if (isRecognitionSource) {
2794             AudioServerProxy::GetInstance().SetDmDeviceTypeProxy(DM_DEVICE_TYPE_NEARLINK_SCO, DEVICE_TYPE_NEARLINK_IN);
2795         }
2796         ResetNearlinkDeviceState(deviceDesc);
2797         int32_t result = std::visit(runDeviceActivationFlow, audioStreamConfig);
2798         if (result != SUCCESS) {
2799             AUDIO_ERR_LOG("Nearlink device activation failed, macAddress: %{public}s",
2800                 GetEncryptAddr(deviceDesc->macAddress_).c_str());
2801             deviceDesc->exceptionFlag_ = true;
2802             audioDeviceManager_.UpdateDevicesListInfo(deviceDesc, EXCEPTION_FLAG_UPDATE);
2803             if (deviceDesc->deviceType_ == DEVICE_TYPE_NEARLINK) {
2804                 FetchOutputDeviceAndRoute("ActivateNearlinkDevice", reason);
2805             } else {
2806                 FetchInputDeviceAndRoute("ActivateNearlinkDevice");
2807             }
2808         }
2809     }
2810     return SUCCESS;
2811 }
2812 
SwitchActiveHearingAidDevice(std::shared_ptr<AudioDeviceDescriptor> deviceDescriptor)2813 int32_t AudioCoreService::SwitchActiveHearingAidDevice(std::shared_ptr<AudioDeviceDescriptor> deviceDescriptor)
2814 {
2815     CHECK_AND_RETURN_RET_LOG(deviceDescriptor != nullptr &&
2816         audioA2dpDevice_.CheckHearingAidDeviceExist(deviceDescriptor->macAddress_),
2817         ERR_INVALID_PARAM, "Target HearingAid device doesn't exist.");
2818     int32_t result = ERROR;
2819 #ifdef BLUETOOTH_ENABLE
2820     if (audioIOHandleMap_.CheckIOHandleExist(HEARING_AID_SPEAKER)) {
2821         AUDIO_WARNING_LOG("HearingAid device [%{public}s] [%{public}s] is already active",
2822             GetEncryptAddr(deviceDescriptor->macAddress_).c_str(), deviceDescriptor->deviceName_.c_str());
2823         return SUCCESS;
2824     }
2825 
2826     AudioStreamInfo audioStreamInfo = {};
2827     DeviceStreamInfo hearingAidStreamInfo = deviceDescriptor->GetDeviceStreamInfo();
2828     audioStreamInfo.samplingRate = hearingAidStreamInfo.samplingRate.empty() ? AudioSamplingRate::SAMPLE_RATE_16000 :
2829         *hearingAidStreamInfo.samplingRate.rbegin();
2830     audioStreamInfo.encoding = hearingAidStreamInfo.encoding;
2831     audioStreamInfo.format = hearingAidStreamInfo.format;
2832     audioStreamInfo.channelLayout = hearingAidStreamInfo.channelLayout.empty() ? AudioChannelLayout::CH_LAYOUT_UNKNOWN :
2833         *hearingAidStreamInfo.channelLayout.rbegin();
2834     audioStreamInfo.channels = hearingAidStreamInfo.GetChannels().empty() ? AudioChannel::CHANNEL_UNKNOW :
2835         *hearingAidStreamInfo.GetChannels().rbegin();
2836 
2837     std::string networkId = audioActiveDevice_.GetCurrentOutputDeviceNetworkId();
2838     std::string sinkName = AudioPolicyUtils::GetInstance().GetSinkPortName(DEVICE_TYPE_HEARING_AID);
2839     result = LoadHearingAidModule(DEVICE_TYPE_HEARING_AID, audioStreamInfo, networkId, sinkName, SOURCE_TYPE_INVALID);
2840     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "LoadHearingAidModule failed %{public}d", result);
2841 #endif
2842     return result;
2843 }
2844 
LoadHearingAidModule(DeviceType deviceType,const AudioStreamInfo & audioStreamInfo,std::string networkId,std::string sinkName,SourceType sourceType)2845 int32_t AudioCoreService::LoadHearingAidModule(DeviceType deviceType, const AudioStreamInfo &audioStreamInfo,
2846     std::string networkId, std::string sinkName, SourceType sourceType)
2847 {
2848     std::list<AudioModuleInfo> moduleInfoList;
2849     bool ret = policyConfigMananger_.GetModuleListByType(ClassType::TYPE_HEARING_AID, moduleInfoList);
2850     CHECK_AND_RETURN_RET_LOG(ret, ERR_OPERATION_FAILED, "HearingAid module is not exist in the configuration file");
2851 
2852     int32_t loadRet = AudioServerProxy::GetInstance().LoadHdiAdapterProxy(HDI_DEVICE_MANAGER_TYPE_BLUETOOTH,
2853         "bt_hearing_aid");
2854     if (loadRet) {
2855         AUDIO_ERR_LOG("load adapter failed");
2856     }
2857     for (auto &moduleInfo : moduleInfoList) {
2858         if (moduleInfo.role != "sink") {
2859             AUDIO_INFO_LOG("Load hearingAid module [%{public}s], role[%{public}s]",
2860                 moduleInfo.name.c_str(), moduleInfo.role.c_str());
2861             continue;
2862         }
2863         DeviceRole configRole = OUTPUT_DEVICE;
2864         DeviceRole deviceRole = deviceType == DEVICE_TYPE_HEARING_AID ? OUTPUT_DEVICE : INPUT_DEVICE;
2865         AUDIO_INFO_LOG("Load hearingAid module [%{public}s], role[%{public}d], config role[%{public}d]",
2866             moduleInfo.name.c_str(), deviceRole, configRole);
2867         if (configRole != deviceRole) {continue;}
2868         if (audioIOHandleMap_.CheckIOHandleExist(moduleInfo.name) == false) {
2869             AUDIO_INFO_LOG("hearingAid device connects for the first time");
2870             // HearingAid device connects for the first time
2871             GetA2dpModuleInfo(moduleInfo, audioStreamInfo, sourceType);
2872             uint32_t paIndex = 0;
2873             AudioIOHandle ioHandle = audioPolicyManager_.OpenAudioPort(moduleInfo, paIndex);
2874             CHECK_AND_RETURN_RET_LOG(ioHandle != HDI_INVALID_ID,
2875                 ERR_INVALID_HANDLE, "OpenAudioPort failed ioHandle[%{public}u]", ioHandle);
2876             CHECK_AND_RETURN_RET_LOG(paIndex != OPEN_PORT_FAILURE,
2877                 ERR_OPERATION_FAILED, "OpenAudioPort failed paId[%{public}u]", paIndex);
2878             audioIOHandleMap_.AddIOHandleInfo(moduleInfo.name, ioHandle);
2879 
2880             std::shared_ptr<AudioPipeInfo> pipeInfo = std::make_shared<AudioPipeInfo>();
2881             pipeInfo->id_ = ioHandle;
2882             pipeInfo->paIndex_ = paIndex;
2883             pipeInfo->name_ = "hearing_aid_output";
2884             pipeInfo->pipeRole_ = PIPE_ROLE_OUTPUT;
2885             pipeInfo->routeFlag_ = AUDIO_OUTPUT_FLAG_NORMAL;
2886             pipeInfo->adapterName_ = "hearing_aid";
2887             pipeInfo->moduleInfo_ = moduleInfo;
2888             pipeInfo->pipeAction_ = PIPE_ACTION_DEFAULT;
2889             pipeInfo->InitAudioStreamInfo();
2890             pipeManager_->AddAudioPipeInfo(pipeInfo);
2891             AUDIO_INFO_LOG("Add PipeInfo %{public}u in load hearingAid.", pipeInfo->id_);
2892         }
2893     }
2894 
2895     return SUCCESS;
2896 }
2897 
GetAppState(int32_t appPid)2898 static AppExecFwk::AppProcessState GetAppState(int32_t appPid)
2899 {
2900     OHOS::AppExecFwk::AppMgrClient appManager;
2901     OHOS::AppExecFwk::RunningProcessInfo infos;
2902     int32_t res = appManager.GetRunningProcessInfoByPid(appPid, infos);
2903     if (res != ERR_OK) {
2904         AUDIO_WARNING_LOG("GetRunningProcessInfoByPid failed, appPid=%{public}d", appPid);
2905     }
2906     return infos.state_;
2907 }
2908 
GetTimeCostFrom(int64_t timeNS)2909 static uint32_t GetTimeCostFrom(int64_t timeNS)
2910 {
2911     return static_cast<uint32_t>((ClockTime::GetCurNano() - timeNS) / AUDIO_NS_PER_SECOND);
2912 }
2913 
GetHdiInfo(uint8_t & hdiSourceType,std::string & hdiSourceAlg)2914 static void GetHdiInfo(uint8_t &hdiSourceType, std::string &hdiSourceAlg)
2915 {
2916     std::string hdiInfoStr = AudioServerProxy::GetInstance().GetAudioParameterProxy("concurrent_capture_stream_info");
2917     AUDIO_INFO_LOG("hdiInfo = %{public}s", hdiInfoStr.c_str());
2918 
2919     std::vector<std::string> hdiSegments;
2920     std::istringstream infoStream(hdiInfoStr);
2921     std::string segment;
2922     while (std::getline(infoStream, segment, '#')) {
2923         if (!segment.empty()) {
2924             hdiSegments.push_back(segment);
2925         }
2926     }
2927 
2928     if (hdiSegments.size() != CONCURRENT_CAPTURE_DFX_HDI_SEGMENTS) {
2929         hdiSourceType = 0;
2930         hdiSourceAlg.clear();
2931         return;
2932     }
2933 
2934     int sourceTypeInt = std::atoi(hdiSegments[0].c_str());
2935     if (sourceTypeInt == 0 && hdiSegments[0] != "0") {
2936         AUDIO_ERR_LOG("Failed to convert hdiSegments[0] to uint8_t");
2937         hdiSourceType = 0;
2938         hdiSourceAlg.clear();
2939         return;
2940     }
2941 
2942     hdiSourceType = static_cast<uint8_t>(sourceTypeInt);
2943     hdiSourceAlg = hdiSegments[1];
2944 }
2945 
WriteCapturerConcurrentMsg(std::shared_ptr<AudioStreamDescriptor> streamDesc,const std::unique_ptr<ConcurrentCaptureDfxResult> & result)2946 bool AudioCoreService::WriteCapturerConcurrentMsg(std::shared_ptr<AudioStreamDescriptor> streamDesc,
2947     const std::unique_ptr<ConcurrentCaptureDfxResult> &result)
2948 {
2949     CHECK_AND_RETURN_RET_LOG(result != nullptr, false, "result is null");
2950     std::vector<std::string> existingAppName{};
2951     std::vector<uint8_t> existingAppState{};
2952     std::vector<uint8_t> existingSourceType{};
2953     std::vector<uint8_t> existingCaptureState{};
2954     std::vector<uint32_t> existingCreateDuration{};
2955     std::vector<uint32_t> existingStartDuration{};
2956     std::vector<bool> existingFastFlag{};
2957     std::vector<std::shared_ptr<AudioStreamDescriptor>> capturerStreamDescs = pipeManager_->GetAllCapturerStreamDescs();
2958     if (capturerStreamDescs.size() < CONCURRENT_CAPTURE_DFX_THRESHOLD) {
2959         return false;
2960     }
2961     for (auto &desc : capturerStreamDescs) {
2962         CHECK_AND_CONTINUE_LOG(desc != nullptr, "desc is nullptr");
2963         if (existingAppName.size() >= CONCURRENT_CAPTURE_DFX_MSG_ARRAY_MAX) {
2964             break;
2965         }
2966         int32_t uid = desc->appInfo_.appUid;
2967         std::string bundleName = AudioBundleManager::GetBundleNameFromUid(uid);
2968         existingAppName.push_back(bundleName);
2969         existingAppState.push_back(static_cast<uint8_t>(GetAppState(desc->appInfo_.appPid)));
2970         existingSourceType.push_back(static_cast<uint8_t>(desc->capturerInfo_.sourceType));
2971         existingCaptureState.push_back(static_cast<uint8_t>(desc->streamStatus_));
2972         existingCreateDuration.push_back(GetTimeCostFrom(desc->createTimeStamp_));
2973         existingStartDuration.push_back(GetTimeCostFrom(desc->startTimeStamp_));
2974         existingFastFlag.push_back(static_cast<bool>(desc->routeFlag_ & AUDIO_INPUT_FLAG_FAST));
2975     }
2976     result->existingAppName = std::move(existingAppName);
2977     result->existingAppState = std::move(existingAppState);
2978     result->existingSourceType = std::move(existingSourceType);
2979     result->existingCaptureState = std::move(existingCaptureState);
2980     result->existingCreateDuration = std::move(existingCreateDuration);
2981     result->existingStartDuration = std::move(existingStartDuration);
2982     result->existingFastFlag = std::move(existingFastFlag);
2983     GetHdiInfo(result->hdiSourceType, result->hdiSourceAlg);
2984     result->deviceType = streamDesc->newDeviceDescs_[0]->deviceType_;
2985     return true;
2986 }
2987 
LogCapturerConcurrentResult(const std::unique_ptr<ConcurrentCaptureDfxResult> & result)2988 void AudioCoreService::LogCapturerConcurrentResult(const std::unique_ptr<ConcurrentCaptureDfxResult> &result)
2989 {
2990     CHECK_AND_RETURN_LOG(result != nullptr, "result is null");
2991     size_t count = result->existingAppName.size();
2992     for (size_t i = 0; i < count; ++i) {
2993         AUDIO_INFO_LOG("------------------APP%{public}zu begin---------------------", i);
2994         AUDIO_INFO_LOG("AppName:          %{public}s", result->existingAppName[i].c_str());
2995         AUDIO_INFO_LOG("AppState:         %{public}d", result->existingAppState[i]);
2996         AUDIO_INFO_LOG("SourceType:       %{public}d", result->existingSourceType[i]);
2997         AUDIO_INFO_LOG("CaptureState:     %{public}d", result->existingCaptureState[i]);
2998         AUDIO_INFO_LOG("CreateDuration: 0x%{public}u", result->existingCreateDuration[i]);
2999         AUDIO_INFO_LOG("StartDuration:  0x%{public}u", result->existingStartDuration[i]);
3000         AUDIO_INFO_LOG("FastFlag:         %{public}d", static_cast<uint32_t>(result->existingFastFlag[i]));
3001         AUDIO_INFO_LOG("hdiSourceType:    %{public}d", result->hdiSourceType);
3002         AUDIO_INFO_LOG("hdiSourceAlg:     %{public}s", result->hdiSourceAlg.c_str());
3003         AUDIO_INFO_LOG("deviceType:       %{public}d", result->deviceType);
3004         AUDIO_INFO_LOG("------------------APP%{public}zu end-----------------------", i);
3005     }
3006 }
3007 
WriteCapturerConcurrentEvent(const std::unique_ptr<ConcurrentCaptureDfxResult> & result)3008 void AudioCoreService::WriteCapturerConcurrentEvent(const std::unique_ptr<ConcurrentCaptureDfxResult> &result)
3009 {
3010     CHECK_AND_RETURN_LOG(result != nullptr, "result is null");
3011     auto ret = HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::AUDIO, "CONCURRENT_CAPTURE",
3012         HiviewDFX::HiSysEvent::EventType::STATISTIC,
3013         "EXISTING_APP_NAME", result->existingAppName,
3014         "EXISTING_APP_STATE", result->existingAppState,
3015         "EXISTING_SOURCE_TYPE", result->existingSourceType,
3016         "EXISTING_CAPTURE_STATE", result->existingCaptureState,
3017         "EXISTING_CREATE_DURATION", result->existingCreateDuration,
3018         "EXISTING_START_DURATION", result->existingStartDuration,
3019         "EXISTING_FAST_FLAG", result->existingFastFlag,
3020         "HDI_SOURCE_TYPE", result->hdiSourceType,
3021         "HDI_SOURCE_ALG", result->hdiSourceAlg,
3022         "DEVICE_TYPE", result->deviceType);
3023     if (ret) {
3024         AUDIO_ERR_LOG("Write event fail: CONCURRENT_CAPTURE, ret = %{public}d", ret);
3025     }
3026 }
3027 
SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig & config)3028 int32_t AudioCoreService::SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig &config)
3029 {
3030     return audioCapturerSession_.SetWakeUpAudioCapturerFromAudioServer(config);
3031 }
3032 
UpdateRouteForCollaboration(InternalDeviceType deviceType)3033 void AudioCoreService::UpdateRouteForCollaboration(InternalDeviceType deviceType)
3034 {
3035     if (AudioCollaborativeService::GetAudioCollaborativeService().GetRealCollaborativeState()) {
3036         std::vector<std::pair<InternalDeviceType, DeviceFlag>> activeDevices;
3037         activeDevices.push_back(make_pair(deviceType, DeviceFlag::OUTPUT_DEVICES_FLAG));
3038         activeDevices.push_back(make_pair(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG));
3039         audioActiveDevice_.UpdateActiveDevicesRoute(activeDevices);
3040         AUDIO_INFO_LOG("collaboration Update desc [%{public}d] with speaker", deviceType);
3041     }
3042 }
3043 } // namespace AudioStandard
3044 } // namespace OHOS
3045