• 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 "AudioCoreService"
17 #endif
18 
19 #include "audio_core_service.h"
20 #include "system_ability.h"
21 #include "audio_server_proxy.h"
22 #include "audio_policy_utils.h"
23 #include "iservice_registry.h"
24 #include "hdi_adapter_info.h"
25 #include "audio_usb_manager.h"
26 #include "audio_spatialization_service.h"
27 #include "audio_zone_service.h"
28 #include "audio_bundle_manager.h"
29 
30 namespace OHOS {
31 namespace AudioStandard {
32 namespace {
33 const size_t SELECT_DEVICE_HISTORY_LIMIT = 10;
34 const uint32_t FIRST_SESSIONID = 100000;
35 static const char* CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#";
36 static const int32_t BLUETOOTH_FETCH_RESULT_DEFAULT = 0;
37 static const int32_t BLUETOOTH_FETCH_RESULT_CONTINUE = 1;
38 static const int32_t BLUETOOTH_FETCH_RESULT_ERROR = 2;
39 }
40 
IsRemoteOffloadActive(uint32_t remoteOffloadStreamPropSize,int32_t streamUsage)41 static bool IsRemoteOffloadActive(uint32_t remoteOffloadStreamPropSize, int32_t streamUsage)
42 {
43     CHECK_AND_RETURN_RET_LOG(remoteOffloadStreamPropSize != 0 && streamUsage == STREAM_USAGE_MUSIC, false,
44         "Use normal for remote device or remotecast");
45     AUDIO_INFO_LOG("remote offload active, music use offload");
46     return true;
47 }
48 
49 bool AudioCoreService::isBtListenerRegistered = false;
50 bool AudioCoreService::isBtCrashed = false;
51 #ifdef BLUETOOTH_ENABLE
52 mutex g_btProxyMutex;
53 #endif
54 
AudioCoreService()55 AudioCoreService::AudioCoreService()
56     : audioPolicyServerHandler_(DelayedSingleton<AudioPolicyServerHandler>::GetInstance()),
57       audioActiveDevice_(AudioActiveDevice::GetInstance()),
58       audioSceneManager_(AudioSceneManager::GetInstance()),
59       audioVolumeManager_(AudioVolumeManager::GetInstance()),
60       audioCapturerSession_(AudioCapturerSession::GetInstance()),
61       audioDeviceManager_(AudioDeviceManager::GetAudioDeviceManager()),
62       audioConnectedDevice_(AudioConnectedDevice::GetInstance()),
63       audioDeviceStatus_(AudioDeviceStatus::GetInstance()),
64       audioEffectService_(AudioEffectService::GetAudioEffectService()),
65       audioMicrophoneDescriptor_(AudioMicrophoneDescriptor::GetInstance()),
66       audioRecoveryDevice_(AudioRecoveryDevice::GetInstance()),
67       audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()),
68       streamCollector_(AudioStreamCollector::GetAudioStreamCollector()),
69       audioStateManager_(AudioStateManager::GetAudioStateManager()),
70       audioDeviceCommon_(AudioDeviceCommon::GetInstance()),
71       audioOffloadStream_(AudioOffloadStream::GetInstance()),
72       audioA2dpOffloadFlag_(AudioA2dpOffloadFlag::GetInstance()),
73       audioPolicyManager_(AudioPolicyManagerFactory::GetAudioPolicyManager()),
74       audioRouteMap_(AudioRouteMap::GetInstance()),
75       audioIOHandleMap_(AudioIOHandleMap::GetInstance()),
76       audioA2dpDevice_(AudioA2dpDevice::GetInstance()),
77       audioEcManager_(AudioEcManager::GetInstance()),
78       policyConfigMananger_(AudioPolicyConfigManager::GetInstance()),
79       audioAffinityManager_(AudioAffinityManager::GetAudioAffinityManager()),
80       sleAudioDeviceManager_(SleAudioDeviceManager::GetInstance()),
81       audioPipeSelector_(AudioPipeSelector::GetPipeSelector()),
82       audioSessionService_(AudioSessionService::GetAudioSessionService()),
83       pipeManager_(AudioPipeManager::GetPipeManager())
84 {
85     AUDIO_INFO_LOG("Ctor");
86 }
87 
~AudioCoreService()88 AudioCoreService::~AudioCoreService()
89 {
90     AUDIO_INFO_LOG("Dtor");
91 }
92 
GetCoreService()93 std::shared_ptr<AudioCoreService> AudioCoreService::GetCoreService()
94 {
95     static std::shared_ptr<AudioCoreService> instance = std::make_shared<AudioCoreService>();
96     return instance;
97 }
98 
Init()99 void AudioCoreService::Init()
100 {
101     serviceFlag_.reset();
102     eventEntry_ = std::make_shared<EventEntry>(shared_from_this());
103 
104     audioA2dpOffloadManager_ = std::make_shared<AudioA2dpOffloadManager>();
105     if (audioA2dpOffloadManager_ != nullptr) {
106         audioA2dpOffloadManager_->Init();
107     }
108     audioVolumeManager_.Init(audioPolicyServerHandler_);
109     audioDeviceCommon_.Init(audioPolicyServerHandler_);
110     audioRecoveryDevice_.Init(audioA2dpOffloadManager_);
111 
112     audioDeviceStatus_.Init(audioA2dpOffloadManager_, audioPolicyServerHandler_);
113     audioCapturerSession_.Init(audioA2dpOffloadManager_);
114 
115     deviceStatusListener_ = std::make_shared<DeviceStatusListener>(*eventEntry_); // shared_ptr.get() -> *
116     isFastControlled_ = GetFastControlParam();
117     // Register device status listener
118     int32_t status = deviceStatusListener_->RegisterDeviceStatusListener();
119     if (status != SUCCESS) {
120         AudioPolicyUtils::GetInstance().WriteServiceStartupError("Register for device status events failed");
121         AUDIO_ERR_LOG("Register for device status events failed");
122     }
123 }
124 
DeInit()125 void AudioCoreService::DeInit()
126 {
127     // Remove device status listener
128     deviceStatusListener_->UnRegisterDeviceStatusListener();
129     if (isBtListenerRegistered) {
130         UnregisterBluetoothListener();
131     }
132 }
133 
SetCallbackHandler(std::shared_ptr<AudioPolicyServerHandler> handler)134 void AudioCoreService::SetCallbackHandler(std::shared_ptr<AudioPolicyServerHandler> handler)
135 {
136     audioPolicyServerHandler_ = handler;
137 }
138 
GetEventEntry()139 std::shared_ptr<AudioCoreService::EventEntry> AudioCoreService::GetEventEntry()
140 {
141     return eventEntry_;
142 }
143 
DumpPipeManager(std::string & dumpString)144 void AudioCoreService::DumpPipeManager(std::string &dumpString)
145 {
146     if (pipeManager_ != nullptr) {
147         pipeManager_->Dump(dumpString);
148     }
149 }
150 
CreateRendererClient(std::shared_ptr<AudioStreamDescriptor> streamDesc,uint32_t & audioFlag,uint32_t & sessionId,std::string & networkId)151 int32_t AudioCoreService::CreateRendererClient(
152     std::shared_ptr<AudioStreamDescriptor> streamDesc, uint32_t &audioFlag, uint32_t &sessionId, std::string &networkId)
153 {
154     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, ERR_NULL_POINTER, "stream desc is nullptr");
155     if (sessionId == 0) {
156         streamDesc->sessionId_ = GenerateSessionId();
157         sessionId = streamDesc->sessionId_;
158         AUDIO_INFO_LOG("Generate session id %{public}u for stream", sessionId);
159     }
160 
161     // Modem stream need special process, because there are no real hdi output or input in fwk.
162     // Input also need to be handled because capturer won't be created, only has renderer.
163     bool isModemStream = false;
164     if (streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_VOICE_MODEM_COMMUNICATION) {
165         AUDIO_INFO_LOG("Modem communication renderer create, sessionId %{public}u", sessionId);
166         isModemStream = true;
167         audioFlag = AUDIO_FLAG_NORMAL;
168         AddSessionId(sessionId);
169         pipeManager_->AddModemCommunicationId(sessionId, streamDesc);
170     } else if (streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_RINGTONE ||
171         streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION) {
172         std::string bundleName = AudioBundleManager::GetBundleNameFromUid(streamDesc->appInfo_.appUid);
173         Bluetooth::AudioHfpManager::AddVirtualCallBundleName(bundleName, streamDesc->sessionId_);
174     }
175 
176     AUDIO_INFO_LOG("[DeviceFetchStart] for stream %{public}d", sessionId);
177     streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_;
178     streamDesc->newDeviceDescs_ =
179         audioRouterCenter_.FetchOutputDevices(streamDesc->rendererInfo_.streamUsage,
180             GetRealUid(streamDesc), "CreateRendererClient");
181     CHECK_AND_RETURN_RET_LOG(streamDesc->newDeviceDescs_.size() > 0 && streamDesc->newDeviceDescs_.front() != nullptr,
182         ERR_NULL_POINTER, "Invalid deviceDesc");
183     AUDIO_INFO_LOG("[DeviceFetchInfo] device %{public}s for stream %{public}d",
184         streamDesc->GetNewDevicesTypeString().c_str(), sessionId);
185 
186     if (isModemStream) {
187         return SUCCESS;
188     }
189 
190     ActivateOutputDevice(streamDesc);
191 
192     // Bluetooth may be inactive (paused ringtone stream at Speaker switches to A2dp)
193     std::string encryptMacAddr = GetEncryptAddr(streamDesc->newDeviceDescs_.front()->macAddress_);
194     int32_t bluetoothFetchResult = BluetoothDeviceFetchOutputHandle(streamDesc,
195         AudioStreamDeviceChangeReason::UNKNOWN, encryptMacAddr);
196     CHECK_AND_RETURN_RET(bluetoothFetchResult == BLUETOOTH_FETCH_RESULT_DEFAULT, ERR_OPERATION_FAILED);
197 
198     UpdatePlaybackStreamFlag(streamDesc, true);
199     AUDIO_INFO_LOG("Target audioFlag 0x%{public}x for stream %{public}d",
200         streamDesc->audioFlag_, sessionId);
201 
202     // Fetch pipe
203     audioActiveDevice_.UpdateStreamDeviceMap("CreateRendererClient");
204     int32_t ret = FetchRendererPipeAndExecute(streamDesc, sessionId, audioFlag);
205     networkId = streamDesc->newDeviceDescs_.front()->networkId_;
206     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "FetchPipeAndExecute failed");
207     AddSessionId(sessionId);
208     return SUCCESS;
209 }
210 
CreateCapturerClient(std::shared_ptr<AudioStreamDescriptor> streamDesc,uint32_t & audioFlag,uint32_t & sessionId)211 int32_t AudioCoreService::CreateCapturerClient(
212     std::shared_ptr<AudioStreamDescriptor> streamDesc, uint32_t &audioFlag, uint32_t &sessionId)
213 {
214     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, ERR_INVALID_PARAM, "streamDesc is nullptr");
215 
216     AUDIO_INFO_LOG("[DeviceFetchStart] for stream %{public}d", sessionId);
217     streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_;
218     std::shared_ptr<AudioDeviceDescriptor> inputDeviceDesc =
219         audioRouterCenter_.FetchInputDevice(streamDesc->capturerInfo_.sourceType,
220         GetRealUid(streamDesc), sessionId);
221     CHECK_AND_RETURN_RET_LOG(inputDeviceDesc != nullptr, ERR_INVALID_PARAM, "inputDeviceDesc is nullptr");
222     streamDesc->newDeviceDescs_.clear();
223     streamDesc->newDeviceDescs_.push_back(inputDeviceDesc);
224     AUDIO_INFO_LOG("[DeviceFetchInfo] device %{public}s for stream %{public}d",
225         streamDesc->GetNewDevicesTypeString().c_str(), sessionId);
226 
227     UpdateRecordStreamFlag(streamDesc);
228     AUDIO_INFO_LOG("Target audioFlag 0x%{public}x for stream %{public}d",
229         streamDesc->audioFlag_, sessionId);
230 
231     // Fetch pipe
232     int32_t ret = FetchCapturerPipeAndExecute(streamDesc, audioFlag, sessionId);
233     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "FetchPipeAndExecute failed");
234     AddSessionId(sessionId);
235     return SUCCESS;
236 }
237 
IsStreamSupportMultiChannel(std::shared_ptr<AudioStreamDescriptor> streamDesc)238 bool AudioCoreService::IsStreamSupportMultiChannel(std::shared_ptr<AudioStreamDescriptor> streamDesc)
239 {
240     Trace trace("IsStreamSupportMultiChannel");
241 
242     // MultiChannel: Speaker, A2dp offload
243     if (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_SPEAKER &&
244         (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP ||
245         streamDesc->newDeviceDescs_[0]->a2dpOffloadFlag_ != A2DP_OFFLOAD)) {
246         AUDIO_INFO_LOG("normal stream, deviceType: %{public}d", streamDesc->newDeviceDescs_[0]->deviceType_);
247         return false;
248     }
249     if (streamDesc->streamInfo_.channels <= STEREO ||
250         (streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_MOVIE &&
251          streamDesc->rendererInfo_.originalFlag == AUDIO_FLAG_PCM_OFFLOAD)) {
252         return false;
253     }
254     // The multi-channel algorithm needs to be supported in the dsp
255     bool isSupported = AudioServerProxy::GetInstance().GetEffectOffloadEnabledProxy();
256     AUDIO_INFO_LOG("effect offload enable is %{public}d", isSupported);
257     return isSupported;
258 }
259 
IsStreamSupportDirect(std::shared_ptr<AudioStreamDescriptor> streamDesc)260 bool AudioCoreService::IsStreamSupportDirect(std::shared_ptr<AudioStreamDescriptor> streamDesc)
261 {
262     Trace trace("IsStreamSupportDirect");
263     if (streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_WIRED_HEADSET &&
264         streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_USB_HEADSET &&
265         streamDesc->newDeviceDescs_[0]->deviceType_ != DEVICE_TYPE_NEARLINK) {
266             return false;
267         }
268     if (streamDesc->rendererInfo_.streamUsage != STREAM_USAGE_MUSIC ||
269         streamDesc->streamInfo_.samplingRate < SAMPLE_RATE_48000 ||
270         streamDesc->streamInfo_.format < SAMPLE_S24LE) {
271             AUDIO_INFO_LOG("normal stream because stream info");
272             return false;
273         }
274     if (streamDesc->streamInfo_.samplingRate > SAMPLE_RATE_192000) {
275         AUDIO_INFO_LOG("sample rate over 192k");
276         return false;
277     }
278     return true;
279 }
280 
IsForcedNormal(std::shared_ptr<AudioStreamDescriptor> & streamDesc)281 bool AudioCoreService::IsForcedNormal(std::shared_ptr<AudioStreamDescriptor> &streamDesc)
282 {
283     const auto &rendererInfo = streamDesc->rendererInfo_;
284     if (rendererInfo.originalFlag == AUDIO_FLAG_FORCED_NORMAL ||
285         rendererInfo.rendererFlags == AUDIO_FLAG_FORCED_NORMAL) {
286         streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_NORMAL;
287         return true;
288     }
289     if (rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION &&
290         rendererInfo.samplingRate != SAMPLE_RATE_48000) {
291         streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_NORMAL;
292         return true;
293     }
294     return false;
295 }
296 
UpdatePlaybackStreamFlag(std::shared_ptr<AudioStreamDescriptor> & streamDesc,bool isCreateProcess)297 void AudioCoreService::UpdatePlaybackStreamFlag(std::shared_ptr<AudioStreamDescriptor> &streamDesc, bool isCreateProcess)
298 {
299     CHECK_AND_RETURN_LOG(streamDesc, "Input param error");
300     // fast/normal has done in audioRendererPrivate
301     CHECK_AND_RETURN_LOG(IsForcedNormal(streamDesc) == false, "Forced normal cases");
302 
303     if (streamDesc->newDeviceDescs_.back()->deviceType_ == DEVICE_TYPE_REMOTE_CAST ||
304         streamDesc->newDeviceDescs_.back()->networkId_ != LOCAL_NETWORK_ID) {
305         auto remoteOffloadStreamPropSize = policyConfigMananger_.GetStreamPropInfoSize("remote",
306             "offload_distributed_output");
307         streamDesc->audioFlag_ = IsRemoteOffloadActive(remoteOffloadStreamPropSize,
308             streamDesc->rendererInfo_.streamUsage) ? AUDIO_OUTPUT_FLAG_LOWPOWER : AUDIO_OUTPUT_FLAG_NORMAL;
309         return;
310     }
311 
312     if (streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION ||
313         streamDesc->rendererInfo_.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) {
314         std::string sinkPortName =
315             AudioPolicyUtils::GetInstance().GetSinkPortName(streamDesc->newDeviceDescs_.front()->deviceType_);
316         // in plan: if has two voip, return normal
317         streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_VOIP;
318         AUDIO_INFO_LOG("sinkPortName %{public}s, audioFlag 0x%{public}x",
319             sinkPortName.c_str(), streamDesc->audioFlag_);
320         return;
321     }
322     HandlePlaybackStreamInA2dp(streamDesc, isCreateProcess);
323     switch (streamDesc->rendererInfo_.originalFlag) {
324         case AUDIO_FLAG_MMAP:
325             streamDesc->audioFlag_ =
326                 IsFastAllowed(streamDesc->bundleName_) ? AUDIO_OUTPUT_FLAG_FAST : AUDIO_OUTPUT_FLAG_NORMAL;
327             return;
328         case AUDIO_FLAG_VOIP_FAST:
329             streamDesc->audioFlag_ =
330                 IsFastAllowed(streamDesc->bundleName_) ? AUDIO_OUTPUT_FLAG_VOIP : AUDIO_OUTPUT_FLAG_NORMAL;
331             return;
332         case AUDIO_FLAG_VOIP_DIRECT:
333             streamDesc->audioFlag_ = AUDIO_OUTPUT_FLAG_VOIP;
334             return;
335         default:
336             break;
337     }
338     streamDesc->audioFlag_ = SetFlagForSpecialStream(streamDesc, isCreateProcess);
339 }
340 
SetFlagForSpecialStream(std::shared_ptr<AudioStreamDescriptor> & streamDesc,bool isCreateProcess)341 AudioFlag AudioCoreService::SetFlagForSpecialStream(std::shared_ptr<AudioStreamDescriptor> &streamDesc,
342     bool isCreateProcess)
343 {
344     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr && streamDesc->newDeviceDescs_.size() > 0 &&
345         streamDesc->newDeviceDescs_[0] != nullptr, AUDIO_OUTPUT_FLAG_NORMAL, "Invalid stream desc");
346 
347     if (IsStreamSupportDirect(streamDesc)) {
348         return AUDIO_OUTPUT_FLAG_HD;
349     }
350     if (IsStreamSupportLowpower(streamDesc)) {
351         return AUDIO_OUTPUT_FLAG_LOWPOWER;
352     }
353     if (IsStreamSupportMultiChannel(streamDesc)) {
354         return AUDIO_OUTPUT_FLAG_MULTICHANNEL;
355     }
356     return AUDIO_OUTPUT_FLAG_NORMAL;
357 }
358 
UpdateRecordStreamFlag(std::shared_ptr<AudioStreamDescriptor> streamDesc)359 void AudioCoreService::UpdateRecordStreamFlag(std::shared_ptr<AudioStreamDescriptor> streamDesc)
360 {
361     if (streamDesc->capturerInfo_.originalFlag == AUDIO_FLAG_FORCED_NORMAL ||
362         streamDesc->capturerInfo_.capturerFlags == AUDIO_FLAG_FORCED_NORMAL) {
363         streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_NORMAL;
364         AUDIO_INFO_LOG("Forced normal cases");
365         return;
366     }
367 
368     // fast/normal has done in audioCapturerPrivate
369     if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) {
370         // in plan: if has two voip, return normal
371         streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_VOIP;
372         AUDIO_INFO_LOG("Use voip");
373         return;
374     }
375     if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_REMOTE_CAST) {
376         streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_NORMAL;
377         AUDIO_WARNING_LOG("Use normal for remotecast");
378         return;
379     }
380 
381     if (streamDesc->capturerInfo_.sourceType == SOURCE_TYPE_WAKEUP) {
382         streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_WAKEUP;
383     }
384     switch (streamDesc->capturerInfo_.capturerFlags) {
385         case AUDIO_FLAG_MMAP:
386             streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_FAST;
387             return;
388         case AUDIO_FLAG_VOIP_FAST:
389             streamDesc->audioFlag_ = AUDIO_INPUT_FLAG_VOIP_FAST;
390             return;
391         default:
392             break;
393     }
394     // In plan: streamDesc to audioFlag;
395     streamDesc->audioFlag_ = AUDIO_FLAG_NONE;
396 }
397 
CheckAndSetCurrentOutputDevice(std::shared_ptr<AudioDeviceDescriptor> & desc,int32_t sessionId)398 void AudioCoreService::CheckAndSetCurrentOutputDevice(std::shared_ptr<AudioDeviceDescriptor> &desc, int32_t sessionId)
399 {
400     CHECK_AND_RETURN_LOG(desc != nullptr, "desc is null");
401     CHECK_AND_RETURN_LOG(!IsSameDevice(desc, audioActiveDevice_.GetCurrentOutputDevice()), "same device");
402     audioActiveDevice_.SetCurrentOutputDevice(*(desc));
403     std::string sinkName = AudioPolicyUtils::GetInstance().GetSinkName(desc, sessionId);
404     if (audioDeviceManager_.IsDeviceConnected(desc)) {
405         audioVolumeManager_.SetVolumeForSwitchDevice(*(desc), sinkName);
406     }
407     OnPreferredOutputDeviceUpdated(audioActiveDevice_.GetCurrentOutputDevice(),
408         AudioStreamDeviceChangeReason::STREAM_PRIORITY_CHANGED);
409 }
410 
CheckAndSetCurrentInputDevice(std::shared_ptr<AudioDeviceDescriptor> & desc)411 void AudioCoreService::CheckAndSetCurrentInputDevice(std::shared_ptr<AudioDeviceDescriptor> &desc)
412 {
413     CHECK_AND_RETURN_LOG(desc != nullptr, "desc is null");
414     CHECK_AND_RETURN_LOG(!IsSameDevice(desc, audioActiveDevice_.GetCurrentInputDevice()),
415         "current input device is same as new device");
416     audioActiveDevice_.SetCurrentInputDevice(*(desc));
417     OnPreferredInputDeviceUpdated(audioActiveDevice_.GetCurrentInputDeviceType(), "");
418 }
419 
CheckForRemoteDeviceState(std::shared_ptr<AudioDeviceDescriptor> desc)420 void AudioCoreService::CheckForRemoteDeviceState(std::shared_ptr<AudioDeviceDescriptor> desc)
421 {
422     CHECK_AND_RETURN_LOG(desc != nullptr, "desc is null");
423     std::string networkId = desc->networkId_;
424     DeviceRole deviceRole = desc->deviceRole_;
425     CHECK_AND_RETURN(networkId != LOCAL_NETWORK_ID);
426     int32_t res = AudioServerProxy::GetInstance().CheckRemoteDeviceStateProxy(networkId, deviceRole, true);
427     CHECK_AND_RETURN_LOG(res == SUCCESS, "remote device state is invalid!");
428 }
429 
StartClient(uint32_t sessionId)430 int32_t AudioCoreService::StartClient(uint32_t sessionId)
431 {
432     if (pipeManager_->IsModemCommunicationIdExist(sessionId)) {
433         AUDIO_INFO_LOG("Modem communication ring, directly return");
434         return SUCCESS;
435     }
436 
437     std::shared_ptr<AudioStreamDescriptor> streamDesc = pipeManager_->GetStreamDescById(sessionId);
438     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, ERR_NULL_POINTER, "Cannot find session %{public}u", sessionId);
439     pipeManager_->StartClient(sessionId);
440 
441     // A stream set default device special case
442     if (audioDeviceManager_.IsSessionSetDefaultDevice(sessionId)) {
443         audioDeviceManager_.UpdateDefaultOutputDeviceWhenStarting(sessionId);
444         std::vector<std::shared_ptr<AudioStreamDescriptor>> outputDescs = pipeManager_->GetAllOutputStreamDescs();
445         for (auto &desc : outputDescs) {
446             CHECK_AND_CONTINUE_LOG(desc != nullptr, "desc is null");
447             desc->newDeviceDescs_ = audioRouterCenter_.FetchOutputDevices(desc->rendererInfo_.streamUsage,
448                 GetRealUid(desc), "StartClient");
449         }
450     }
451 
452     CHECK_AND_RETURN_RET_LOG(!streamDesc->newDeviceDescs_.empty(), ERR_INVALID_PARAM, "newDeviceDescs_ is empty");
453     if (streamDesc->audioMode_ == AUDIO_MODE_PLAYBACK) {
454         int32_t outputRet = ActivateOutputDevice(streamDesc);
455         CHECK_AND_RETURN_RET_LOG(outputRet == SUCCESS, outputRet, "Activate output device failed");
456         CheckAndSetCurrentOutputDevice(streamDesc->newDeviceDescs_.front(), streamDesc->sessionId_);
457         std::vector<std::pair<DeviceType, DeviceFlag>> activeDevices;
458         if (policyConfigMananger_.GetUpdateRouteSupport()) {
459             UpdateOutputRoute(streamDesc);
460         }
461     } else {
462         int32_t inputRet = ActivateInputDevice(streamDesc);
463         CHECK_AND_RETURN_RET_LOG(inputRet == SUCCESS, inputRet, "Activate input device failed");
464         CheckAndSetCurrentInputDevice(streamDesc->newDeviceDescs_.front());
465         audioActiveDevice_.UpdateActiveDeviceRoute(
466             streamDesc->newDeviceDescs_[0]->deviceType_, DeviceFlag::INPUT_DEVICES_FLAG,
467             streamDesc->newDeviceDescs_[0]->deviceName_, streamDesc->newDeviceDescs_[0]->networkId_);
468         streamCollector_.UpdateCapturerDeviceInfo(streamDesc->newDeviceDescs_.front());
469     }
470     streamDesc->startTimeStamp_ = ClockTime::GetCurNano();
471     sleAudioDeviceManager_.UpdateSleStreamTypeCount(streamDesc);
472 
473     CheckForRemoteDeviceState(streamDesc->newDeviceDescs_.front());
474     return SUCCESS;
475 }
476 
PauseClient(uint32_t sessionId)477 int32_t AudioCoreService::PauseClient(uint32_t sessionId)
478 {
479     pipeManager_->PauseClient(sessionId);
480     return SUCCESS;
481 }
482 
StopClient(uint32_t sessionId)483 int32_t AudioCoreService::StopClient(uint32_t sessionId)
484 {
485     pipeManager_->StopClient(sessionId);
486     return SUCCESS;
487 }
488 
ReleaseClient(uint32_t sessionId,SessionOperationMsg opMsg)489 int32_t AudioCoreService::ReleaseClient(uint32_t sessionId, SessionOperationMsg opMsg)
490 {
491     if (pipeManager_->IsModemCommunicationIdExist(sessionId)) {
492         AUDIO_INFO_LOG("Modem communication, sessionId %{public}u", sessionId);
493         bool isRemoved = true;
494         sleAudioDeviceManager_.UpdateSleStreamTypeCount(pipeManager_->GetModemCommunicationStreamDescById(sessionId),
495             isRemoved);
496         pipeManager_->RemoveModemCommunicationId(sessionId);
497         return SUCCESS;
498     }
499     pipeManager_->RemoveClient(sessionId);
500     audioOffloadStream_.ResetOffloadStatus(sessionId);
501     RemoveUnusedPipe();
502     if (opMsg == SESSION_OP_MSG_REMOVE_PIPE) {
503         RemoveUnusedRecordPipe();
504     }
505     DeleteSessionId(sessionId);
506 
507     return SUCCESS;
508 }
509 
SetAudioScene(AudioScene audioScene,const int32_t uid,const int32_t pid)510 int32_t AudioCoreService::SetAudioScene(AudioScene audioScene, const int32_t uid, const int32_t pid)
511 {
512     audioSceneManager_.SetAudioScenePre(audioScene);
513     audioStateManager_.SetAudioSceneOwnerUid(audioScene == 0 ? 0 : uid);
514     AudioScene lastAudioScene = audioSceneManager_.GetLastAudioScene();
515     bool isSameScene = audioSceneManager_.IsSameAudioScene();
516     int32_t result = audioSceneManager_.SetAudioSceneAfter(audioScene, audioA2dpOffloadFlag_.GetA2dpOffloadFlag());
517     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, ERR_OPERATION_FAILED, "failed [%{public}d]", result);
518     FetchDeviceAndRoute("SetAudioScene", AudioStreamDeviceChangeReasonExt::ExtEnum::SET_AUDIO_SCENE);
519 
520     if (!isSameScene) {
521         OnAudioSceneChange(audioScene);
522     }
523 
524     if (audioScene == AUDIO_SCENE_PHONE_CALL) {
525         // Make sure the STREAM_VOICE_CALL volume is set before the calling starts.
526         audioVolumeManager_.SetVoiceCallVolume(audioVolumeManager_.GetSystemVolumeLevel(STREAM_VOICE_CALL));
527     } else {
528         audioVolumeManager_.SetVoiceRingtoneMute(false);
529     }
530     if (lastAudioScene == AUDIO_SCENE_RINGING && audioScene != AUDIO_SCENE_RINGING &&
531         audioVolumeManager_.IsAppRingMuted(uid)) {
532         audioVolumeManager_.SetAppRingMuted(uid, false); // unmute the STREAM_RING for the app.
533     }
534     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
535         audioActiveDevice_.GetCurrentOutputDevice(), "SetAudioScene");
536     return SUCCESS;
537 }
538 
IsArmUsbDevice(const AudioDeviceDescriptor & deviceDesc)539 bool AudioCoreService::IsArmUsbDevice(const AudioDeviceDescriptor &deviceDesc)
540 {
541     return audioDeviceManager_.IsArmUsbDevice(deviceDesc);
542 }
543 
GetDevices(DeviceFlag deviceFlag)544 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioCoreService::GetDevices(DeviceFlag deviceFlag)
545 {
546     return audioConnectedDevice_.GetDevicesInner(deviceFlag);
547 }
548 
SetDeviceActive(InternalDeviceType deviceType,bool active,const int32_t uid)549 int32_t AudioCoreService::SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t uid)
550 {
551     AUDIO_INFO_LOG("[ADeviceEvent] withlock device %{public}d, active %{public}d from uid %{public}d",
552         deviceType, active, uid);
553     int32_t ret = audioActiveDevice_.SetDeviceActive(deviceType, active, uid);
554     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetDeviceActive failed");
555 
556     FetchDeviceAndRoute("SetDeviceActive", AudioStreamDeviceChangeReasonExt::ExtEnum::OVERRODE);
557 
558     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
559         audioActiveDevice_.GetCurrentOutputDevice(), "SetDevcieActive");
560     return SUCCESS;
561 }
562 
SetInputDevice(const DeviceType deviceType,const uint32_t sessionID,const SourceType sourceType,bool isRunning)563 int32_t AudioCoreService::SetInputDevice(const DeviceType deviceType, const uint32_t sessionID,
564     const SourceType sourceType, bool isRunning)
565 {
566     int32_t ret = audioDeviceManager_.SetInputDevice(deviceType, sessionID, sourceType, isRunning);
567     if (ret == NEED_TO_FETCH) {
568         FetchInputDeviceAndRoute("SetInputDevice");
569         return SUCCESS;
570     }
571     return ret;
572 }
573 
GetPreferredOutputDeviceDescInner(AudioRendererInfo & rendererInfo,std::string networkId)574 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioCoreService::GetPreferredOutputDeviceDescInner(
575     AudioRendererInfo &rendererInfo, std::string networkId)
576 {
577     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceList = {};
578     if (rendererInfo.streamUsage <= STREAM_USAGE_UNKNOWN ||
579         rendererInfo.streamUsage > STREAM_USAGE_MAX) {
580         AUDIO_WARNING_LOG("Invalid usage[%{public}d], return current device.", rendererInfo.streamUsage);
581         std::shared_ptr<AudioDeviceDescriptor> devDesc =
582             std::make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentOutputDevice());
583         deviceList.push_back(devDesc);
584         return deviceList;
585     }
586     if (networkId == LOCAL_NETWORK_ID) {
587         vector<std::shared_ptr<AudioDeviceDescriptor>> descs =
588             audioRouterCenter_.FetchOutputDevices(rendererInfo.streamUsage, -1, "GetPreferredOutputDeviceDescInner");
589         for (size_t i = 0; i < descs.size(); i++) {
590             std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*descs[i]);
591             deviceList.push_back(devDesc);
592         }
593     } else {
594         vector<shared_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetRemoteRenderDevices();
595         for (const auto &desc : descs) {
596             std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*desc);
597             deviceList.push_back(devDesc);
598         }
599     }
600 
601     return deviceList;
602 }
603 
GetPreferredInputDeviceDescInner(AudioCapturerInfo & captureInfo,std::string networkId)604 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioCoreService::GetPreferredInputDeviceDescInner(
605     AudioCapturerInfo &captureInfo, std::string networkId)
606 {
607     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceList = {};
608     if (captureInfo.sourceType <= SOURCE_TYPE_INVALID ||
609         captureInfo.sourceType > SOURCE_TYPE_MAX) {
610         std::shared_ptr<AudioDeviceDescriptor> devDesc =
611             std::make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentInputDevice());
612         deviceList.push_back(devDesc);
613         return deviceList;
614     }
615 
616     if (captureInfo.sourceType == SOURCE_TYPE_WAKEUP) {
617         std::shared_ptr<AudioDeviceDescriptor> devDesc =
618             std::make_shared<AudioDeviceDescriptor>(DEVICE_TYPE_MIC, INPUT_DEVICE);
619         devDesc->networkId_ = LOCAL_NETWORK_ID;
620         deviceList.push_back(devDesc);
621         return deviceList;
622     }
623 
624     if (networkId == LOCAL_NETWORK_ID) {
625         std::shared_ptr<AudioDeviceDescriptor> desc = audioRouterCenter_.FetchInputDevice(captureInfo.sourceType, -1);
626         CHECK_AND_RETURN_RET_LOG(desc != nullptr, deviceList, "desc is nullptr");
627         if (desc->deviceType_ == DEVICE_TYPE_NONE && (captureInfo.sourceType == SOURCE_TYPE_PLAYBACK_CAPTURE ||
628             captureInfo.sourceType == SOURCE_TYPE_REMOTE_CAST)) {
629             desc->deviceType_ = DEVICE_TYPE_INVALID;
630             desc->deviceRole_ = INPUT_DEVICE;
631         }
632         std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*desc);
633         deviceList.push_back(devDesc);
634     } else {
635         vector<shared_ptr<AudioDeviceDescriptor>> descs = audioDeviceManager_.GetRemoteCaptureDevices();
636         for (const auto &desc : descs) {
637             std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*desc);
638             deviceList.push_back(devDesc);
639         }
640     }
641 
642     return deviceList;
643 }
644 
GetPreferredOutputStreamType(AudioRendererInfo & rendererInfo,const std::string & bundleName)645 int32_t AudioCoreService::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo,
646     const std::string &bundleName)
647 {
648     // Use GetPreferredOutputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream
649     std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
650         GetPreferredOutputDeviceDescInner(rendererInfo, LOCAL_NETWORK_ID);
651     if (preferredDeviceList.size() == 0) {
652         return AUDIO_FLAG_NORMAL;
653     }
654 
655     int32_t flag = AUDIO_FLAG_NORMAL;
656     if (isFastControlled_ && (rendererInfo.playerType != PLAYER_TYPE_SOUND_POOL) &&
657         (flag == AUDIO_FLAG_MMAP || flag == AUDIO_FLAG_VOIP_FAST)) {
658         std::string bundleNamePre = CHECK_FAST_BLOCK_PREFIX + bundleName;
659         std::string result = AudioServerProxy::GetInstance().GetAudioParameterProxy(bundleNamePre);
660         if (result == "true") {
661             AUDIO_INFO_LOG("%{public}s not in fast list", bundleName.c_str());
662             return AUDIO_FLAG_NORMAL;
663         }
664     }
665     if (flag == AUDIO_FLAG_VOIP_FAST && audioSceneManager_.GetAudioScene() == AUDIO_SCENE_PHONE_CALL) {
666         AUDIO_INFO_LOG("Current scene is phone call, concede incoming voip fast output stream");
667         flag = AUDIO_FLAG_NORMAL;
668     }
669     return flag;
670 }
671 
GetSessionDefaultOutputDevice(const int32_t callerPid,DeviceType & deviceType)672 int32_t AudioCoreService::GetSessionDefaultOutputDevice(const int32_t callerPid, DeviceType &deviceType)
673 {
674     if (audioSessionService_ == nullptr) {
675         AUDIO_ERR_LOG("GetSessionDefaultOutputDevice audioSessionService_ is nullptr!");
676         return ERR_UNKNOWN;
677     }
678 
679     deviceType = audioSessionService_->GetSessionDefaultOutputDevice(callerPid);
680     return SUCCESS;
681 }
682 
SetSessionDefaultOutputDevice(const int32_t callerPid,const DeviceType & deviceType)683 int32_t AudioCoreService::SetSessionDefaultOutputDevice(const int32_t callerPid, const DeviceType &deviceType)
684 {
685     CHECK_AND_RETURN_RET_LOG(AudioPolicyConfigManager::GetInstance().GetHasEarpiece(), ERR_NOT_SUPPORTED,
686         "the device has no earpiece");
687 
688     if (audioSessionService_ == nullptr) {
689         AUDIO_ERR_LOG("SetSessionDefaultOutputDevice audioSessionService_ is nullptr!");
690         return ERR_UNKNOWN;
691     }
692 
693     return audioSessionService_->SetSessionDefaultOutputDevice(callerPid, deviceType);
694 }
695 
GetPreferredInputStreamType(AudioCapturerInfo & capturerInfo)696 int32_t AudioCoreService::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo)
697 {
698     // Use GetPreferredInputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream
699     std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
700         GetPreferredInputDeviceDescInner(capturerInfo, LOCAL_NETWORK_ID);
701     if (preferredDeviceList.size() == 0) {
702         return AUDIO_FLAG_NORMAL;
703     }
704     int32_t flag = audioDeviceCommon_.GetPreferredInputStreamTypeInner(capturerInfo.sourceType,
705         preferredDeviceList[0]->deviceType_,
706         capturerInfo.originalFlag, preferredDeviceList[0]->networkId_, capturerInfo.samplingRate);
707     if (flag == AUDIO_FLAG_VOIP_FAST && audioSceneManager_.GetAudioScene() == AUDIO_SCENE_PHONE_CALL) {
708         AUDIO_INFO_LOG("Current scene is phone call, concede incoming voip fast input stream");
709         flag = AUDIO_FLAG_NORMAL;
710     }
711     return flag;
712 }
713 
GetVolumeGroupInfos(std::vector<sptr<VolumeGroupInfo>> & infos)714 bool AudioCoreService::GetVolumeGroupInfos(std::vector<sptr<VolumeGroupInfo>> &infos)
715 {
716     return audioVolumeManager_.GetVolumeGroupInfosNotWait(infos);
717 }
718 
GetActiveBluetoothDevice()719 std::shared_ptr<AudioDeviceDescriptor> AudioCoreService::GetActiveBluetoothDevice()
720 {
721     std::shared_ptr<AudioDeviceDescriptor> preferredDesc = audioStateManager_.GetPreferredCallRenderDevice();
722     if (preferredDesc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO) {
723         return preferredDesc;
724     }
725 
726     std::vector<shared_ptr<AudioDeviceDescriptor>> audioPrivacyDeviceDescriptors =
727         audioDeviceManager_.GetCommRenderPrivacyDevices();
728     std::vector<shared_ptr<AudioDeviceDescriptor>> activeDeviceDescriptors;
729 
730     for (const auto &desc : audioPrivacyDeviceDescriptors) {
731         if (desc->deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO || desc->exceptionFlag_ || !desc->isEnable_ ||
732             desc->connectState_ == SUSPEND_CONNECTED || AudioPolicyUtils::GetInstance().GetScoExcluded() ||
733             audioStateManager_.IsExcludedDevice(AudioDeviceUsage::CALL_OUTPUT_DEVICES, desc)) {
734             continue;
735         }
736         activeDeviceDescriptors.push_back(make_shared<AudioDeviceDescriptor>(*desc));
737     }
738 
739     uint32_t btDeviceSize = activeDeviceDescriptors.size();
740     if (btDeviceSize == 0) {
741         activeDeviceDescriptors = audioDeviceManager_.GetCommRenderBTCarDevices();
742     }
743     btDeviceSize = activeDeviceDescriptors.size();
744     if (btDeviceSize == 0) {
745         return make_shared<AudioDeviceDescriptor>();
746     } else if (btDeviceSize == 1) {
747         shared_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[0]);
748         return res;
749     }
750 
751     uint32_t index = 0;
752     for (uint32_t i = 1; i < btDeviceSize; ++i) {
753         if (activeDeviceDescriptors[i]->connectTimeStamp_ >
754             activeDeviceDescriptors[index]->connectTimeStamp_) {
755             index = i;
756         }
757     }
758     shared_ptr<AudioDeviceDescriptor> res = std::move(activeDeviceDescriptors[index]);
759     return res;
760 }
761 
OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)762 void AudioCoreService::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command)
763 {
764     audioDeviceStatus_.OnDeviceInfoUpdated(desc, command);
765 }
766 
SetCallDeviceActive(InternalDeviceType deviceType,bool active,std::string address,const int32_t uid)767 int32_t AudioCoreService::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address,
768     const int32_t uid)
769 {
770     CHECK_AND_RETURN_RET_LOG(deviceType != DEVICE_TYPE_NONE, ERR_DEVICE_NOT_SUPPORTED, "Invalid device");
771 
772     int32_t ret = audioActiveDevice_.SetCallDeviceActive(deviceType, active, address, uid);
773     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "SetCallDeviceActive failed");
774     ret = FetchDeviceAndRoute("SetCallDeviceActive", AudioStreamDeviceChangeReason::OVERRODE);
775     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "FetchDeviceAndRoute failed");
776     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
777         audioActiveDevice_.GetCurrentOutputDevice(), "SetCallDeviceActive");
778 
779     return SUCCESS;
780 }
781 
GetAvailableDevices(AudioDeviceUsage usage)782 std::vector<shared_ptr<AudioDeviceDescriptor>> AudioCoreService::GetAvailableDevices(AudioDeviceUsage usage)
783 {
784     std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
785     audioDeviceDescriptors = audioDeviceManager_.GetAvailableDevicesByUsage(usage);
786     return audioDeviceDescriptors;
787 }
788 
GetAvailableMicrophones()789 std::vector<sptr<MicrophoneDescriptor>> AudioCoreService::GetAvailableMicrophones()
790 {
791     return audioMicrophoneDescriptor_.GetAvailableMicrophones();
792 }
793 
GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)794 std::vector<sptr<MicrophoneDescriptor>> AudioCoreService::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)
795 {
796     return audioMicrophoneDescriptor_.GetAudioCapturerMicrophoneDescriptors(sessionId);
797 }
798 
GetCurrentRendererChangeInfos(vector<shared_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos,bool hasBTPermission,bool hasSystemPermission)799 int32_t AudioCoreService::GetCurrentRendererChangeInfos(vector<shared_ptr<AudioRendererChangeInfo>>
800     &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission)
801 {
802     int32_t status = streamCollector_.GetCurrentRendererChangeInfos(audioRendererChangeInfos);
803     CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status,
804         "AudioPolicyServer Get renderer change info failed");
805 
806     std::vector<std::shared_ptr<AudioDeviceDescriptor>> outputDevices =
807         audioConnectedDevice_.GetDevicesInner(OUTPUT_DEVICES_FLAG);
808     DeviceType activeDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
809     DeviceRole activeDeviceRole = OUTPUT_DEVICE;
810     std::string activeDeviceMac = audioActiveDevice_.GetCurrentOutputDeviceMacAddr();
811 
812     const auto& itr = std::find_if(outputDevices.begin(), outputDevices.end(),
813         [&activeDeviceType, &activeDeviceRole, &activeDeviceMac](const std::shared_ptr<AudioDeviceDescriptor> &desc) {
814         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
815             // This A2DP device is not the active A2DP device. Skip it.
816             return activeDeviceType != DEVICE_TYPE_BLUETOOTH_A2DP || desc->macAddress_ == activeDeviceMac;
817         }
818         return false;
819     });
820 
821     if (itr != outputDevices.end()) {
822         size_t rendererInfosSize = audioRendererChangeInfos.size();
823         for (size_t i = 0; i < rendererInfosSize; i++) {
824             UpdateRendererInfoWhenNoPermission(audioRendererChangeInfos[i], hasSystemPermission);
825             audioDeviceCommon_.UpdateDeviceInfo(audioRendererChangeInfos[i]->outputDeviceInfo, *itr,
826                 hasBTPermission, hasSystemPermission);
827         }
828     }
829     return status;
830 }
831 
GetCurrentCapturerChangeInfos(vector<shared_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos,bool hasBTPermission,bool hasSystemPermission)832 int32_t AudioCoreService::GetCurrentCapturerChangeInfos(
833     vector<shared_ptr<AudioCapturerChangeInfo>> &audioCapturerChangeInfos,
834     bool hasBTPermission, bool hasSystemPermission)
835 {
836     int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
837     CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status,
838         "AudioPolicyServer:: Get capturer change info failed");
839 
840     std::vector<std::shared_ptr<AudioDeviceDescriptor>> inputDevices = GetDevices(INPUT_DEVICES_FLAG);
841     DeviceType activeDeviceType = audioActiveDevice_.GetCurrentInputDeviceType();
842     DeviceRole activeDeviceRole = INPUT_DEVICE;
843     for (std::shared_ptr<AudioDeviceDescriptor> desc : inputDevices) {
844         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
845             size_t capturerInfosSize = audioCapturerChangeInfos.size();
846             for (size_t i = 0; i < capturerInfosSize; i++) {
847                 CHECK_AND_CONTINUE(audioCapturerChangeInfos[i] != nullptr);
848                 UpdateCapturerInfoWhenNoPermission(audioCapturerChangeInfos[i], hasSystemPermission);
849                 CHECK_AND_CONTINUE(audioRouterCenter_.IsConfigRouterStrategy(
850                     audioCapturerChangeInfos[i]->capturerInfo.sourceType));
851                 audioDeviceCommon_.UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc,
852                     hasBTPermission, hasSystemPermission);
853             }
854             break;
855         }
856     }
857     return status;
858 }
859 
GetExcludedDevices(AudioDeviceUsage audioDevUsage)860 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioCoreService::GetExcludedDevices(
861     AudioDeviceUsage audioDevUsage)
862 {
863     return audioStateManager_.GetExcludedDevices(audioDevUsage);
864 }
865 
FetchOutputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo,const AudioStreamDeviceChangeReasonExt reason)866 void AudioCoreService::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
867     const AudioStreamDeviceChangeReasonExt reason)
868 {
869     AUDIO_WARNING_LOG("Not Supported");
870 }
871 
FetchInputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo)872 void AudioCoreService::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo)
873 {
874     AUDIO_WARNING_LOG("Not Supported");
875 }
876 
ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)877 int32_t AudioCoreService::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,
878     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
879 {
880     return audioRecoveryDevice_.ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
881 }
882 
UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)883 int32_t AudioCoreService::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,
884     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
885 {
886     return audioRecoveryDevice_.UnexcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
887 }
888 
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object,const int32_t apiVersion)889 int32_t AudioCoreService::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
890     const sptr<IRemoteObject> &object, const int32_t apiVersion)
891 {
892     if (mode == AUDIO_MODE_RECORD) {
893         audioMicrophoneDescriptor_.AddAudioCapturerMicrophoneDescriptor(
894             streamChangeInfo.audioCapturerChangeInfo.sessionId, DEVICE_TYPE_NONE);
895         if (apiVersion > 0 && apiVersion < API_11) {
896             audioDeviceCommon_.UpdateDeviceInfo(streamChangeInfo.audioCapturerChangeInfo.inputDeviceInfo,
897                 std::make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentInputDevice()), false, false);
898         }
899     } else if (apiVersion > 0 && apiVersion < API_11) {
900         audioDeviceCommon_.UpdateDeviceInfo(streamChangeInfo.audioRendererChangeInfo.outputDeviceInfo,
901             std::make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentOutputDevice()), false, false);
902     }
903     return streamCollector_.RegisterTracker(mode, streamChangeInfo, object);
904 }
905 
SetAudioRouteCallback(uint32_t sessionId,const sptr<IRemoteObject> & object)906 void AudioCoreService::SetAudioRouteCallback(uint32_t sessionId, const sptr<IRemoteObject> &object)
907 {
908     CHECK_AND_RETURN_LOG(object != nullptr, "object is nullptr");
909     sptr<IStandardAudioPolicyManagerListener> listener = iface_cast<IStandardAudioPolicyManagerListener>(object);
910     CHECK_AND_RETURN_LOG(listener != nullptr, "listener is nullptr");
911     std::lock_guard<std::mutex> lock(routeUpdateCallbackMutex_);
912     routeUpdateCallback_[sessionId] = listener;
913 }
914 
UnsetAudioRouteCallback(uint32_t sessionId)915 void AudioCoreService::UnsetAudioRouteCallback(uint32_t sessionId)
916 {
917     std::lock_guard<std::mutex> lock(routeUpdateCallbackMutex_);
918     CHECK_AND_RETURN_LOG(routeUpdateCallback_.count(sessionId) != 0, "sessionId not exists");
919     routeUpdateCallback_.erase(sessionId);
920 }
921 
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)922 int32_t AudioCoreService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
923 {
924     int32_t ret = streamCollector_.UpdateTracker(mode, streamChangeInfo);
925     HandleAudioCaptureState(mode, streamChangeInfo);
926 
927     const auto &rendererState = streamChangeInfo.audioRendererChangeInfo.rendererState;
928     if (rendererState == RENDERER_PREPARED || rendererState == RENDERER_NEW || rendererState == RENDERER_INVALID) {
929         return ret; // only update tracker in new and prepared
930     }
931 
932     const auto &rendererChangeInfo = streamChangeInfo.audioRendererChangeInfo;
933     if ((mode == AUDIO_MODE_PLAYBACK) && (rendererChangeInfo.rendererInfo.streamUsage == STREAM_USAGE_RINGTONE ||
934         rendererChangeInfo.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION)) {
935         if ((rendererState == RENDERER_STOPPED ||rendererState == RENDERER_RELEASED ||
936             rendererState == RENDERER_PAUSED)) {
937             Bluetooth::AudioHfpManager::DeleteVirtualCallStream(rendererChangeInfo.sessionId);
938         }
939     }
940 
941     UpdateTracker(mode, streamChangeInfo, rendererState);
942 
943     if (audioA2dpOffloadManager_) {
944         audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(audioActiveDevice_.GetCurrentOutputDeviceType());
945     }
946 
947     SendA2dpConnectedWhileRunning(rendererState, streamChangeInfo.audioRendererChangeInfo.sessionId);
948 
949     if (mode == AUDIO_MODE_PLAYBACK) {
950         CheckOffloadStream(streamChangeInfo);
951     }
952     return ret;
953 }
954 
RegisteredTrackerClientDied(pid_t uid,pid_t pid)955 void AudioCoreService::RegisteredTrackerClientDied(pid_t uid, pid_t pid)
956 {
957     UpdateDefaultOutputDeviceWhenStopping(static_cast<int32_t>(uid));
958     UpdateInputDeviceWhenStopping(static_cast<int32_t>(uid));
959 
960     audioMicrophoneDescriptor_.RemoveAudioCapturerMicrophoneDescriptor(static_cast<int32_t>(uid));
961     streamCollector_.RegisteredTrackerClientDied(static_cast<int32_t>(uid), static_cast<int32_t>(pid));
962     CHECK_AND_RETURN_LOG(pipeManager_ != nullptr, "pipeManager is nullptr");
963     std::vector<uint32_t> sessionIds = pipeManager_->GetStreamIdsByUid(uid,
964         (AUDIO_OUTPUT_FLAG_FAST | AUDIO_INPUT_FLAG_FAST));
965     for (auto sessionId : sessionIds) {
966         ReleaseClient(sessionId);
967     }
968     sessionIds = pipeManager_->GetStreamIdsByUid(uid);
969     for (auto sessionId : sessionIds) {
970         UnsetAudioRouteCallback(sessionId);
971     }
972     FetchOutputDeviceAndRoute("RegisteredTrackerClientDied");
973 
974     audioDeviceCommon_.ClientDiedDisconnectScoNormal();
975     audioDeviceCommon_.ClientDiedDisconnectScoRecognition();
976 }
977 
ConnectServiceAdapter()978 bool AudioCoreService::ConnectServiceAdapter()
979 {
980     return audioPolicyManager_.ConnectServiceAdapter();
981 }
982 
OnReceiveBluetoothEvent(const std::string macAddress,const std::string deviceName)983 void AudioCoreService::OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName)
984 {
985     audioDeviceManager_.OnReceiveBluetoothEvent(macAddress, deviceName);
986     audioConnectedDevice_.SetDisplayName(macAddress, deviceName);
987 }
988 
DumpSelectHistory(std::string & dumpString)989 void AudioCoreService::DumpSelectHistory(std::string &dumpString)
990 {
991     dumpString += "Select device history infos\n";
992     std::lock_guard<std::mutex> lock(hisQueueMutex_);
993     dumpString += "  - TotalPipeNums: " + std::to_string(selectDeviceHistory_.size()) + "\n\n";
994     for (auto &item : selectDeviceHistory_) {
995         dumpString += item + "\n";
996     }
997     dumpString += "\n";
998 }
999 
RecordSelectDevice(const std::string & selectHistory)1000 void AudioCoreService::RecordSelectDevice(const std::string &selectHistory)
1001 {
1002     std::lock_guard<std::mutex> lock(hisQueueMutex_);
1003     if (selectDeviceHistory_.size() < SELECT_DEVICE_HISTORY_LIMIT) {
1004         selectDeviceHistory_.push_back(selectHistory);
1005         return;
1006     }
1007     while (selectDeviceHistory_.size() >= SELECT_DEVICE_HISTORY_LIMIT) {
1008         selectDeviceHistory_.pop_front();
1009     }
1010     selectDeviceHistory_.push_back(selectHistory);
1011     return;
1012 }
1013 
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)1014 int32_t AudioCoreService::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
1015     std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)
1016 {
1017     if (!selectedDesc.empty() && selectedDesc[0] != nullptr) {
1018         // eg. 2025-06-22-21:12:07:666|Uid: 6700 select output device: LOCAL_DEVICE type:2
1019         std::string selectHistory = GetTime() + "|Uid:" + std::to_string(IPCSkeleton::GetCallingUid()) + " Pid:" +
1020             std::to_string(IPCSkeleton::GetCallingPid()) + " select output device:" + selectedDesc[0]->networkId_ +
1021             " type:" + std::to_string(selectedDesc[0]->deviceType_);
1022         RecordSelectDevice(selectHistory);
1023     }
1024 
1025     return audioRecoveryDevice_.SelectOutputDevice(audioRendererFilter, selectedDesc);
1026 }
1027 
NotifyDistributedOutputChange(const AudioDeviceDescriptor & deviceDesc)1028 void AudioCoreService::NotifyDistributedOutputChange(const AudioDeviceDescriptor &deviceDesc)
1029 {
1030     audioDeviceCommon_.NotifyDistributedOutputChange(deviceDesc);
1031 }
1032 
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)1033 int32_t AudioCoreService::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
1034     std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)
1035 {
1036     if (!selectedDesc.empty() && selectedDesc[0] != nullptr) {
1037         // eg. 2025-06-22-21:12:07:666|Uid: 6700 select input device: LOCAL_DEVICE type:15
1038         std::string selectHistory = GetTime() + "|Uid:" + std::to_string(IPCSkeleton::GetCallingUid()) + " Pid:" +
1039             std::to_string(IPCSkeleton::GetCallingPid()) + " select input device:" + selectedDesc[0]->networkId_ +
1040             " type:" + std::to_string(selectedDesc[0]->deviceType_);
1041         RecordSelectDevice(selectHistory);
1042     }
1043 
1044     return audioRecoveryDevice_.SelectInputDevice(audioCapturerFilter, selectedDesc);
1045 }
1046 
NotifyRemoteRenderState(std::string networkId,std::string condition,std::string value)1047 void AudioCoreService::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value)
1048 {
1049     AUDIO_INFO_LOG("device<%{public}s> condition:%{public}s value:%{public}s",
1050         GetEncryptStr(networkId).c_str(), condition.c_str(), value.c_str());
1051 
1052     vector<SinkInput> sinkInputs;
1053     audioPolicyManager_.GetAllSinkInputs(sinkInputs);
1054     vector<SinkInput> targetSinkInputs = {};
1055     for (auto sinkInput : sinkInputs) {
1056         if (sinkInput.sinkName == networkId) {
1057             targetSinkInputs.push_back(sinkInput);
1058         }
1059     }
1060     AUDIO_DEBUG_LOG("move [%{public}zu] of all [%{public}zu]sink-inputs to local.",
1061         targetSinkInputs.size(), sinkInputs.size());
1062     std::shared_ptr<AudioDeviceDescriptor> localDevice = std::make_shared<AudioDeviceDescriptor>();
1063     CHECK_AND_RETURN_LOG(localDevice != nullptr, "Device error: null device.");
1064     localDevice->networkId_ = LOCAL_NETWORK_ID;
1065     localDevice->deviceRole_ = DeviceRole::OUTPUT_DEVICE;
1066     localDevice->deviceType_ = DeviceType::DEVICE_TYPE_SPEAKER;
1067 
1068     int32_t ret;
1069     AudioDeviceDescriptor curOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
1070     if (localDevice->deviceType_ != curOutputDeviceDesc.deviceType_) {
1071         AUDIO_WARNING_LOG("device[%{public}d] not active, use device[%{public}d] instead.",
1072             static_cast<int32_t>(localDevice->deviceType_), static_cast<int32_t>(curOutputDeviceDesc.deviceType_));
1073         ret = audioDeviceCommon_.MoveToLocalOutputDevice(targetSinkInputs,
1074             std::make_shared<AudioDeviceDescriptor>(curOutputDeviceDesc));
1075     } else {
1076         ret = audioDeviceCommon_.MoveToLocalOutputDevice(targetSinkInputs, localDevice);
1077     }
1078     CHECK_AND_RETURN_LOG((ret == SUCCESS), "MoveToLocalOutputDevice failed!");
1079 
1080     // Suspend device, notify audio stream manager that device has been changed.
1081     ret = audioPolicyManager_.SuspendAudioDevice(networkId, true);
1082     CHECK_AND_RETURN_LOG((ret == SUCCESS), "SuspendAudioDevice failed!");
1083 
1084     std::vector<std::shared_ptr<AudioDeviceDescriptor>> desc = {};
1085     desc.push_back(localDevice);
1086     UpdateTrackerDeviceChange(desc);
1087     audioDeviceCommon_.OnPreferredOutputDeviceUpdated(curOutputDeviceDesc,
1088         AudioStreamDeviceChangeReason::OLD_DEVICE_UNAVALIABLE);
1089     AUDIO_DEBUG_LOG("Success");
1090 }
1091 
OnCapturerSessionAdded(uint64_t sessionID,SessionInfo sessionInfo,AudioStreamInfo streamInfo)1092 int32_t AudioCoreService::OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo,
1093     AudioStreamInfo streamInfo)
1094 {
1095     return audioCapturerSession_.OnCapturerSessionAdded(sessionID, sessionInfo, streamInfo);
1096 }
1097 
OnCapturerSessionRemoved(uint64_t sessionID)1098 void AudioCoreService::OnCapturerSessionRemoved(uint64_t sessionID)
1099 {
1100     audioCapturerSession_.OnCapturerSessionRemoved(sessionID);
1101 }
1102 
CloseWakeUpAudioCapturer()1103 void AudioCoreService::CloseWakeUpAudioCapturer()
1104 {
1105     audioCapturerSession_.CloseWakeUpAudioCapturer();
1106 }
1107 
TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)1108 int32_t AudioCoreService::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)
1109 {
1110     FetchOutputDeviceAndRoute("TriggerFetchDevice", reason);
1111     FetchInputDeviceAndRoute("TriggerFetchDevice");
1112 
1113     // update a2dp offload
1114     audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream();
1115     audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
1116         audioActiveDevice_.GetCurrentOutputDevice(), "TriggerFetchDevice");
1117     return SUCCESS;
1118 }
1119 
1120 // No lock
SetAudioDeviceAnahsCallback(const sptr<IRemoteObject> & object)1121 int32_t AudioCoreService::SetAudioDeviceAnahsCallback(const sptr<IRemoteObject> &object)
1122 {
1123     return deviceStatusListener_->SetAudioDeviceAnahsCallback(object);
1124 }
1125 
UnsetAudioDeviceAnahsCallback()1126 int32_t AudioCoreService::UnsetAudioDeviceAnahsCallback()
1127 {
1128     return deviceStatusListener_->UnsetAudioDeviceAnahsCallback();
1129 }
1130 
OnUpdateAnahsSupport(std::string anahsShowType)1131 void AudioCoreService::OnUpdateAnahsSupport(std::string anahsShowType)
1132 {
1133     AUDIO_INFO_LOG("OnUpdateAnahsSupport show type: %{public}s", anahsShowType.c_str());
1134     deviceStatusListener_->UpdateAnahsPlatformType(anahsShowType);
1135 }
1136 
RegisterBluetoothListener()1137 void AudioCoreService::RegisterBluetoothListener()
1138 {
1139 #ifdef BLUETOOTH_ENABLE
1140     AUDIO_INFO_LOG("Enter");
1141     Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_);
1142     if (isBtListenerRegistered) {
1143         AUDIO_INFO_LOG("audio policy service already register bt listerer, return");
1144         return;
1145     }
1146     if (!isBtCrashed) {
1147         Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener();
1148         Bluetooth::AudioHfpManager::RegisterBluetoothScoListener();
1149     }
1150     isBtListenerRegistered = true;
1151     isBtCrashed = false;
1152     RegisterBluetoothDeathCallback();
1153     AudioPolicyUtils::GetInstance().SetBtConnecting(true);
1154     Bluetooth::AudioA2dpManager::CheckA2dpDeviceReconnect();
1155     Bluetooth::AudioHfpManager::CheckHfpDeviceReconnect();
1156     AudioPolicyUtils::GetInstance().SetBtConnecting(false);
1157 #endif
1158 }
1159 
UnregisterBluetoothListener()1160 void AudioCoreService::UnregisterBluetoothListener()
1161 {
1162 #ifdef BLUETOOTH_ENABLE
1163     AUDIO_INFO_LOG("Enter");
1164     Bluetooth::UnregisterDeviceObserver();
1165     Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener();
1166     Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener();
1167     isBtListenerRegistered = false;
1168 #endif
1169 }
1170 
ConfigDistributedRoutingRole(const std::shared_ptr<AudioDeviceDescriptor> descriptor,CastType type)1171 void AudioCoreService::ConfigDistributedRoutingRole(
1172     const std::shared_ptr<AudioDeviceDescriptor> descriptor, CastType type)
1173 {
1174     AUDIO_INFO_LOG("[ADeviceEvent] device %{public}d, cast type %{public}d",
1175         (descriptor != nullptr) ? descriptor->deviceType_ : -1, type);
1176     StoreDistributedRoutingRoleInfo(descriptor, type);
1177     FetchDeviceAndRoute("ConfigDistributedRoutingRole", AudioStreamDeviceChangeReason::OVERRODE);
1178 }
1179 
SetRingerMode(AudioRingerMode ringMode)1180 int32_t AudioCoreService::SetRingerMode(AudioRingerMode ringMode)
1181 {
1182     int32_t result = audioPolicyManager_.SetRingerMode(ringMode);
1183     if (result == SUCCESS) {
1184         if (Util::IsRingerAudioScene(audioSceneManager_.GetAudioScene(true))) {
1185             AUDIO_INFO_LOG("[ADeviceEvent] fetch output device after switch new ringmode");
1186             FetchOutputDeviceAndRoute("SetRingerMode");
1187             audioCapturerSession_.ReloadSourceForDeviceChange(audioActiveDevice_.GetCurrentInputDevice(),
1188                 audioActiveDevice_.GetCurrentOutputDevice(), "SetRingerMode");
1189         }
1190         Volume vol = {false, 1.0f, 0};
1191         DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1192         vol.isMute = (ringMode == RINGER_MODE_NORMAL) ? false : true;
1193         vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevel(STREAM_RING));
1194         vol.volumeFloat = GetSystemVolumeInDb(STREAM_RING, vol.volumeInt, curOutputDeviceType);
1195         audioVolumeManager_.SetSharedVolume(STREAM_RING, curOutputDeviceType, vol);
1196     }
1197     return result;
1198 }
1199 
IsNoRunningStream(std::vector<std::shared_ptr<AudioStreamDescriptor>> outputStreamDescs)1200 bool AudioCoreService::IsNoRunningStream(std::vector<std::shared_ptr<AudioStreamDescriptor>> outputStreamDescs)
1201 {
1202     for (auto streamDesc : outputStreamDescs) {
1203         if (streamDesc->streamStatus_ == STREAM_STATUS_STARTED) {
1204             return false;
1205         }
1206     }
1207     return true;
1208 }
1209 
FetchOutputDeviceAndRoute(std::string caller,const AudioStreamDeviceChangeReasonExt reason)1210 int32_t AudioCoreService::FetchOutputDeviceAndRoute(std::string caller, const AudioStreamDeviceChangeReasonExt reason)
1211 {
1212     CHECK_AND_RETURN_RET_LOG(pipeManager_ != nullptr, ERROR, "pipeManager_ is nullptr");
1213     std::vector<std::shared_ptr<AudioStreamDescriptor>> outputStreamDescs = pipeManager_->GetAllOutputStreamDescs();
1214     AUDIO_INFO_LOG("[DeviceFetchStart] by %{public}s for %{public}zu output streams, in devices %{public}s",
1215         caller.c_str(), outputStreamDescs.size(), audioDeviceManager_.GetConnDevicesStr().c_str());
1216 
1217     if (outputStreamDescs.empty() && !pipeManager_->IsModemCommunicationIdExist()) {
1218         return HandleFetchOutputWhenNoRunningStream(reason);
1219     }
1220     std::vector<std::shared_ptr<AudioDeviceDescriptor>> modemDescs;
1221     CheckModemScene(modemDescs, reason);
1222 
1223     for (auto &streamDesc : outputStreamDescs) {
1224         CHECK_AND_CONTINUE_LOG(streamDesc != nullptr, "Stream desc is nullptr");
1225         streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_;
1226         StreamUsage streamUsage = StreamUsage::STREAM_USAGE_INVALID;
1227         if (audioSessionService_ != nullptr) {
1228             streamUsage = audioSessionService_->GetAudioSessionStreamUsage(GetRealPid(streamDesc));
1229         }
1230         streamUsage = (streamUsage != StreamUsage::STREAM_USAGE_INVALID) ? streamUsage :
1231             streamDesc->rendererInfo_.streamUsage;
1232         streamDesc->newDeviceDescs_ =
1233             audioRouterCenter_.FetchOutputDevices(streamUsage, GetRealUid(streamDesc),
1234                 caller + "FetchOutputDeviceAndRoute");
1235         AUDIO_INFO_LOG("[AudioSession] streamUsage %{public}d renderer streamUsage %{public}d",
1236             streamUsage, streamDesc->rendererInfo_.streamUsage);
1237         AUDIO_INFO_LOG("[DeviceFetchInfo] device %{public}s for stream %{public}d with status %{public}u",
1238             streamDesc->GetNewDevicesTypeString().c_str(), streamDesc->sessionId_, streamDesc->streamStatus_);
1239         AUDIO_INFO_LOG("Target audioFlag 0x%{public}x for stream %{public}u",
1240             streamDesc->audioFlag_, streamDesc->sessionId_);
1241     }
1242 
1243     audioActiveDevice_.UpdateStreamDeviceMap("FetchOutputDeviceAndRoute");
1244     int32_t ret = FetchRendererPipesAndExecute(outputStreamDescs, reason);
1245     UpdateModemRoute(modemDescs);
1246     if (IsNoRunningStream(outputStreamDescs)) {
1247         HandleFetchOutputWhenNoRunningStream(reason);
1248     }
1249     return ret;
1250 }
1251 
FetchInputDeviceAndRoute(std::string caller)1252 int32_t AudioCoreService::FetchInputDeviceAndRoute(std::string caller)
1253 {
1254     std::vector<std::shared_ptr<AudioStreamDescriptor>> inputStreamDescs = pipeManager_->GetAllInputStreamDescs();
1255     AUDIO_INFO_LOG("[DeviceFetchStart] by %{public}s for %{public}zu input streams, in devices %{public}s",
1256         caller.c_str(), inputStreamDescs.size(), audioDeviceManager_.GetConnDevicesStr().c_str());
1257 
1258     if (inputStreamDescs.empty()) {
1259         return HandleFetchInputWhenNoRunningStream();
1260     }
1261 
1262     bool needUpdateActiveDevice = true;
1263     bool isUpdateActiveDevice = false;
1264     for (auto streamDesc : inputStreamDescs) {
1265         streamDesc->oldDeviceDescs_ = streamDesc->newDeviceDescs_;
1266         streamDesc->newDeviceDescs_.clear();
1267         std::shared_ptr<AudioDeviceDescriptor> inputDeviceDesc =
1268             audioRouterCenter_.FetchInputDevice(streamDesc->capturerInfo_.sourceType, GetRealUid(streamDesc),
1269                 streamDesc->sessionId_);
1270         CHECK_AND_RETURN_RET_LOG(inputDeviceDesc != nullptr, ERR_INVALID_PARAM, "inputDeviceDesc is nullptr");
1271         streamDesc->newDeviceDescs_.push_back(inputDeviceDesc);
1272         AUDIO_INFO_LOG("[DeviceFetchInfo] device %{public}s for stream %{public}d with status %{public}u",
1273             streamDesc->GetNewDevicesTypeString().c_str(), streamDesc->sessionId_, streamDesc->streamStatus_);
1274 
1275         UpdateRecordStreamFlag(streamDesc);
1276         if (!HandleInputStreamInRunning(streamDesc)) {
1277             continue;
1278         }
1279 
1280         // handle nearlink
1281         int32_t inputRet = ActivateInputDevice(streamDesc);
1282         CHECK_AND_RETURN_RET_LOG(inputRet == SUCCESS, inputRet, "Activate input device failed");
1283 
1284         if (needUpdateActiveDevice) {
1285             isUpdateActiveDevice = UpdateInputDevice(inputDeviceDesc, GetRealUid(streamDesc));
1286             needUpdateActiveDevice = false;
1287         }
1288     }
1289 
1290     int32_t ret = FetchCapturerPipesAndExecute(inputStreamDescs);
1291     if (isUpdateActiveDevice) {
1292         OnPreferredInputDeviceUpdated(audioActiveDevice_.GetCurrentInputDeviceType(), ""); // networkId is not used.
1293     }
1294     return ret;
1295 }
1296 
SetAudioServerProxy()1297 void AudioCoreService::SetAudioServerProxy()
1298 {
1299     AUDIO_INFO_LOG("SetAudioServerProxy Start");
1300     const sptr<IStandardAudioService> gsp = AudioServerProxy::GetInstance().GetAudioServerProxy();
1301     CHECK_AND_RETURN_LOG(gsp != nullptr, "SetAudioServerProxy, Audio Server Proxy is null");
1302     audioPolicyManager_.SetAudioServerProxy(gsp);
1303 }
1304 
GetDirectPlaybackSupport(const AudioStreamInfo & streamInfo,const StreamUsage & streamUsage)1305 DirectPlaybackMode AudioCoreService::GetDirectPlaybackSupport(const AudioStreamInfo &streamInfo,
1306     const StreamUsage &streamUsage)
1307 {
1308     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descs = audioRouterCenter_.FetchOutputDevices(
1309         streamUsage, getuid(), "GetDirectPlaybackSupport");
1310     CHECK_AND_RETURN_RET_LOG(!descs.empty(), DIRECT_PLAYBACK_NOT_SUPPORTED, "find output device failed");
1311     return policyConfigMananger_.GetDirectPlaybackSupport(descs.front(), streamInfo);
1312 }
1313 
1314 #ifdef BLUETOOTH_ENABLE
RegisterBluetoothDeathCallback()1315 void AudioCoreService::RegisterBluetoothDeathCallback()
1316 {
1317     lock_guard<mutex> lock(g_btProxyMutex);
1318     AUDIO_INFO_LOG("Enter");
1319     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1320     CHECK_AND_RETURN_LOG(samgr != nullptr,
1321         "get sa manager failed");
1322     sptr<IRemoteObject> object = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
1323     CHECK_AND_RETURN_LOG(object != nullptr,
1324         "get audio service remote object failed");
1325     // register death recipent
1326     sptr<AudioServerDeathRecipient> asDeathRecipient =
1327         new(std::nothrow) AudioServerDeathRecipient(getpid(), getuid());
1328     if (asDeathRecipient != nullptr) {
1329         asDeathRecipient->SetNotifyCb([] (pid_t pid, pid_t uid) {
1330             BluetoothServiceCrashedCallback(pid, uid);
1331         });
1332         bool result = object->AddDeathRecipient(asDeathRecipient);
1333         if (!result) {
1334             AUDIO_ERR_LOG("failed to add deathRecipient");
1335         }
1336     }
1337 }
1338 
BluetoothServiceCrashedCallback(pid_t pid,pid_t uid)1339 void AudioCoreService::BluetoothServiceCrashedCallback(pid_t pid, pid_t uid)
1340 {
1341     AUDIO_INFO_LOG("Bluetooth sa crashed, will restore proxy in next call");
1342     lock_guard<mutex> lock(g_btProxyMutex);
1343     isBtListenerRegistered = false;
1344     isBtCrashed = true;
1345     Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSink();
1346     Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSource();
1347     Bluetooth::AudioHfpManager::DisconnectBluetoothHfpSink();
1348 }
1349 #endif
1350 
UpdateStreamPropInfo(const std::string & adapterName,const std::string & pipeName,const std::list<DeviceStreamInfo> & deviceStreamInfo,const std::list<std::string> & supportDevices)1351 void AudioCoreService::UpdateStreamPropInfo(const std::string &adapterName, const std::string &pipeName,
1352     const std::list<DeviceStreamInfo> &deviceStreamInfo, const std::list<std::string> &supportDevices)
1353 {
1354     policyConfigMananger_.UpdateStreamPropInfo(adapterName, pipeName, deviceStreamInfo, supportDevices);
1355 }
1356 
ClearStreamPropInfo(const std::string & adapterName,const std::string & pipeName)1357 void AudioCoreService::ClearStreamPropInfo(const std::string &adapterName, const std::string &pipeName)
1358 {
1359     policyConfigMananger_.ClearStreamPropInfo(adapterName, pipeName);
1360 }
1361 
GetStreamPropInfoSize(const std::string & adapterName,const std::string & pipeName)1362 uint32_t AudioCoreService::GetStreamPropInfoSize(const std::string &adapterName, const std::string &pipeName)
1363 {
1364     return policyConfigMananger_.GetStreamPropInfoSize(adapterName, pipeName);
1365 }
1366 
CaptureConcurrentCheck(uint32_t sessionId)1367 int32_t AudioCoreService::CaptureConcurrentCheck(uint32_t sessionId)
1368 {
1369     std::shared_ptr<AudioStreamDescriptor> streamDesc = pipeManager_->GetStreamDescById(sessionId);
1370     CHECK_AND_RETURN_RET_LOG(streamDesc != nullptr, ERR_NULL_POINTER, "streamDesc is null");
1371     if (streamDesc->audioMode_ != AUDIO_MODE_RECORD) {
1372         return ERR_NOT_SUPPORTED;
1373     }
1374 
1375     auto dfxResult = std::make_unique<struct ConcurrentCaptureDfxResult>();
1376     if (!WriteCapturerConcurrentMsg(streamDesc, dfxResult)) {
1377         return ERR_INVALID_HANDLE;
1378     }
1379     LogCapturerConcurrentResult(dfxResult);
1380     WriteCapturerConcurrentEvent(dfxResult);
1381     return SUCCESS;
1382 }
1383 } // namespace AudioStandard
1384 } // namespace OHOS
1385