• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "AudioPolicyService"
17 #endif
18 
19 #include "audio_policy_service.h"
20 #include <ability_manager_client.h>
21 #include <dlfcn.h>
22 #include "iservice_registry.h"
23 
24 #include "audio_manager_listener_stub_impl.h"
25 #include "parameter.h"
26 #include "parameters.h"
27 #include "device_init_callback.h"
28 #include "audio_inner_call.h"
29 #ifdef FEATURE_DEVICE_MANAGER
30 #endif
31 
32 #include "audio_affinity_manager.h"
33 #include "audio_collaborative_service.h"
34 #include "audio_spatialization_service.h"
35 #include "audio_converter_parser.h"
36 #include "media_monitor_manager.h"
37 #include "client_type_manager.h"
38 #include "audio_safe_volume_notification.h"
39 #include "audio_setting_provider.h"
40 #include "audio_spatialization_service.h"
41 #include "audio_usb_manager.h"
42 
43 #include "audio_server_proxy.h"
44 #include "audio_policy_utils.h"
45 #include "audio_policy_global_parser.h"
46 #include "audio_background_manager.h"
47 #include "audio_core_service.h"
48 #include "audio_policy_datashare_listener.h"
49 #include "audio_zone_service.h"
50 #include "audio_policy_manager_listener.h"
51 
52 namespace OHOS {
53 namespace AudioStandard {
54 using namespace std;
55 
56 namespace {
57 static const char* CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#";
58 static const char* AUDIO_SERVICE_PKG = "audio_manager_service";
59 }
60 
61 const int32_t UID_AUDIO = 1041;
62 
63 mutex g_dataShareHelperMutex;
64 bool AudioPolicyService::isBtListenerRegistered = false;
65 bool AudioPolicyService::isBtCrashed = false;
66 
~AudioPolicyService()67 AudioPolicyService::~AudioPolicyService()
68 {
69     AUDIO_INFO_LOG("~AudioPolicyService()");
70     Deinit();
71 }
72 
LoadAudioPolicyConfig()73 bool AudioPolicyService::LoadAudioPolicyConfig()
74 {
75     bool ret = audioConfigManager_.Init();
76     if (!ret) {
77         AudioPolicyUtils::GetInstance().WriteServiceStartupError("Audio Policy Config Load Configuration failed");
78         audioCapturerSession_.SetConfigParserFlag();
79     }
80     CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Policy Config Load Configuration failed");
81     audioCapturerSession_.SetConfigParserFlag();
82     isFastControlled_ = getFastControlParam();
83     if (!ret) {
84         AudioPolicyUtils::GetInstance().WriteServiceStartupError("Audio Config Parse failed");
85     }
86     CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Config Parse failed");
87     SetDefaultAdapterEnable(audioConfigManager_.GetDefaultAdapterEnable());
88     return ret;
89 }
90 
Init(void)91 bool AudioPolicyService::Init(void)
92 {
93     audioPolicyManager_.Init();
94     audioEffectService_.EffectServiceInit();
95     audioDeviceManager_.ParseDeviceXml();
96     audioAffinityManager_.ParseAffinityXml();
97 #ifdef AUDIO_WIRED_DETECT
98     audioPnpServer_.init();
99 #endif
100     audioGlobalConfigManager_.ParseGlobalConfigXml();
101 
102     bool ret = LoadAudioPolicyConfig();
103     if (!ret) {
104         return ret;
105     }
106 
107 #ifdef FEATURE_DTMF_TONE
108     ret = audioToneManager_.LoadToneDtmfConfig();
109     CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Tone Load Configuration failed");
110 #endif
111 
112     CreateRecoveryThread();
113     std::string versionType = OHOS::system::GetParameter("const.logsystem.versiontype", "commercial");
114     AudioDump::GetInstance().SetVersionType(versionType);
115 
116     int32_t ecEnableState = system::GetBoolParameter("const.multimedia.audio.fwk_ec.enable", 0);
117     int32_t micRefEnableState = system::GetBoolParameter("const.multimedia.audio.fwk_pnr.enable", 0);
118 
119     audioEcManager_.Init(ecEnableState, micRefEnableState);
120 #ifdef HAS_FEATURE_INNERCAPTURER
121     AudioServerProxy::GetInstance().SetInnerCapLimitProxy(audioGlobalConfigManager_.GetCapLimit());
122 #endif
123     return true;
124 }
125 
CreateRecoveryThread()126 void AudioPolicyService::CreateRecoveryThread()
127 {
128     if (RecoveryDevicesThread_ != nullptr) {
129         RecoveryDevicesThread_->detach();
130     }
131     RecoveryDevicesThread_ = std::make_unique<std::thread>([this] {
132         audioRecoveryDevice_.RecoverExcludedOutputDevices();
133         audioRecoveryDevice_.RecoveryPreferredDevices();
134     });
135     pthread_setname_np(RecoveryDevicesThread_->native_handle(), "APSRecovery");
136 }
137 
Deinit(void)138 void AudioPolicyService::Deinit(void)
139 {
140     AUDIO_WARNING_LOG("Policy service died. closing active ports");
141     std::unordered_map<std::string, AudioIOHandle> mapCopy = audioIOHandleMap_.GetCopy();
142     std::for_each(mapCopy.begin(), mapCopy.end(), [&](std::pair<std::string, AudioIOHandle> handle) {
143         audioPolicyManager_.CloseAudioPort(handle.second);
144     });
145     audioPolicyManager_.Deinit();
146     audioIOHandleMap_.DeInit();
147     deviceStatusListener_->UnRegisterDeviceStatusListener();
148 #ifdef AUDIO_WIRED_DETECT
149     audioPnpServer_.StopPnpServer();
150 #endif
151 
152     if (isBtListenerRegistered) {
153         UnregisterBluetoothListener();
154     }
155 
156     audioVolumeManager_.DeInit();
157     if (RecoveryDevicesThread_ != nullptr && RecoveryDevicesThread_->joinable()) {
158         RecoveryDevicesThread_->join();
159         RecoveryDevicesThread_.reset();
160         RecoveryDevicesThread_ = nullptr;
161     }
162 
163     audioDeviceCommon_.DeInit();
164     audioRecoveryDevice_.DeInit();
165     audioDeviceStatus_.DeInit();
166     audioDeviceLock_.DeInit();
167     audioCapturerSession_.DeInit();
168     return;
169 }
170 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)171 void SafeVolumeEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
172 {
173     if (eventReceiver_ == nullptr) {
174         AUDIO_ERR_LOG("eventReceiver_ is nullptr.");
175         return;
176     }
177     eventReceiver_(eventData);
178 }
179 
SubscribeSafeVolumeEvent()180 void AudioPolicyService::SubscribeSafeVolumeEvent()
181 {
182     AUDIO_INFO_LOG("enter.");
183     EventFwk::MatchingSkills matchingSkills;
184     matchingSkills.AddEvent(AUDIO_RESTORE_VOLUME_EVENT);
185     matchingSkills.AddEvent(AUDIO_INCREASE_VOLUME_EVENT);
186     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
187     auto commonSubscribePtr = std::make_shared<SafeVolumeEventSubscriber>(subscribeInfo,
188         std::bind(&AudioPolicyService::OnReceiveEvent, this, std::placeholders::_1));
189     if (commonSubscribePtr == nullptr) {
190         AUDIO_ERR_LOG("commonSubscribePtr is nullptr");
191         return;
192     }
193     EventFwk::CommonEventManager::SubscribeCommonEvent(commonSubscribePtr);
194 }
195 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)196 void AudioPolicyService::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
197 {
198     audioVolumeManager_.OnReceiveEvent(eventData);
199 }
200 
SetAppVolumeLevel(int32_t appUid,int32_t volumeLevel)201 int32_t AudioPolicyService::SetAppVolumeLevel(int32_t appUid, int32_t volumeLevel)
202 {
203     // update dump appvolume
204     audioDeviceLock_.UpdateAppVolume(appUid, volumeLevel);
205     return audioVolumeManager_.SetAppVolumeLevel(appUid, volumeLevel);
206 }
207 
SetSourceOutputStreamMute(int32_t uid,bool setMute) const208 int32_t AudioPolicyService::SetSourceOutputStreamMute(int32_t uid, bool setMute) const
209 {
210     int32_t status = audioPolicyManager_.SetSourceOutputStreamMute(uid, setMute);
211     if (status > 0) {
212         streamCollector_.UpdateCapturerInfoMuteStatus(uid, setMute);
213     }
214     return status;
215 }
216 
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)217 std::string AudioPolicyService::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
218 {
219     (void)streamType;
220 
221     std::string selectedDevice = audioRouteMap_.GetDeviceInfoByUidAndPid(uid, pid);
222     if (selectedDevice == "") {
223         return selectedDevice;
224     }
225 
226     if (LOCAL_NETWORK_ID == selectedDevice) {
227         AUDIO_INFO_LOG("uid[%{public}d]-->local.", uid);
228         return "";
229     }
230     // check if connected.
231     if (audioConnectedDevice_.CheckDeviceConnected(selectedDevice)) {
232         AUDIO_INFO_LOG("result[%{public}s]", selectedDevice.c_str());
233         return selectedDevice;
234     } else {
235         audioRouteMap_.DelRouteMapInfoByKey(uid);
236         AUDIO_INFO_LOG("device already disconnected.");
237         return "";
238     }
239 }
240 
RestoreSession(const uint32_t & sessionID,RestoreInfo restoreInfo)241 void AudioPolicyService::RestoreSession(const uint32_t &sessionID, RestoreInfo restoreInfo)
242 {
243     AudioServerProxy::GetInstance().RestoreSessionProxy(sessionID, restoreInfo);
244 }
245 
GetDistributedRoutingRoleInfo()246 DistributedRoutingInfo AudioPolicyService::GetDistributedRoutingRoleInfo()
247 {
248     return distributedRoutingInfo_;
249 }
250 
NotifyCapturerAdded(AudioCapturerInfo capturerInfo,AudioStreamInfo streamInfo,uint32_t sessionId)251 int32_t AudioPolicyService::NotifyCapturerAdded(AudioCapturerInfo capturerInfo, AudioStreamInfo streamInfo,
252     uint32_t sessionId)
253 {
254     int32_t error = SUCCESS;
255     audioPolicyServerHandler_->SendCapturerCreateEvent(capturerInfo, streamInfo, sessionId, true, error);
256     return error;
257 }
258 
NotifyWakeUpCapturerRemoved()259 int32_t AudioPolicyService::NotifyWakeUpCapturerRemoved()
260 {
261     audioPolicyServerHandler_->SendWakeupCloseEvent(false);
262     return SUCCESS;
263 }
264 
GetFastStreamInfo()265 AudioStreamInfo AudioPolicyService::GetFastStreamInfo()
266 {
267     AudioStreamInfo streamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO};
268     streamInfo.format = audioConfigManager_.GetFastFormat();
269 
270     // change to SAMPLE_S16LE for bluetooth
271     if (streamInfo.format == SAMPLE_S32LE) {
272         DeviceType deviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
273         streamInfo.format = deviceType == DEVICE_TYPE_BLUETOOTH_A2DP ? SAMPLE_S16LE : SAMPLE_S32LE;
274     }
275     AUDIO_INFO_LOG("Fast format is %{public}d", streamInfo.format);
276     return streamInfo;
277 }
278 
IsAbsVolumeSupported()279 bool AudioPolicyService::IsAbsVolumeSupported()
280 {
281     return audioPolicyManager_.IsAbsVolumeScene();
282 }
283 
GetDevices(DeviceFlag deviceFlag)284 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevices(DeviceFlag deviceFlag)
285 {
286     return audioDeviceLock_.GetDevices(deviceFlag);
287 }
288 
GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo,std::string networkId)289 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescriptors(
290     AudioCapturerInfo &captureInfo, std::string networkId)
291 {
292     return audioDeviceLock_.GetPreferredInputDeviceDescriptors(captureInfo, networkId);
293 }
294 
GetPreferredOutputDeviceDescInner(AudioRendererInfo & rendererInfo,std::string networkId)295 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescInner(
296     AudioRendererInfo &rendererInfo, std::string networkId)
297 {
298     return audioDeviceCommon_.GetPreferredOutputDeviceDescInner(rendererInfo, networkId);
299 }
300 
GetPreferredInputDeviceDescInner(AudioCapturerInfo & captureInfo,std::string networkId)301 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescInner(
302     AudioCapturerInfo &captureInfo, std::string networkId)
303 {
304     return audioDeviceCommon_.GetPreferredInputDeviceDescInner(captureInfo, networkId);
305 }
306 
GetOutputDevice(sptr<AudioRendererFilter> audioRendererFilter)307 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetOutputDevice(
308     sptr<AudioRendererFilter> audioRendererFilter)
309 {
310     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceList = {};
311     if (audioRendererFilter->uid != -1) {
312         shared_ptr<AudioDeviceDescriptor> preferredDesc =
313             audioAffinityManager_.GetRendererDevice(audioRendererFilter->uid);
314         std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*preferredDesc);
315         deviceList.push_back(devDesc);
316     }
317     return deviceList;
318 }
319 
GetInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter)320 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetInputDevice(
321     sptr<AudioCapturerFilter> audioCapturerFilter)
322 {
323     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceList = {};
324     if (audioCapturerFilter->uid != -1) {
325         shared_ptr<AudioDeviceDescriptor> preferredDesc =
326             audioAffinityManager_.GetCapturerDevice(audioCapturerFilter->uid);
327         std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*preferredDesc);
328         deviceList.push_back(devDesc);
329     }
330     return deviceList;
331 }
332 
GetActiveOutputDeviceDescriptor()333 shared_ptr<AudioDeviceDescriptor> AudioPolicyService::GetActiveOutputDeviceDescriptor()
334 {
335     return make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentOutputDevice());
336 }
337 
OnUpdateAnahsSupport(std::string anahsShowType)338 void AudioPolicyService::OnUpdateAnahsSupport(std::string anahsShowType)
339 {
340     AUDIO_INFO_LOG("OnUpdateAnahsSupport show type: %{public}s", anahsShowType.c_str());
341     deviceStatusListener_->UpdateAnahsPlatformType(anahsShowType);
342 }
343 
OnPnpDeviceStatusUpdated(AudioDeviceDescriptor & desc,bool isConnected)344 void AudioPolicyService::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected)
345 {
346     audioDeviceLock_.OnPnpDeviceStatusUpdated(desc, isConnected);
347 }
348 
OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)349 void AudioPolicyService::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status)
350 {
351     CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
352     audioDeviceLock_.OnMicrophoneBlockedUpdate(devType, status);
353 }
354 
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo,DeviceRole role,bool hasPair)355 void AudioPolicyService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
356     const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair)
357 {
358     audioDeviceLock_.OnDeviceStatusUpdated(devType, isConnected, macAddress, deviceName, streamInfo, role, hasPair);
359 }
360 
OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,bool isConnected)361 void AudioPolicyService::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected)
362 {
363     audioDeviceLock_.OnDeviceStatusUpdated(updatedDesc, isConnected);
364 }
365 
UpdateA2dpOffloadFlagBySpatialService(const std::string & macAddress,std::unordered_map<uint32_t,bool> & sessionIDToSpatializationEnableMap)366 void AudioPolicyService::UpdateA2dpOffloadFlagBySpatialService(
367     const std::string& macAddress, std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnableMap)
368 {
369     DeviceType spatialDevice = audioDeviceCommon_.GetSpatialDeviceType(macAddress);
370     if (audioA2dpOffloadManager_) {
371         audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(sessionIDToSpatializationEnableMap, spatialDevice);
372     }
373 }
374 
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)375 void AudioPolicyService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
376     const std::string &deviceName, const AudioStreamInfo &streamInfo)
377 {
378     audioDeviceLock_.OnDeviceConfigurationChanged(deviceType, macAddress, deviceName, streamInfo);
379 }
380 
RegisterRemoteDevStatusCallback()381 void AudioPolicyService::RegisterRemoteDevStatusCallback()
382 {
383 #ifdef FEATURE_DEVICE_MANAGER
384     std::shared_ptr<DistributedHardware::DmInitCallback> initCallback = std::make_shared<DeviceInitCallBack>();
385     int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, initCallback);
386     CHECK_AND_RETURN_LOG(ret == SUCCESS, "Init device manage failed");
387     auto callback = std::make_shared<DeviceStatusCallbackImpl>();
388     DistributedHardware::DeviceManager::GetInstance().RegisterDevStatusCallback(AUDIO_SERVICE_PKG, "", callback);
389     DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(AUDIO_SERVICE_PKG, "", callback);
390     AUDIO_INFO_LOG("Done");
391 #endif
392 }
393 
GetAllSinkInputs(std::vector<SinkInput> & sinkInputs)394 void AudioPolicyService::GetAllSinkInputs(std::vector<SinkInput> &sinkInputs)
395 {
396     AudioServerProxy::GetInstance().GetAllSinkInputsProxy(sinkInputs);
397 }
398 
RegisterAccessibilityMonitorHelper()399 void AudioPolicyService::RegisterAccessibilityMonitorHelper()
400 {
401     AudioPolicyDataShareListener::RegisterAccessiblilityBalance();
402     AudioPolicyDataShareListener::RegisterAccessiblilityMono();
403 }
404 
OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)405 void AudioPolicyService::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop)
406 {
407     audioDeviceLock_.OnDeviceStatusUpdated(statusInfo, isStop);
408 }
409 
OnServiceConnected(AudioServiceIndex serviceIndex)410 void AudioPolicyService::OnServiceConnected(AudioServiceIndex serviceIndex)
411 {
412     AUDIO_INFO_LOG("Not support, use AudioCoreService");
413 }
414 
OnServiceDisconnected(AudioServiceIndex serviceIndex)415 void AudioPolicyService::OnServiceDisconnected(AudioServiceIndex serviceIndex)
416 {
417     AUDIO_WARNING_LOG("Start for [%{public}d]", serviceIndex);
418 }
419 
OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)420 void AudioPolicyService::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress)
421 {
422     audioDeviceLock_.OnForcedDeviceSelected(devType, macAddress);
423 }
424 
LoadEffectLibrary()425 void AudioPolicyService::LoadEffectLibrary()
426 {
427     // IPC -> audioservice load library
428     OriginalEffectConfig oriEffectConfig = {};
429     audioEffectService_.GetOriginalEffectConfig(oriEffectConfig);
430     vector<Effect> successLoadedEffects;
431 
432     bool loadSuccess = AudioServerProxy::GetInstance().LoadAudioEffectLibrariesProxy(oriEffectConfig.libraries,
433         oriEffectConfig.effects, successLoadedEffects);
434     if (!loadSuccess) {
435         AUDIO_ERR_LOG("Load audio effect failed, please check log");
436     }
437 
438     audioEffectService_.UpdateAvailableEffects(successLoadedEffects);
439     audioEffectService_.BuildAvailableAEConfig();
440 
441     // Initialize EffectChainManager in audio service through IPC
442     SupportedEffectConfig supportedEffectConfig;
443     audioEffectService_.GetSupportedEffectConfig(supportedEffectConfig);
444     EffectChainManagerParam effectChainManagerParam;
445     EffectChainManagerParam enhanceChainManagerParam;
446     audioEffectService_.ConstructEffectChainManagerParam(effectChainManagerParam);
447     audioEffectService_.ConstructEnhanceChainManagerParam(enhanceChainManagerParam);
448 
449     bool ret = AudioServerProxy::GetInstance().CreateEffectChainManagerProxy(supportedEffectConfig.effectChains,
450         effectChainManagerParam, enhanceChainManagerParam);
451     CHECK_AND_RETURN_LOG(ret, "EffectChainManager create failed");
452 
453     audioEffectService_.SetEffectChainManagerAvailable();
454     AudioSpatializationService::GetAudioSpatializationService().Init(supportedEffectConfig.effectChains);
455     AudioCollaborativeService::GetAudioCollaborativeService().Init(supportedEffectConfig.effectChains);
456 }
457 
SetAvailableDeviceChangeCallback(const int32_t clientId,const AudioDeviceUsage usage,const sptr<IRemoteObject> & object,bool hasBTPermission)458 int32_t AudioPolicyService::SetAvailableDeviceChangeCallback(const int32_t clientId, const AudioDeviceUsage usage,
459     const sptr<IRemoteObject> &object, bool hasBTPermission)
460 {
461     sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
462 
463     if (callback != nullptr) {
464         auto cb = std::make_shared<AudioPolicyManagerListenerCallback>(callback);
465         CHECK_AND_RETURN_RET_LOG(cb != nullptr, SUCCESS, "AudioPolicyManagerListenerCallback create failed");
466         cb->hasBTPermission_ = hasBTPermission;
467 
468         if (audioPolicyServerHandler_ != nullptr) {
469             audioPolicyServerHandler_->AddAvailableDeviceChangeMap(clientId, usage, cb);
470         }
471     }
472 
473     return SUCCESS;
474 }
475 
SetQueryClientTypeCallback(const sptr<IRemoteObject> & object)476 int32_t AudioPolicyService::SetQueryClientTypeCallback(const sptr<IRemoteObject> &object)
477 {
478 #ifdef FEATURE_APPGALLERY
479     sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
480 
481     if (callback != nullptr) {
482         ClientTypeManager::GetInstance()->SetQueryClientTypeCallback(callback);
483     } else {
484         AUDIO_ERR_LOG("Client type callback is null");
485     }
486 #endif
487     return SUCCESS;
488 }
489 
SetQueryDeviceVolumeBehaviorCallback(const sptr<IRemoteObject> & object)490 int32_t AudioPolicyService::SetQueryDeviceVolumeBehaviorCallback(const sptr<IRemoteObject> &object)
491 {
492     return audioPolicyManager_.SetQueryDeviceVolumeBehaviorCallback(object);
493 }
494 
UpdateCapturerInfoWhenNoPermission(const shared_ptr<AudioCapturerChangeInfo> & audioCapturerChangeInfos,bool hasSystemPermission)495 static void UpdateCapturerInfoWhenNoPermission(const shared_ptr<AudioCapturerChangeInfo> &audioCapturerChangeInfos,
496     bool hasSystemPermission)
497 {
498     if (!hasSystemPermission) {
499         audioCapturerChangeInfos->clientUID = 0;
500         audioCapturerChangeInfos->capturerState = CAPTURER_INVALID;
501     }
502 }
503 
GetCurrentCapturerChangeInfos(vector<shared_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos,bool hasBTPermission,bool hasSystemPermission)504 int32_t AudioPolicyService::GetCurrentCapturerChangeInfos(vector<shared_ptr<AudioCapturerChangeInfo>>
505     &audioCapturerChangeInfos, bool hasBTPermission, bool hasSystemPermission)
506 {
507     int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
508     CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status,
509         "AudioPolicyServer:: Get capturer change info failed");
510 
511     std::vector<std::shared_ptr<AudioDeviceDescriptor>> inputDevices =
512         audioConnectedDevice_.GetDevicesInner(INPUT_DEVICES_FLAG);
513     DeviceType activeDeviceType = audioActiveDevice_.GetCurrentInputDeviceType();
514     DeviceRole activeDeviceRole = INPUT_DEVICE;
515     for (std::shared_ptr<AudioDeviceDescriptor> desc : inputDevices) {
516         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
517             size_t capturerInfosSize = audioCapturerChangeInfos.size();
518             for (size_t i = 0; i < capturerInfosSize; i++) {
519                 UpdateCapturerInfoWhenNoPermission(audioCapturerChangeInfos[i], hasSystemPermission);
520                 audioDeviceCommon_.UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc,
521                     hasBTPermission, hasSystemPermission);
522             }
523             break;
524         }
525     }
526 
527     return status;
528 }
529 
UpdateDescWhenNoBTPermission(vector<std::shared_ptr<AudioDeviceDescriptor>> & deviceDescs)530 void AudioPolicyService::UpdateDescWhenNoBTPermission(vector<std::shared_ptr<AudioDeviceDescriptor>> &deviceDescs)
531 {
532     for (std::shared_ptr<AudioDeviceDescriptor> &desc : deviceDescs) {
533         CHECK_AND_CONTINUE_LOG(desc != nullptr, "Device is nullptr, continue");
534         if ((desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) || (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO)) {
535             std::shared_ptr<AudioDeviceDescriptor> copyDesc = std::make_shared<AudioDeviceDescriptor>(desc);
536             copyDesc->deviceName_ = "";
537             copyDesc->macAddress_ = "";
538             desc = copyDesc;
539         }
540     }
541 }
542 
getFastControlParam()543 bool AudioPolicyService::getFastControlParam()
544 {
545     int32_t fastControlFlag = 1; // default 1, set isFastControlled_ true
546     GetSysPara("persist.multimedia.audioflag.fastcontrolled", fastControlFlag);
547     if (fastControlFlag == 0) {
548         isFastControlled_ = false;
549     }
550     return isFastControlled_;
551 }
552 
GetPreferredOutputStreamType(AudioRendererInfo & rendererInfo,const std::string & bundleName)553 int32_t AudioPolicyService::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo,
554     const std::string &bundleName)
555 {
556     // Use GetPreferredOutputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream
557     std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
558         audioDeviceLock_.GetPreferredOutputDeviceDescriptors(rendererInfo, LOCAL_NETWORK_ID);
559     if (preferredDeviceList.size() == 0) {
560         return AUDIO_FLAG_NORMAL;
561     }
562 
563     int32_t flag = audioDeviceCommon_.GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage,
564         preferredDeviceList[0]->deviceType_, rendererInfo.rendererFlags, preferredDeviceList[0]->networkId_,
565         rendererInfo.samplingRate);
566     if (isFastControlled_ && (rendererInfo.playerType != PLAYER_TYPE_SOUND_POOL) &&
567         (flag == AUDIO_FLAG_MMAP || flag == AUDIO_FLAG_VOIP_FAST)) {
568         std::string bundleNamePre = CHECK_FAST_BLOCK_PREFIX + bundleName;
569         std::string result = AudioServerProxy::GetInstance().GetAudioParameterProxy(bundleNamePre);
570         if (result == "true") {
571             AUDIO_INFO_LOG("%{public}s not in fast list", bundleName.c_str());
572             return AUDIO_FLAG_NORMAL;
573         }
574     }
575     if (flag == AUDIO_FLAG_VOIP_FAST && audioSceneManager_.GetAudioScene() == AUDIO_SCENE_PHONE_CALL) {
576         AUDIO_INFO_LOG("Current scene is phone call, concede incoming voip fast output stream");
577         flag = AUDIO_FLAG_NORMAL;
578     }
579     return flag;
580 }
581 
SetDefaultDeviceLoadFlag(bool isLoad)582 void AudioPolicyService::SetDefaultDeviceLoadFlag(bool isLoad)
583 {
584     audioVolumeManager_.SetDefaultDeviceLoadFlag(isLoad);
585 }
586 
RegiestPolicy()587 void AudioPolicyService::RegiestPolicy()
588 {
589     AUDIO_INFO_LOG("Start");
590     sptr<PolicyProviderWrapper> wrapper = new(std::nothrow) PolicyProviderWrapper(this);
591     CHECK_AND_RETURN_LOG(wrapper != nullptr, "Get null PolicyProviderWrapper");
592     sptr<IRemoteObject> object = wrapper->AsObject();
593     CHECK_AND_RETURN_LOG(object != nullptr, "RegiestPolicy AsObject is nullptr");
594 
595     int32_t ret = AudioServerProxy::GetInstance().RegiestPolicyProviderProxy(object);
596     AUDIO_DEBUG_LOG("result:%{public}d", ret);
597 }
598 
599 /*
600  * lockFlag is use to determinewhether GetPreferredOutputDeviceDescriptor or
601 *  GetPreferredOutputDeviceDescInner is invoked.
602  * If deviceStatusUpdateSharedMutex_ write lock is not invoked at the outer layer, lockFlag can be set to true.
603  * When deviceStatusUpdateSharedMutex_ write lock has been invoked, lockFlag must be set to false.
604  */
605 
GetProcessDeviceInfo(const AudioProcessConfig & config,bool lockFlag,AudioDeviceDescriptor & deviceInfo)606 int32_t AudioPolicyService::GetProcessDeviceInfo(const AudioProcessConfig &config, bool lockFlag,
607     AudioDeviceDescriptor &deviceInfo)
608 {
609     AUDIO_INFO_LOG("%{public}s", ProcessConfig::DumpProcessConfig(config).c_str());
610     AudioSamplingRate samplingRate = config.streamInfo.samplingRate;
611     AudioStreamInfo targetStreamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO};
612     if (config.audioMode == AUDIO_MODE_PLAYBACK) {
613         if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION ||
614             config.rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) {
615             AudioRendererInfo rendererInfo = config.rendererInfo;
616             std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
617                 (lockFlag ? audioDeviceLock_.GetPreferredOutputDeviceDescriptors(rendererInfo, LOCAL_NETWORK_ID)
618                           : audioDeviceCommon_.GetPreferredOutputDeviceDescInner(rendererInfo, LOCAL_NETWORK_ID));
619             int32_t type = audioDeviceCommon_.GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage,
620                 preferredDeviceList[0]->deviceType_, rendererInfo.originalFlag, preferredDeviceList[0]->networkId_,
621                 samplingRate);
622             deviceInfo.deviceRole_ = OUTPUT_DEVICE;
623             return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList);
624         }
625         AudioDeviceDescriptor curOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
626         deviceInfo.deviceId_ = curOutputDeviceDesc.deviceId_;
627         deviceInfo.networkId_ = curOutputDeviceDesc.networkId_;
628         deviceInfo.deviceType_ = curOutputDeviceDesc.deviceType_;
629         deviceInfo.deviceRole_ = OUTPUT_DEVICE;
630         targetStreamInfo.format = curOutputDeviceDesc.deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP ?
631             audioConfigManager_.GetFastFormat() : SAMPLE_S16LE;
632         CHECK_AND_RETURN_RET_LOG(IsDevicePlaybackSupported(config, deviceInfo), ERROR, "device not support playback");
633     } else {
634         if (config.capturerInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) {
635             AudioCapturerInfo capturerInfo = config.capturerInfo;
636             std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
637                 (lockFlag ? GetPreferredInputDeviceDescriptors(capturerInfo, LOCAL_NETWORK_ID)
638                           : audioDeviceCommon_.GetPreferredInputDeviceDescInner(capturerInfo, LOCAL_NETWORK_ID));
639             int32_t type = audioDeviceCommon_.GetPreferredInputStreamTypeInner(capturerInfo.sourceType,
640                 preferredDeviceList[0]->deviceType_, capturerInfo.originalFlag, preferredDeviceList[0]->networkId_,
641                 samplingRate);
642             deviceInfo.deviceRole_ = INPUT_DEVICE;
643             return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList);
644         }
645         deviceInfo.deviceId_ = audioActiveDevice_.GetCurrentInputDevice().deviceId_;
646         deviceInfo.networkId_ = audioActiveDevice_.GetCurrentInputDevice().networkId_;
647         deviceInfo.deviceRole_ = INPUT_DEVICE;
648         deviceInfo.deviceType_ = audioActiveDevice_.GetCurrentInputDeviceType();
649     }
650 
651     // todo
652     // check process in routerMap, return target device for it
653     // put the currentActiveDevice_ in deviceinfo, so it can create with current using device.
654     // genarate the unique deviceid?
655     deviceInfo.audioStreamInfo_ = { targetStreamInfo };
656     deviceInfo.deviceName_ = "mmap_device";
657     audioRouteMap_.GetNetworkIDInFastRouterMap(config.appInfo.appUid, deviceInfo.deviceRole_, deviceInfo.networkId_);
658     deviceInfo.a2dpOffloadFlag_ = GetA2dpOffloadFlag();
659     return SUCCESS;
660 }
661 
GetVoipDeviceInfo(const AudioProcessConfig & config,AudioDeviceDescriptor & deviceInfo,int32_t type,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & preferredDeviceList)662 int32_t AudioPolicyService::GetVoipDeviceInfo(const AudioProcessConfig &config, AudioDeviceDescriptor &deviceInfo,
663     int32_t type, std::vector<std::shared_ptr<AudioDeviceDescriptor>> &preferredDeviceList)
664 {
665     if (type == AUDIO_FLAG_NORMAL) {
666         AUDIO_WARNING_LOG("Current device %{public}d not support", type);
667         return ERROR;
668     }
669     deviceInfo.deviceId_ = preferredDeviceList[0]->deviceId_;
670     deviceInfo.networkId_ = preferredDeviceList[0]->networkId_;
671     deviceInfo.deviceType_ = preferredDeviceList[0]->deviceType_;
672     deviceInfo.deviceName_ = preferredDeviceList[0]->deviceName_;
673     if (config.streamInfo.samplingRate <= SAMPLE_RATE_16000) {
674         deviceInfo.audioStreamInfo_ = {{SAMPLE_RATE_16000, ENCODING_PCM, SAMPLE_S16LE, CH_LAYOUT_STEREO}};
675     } else {
676         deviceInfo.audioStreamInfo_ = {{SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, CH_LAYOUT_STEREO}};
677     }
678     if (type == AUDIO_FLAG_VOIP_DIRECT) {
679         AUDIO_INFO_LOG("Direct VoIP stream, deviceInfo has been updated: deviceInfo.deviceType %{public}d",
680             deviceInfo.deviceType_);
681         return SUCCESS;
682     }
683     audioRouteMap_.GetNetworkIDInFastRouterMap(config.appInfo.appUid, deviceInfo.deviceRole_, deviceInfo.networkId_);
684     deviceInfo.a2dpOffloadFlag_ = GetA2dpOffloadFlag();
685     deviceInfo.isLowLatencyDevice_ = true;
686     return SUCCESS;
687 }
688 
InitSharedVolume(std::shared_ptr<AudioSharedMemory> & buffer)689 int32_t AudioPolicyService::InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer)
690 {
691     return audioVolumeManager_.InitSharedVolume(buffer);
692 }
693 
SetParameterCallback(const std::shared_ptr<AudioParameterCallback> & callback)694 void AudioPolicyService::SetParameterCallback(const std::shared_ptr<AudioParameterCallback>& callback)
695 {
696     AUDIO_INFO_LOG("Start");
697     sptr<AudioManagerListenerStubImpl> parameterChangeCbStub = new(std::nothrow) AudioManagerListenerStubImpl();
698     CHECK_AND_RETURN_LOG(parameterChangeCbStub != nullptr,
699         "parameterChangeCbStub null");
700     parameterChangeCbStub->SetParameterCallback(callback);
701 
702     sptr<IRemoteObject> object = parameterChangeCbStub->AsObject();
703     if (object == nullptr) {
704         AUDIO_ERR_LOG("listenerStub object is nullptr");
705         return;
706     }
707     AUDIO_DEBUG_LOG("done");
708     AudioServerProxy::GetInstance().SetParameterCallbackProxy(object);
709 }
710 
DynamicUnloadModule(const AudioPipeType pipeType)711 int32_t AudioPolicyService::DynamicUnloadModule(const AudioPipeType pipeType)
712 {
713     switch (pipeType) {
714         case PIPE_TYPE_OFFLOAD:
715             audioOffloadStream_.DynamicUnloadOffloadModule();
716             break;
717         case PIPE_TYPE_MULTICHANNEL:
718             return audioOffloadStream_.UnloadMchModule();
719         default:
720             AUDIO_WARNING_LOG("not supported for pipe type %{public}d", pipeType);
721             break;
722     }
723     return SUCCESS;
724 }
725 
GetMaxRendererInstances()726 int32_t AudioPolicyService::GetMaxRendererInstances()
727 {
728     return audioConfigManager_.GetMaxRendererInstances();
729 }
730 
RegisterBluetoothListener()731 void AudioPolicyService::RegisterBluetoothListener()
732 {
733 #ifdef BLUETOOTH_ENABLE
734     AUDIO_INFO_LOG("Enter");
735     Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_);
736     if (isBtListenerRegistered) {
737         AUDIO_INFO_LOG("audio policy service already register bt listerer, return");
738         return;
739     }
740 
741     if (!isBtCrashed) {
742         Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener();
743         Bluetooth::AudioHfpManager::RegisterBluetoothScoListener();
744     }
745 
746     isBtListenerRegistered = true;
747     isBtCrashed = false;
748 #endif
749 }
750 
UnregisterBluetoothListener()751 void AudioPolicyService::UnregisterBluetoothListener()
752 {
753 #ifdef BLUETOOTH_ENABLE
754     AUDIO_INFO_LOG("Enter");
755     Bluetooth::UnregisterDeviceObserver();
756     Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener();
757     Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener();
758     isBtListenerRegistered = false;
759 #endif
760 }
761 
SubscribeAccessibilityConfigObserver()762 void AudioPolicyService::SubscribeAccessibilityConfigObserver()
763 {
764 #ifdef ACCESSIBILITY_ENABLE
765     RegisterAccessibilityMonitorHelper();
766     AUDIO_INFO_LOG("Subscribe accessibility config observer successfully");
767 #endif
768 }
769 
QueryEffectManagerSceneMode(SupportedEffectConfig & supportedEffectConfig)770 int32_t AudioPolicyService::QueryEffectManagerSceneMode(SupportedEffectConfig& supportedEffectConfig)
771 {
772     int32_t ret = audioEffectService_.QueryEffectManagerSceneMode(supportedEffectConfig);
773     return ret;
774 }
775 
RegisterDataObserver()776 void AudioPolicyService::RegisterDataObserver()
777 {
778     std::string devicesName = "";
779     int32_t ret = AudioPolicyUtils::GetInstance().GetDeviceNameFromDataShareHelper(devicesName);
780     CHECK_AND_RETURN_LOG(ret == SUCCESS, "RegisterDataObserver get devicesName failed");
781     audioConnectedDevice_.SetDisplayName(devicesName, true);
782     audioConnectedDevice_.RegisterNameMonitorHelper();
783     audioPolicyManager_.RegisterDoNotDisturbStatus();
784     audioPolicyManager_.RegisterDoNotDisturbStatusWhiteList();
785 }
786 
GetHardwareOutputSamplingRate(const std::shared_ptr<AudioDeviceDescriptor> & desc)787 int32_t AudioPolicyService::GetHardwareOutputSamplingRate(const std::shared_ptr<AudioDeviceDescriptor> &desc)
788 {
789     int32_t rate = 48000;
790 
791     CHECK_AND_RETURN_RET_LOG(desc != nullptr, -1, "desc is null!");
792 
793     bool ret = audioConnectedDevice_.IsConnectedOutputDevice(desc);
794     CHECK_AND_RETURN_RET(ret, -1);
795 
796     std::unordered_map<ClassType, std::list<AudioModuleInfo>> deviceClassInfo = {};
797     audioConfigManager_.GetDeviceClassInfo(deviceClassInfo);
798     DeviceType clientDevType = desc->deviceType_;
799     for (const auto &device : deviceClassInfo) {
800         auto moduleInfoList = device.second;
801         for (auto &moduleInfo : moduleInfoList) {
802             auto serverDevType = AudioPolicyUtils::GetInstance().GetDeviceType(moduleInfo.name);
803             if (clientDevType == serverDevType) {
804                 rate = atoi(moduleInfo.rate.c_str());
805                 return rate;
806             }
807         }
808     }
809 
810     return rate;
811 }
812 
DeviceFilterByUsageInner(AudioDeviceUsage usage,const std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descs)813 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::DeviceFilterByUsageInner(AudioDeviceUsage usage,
814     const std::vector<std::shared_ptr<AudioDeviceDescriptor>>& descs)
815 {
816     std::vector<shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
817 
818     unordered_map<AudioDevicePrivacyType, list<DevicePrivacyInfo>> devicePrivacyMaps =
819         audioDeviceManager_.GetDevicePrivacyMaps();
820     for (const auto &dev : descs) {
821         for (const auto &devicePrivacy : devicePrivacyMaps) {
822             list<DevicePrivacyInfo> deviceInfos = devicePrivacy.second;
823             audioDeviceManager_.GetAvailableDevicesWithUsage(usage, deviceInfos, dev, audioDeviceDescriptors);
824         }
825     }
826     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescriptors;
827     for (const auto &dec : audioDeviceDescriptors) {
828         std::shared_ptr<AudioDeviceDescriptor> tempDec = std::make_shared<AudioDeviceDescriptor>(*dec);
829         deviceDescriptors.push_back(move(tempDec));
830     }
831     return deviceDescriptors;
832 }
833 
OffloadStartPlaying(const std::vector<int32_t> & sessionIds)834 int32_t AudioPolicyService::OffloadStartPlaying(const std::vector<int32_t> &sessionIds)
835 {
836 #ifdef BLUETOOTH_ENABLE
837     if (audioA2dpOffloadManager_) {
838         return audioA2dpOffloadManager_->OffloadStartPlaying(sessionIds);
839     }
840     AUDIO_WARNING_LOG("Null audioA2dpOffloadManager");
841 #endif
842     return SUCCESS;
843 }
844 
OffloadStopPlaying(const std::vector<int32_t> & sessionIds)845 int32_t AudioPolicyService::OffloadStopPlaying(const std::vector<int32_t> &sessionIds)
846 {
847 #ifdef BLUETOOTH_ENABLE
848     if (audioA2dpOffloadManager_) {
849         return audioA2dpOffloadManager_->OffloadStopPlaying(sessionIds);
850     }
851     AUDIO_WARNING_LOG("Null audioA2dpOffloadManager");
852 #endif
853     return SUCCESS;
854 }
855 
OffloadGetRenderPosition(uint32_t & delayValue,uint64_t & sendDataSize,uint32_t & timeStamp)856 int32_t AudioPolicyService::OffloadGetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp)
857 {
858     Trace trace("AudioPolicyService::OffloadGetRenderPosition");
859 #ifdef BLUETOOTH_ENABLE
860     DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
861     AUDIO_DEBUG_LOG("GetRenderPosition, deviceType: %{public}d, a2dpOffloadFlag: %{public}d",
862         GetA2dpOffloadFlag(), curOutputDeviceType);
863     int32_t ret = SUCCESS;
864     if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP &&
865         audioActiveDevice_.GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID &&
866         GetA2dpOffloadFlag() == A2DP_OFFLOAD) {
867         ret = Bluetooth::AudioA2dpManager::GetRenderPosition(delayValue, sendDataSize, timeStamp);
868     } else {
869         delayValue = 0;
870         sendDataSize = 0;
871         timeStamp = 0;
872     }
873     return ret;
874 #else
875     return SUCCESS;
876 #endif
877 }
878 
NearlinkGetRenderPosition(uint32_t & delayValue)879 int32_t AudioPolicyService::NearlinkGetRenderPosition(uint32_t &delayValue)
880 {
881     Trace trace("AudioPolicyService::NearlinkGetRenderPosition");
882     AudioDeviceDescriptor curOutputDevice = audioActiveDevice_.GetCurrentOutputDevice();
883     AUDIO_DEBUG_LOG("GetRenderPosition, deviceType: %{public}d", curOutputDevice.deviceType_);
884     int32_t ret = SUCCESS;
885     delayValue = 0;
886 
887     CHECK_AND_RETURN_RET(curOutputDevice.deviceType_ == DEVICE_TYPE_NEARLINK, ret);
888 
889     ret = sleAudioDeviceManager_.GetRenderPosition(curOutputDevice.macAddress_, delayValue);
890     return ret;
891 }
892 
GetAndSaveClientType(uint32_t uid,const std::string & bundleName)893 int32_t AudioPolicyService::GetAndSaveClientType(uint32_t uid, const std::string &bundleName)
894 {
895 #ifdef FEATURE_APPGALLERY
896     ClientTypeManager::GetInstance()->GetAndSaveClientType(uid, bundleName);
897 #endif
898     return SUCCESS;
899 }
900 
OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)901 void AudioPolicyService::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command)
902 {
903     audioDeviceLock_.OnDeviceInfoUpdated(desc, command);
904 }
905 
NotifyAccountsChanged(const int & id)906 void AudioPolicyService::NotifyAccountsChanged(const int &id)
907 {
908     audioPolicyManager_.NotifyAccountsChanged(id);
909     RegisterDataObserver();
910     SubscribeAccessibilityConfigObserver();
911     AudioServerProxy::GetInstance().NotifyAccountsChanged();
912 }
913 
LoadHdiEffectModel()914 void AudioPolicyService::LoadHdiEffectModel()
915 {
916     return AudioServerProxy::GetInstance().LoadHdiEffectModelProxy();
917 }
918 
GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)919 int32_t AudioPolicyService::GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
920 {
921     AudioEffectPropertyArrayV3 effectPropertyArray = {};
922     GetSupportedEffectProperty(effectPropertyArray);
923     for (auto &effectItem : effectPropertyArray.property) {
924         effectItem.flag = RENDER_EFFECT_FLAG;
925         propertyArray.property.push_back(effectItem);
926     }
927     AudioEffectPropertyArrayV3 enhancePropertyArray = {};
928     GetSupportedEnhanceProperty(enhancePropertyArray);
929     for (auto &enhanceItem : enhancePropertyArray.property) {
930         enhanceItem.flag = CAPTURE_EFFECT_FLAG;
931         propertyArray.property.push_back(enhanceItem);
932     }
933     return AUDIO_OK;
934 }
935 
GetSupportedEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)936 void AudioPolicyService::GetSupportedEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
937 {
938     std::set<std::pair<std::string, std::string>> mergedSet = {};
939     audioEffectService_.AddSupportedAudioEffectPropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
940     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(OUTPUT_DEVICES_FLAG);
941     for (auto &item : descriptor) {
942         audioEffectService_.AddSupportedAudioEffectPropertyByDevice(item->getType(), mergedSet);
943     }
944     propertyArray.property.reserve(mergedSet.size());
945     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
946         [](const std::pair<std::string, std::string>& p) {
947             return AudioEffectPropertyV3{p.first, p.second, RENDER_EFFECT_FLAG};
948         });
949     return;
950 }
951 
GetSupportedEnhanceProperty(AudioEffectPropertyArrayV3 & propertyArray)952 void AudioPolicyService::GetSupportedEnhanceProperty(AudioEffectPropertyArrayV3 &propertyArray)
953 {
954     std::set<std::pair<std::string, std::string>> mergedSet = {};
955     audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
956     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(INPUT_DEVICES_FLAG);
957     for (auto &item : descriptor) {
958         audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(item->getType(), mergedSet);
959     }
960     propertyArray.property.reserve(mergedSet.size());
961     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
962         [](const std::pair<std::string, std::string>& p) {
963             return AudioEffectPropertyV3{p.first, p.second, CAPTURE_EFFECT_FLAG};
964         });
965     return;
966 }
967 
CheckSupportedAudioEffectProperty(const AudioEffectPropertyArrayV3 & propertyArray,const EffectFlag & flag)968 int32_t AudioPolicyService::CheckSupportedAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray,
969     const EffectFlag& flag)
970 {
971     AudioEffectPropertyArrayV3 supportPropertyArray;
972     if (flag == CAPTURE_EFFECT_FLAG) {
973         GetSupportedEnhanceProperty(supportPropertyArray);
974     } else {
975         GetSupportedEffectProperty(supportPropertyArray);
976     }
977     for (auto &item : propertyArray.property) {
978         auto oIter = std::find(supportPropertyArray.property.begin(), supportPropertyArray.property.end(), item);
979         CHECK_AND_RETURN_RET_LOG(oIter != supportPropertyArray.property.end(),
980             ERR_INVALID_PARAM, "set property not valid name:%{public}s,category:%{public}s,flag:%{public}d",
981             item.name.c_str(), item.category.c_str(), item.flag);
982     }
983     return AUDIO_OK;
984 }
985 
SetAudioEffectProperty(const AudioEffectPropertyArrayV3 & propertyArray)986 int32_t AudioPolicyService::SetAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray)
987 {
988     int32_t ret = AUDIO_OK;
989     AudioEffectPropertyArrayV3 effectPropertyArray = {};
990     AudioEffectPropertyArrayV3 enhancePropertyArray = {};
991     for (auto &item : propertyArray.property) {
992         if (item.flag == CAPTURE_EFFECT_FLAG) {
993             enhancePropertyArray.property.push_back(item);
994         } else {
995             effectPropertyArray.property.push_back(item);
996         }
997     }
998     CHECK_AND_RETURN_RET_LOG(CheckSupportedAudioEffectProperty(enhancePropertyArray, CAPTURE_EFFECT_FLAG) == AUDIO_OK,
999         ERR_INVALID_PARAM, "check Audio Enhance property failed");
1000     CHECK_AND_RETURN_RET_LOG(CheckSupportedAudioEffectProperty(effectPropertyArray, RENDER_EFFECT_FLAG) == AUDIO_OK,
1001         ERR_INVALID_PARAM, "check Audio Effect property failed");
1002     if (enhancePropertyArray.property.size() > 0) {
1003         AudioEffectPropertyArrayV3 oldPropertyArray = {};
1004         ret = GetAudioEnhanceProperty(oldPropertyArray);
1005         CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "get audio enhance property fail");
1006         ret = AudioServerProxy::GetInstance().SetAudioEffectPropertyProxy(enhancePropertyArray,
1007             audioActiveDevice_.GetCurrentInputDeviceType());
1008         CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "set audio enhance property fail");
1009         audioCapturerSession_.ReloadSourceForEffect(oldPropertyArray, enhancePropertyArray);
1010     }
1011     if (effectPropertyArray.property.size() > 0) {
1012         ret = AudioServerProxy::GetInstance().SetAudioEffectPropertyProxy(effectPropertyArray);
1013         CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "set audio effect property fail");
1014     }
1015     return ret;
1016 }
1017 
GetAudioEnhanceProperty(AudioEffectPropertyArrayV3 & propertyArray)1018 int32_t AudioPolicyService::GetAudioEnhanceProperty(AudioEffectPropertyArrayV3 &propertyArray)
1019 {
1020     int32_t ret = AUDIO_OK;
1021     int32_t engineFlag = GetEngineFlag();
1022     if (engineFlag == 1) {
1023         return audioPolicyManager_.GetAudioEffectProperty(propertyArray);
1024     } else {
1025         ret = AudioServerProxy::GetInstance().GetAudioEffectPropertyProxy(propertyArray);
1026     }
1027     CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "get audio enhance property fail");
1028     auto oIter = propertyArray.property.begin();
1029     while (oIter != propertyArray.property.end()) {
1030         if (oIter->flag == RENDER_EFFECT_FLAG) {
1031             oIter = propertyArray.property.erase(oIter);
1032         } else {
1033             oIter++;
1034         }
1035     }
1036     return ret;
1037 }
1038 
GetAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)1039 int32_t AudioPolicyService::GetAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
1040 {
1041     int32_t engineFlag = GetEngineFlag();
1042     if (engineFlag == 1) {
1043         return audioPolicyManager_.GetAudioEffectProperty(propertyArray);
1044     } else {
1045         return AudioServerProxy::GetInstance().GetAudioEffectPropertyProxy(propertyArray);
1046     }
1047 }
1048 
GetSupportedAudioEffectProperty(AudioEffectPropertyArray & propertyArray)1049 int32_t AudioPolicyService::GetSupportedAudioEffectProperty(AudioEffectPropertyArray &propertyArray)
1050 {
1051     std::set<std::pair<std::string, std::string>> mergedSet = {};
1052     audioEffectService_.AddSupportedAudioEffectPropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
1053     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(OUTPUT_DEVICES_FLAG);
1054     for (auto &item : descriptor) {
1055         audioEffectService_.AddSupportedAudioEffectPropertyByDevice(item->getType(), mergedSet);
1056     }
1057     propertyArray.property.reserve(mergedSet.size());
1058     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
1059         [](const std::pair<std::string, std::string>& p) {
1060             return AudioEffectProperty{p.first, p.second};
1061         });
1062     return AUDIO_OK;
1063 }
1064 
GetSupportedAudioEnhanceProperty(AudioEnhancePropertyArray & propertyArray)1065 int32_t AudioPolicyService::GetSupportedAudioEnhanceProperty(AudioEnhancePropertyArray &propertyArray)
1066 {
1067     std::set<std::pair<std::string, std::string>> mergedSet = {};
1068     audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
1069     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(INPUT_DEVICES_FLAG);
1070     for (auto &item : descriptor) {
1071         audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(item->getType(), mergedSet);
1072     }
1073     propertyArray.property.reserve(mergedSet.size());
1074     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
1075         [](const std::pair<std::string, std::string>& p) {
1076             return AudioEnhanceProperty{p.first, p.second};
1077         });
1078     return AUDIO_OK;
1079 }
1080 
SetAudioEffectProperty(const AudioEffectPropertyArray & propertyArray)1081 int32_t AudioPolicyService::SetAudioEffectProperty(const AudioEffectPropertyArray &propertyArray)
1082 {
1083     AudioEffectPropertyArray supportPropertyArray;
1084     std::vector<AudioEffectProperty>::iterator oIter;
1085     (void)GetSupportedAudioEffectProperty(supportPropertyArray);
1086     for (auto &item : propertyArray.property) {
1087         oIter = std::find(supportPropertyArray.property.begin(), supportPropertyArray.property.end(), item);
1088         CHECK_AND_RETURN_RET_LOG(oIter != supportPropertyArray.property.end(),
1089             ERR_INVALID_PARAM, "set audio effect property not valid %{public}s:%{public}s",
1090             item.effectClass.c_str(), item.effectProp.c_str());
1091     }
1092     return AudioServerProxy::GetInstance().SetAudioEffectPropertyProxy(propertyArray);
1093 }
1094 
GetAudioEffectProperty(AudioEffectPropertyArray & propertyArray)1095 int32_t AudioPolicyService::GetAudioEffectProperty(AudioEffectPropertyArray &propertyArray)
1096 {
1097     int32_t engineFlag = GetEngineFlag();
1098     if (engineFlag == 1) {
1099         return audioPolicyManager_.GetAudioEffectProperty(propertyArray);
1100     } else {
1101         return AudioServerProxy::GetInstance().GetAudioEffectPropertyProxy(propertyArray);
1102     }
1103 }
1104 
SetAudioEnhanceProperty(const AudioEnhancePropertyArray & propertyArray)1105 int32_t AudioPolicyService::SetAudioEnhanceProperty(const AudioEnhancePropertyArray &propertyArray)
1106 {
1107     AudioEnhancePropertyArray supportPropertyArray;
1108     std::vector<AudioEnhanceProperty>::iterator oIter;
1109     (void)GetSupportedAudioEnhanceProperty(supportPropertyArray);
1110     for (auto &item : propertyArray.property) {
1111         oIter = std::find(supportPropertyArray.property.begin(), supportPropertyArray.property.end(), item);
1112         CHECK_AND_RETURN_RET_LOG(oIter != supportPropertyArray.property.end(),
1113             ERR_INVALID_PARAM, "set audio enhance property not valid %{public}s:%{public}s",
1114             item.enhanceClass.c_str(), item.enhanceProp.c_str());
1115     }
1116     AudioEnhancePropertyArray oldPropertyArray = {};
1117     int32_t ret = AudioServerProxy::GetInstance().GetAudioEnhancePropertyProxy(oldPropertyArray);
1118     CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "get audio enhance property fail");
1119 
1120     ret = AudioServerProxy::GetInstance().SetAudioEnhancePropertyProxy(propertyArray,
1121         audioActiveDevice_.GetCurrentInputDeviceType());
1122     CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "set audio enhance property fail");
1123 
1124     audioCapturerSession_.ReloadSourceForEffect(oldPropertyArray, propertyArray);
1125     return ret;
1126 }
1127 
GetAudioEnhanceProperty(AudioEnhancePropertyArray & propertyArray)1128 int32_t AudioPolicyService::GetAudioEnhanceProperty(AudioEnhancePropertyArray &propertyArray)
1129 {
1130     return AudioServerProxy::GetInstance().GetAudioEnhancePropertyProxy(propertyArray);
1131 }
1132 
GetA2dpOffloadFlag()1133 BluetoothOffloadState AudioPolicyService::GetA2dpOffloadFlag()
1134 {
1135     if (audioA2dpOffloadManager_) {
1136         return audioA2dpOffloadManager_->GetA2dpOffloadFlag();
1137     }
1138     return NO_A2DP_DEVICE;
1139 }
1140 
SetDefaultAdapterEnable(bool isEnable)1141 void AudioPolicyService::SetDefaultAdapterEnable(bool isEnable)
1142 {
1143     return AudioServerProxy::GetInstance().SetDefaultAdapterEnableProxy(isEnable);
1144 }
1145 
SetSleAudioOperationCallback(const sptr<IRemoteObject> & object)1146 int32_t AudioPolicyService::SetSleAudioOperationCallback(const sptr<IRemoteObject> &object)
1147 {
1148     sptr<IStandardSleAudioOperationCallback> sleAudioOperationCallback =
1149         iface_cast<IStandardSleAudioOperationCallback>(object);
1150     CHECK_AND_RETURN_RET_LOG(sleAudioOperationCallback != nullptr, ERROR,
1151         "sleAudioOperationCallback_ is nullptr");
1152 
1153     sleAudioDeviceManager_.SetSleAudioOperationCallback(sleAudioOperationCallback);
1154 
1155     return SUCCESS;
1156 }
1157 
NotifyCapturerRemoved(uint64_t sessionId)1158 int32_t AudioPolicyService::NotifyCapturerRemoved(uint64_t sessionId)
1159 {
1160     CHECK_AND_RETURN_RET_LOG(audioPolicyServerHandler_ != nullptr, ERROR, "audioPolicyServerHandler_ is nullptr");
1161     audioPolicyServerHandler_->SendCapturerRemovedEvent(sessionId, false);
1162     return SUCCESS;
1163 }
1164 
UpdateSpatializationSupported(const std::string macAddress,const bool support)1165 void AudioPolicyService::UpdateSpatializationSupported(const std::string macAddress, const bool support)
1166 {
1167     audioDeviceLock_.UpdateSpatializationSupported(macAddress, support);
1168 }
1169 #ifdef HAS_FEATURE_INNERCAPTURER
LoadModernInnerCapSink(int32_t innerCapId)1170 int32_t AudioPolicyService::LoadModernInnerCapSink(int32_t innerCapId)
1171 {
1172     AUDIO_INFO_LOG("Start");
1173     AudioModuleInfo moduleInfo = {};
1174     moduleInfo.lib = "libmodule-inner-capturer-sink.z.so";
1175     std::string name = INNER_CAPTURER_SINK;
1176     moduleInfo.name = name + std::to_string(innerCapId);
1177 
1178     moduleInfo.format = "s16le";
1179     moduleInfo.channels = "2"; // 2 channel
1180     moduleInfo.rate = "48000";
1181     moduleInfo.bufferSize = "3840"; // 20ms
1182 
1183     audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
1184     return SUCCESS;
1185 }
1186 
UnloadModernInnerCapSink(int32_t innerCapId)1187 int32_t AudioPolicyService::UnloadModernInnerCapSink(int32_t innerCapId)
1188 {
1189     AUDIO_INFO_LOG("Start");
1190     std::string name = INNER_CAPTURER_SINK;
1191     name += std::to_string(innerCapId);
1192 
1193     audioIOHandleMap_.ClosePortAndEraseIOHandle(name);
1194     return SUCCESS;
1195 }
1196 #endif
1197 
IsDevicePlaybackSupported(const AudioProcessConfig & config,const AudioDeviceDescriptor & deviceInfo)1198 bool AudioPolicyService::IsDevicePlaybackSupported(const AudioProcessConfig &config,
1199     const AudioDeviceDescriptor &deviceInfo)
1200 {
1201     if (audioPolicyServerHandler_ && config.streamInfo.encoding == ENCODING_EAC3 &&
1202         deviceInfo.deviceType_ != DEVICE_TYPE_HDMI && deviceInfo.deviceType_ != DEVICE_TYPE_LINE_DIGITAL) {
1203         audioPolicyServerHandler_->SendFormatUnsupportedErrorEvent(ERROR_UNSUPPORTED_FORMAT);
1204         return false;
1205     }
1206     return true;
1207 }
1208 
ClearAudioFocusBySessionID(const int32_t & sessionID)1209 int32_t AudioPolicyService::ClearAudioFocusBySessionID(const int32_t &sessionID)
1210 {
1211     return AudioZoneService::GetInstance().ClearAudioFocusBySessionID(sessionID);
1212 }
1213 
CaptureConcurrentCheck(const uint32_t & sessionID)1214 int32_t AudioPolicyService::CaptureConcurrentCheck(const uint32_t &sessionID)
1215 {
1216     return AudioCoreService::GetCoreService()->CaptureConcurrentCheck(sessionID);
1217 }
1218 } // namespace AudioStandard
1219 } // namespace OHOS
1220