• 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.h"
25 #include "parameter.h"
26 #include "parameters.h"
27 #include "data_share_observer_callback.h"
28 #include "device_init_callback.h"
29 #include "audio_inner_call.h"
30 #ifdef FEATURE_DEVICE_MANAGER
31 #endif
32 
33 #include "audio_affinity_manager.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 
47 namespace OHOS {
48 namespace AudioStandard {
49 using namespace std;
50 
51 namespace {
52 static const char* CHECK_FAST_BLOCK_PREFIX = "Is_Fast_Blocked_For_AppName#";
53 static const char* PREDICATES_STRING = "settings.general.device_name";
54 static const char* SETTINGS_DATA_BASE_URI =
55     "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true";
56 static const char* SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility";
57 static const char* AUDIO_SERVICE_PKG = "audio_manager_service";
58 constexpr int32_t BOOTUP_MUSIC_UID = 1003;
59 }
60 
61 static const std::vector<AudioVolumeType> VOLUME_TYPE_LIST = {
62     STREAM_VOICE_CALL,
63     STREAM_RING,
64     STREAM_MUSIC,
65     STREAM_VOICE_ASSISTANT,
66     STREAM_ALARM,
67     STREAM_ACCESSIBILITY,
68     STREAM_ULTRASONIC,
69     STREAM_SYSTEM,
70     STREAM_VOICE_CALL_ASSISTANT,
71     STREAM_ALL
72 };
73 
74 static const char* CONFIG_AUDIO_BALANACE_KEY = "master_balance";
75 static const char* CONFIG_AUDIO_MONO_KEY = "master_mono";
76 const int32_t UID_AUDIO = 1041;
77 static const int64_t WATI_PLAYBACK_TIME = 200000; // 200ms
78 static const uint32_t DEVICE_CONNECTED_FLAG_DURATION_MS = 3000000; // 3s
79 
IsDistributedOutput(const AudioDeviceDescriptor & desc)80 static int16_t IsDistributedOutput(const AudioDeviceDescriptor &desc)
81 {
82     return (desc.deviceType_ == DEVICE_TYPE_SPEAKER && desc.networkId_ != LOCAL_NETWORK_ID) ? 1 : 0;
83 }
84 
85 mutex g_dataShareHelperMutex;
86 #ifdef BLUETOOTH_ENABLE
87 mutex g_btProxyMutex;
88 #endif
89 bool AudioPolicyService::isBtListenerRegistered = false;
90 bool AudioPolicyService::isBtCrashed = false;
91 mutex g_policyMgrListenerMutex;
92 
~AudioPolicyService()93 AudioPolicyService::~AudioPolicyService()
94 {
95     AUDIO_INFO_LOG("~AudioPolicyService()");
96     Deinit();
97 }
98 
LoadAudioPolicyConfig()99 bool AudioPolicyService::LoadAudioPolicyConfig()
100 {
101     bool ret = audioConfigManager_.Init();
102     if (!ret) {
103         AudioPolicyUtils::GetInstance().WriteServiceStartupError("Audio Policy Config Load Configuration failed");
104         audioCapturerSession_.SetConfigParserFlag();
105     }
106     CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Policy Config Load Configuration failed");
107     audioCapturerSession_.SetConfigParserFlag();
108     isFastControlled_ = getFastControlParam();
109     if (!ret) {
110         AudioPolicyUtils::GetInstance().WriteServiceStartupError("Audio Config Parse failed");
111     }
112     CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Config Parse failed");
113     SetDefaultAdapterEnable(audioConfigManager_.GetDefaultAdapterEnable());
114     return ret;
115 }
116 
Init(void)117 bool AudioPolicyService::Init(void)
118 {
119     serviceFlag_.reset();
120     audioPolicyManager_.Init();
121     audioEffectService_.EffectServiceInit();
122     audioDeviceManager_.ParseDeviceXml();
123     audioAffinityManager_.ParseAffinityXml();
124 #ifdef AUDIO_WIRED_DETECT
125     audioPnpServer_.init();
126 #endif
127     audioGlobalConfigManager_.ParseGlobalConfigXml();
128     audioA2dpOffloadManager_ = std::make_shared<AudioA2dpOffloadManager>();
129     if (audioA2dpOffloadManager_ != nullptr) {audioA2dpOffloadManager_->Init();}
130 
131     bool ret = LoadAudioPolicyConfig();
132     if (!ret) {
133         return ret;
134     }
135 
136 #ifdef FEATURE_DTMF_TONE
137     ret = audioToneManager_.LoadToneDtmfConfig();
138     CHECK_AND_RETURN_RET_LOG(ret, false, "Audio Tone Load Configuration failed");
139 #endif
140 
141     int32_t status = deviceStatusListener_->RegisterDeviceStatusListener();
142     if (status != SUCCESS) {
143         AudioPolicyUtils::GetInstance().WriteServiceStartupError("[Policy Service] Register for device status "
144             "events failed");
145     }
146     CHECK_AND_RETURN_RET_LOG(status == SUCCESS, false, "[Policy Service] Register for device status events failed");
147 
148     audioVolumeManager_.Init(audioPolicyServerHandler_);
149     audioDeviceCommon_.Init(audioPolicyServerHandler_);
150     audioRecoveryDevice_.Init(audioA2dpOffloadManager_);
151 
152     audioDeviceStatus_.Init(audioA2dpOffloadManager_, audioPolicyServerHandler_);
153     audioDeviceLock_.Init(audioA2dpOffloadManager_);
154     audioCapturerSession_.Init(audioA2dpOffloadManager_);
155 
156     CreateRecoveryThread();
157     std::string versionType = OHOS::system::GetParameter("const.logsystem.versiontype", "commercial");
158     AudioDump::GetInstance().SetVersionType(versionType);
159 
160     int32_t ecEnableState = system::GetBoolParameter("const.multimedia.audio.fwk_ec.enable", 0);
161     int32_t micRefEnableState = system::GetBoolParameter("const.multimedia.audio.fwk_pnr.enable", 0);
162 
163     audioEcManager_.Init(ecEnableState, micRefEnableState);
164 #ifdef HAS_FEATURE_INNERCAPTURER
165     AudioServerProxy::GetInstance().SetInnerCapLimitProxy(audioGlobalConfigManager_.GetCapLimit());
166 #endif
167     return true;
168 }
169 
CreateRecoveryThread()170 void AudioPolicyService::CreateRecoveryThread()
171 {
172     if (RecoveryDevicesThread_ != nullptr) {
173         RecoveryDevicesThread_->detach();
174     }
175     RecoveryDevicesThread_ = std::make_unique<std::thread>([this] {
176         this->RecoverExcludedOutputDevices();
177         this->RecoveryPreferredDevices();
178     });
179     pthread_setname_np(RecoveryDevicesThread_->native_handle(), "APSRecovery");
180 }
181 
RecoverExcludedOutputDevices()182 void AudioPolicyService::RecoverExcludedOutputDevices()
183 {
184     audioRecoveryDevice_.RecoverExcludedOutputDevices();
185 }
186 
RecoveryPreferredDevices()187 void AudioPolicyService::RecoveryPreferredDevices()
188 {
189     return audioRecoveryDevice_.RecoveryPreferredDevices();
190 }
191 
InitKVStore()192 void AudioPolicyService::InitKVStore()
193 {
194     audioVolumeManager_.InitKVStore();
195 }
196 
SettingsDataReady()197 void AudioPolicyService::SettingsDataReady()
198 {
199     AudioServerProxy::GetInstance().NotifySettingsDataReady();
200 }
201 
ConnectServiceAdapter()202 bool AudioPolicyService::ConnectServiceAdapter()
203 {
204     bool ret = audioPolicyManager_.ConnectServiceAdapter();
205     CHECK_AND_RETURN_RET_LOG(ret, false, "Error in connecting to audio service adapter");
206 
207     OnServiceConnected(AudioServiceIndex::AUDIO_SERVICE_INDEX);
208 
209     return true;
210 }
211 
Deinit(void)212 void AudioPolicyService::Deinit(void)
213 {
214     AUDIO_WARNING_LOG("Policy service died. closing active ports");
215     std::unordered_map<std::string, AudioIOHandle> mapCopy = audioIOHandleMap_.GetCopy();
216     std::for_each(mapCopy.begin(), mapCopy.end(), [&](std::pair<std::string, AudioIOHandle> handle) {
217         audioPolicyManager_.CloseAudioPort(handle.second);
218     });
219     audioPolicyManager_.Deinit();
220     audioIOHandleMap_.DeInit();
221     deviceStatusListener_->UnRegisterDeviceStatusListener();
222 #ifdef AUDIO_WIRED_DETECT
223     audioPnpServer_.StopPnpServer();
224 #endif
225 
226     if (isBtListenerRegistered) {
227         UnregisterBluetoothListener();
228     }
229 
230     audioVolumeManager_.DeInit();
231     if (RecoveryDevicesThread_ != nullptr && RecoveryDevicesThread_->joinable()) {
232         RecoveryDevicesThread_->join();
233         RecoveryDevicesThread_.reset();
234         RecoveryDevicesThread_ = nullptr;
235     }
236 
237     audioDeviceCommon_.DeInit();
238     audioRecoveryDevice_.DeInit();
239     audioDeviceStatus_.DeInit();
240     audioDeviceLock_.DeInit();
241     audioCapturerSession_.DeInit();
242     return;
243 }
244 
SetAudioStreamRemovedCallback(AudioStreamRemovedCallback * callback)245 int32_t AudioPolicyService::SetAudioStreamRemovedCallback(AudioStreamRemovedCallback *callback)
246 {
247     return audioPolicyManager_.SetAudioStreamRemovedCallback(callback);
248 }
249 
SetAudioDeviceAnahsCallback(const sptr<IRemoteObject> & object)250 int32_t AudioPolicyService::SetAudioDeviceAnahsCallback(const sptr<IRemoteObject> &object)
251 {
252     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "SetAudioDeviceRefinerCallback object is nullptr");
253     auto callerUid = IPCSkeleton::GetCallingUid();
254     if (callerUid != UID_AUDIO) {
255         return ERROR;
256     }
257     return deviceStatusListener_->SetAudioDeviceAnahsCallback(object);
258 }
259 
UnsetAudioDeviceAnahsCallback()260 int32_t AudioPolicyService::UnsetAudioDeviceAnahsCallback()
261 {
262     auto callerUid = IPCSkeleton::GetCallingUid();
263     if (callerUid != UID_AUDIO) {
264         return ERROR;
265     }
266     return deviceStatusListener_->UnsetAudioDeviceAnahsCallback();
267 }
268 
GetMaxVolumeLevel(AudioVolumeType volumeType) const269 int32_t AudioPolicyService::GetMaxVolumeLevel(AudioVolumeType volumeType) const
270 {
271     return audioVolumeManager_.GetMaxVolumeLevel(volumeType);
272 }
273 
GetMinVolumeLevel(AudioVolumeType volumeType) const274 int32_t AudioPolicyService::GetMinVolumeLevel(AudioVolumeType volumeType) const
275 {
276     return audioVolumeManager_.GetMinVolumeLevel(volumeType);
277 }
278 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)279 void SafeVolumeEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
280 {
281     if (eventReceiver_ == nullptr) {
282         AUDIO_ERR_LOG("eventReceiver_ is nullptr.");
283         return;
284     }
285     AUDIO_INFO_LOG("receive DATA_SHARE_READY action success.");
286     eventReceiver_(eventData);
287 }
288 
SubscribeSafeVolumeEvent()289 void AudioPolicyService::SubscribeSafeVolumeEvent()
290 {
291     AUDIO_INFO_LOG("AudioPolicyService::SubscribeSafeVolumeEvent enter.");
292     EventFwk::MatchingSkills matchingSkills;
293     matchingSkills.AddEvent(AUDIO_RESTORE_VOLUME_EVENT);
294     matchingSkills.AddEvent(AUDIO_INCREASE_VOLUME_EVENT);
295     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
296     auto commonSubscribePtr = std::make_shared<SafeVolumeEventSubscriber>(subscribeInfo,
297         std::bind(&AudioPolicyService::OnReceiveEvent, this, std::placeholders::_1));
298     if (commonSubscribePtr == nullptr) {
299         AUDIO_ERR_LOG("commonSubscribePtr is nullptr");
300         return;
301     }
302     EventFwk::CommonEventManager::SubscribeCommonEvent(commonSubscribePtr);
303 }
304 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)305 void AudioPolicyService::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
306 {
307     audioVolumeManager_.OnReceiveEvent(eventData);
308 }
309 
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel)310 int32_t AudioPolicyService::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel)
311 {
312     return audioVolumeManager_.SetSystemVolumeLevel(streamType, volumeLevel);
313 }
314 
SetSystemVolumeLevelWithDevice(AudioStreamType streamType,int32_t volumeLevel,DeviceType deviceType)315 int32_t AudioPolicyService::SetSystemVolumeLevelWithDevice(AudioStreamType streamType, int32_t volumeLevel,
316     DeviceType deviceType)
317 {
318     return audioVolumeManager_.SetSystemVolumeLevelWithDevice(streamType, volumeLevel, deviceType);
319 }
320 
SetAppVolumeLevel(int32_t appUid,int32_t volumeLevel)321 int32_t AudioPolicyService::SetAppVolumeLevel(int32_t appUid, int32_t volumeLevel)
322 {
323     // update dump appvolume
324     audioDeviceLock_.UpdateAppVolume(appUid, volumeLevel);
325     return audioVolumeManager_.SetAppVolumeLevel(appUid, volumeLevel);
326 }
327 
SetAppVolumeMuted(int32_t appUid,bool muted)328 int32_t AudioPolicyService::SetAppVolumeMuted(int32_t appUid, bool muted)
329 {
330     return audioVolumeManager_.SetAppVolumeMuted(appUid, muted);
331 }
332 
IsAppVolumeMute(int32_t appUid,bool owned)333 bool AudioPolicyService::IsAppVolumeMute(int32_t appUid, bool owned)
334 {
335     return audioVolumeManager_.IsAppVolumeMute(appUid, owned);
336 }
337 
SetVoiceRingtoneMute(bool isMute)338 int32_t AudioPolicyService::SetVoiceRingtoneMute(bool isMute)
339 {
340     return audioVolumeManager_.SetVoiceRingtoneMute(isMute);
341 }
342 
GetSystemVolumeLevel(AudioStreamType streamType)343 int32_t AudioPolicyService::GetSystemVolumeLevel(AudioStreamType streamType)
344 {
345     return audioVolumeManager_.GetSystemVolumeLevel(streamType);
346 }
347 
GetAppVolumeLevel(int32_t appUid)348 int32_t AudioPolicyService::GetAppVolumeLevel(int32_t appUid)
349 {
350     return audioVolumeManager_.GetAppVolumeLevel(appUid);
351 }
352 
GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)353 int32_t AudioPolicyService::GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)
354 {
355     return audioVolumeManager_.GetSystemVolumeLevelNoMuteState(streamType);
356 }
357 
GetSystemVolumeDb(AudioStreamType streamType) const358 float AudioPolicyService::GetSystemVolumeDb(AudioStreamType streamType) const
359 {
360     return audioPolicyManager_.GetSystemVolumeDb(streamType);
361 }
362 
SetLowPowerVolume(int32_t streamId,float volume) const363 int32_t AudioPolicyService::SetLowPowerVolume(int32_t streamId, float volume) const
364 {
365     return streamCollector_.SetLowPowerVolume(streamId, volume);
366 }
367 
GetLowPowerVolume(int32_t streamId) const368 float AudioPolicyService::GetLowPowerVolume(int32_t streamId) const
369 {
370     return streamCollector_.GetLowPowerVolume(streamId);
371 }
372 
OffloadStreamSetCheck(uint32_t sessionId)373 void AudioPolicyService::OffloadStreamSetCheck(uint32_t sessionId)
374 {
375     audioOffloadStream_.OffloadStreamSetCheck(sessionId);
376     return;
377 }
378 
OffloadStreamReleaseCheck(uint32_t sessionId)379 void AudioPolicyService::OffloadStreamReleaseCheck(uint32_t sessionId)
380 {
381     audioOffloadStream_.OffloadStreamReleaseCheck(sessionId);
382     return;
383 }
384 
HandlePowerStateChanged(PowerMgr::PowerState state)385 void AudioPolicyService::HandlePowerStateChanged(PowerMgr::PowerState state)
386 {
387     audioOffloadStream_.HandlePowerStateChanged(state);
388 }
389 
GetSingleStreamVolume(int32_t streamId) const390 float AudioPolicyService::GetSingleStreamVolume(int32_t streamId) const
391 {
392     return streamCollector_.GetSingleStreamVolume(streamId);
393 }
394 
SetStreamMute(AudioStreamType streamType,bool mute,const StreamUsage & streamUsage,const DeviceType & deviceType)395 int32_t AudioPolicyService::SetStreamMute(AudioStreamType streamType, bool mute, const StreamUsage &streamUsage,
396     const DeviceType &deviceType)
397 {
398     return audioVolumeManager_.SetStreamMute(streamType, mute, streamUsage, deviceType);
399 }
400 
SetSourceOutputStreamMute(int32_t uid,bool setMute) const401 int32_t AudioPolicyService::SetSourceOutputStreamMute(int32_t uid, bool setMute) const
402 {
403     int32_t status = audioPolicyManager_.SetSourceOutputStreamMute(uid, setMute);
404     if (status > 0) {
405         streamCollector_.UpdateCapturerInfoMuteStatus(uid, setMute);
406     }
407     return status;
408 }
409 
GetStreamMute(AudioStreamType streamType)410 bool AudioPolicyService::GetStreamMute(AudioStreamType streamType)
411 {
412     return audioVolumeManager_.GetStreamMute(streamType);
413 }
414 
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)415 std::string AudioPolicyService::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
416 {
417     (void)streamType;
418 
419     std::string selectedDevice = audioRouteMap_.GetDeviceInfoByUidAndPid(uid, pid);
420     if (selectedDevice == "") {
421         return selectedDevice;
422     }
423 
424     if (LOCAL_NETWORK_ID == selectedDevice) {
425         AUDIO_INFO_LOG("uid[%{public}d]-->local.", uid);
426         return "";
427     }
428     // check if connected.
429     if (audioConnectedDevice_.CheckDeviceConnected(selectedDevice)) {
430         AUDIO_INFO_LOG("result[%{public}s]", selectedDevice.c_str());
431         return selectedDevice;
432     } else {
433         audioRouteMap_.DelRouteMapInfoByKey(uid);
434         AUDIO_INFO_LOG("device already disconnected.");
435         return "";
436     }
437 }
438 
NotifyRemoteRenderState(std::string networkId,std::string condition,std::string value)439 void AudioPolicyService::NotifyRemoteRenderState(std::string networkId, std::string condition, std::string value)
440 {
441     audioDeviceLock_.NotifyRemoteRenderState(networkId, condition, value);
442 }
443 
IsArmUsbDevice(const AudioDeviceDescriptor & desc)444 bool AudioPolicyService::IsArmUsbDevice(const AudioDeviceDescriptor &desc)
445 {
446     return audioDeviceLock_.IsArmUsbDevice(desc);
447 }
448 
RestoreSession(const uint32_t & sessionID,RestoreInfo restoreInfo)449 void AudioPolicyService::RestoreSession(const uint32_t &sessionID, RestoreInfo restoreInfo)
450 {
451     AudioServerProxy::GetInstance().RestoreSessionProxy(sessionID, restoreInfo);
452 }
453 
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)454 int32_t AudioPolicyService::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
455     std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)
456 {
457     Trace trace("AudioPolicyService::SelectOutputDevice");
458     if (!selectedDesc.empty() && selectedDesc[0]) {
459         int16_t isDistOld = IsDistributedOutput(audioActiveDevice_.GetCurrentOutputDevice());
460         int16_t isDistNew = IsDistributedOutput(selectedDesc[0]);
461         AUDIO_INFO_LOG("Entry. Check Distributed Output Change[%{public}d-->%{public}d]", isDistOld, isDistNew);
462         int16_t flag = isDistNew - isDistOld;
463         if (audioPolicyServerHandler_ && flag != 0) {
464             audioPolicyServerHandler_->SendDistribuitedOutputChangeEvent(selectedDesc[0], flag > 0);
465         }
466     }
467     return audioDeviceLock_.SelectOutputDevice(audioRendererFilter, selectedDesc);
468 }
469 
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)470 int32_t AudioPolicyService::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
471     std::vector<std::shared_ptr<AudioDeviceDescriptor>> selectedDesc)
472 {
473     return audioDeviceLock_.SelectInputDevice(audioCapturerFilter, selectedDesc);
474 }
475 
ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)476 int32_t AudioPolicyService::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,
477     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
478 {
479     Trace trace("AudioPolicyService::ExcludeOutputDevices");
480     return audioDeviceLock_.ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
481 }
482 
UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)483 int32_t AudioPolicyService::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,
484     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
485 {
486     return audioDeviceLock_.UnexcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
487 }
488 
GetExcludedDevices(AudioDeviceUsage audioDevUsage)489 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetExcludedDevices(
490     AudioDeviceUsage audioDevUsage)
491 {
492     return audioDeviceLock_.GetExcludedDevices(audioDevUsage);
493 }
494 
IsStreamActive(AudioStreamType streamType) const495 bool AudioPolicyService::IsStreamActive(AudioStreamType streamType) const
496 {
497     return audioSceneManager_.IsStreamActive(streamType);
498 }
499 
ConfigDistributedRoutingRole(const std::shared_ptr<AudioDeviceDescriptor> descriptor,CastType type)500 void AudioPolicyService::ConfigDistributedRoutingRole(
501     const std::shared_ptr<AudioDeviceDescriptor> descriptor, CastType type)
502 {
503     StoreDistributedRoutingRoleInfo(descriptor, type);
504     audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReason::OVERRODE);
505     audioDeviceCommon_.FetchDevice(false);
506 }
507 
StoreDistributedRoutingRoleInfo(const std::shared_ptr<AudioDeviceDescriptor> descriptor,CastType type)508 void AudioPolicyService::StoreDistributedRoutingRoleInfo(
509     const std::shared_ptr<AudioDeviceDescriptor> descriptor, CastType type)
510 {
511     distributedRoutingInfo_.descriptor = descriptor;
512     distributedRoutingInfo_.type = type;
513 }
514 
GetDistributedRoutingRoleInfo()515 DistributedRoutingInfo AudioPolicyService::GetDistributedRoutingRoleInfo()
516 {
517     return distributedRoutingInfo_;
518 }
519 
SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig & config)520 int32_t AudioPolicyService::SetWakeUpAudioCapturerFromAudioServer(const AudioProcessConfig &config)
521 {
522     return audioCapturerSession_.SetWakeUpAudioCapturerFromAudioServer(config);
523 }
524 
NotifyCapturerAdded(AudioCapturerInfo capturerInfo,AudioStreamInfo streamInfo,uint32_t sessionId)525 int32_t AudioPolicyService::NotifyCapturerAdded(AudioCapturerInfo capturerInfo, AudioStreamInfo streamInfo,
526     uint32_t sessionId)
527 {
528     int32_t error = SUCCESS;
529     audioPolicyServerHandler_->SendCapturerCreateEvent(capturerInfo, streamInfo, sessionId, true, error);
530     return error;
531 }
532 
NotifyWakeUpCapturerRemoved()533 int32_t AudioPolicyService::NotifyWakeUpCapturerRemoved()
534 {
535     audioPolicyServerHandler_->SendWakeupCloseEvent(false);
536     return SUCCESS;
537 }
538 
IsAbsVolumeSupported()539 bool AudioPolicyService::IsAbsVolumeSupported()
540 {
541     return IsAbsVolumeScene();
542 }
543 
CloseWakeUpAudioCapturer()544 int32_t AudioPolicyService::CloseWakeUpAudioCapturer()
545 {
546     return audioCapturerSession_.CloseWakeUpAudioCapturer();
547 }
548 
GetDevices(DeviceFlag deviceFlag)549 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevices(DeviceFlag deviceFlag)
550 {
551     return audioDeviceLock_.GetDevices(deviceFlag);
552 }
553 
GetDevicesInner(DeviceFlag deviceFlag)554 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetDevicesInner(DeviceFlag deviceFlag)
555 {
556     return audioConnectedDevice_.GetDevicesInner(deviceFlag);
557 }
558 
GetPreferredOutputDeviceDescriptors(AudioRendererInfo & rendererInfo,std::string networkId)559 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescriptors(
560     AudioRendererInfo &rendererInfo, std::string networkId)
561 {
562     return audioDeviceLock_.GetPreferredOutputDeviceDescriptors(rendererInfo, networkId);
563 }
564 
GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo,std::string networkId)565 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescriptors(
566     AudioCapturerInfo &captureInfo, std::string networkId)
567 {
568     return audioDeviceLock_.GetPreferredInputDeviceDescriptors(captureInfo, networkId);
569 }
570 
GetPreferredOutputDeviceDescInner(AudioRendererInfo & rendererInfo,std::string networkId)571 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredOutputDeviceDescInner(
572     AudioRendererInfo &rendererInfo, std::string networkId)
573 {
574     return audioDeviceCommon_.GetPreferredOutputDeviceDescInner(rendererInfo, networkId);
575 }
576 
GetPreferredInputDeviceDescInner(AudioCapturerInfo & captureInfo,std::string networkId)577 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetPreferredInputDeviceDescInner(
578     AudioCapturerInfo &captureInfo, std::string networkId)
579 {
580     return audioDeviceCommon_.GetPreferredInputDeviceDescInner(captureInfo, networkId);
581 }
582 
GetOutputDevice(sptr<AudioRendererFilter> audioRendererFilter)583 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetOutputDevice(
584     sptr<AudioRendererFilter> audioRendererFilter)
585 {
586     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceList = {};
587     if (audioRendererFilter->uid != -1) {
588         shared_ptr<AudioDeviceDescriptor> preferredDesc =
589             audioAffinityManager_.GetRendererDevice(audioRendererFilter->uid);
590         std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*preferredDesc);
591         deviceList.push_back(devDesc);
592     }
593     return deviceList;
594 }
595 
GetInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter)596 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetInputDevice(
597     sptr<AudioCapturerFilter> audioCapturerFilter)
598 {
599     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceList = {};
600     if (audioCapturerFilter->uid != -1) {
601         shared_ptr<AudioDeviceDescriptor> preferredDesc =
602             audioAffinityManager_.GetCapturerDevice(audioCapturerFilter->uid);
603         std::shared_ptr<AudioDeviceDescriptor> devDesc = std::make_shared<AudioDeviceDescriptor>(*preferredDesc);
604         deviceList.push_back(devDesc);
605     }
606     return deviceList;
607 }
608 
SetClientCallbacksEnable(const CallbackChange & callbackchange,const bool & enable)609 int32_t AudioPolicyService::SetClientCallbacksEnable(const CallbackChange &callbackchange, const bool &enable)
610 {
611     if (audioPolicyServerHandler_ != nullptr) {
612         return audioPolicyServerHandler_->SetClientCallbacksEnable(callbackchange, enable);
613     } else {
614         AUDIO_ERR_LOG("audioPolicyServerHandler_ is nullptr");
615         return AUDIO_ERR;
616     }
617 }
618 
SetMicrophoneMute(bool isMute)619 int32_t AudioPolicyService::SetMicrophoneMute(bool isMute)
620 {
621     return audioMicrophoneDescriptor_.SetMicrophoneMute(isMute);
622 }
623 
SetMicrophoneMutePersistent(const bool isMute)624 int32_t AudioPolicyService::SetMicrophoneMutePersistent(const bool isMute)
625 {
626     return audioMicrophoneDescriptor_.SetMicrophoneMutePersistent(isMute);
627 }
628 
GetPersistentMicMuteState()629 bool AudioPolicyService::GetPersistentMicMuteState()
630 {
631     return audioMicrophoneDescriptor_.GetPersistentMicMuteState();
632 }
633 
InitPersistentMicrophoneMuteState(bool & isMute)634 int32_t AudioPolicyService::InitPersistentMicrophoneMuteState(bool &isMute)
635 {
636     return audioMicrophoneDescriptor_.InitPersistentMicrophoneMuteState(isMute);
637 }
638 
IsMicrophoneMute()639 bool AudioPolicyService::IsMicrophoneMute()
640 {
641     return audioMicrophoneDescriptor_.IsMicrophoneMute();
642 }
643 
SetSystemSoundUri(const std::string & key,const std::string & uri)644 int32_t AudioPolicyService::SetSystemSoundUri(const std::string &key, const std::string &uri)
645 {
646     return audioPolicyManager_.SetSystemSoundUri(key, uri);
647 }
648 
GetSystemSoundUri(const std::string & key)649 std::string AudioPolicyService::GetSystemSoundUri(const std::string &key)
650 {
651     return audioPolicyManager_.GetSystemSoundUri(key);
652 }
653 
SetDeviceActive(InternalDeviceType deviceType,bool active,const int32_t uid)654 int32_t AudioPolicyService::SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t uid)
655 {
656     return audioDeviceLock_.SetDeviceActive(deviceType, active, uid);
657 }
658 
IsDeviceActive(InternalDeviceType deviceType)659 bool AudioPolicyService::IsDeviceActive(InternalDeviceType deviceType)
660 {
661     return audioActiveDevice_.IsDeviceActive(deviceType);
662 }
663 
GetActiveOutputDevice()664 DeviceType AudioPolicyService::GetActiveOutputDevice()
665 {
666     return audioActiveDevice_.GetCurrentOutputDeviceType();
667 }
668 
GetActiveOutputDeviceDescriptor()669 shared_ptr<AudioDeviceDescriptor> AudioPolicyService::GetActiveOutputDeviceDescriptor()
670 {
671     return make_shared<AudioDeviceDescriptor>(audioActiveDevice_.GetCurrentOutputDevice());
672 }
673 
GetActiveInputDevice()674 DeviceType AudioPolicyService::GetActiveInputDevice()
675 {
676     return audioActiveDevice_.GetCurrentInputDeviceType();
677 }
678 
SetRingerMode(AudioRingerMode ringMode)679 int32_t AudioPolicyService::SetRingerMode(AudioRingerMode ringMode)
680 {
681     int32_t result = audioPolicyManager_.SetRingerMode(ringMode);
682     if (result == SUCCESS) {
683         if (Util::IsRingerAudioScene(audioSceneManager_.GetAudioScene(true))) {
684             AUDIO_INFO_LOG("fetch output device after switch new ringmode.");
685             audioDeviceCommon_.FetchDevice(true);
686         }
687         Volume vol = {false, 1.0f, 0};
688         DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
689         vol.isMute = (ringMode == RINGER_MODE_NORMAL) ? false : true;
690         vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevel(STREAM_RING));
691         vol.volumeFloat = GetSystemVolumeInDb(STREAM_RING, vol.volumeInt, curOutputDeviceType);
692         audioVolumeManager_.SetSharedVolume(STREAM_RING, curOutputDeviceType, vol);
693     }
694     return result;
695 }
696 
GetRingerMode() const697 AudioRingerMode AudioPolicyService::GetRingerMode() const
698 {
699     return audioPolicyManager_.GetRingerMode();
700 }
701 
SetAudioScene(AudioScene audioScene,const int32_t uid,const int32_t pid)702 int32_t AudioPolicyService::SetAudioScene(AudioScene audioScene, const int32_t uid, const int32_t pid)
703 {
704     return audioDeviceLock_.SetAudioScene(audioScene, uid, pid);
705 }
706 
GetAudioScene(bool hasSystemPermission) const707 AudioScene AudioPolicyService::GetAudioScene(bool hasSystemPermission) const
708 {
709     return audioSceneManager_.GetAudioScene(hasSystemPermission);
710 }
711 
GetLastAudioScene() const712 AudioScene AudioPolicyService::GetLastAudioScene() const
713 {
714     return audioSceneManager_.GetLastAudioScene();
715 }
716 
OnUpdateAnahsSupport(std::string anahsShowType)717 void AudioPolicyService::OnUpdateAnahsSupport(std::string anahsShowType)
718 {
719     AUDIO_INFO_LOG("OnUpdateAnahsSupport show type: %{public}s", anahsShowType.c_str());
720     deviceStatusListener_->UpdateAnahsPlatformType(anahsShowType);
721 }
722 
OnPnpDeviceStatusUpdated(AudioDeviceDescriptor & desc,bool isConnected)723 void AudioPolicyService::OnPnpDeviceStatusUpdated(AudioDeviceDescriptor &desc, bool isConnected)
724 {
725     audioDeviceLock_.OnPnpDeviceStatusUpdated(desc, isConnected);
726 }
727 
OnMicrophoneBlockedUpdate(DeviceType devType,DeviceBlockStatus status)728 void AudioPolicyService::OnMicrophoneBlockedUpdate(DeviceType devType, DeviceBlockStatus status)
729 {
730     CHECK_AND_RETURN_LOG(devType != DEVICE_TYPE_NONE, "devType is none type");
731     audioDeviceLock_.OnMicrophoneBlockedUpdate(devType, status);
732 }
733 
ResetToSpeaker(DeviceType devType)734 void AudioPolicyService::ResetToSpeaker(DeviceType devType)
735 {
736     if (devType != audioActiveDevice_.GetCurrentOutputDeviceType()) {
737         return;
738     }
739     if (devType == DEVICE_TYPE_BLUETOOTH_SCO || devType == DEVICE_TYPE_USB_HEADSET ||
740         devType == DEVICE_TYPE_WIRED_HEADSET || devType == DEVICE_TYPE_WIRED_HEADPHONES) {
741         audioActiveDevice_.UpdateActiveDeviceRoute(DEVICE_TYPE_SPEAKER, DeviceFlag::OUTPUT_DEVICES_FLAG);
742     }
743 }
744 
OnDeviceStatusUpdated(DeviceType devType,bool isConnected,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo,DeviceRole role,bool hasPair)745 void AudioPolicyService::OnDeviceStatusUpdated(DeviceType devType, bool isConnected, const std::string& macAddress,
746     const std::string& deviceName, const AudioStreamInfo& streamInfo, DeviceRole role, bool hasPair)
747 {
748     audioDeviceLock_.OnDeviceStatusUpdated(devType, isConnected, macAddress, deviceName, streamInfo, role, hasPair);
749 }
750 
OnDeviceStatusUpdated(AudioDeviceDescriptor & updatedDesc,bool isConnected)751 void AudioPolicyService::OnDeviceStatusUpdated(AudioDeviceDescriptor &updatedDesc, bool isConnected)
752 {
753     audioDeviceLock_.OnDeviceStatusUpdated(updatedDesc, isConnected);
754 }
755 
756 #ifdef FEATURE_DTMF_TONE
GetSupportedTones(const std::string & countryCode)757 std::vector<int32_t> AudioPolicyService::GetSupportedTones(const std::string &countryCode)
758 {
759     return audioToneManager_.GetSupportedTones(countryCode);
760 }
761 
GetToneConfig(int32_t ltonetype,const std::string & countryCode)762 std::shared_ptr<ToneInfo> AudioPolicyService::GetToneConfig(int32_t ltonetype, const std::string &countryCode)
763 {
764     return audioToneManager_.GetToneConfig(ltonetype, countryCode);
765 }
766 #endif
UpdateA2dpOffloadFlagBySpatialService(const std::string & macAddress,std::unordered_map<uint32_t,bool> & sessionIDToSpatializationEnableMap)767 void AudioPolicyService::UpdateA2dpOffloadFlagBySpatialService(
768     const std::string& macAddress, std::unordered_map<uint32_t, bool> &sessionIDToSpatializationEnableMap)
769 {
770     DeviceType spatialDevice = audioDeviceCommon_.GetSpatialDeviceType(macAddress);
771     if (audioA2dpOffloadManager_) {
772         audioA2dpOffloadManager_->UpdateA2dpOffloadFlagForAllStream(sessionIDToSpatializationEnableMap, spatialDevice);
773     }
774 }
775 
OnDeviceConfigurationChanged(DeviceType deviceType,const std::string & macAddress,const std::string & deviceName,const AudioStreamInfo & streamInfo)776 void AudioPolicyService::OnDeviceConfigurationChanged(DeviceType deviceType, const std::string &macAddress,
777     const std::string &deviceName, const AudioStreamInfo &streamInfo)
778 {
779     audioDeviceLock_.OnDeviceConfigurationChanged(deviceType, macAddress, deviceName, streamInfo);
780 }
781 
SetDisplayName(const std::string & deviceName,bool isLocalDevice)782 void AudioPolicyService::SetDisplayName(const std::string &deviceName, bool isLocalDevice)
783 {
784     audioDeviceLock_.SetDisplayName(deviceName, isLocalDevice);
785 }
786 
SetDmDeviceType(const uint16_t dmDeviceType)787 void AudioPolicyService::SetDmDeviceType(const uint16_t dmDeviceType)
788 {
789     audioDeviceLock_.SetDmDeviceType(dmDeviceType);
790 }
791 
RegisterRemoteDevStatusCallback()792 void AudioPolicyService::RegisterRemoteDevStatusCallback()
793 {
794 #ifdef FEATURE_DEVICE_MANAGER
795     std::shared_ptr<DistributedHardware::DmInitCallback> initCallback = std::make_shared<DeviceInitCallBack>();
796     int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(AUDIO_SERVICE_PKG, initCallback);
797     CHECK_AND_RETURN_LOG(ret == SUCCESS, "Init device manage failed");
798     std::shared_ptr<DistributedHardware::DeviceStatusCallback> callback = std::make_shared<DeviceStatusCallbackImpl>();
799     DistributedHardware::DeviceManager::GetInstance().RegisterDevStatusCallback(AUDIO_SERVICE_PKG, "", callback);
800     AUDIO_INFO_LOG("Done");
801 #endif
802 }
803 
CreateDataShareHelperInstance()804 std::shared_ptr<DataShare::DataShareHelper> AudioPolicyService::CreateDataShareHelperInstance()
805 {
806     return AudioPolicyUtils::GetInstance().CreateDataShareHelperInstance();
807 }
808 
GetDeviceNameFromDataShareHelper(std::string & deviceName)809 int32_t AudioPolicyService::GetDeviceNameFromDataShareHelper(std::string &deviceName)
810 {
811     return AudioPolicyUtils::GetInstance().GetDeviceNameFromDataShareHelper(deviceName);
812 }
813 
IsDataShareReady()814 bool AudioPolicyService::IsDataShareReady()
815 {
816     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
817     CHECK_AND_RETURN_RET_LOG(samgr != nullptr, false, "[Policy Service] Get samgr failed.");
818     sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(AUDIO_POLICY_SERVICE_ID);
819     CHECK_AND_RETURN_RET_LOG(remoteObject != nullptr, false, "[Policy Service] audio service remote object is NULL.");
820     WatchTimeout guard("DataShare::DataShareHelper::Create:IsDataShareReady", CALL_IPC_COST_TIME_MS);
821     std::pair<int, std::shared_ptr<DataShare::DataShareHelper>> res = DataShare::DataShareHelper::Create(remoteObject,
822         SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI);
823     guard.CheckCurrTimeout();
824     if (res.first == DataShare::E_OK) {
825         AUDIO_INFO_LOG("DataShareHelper is ready.");
826         auto helper = res.second;
827         if (helper != nullptr) {
828             helper->Release();
829         }
830         return true;
831     } else {
832         AUDIO_WARNING_LOG("DataShareHelper::Create failed: E_DATA_SHARE_NOT_READY");
833         return false;
834     }
835 }
836 
SetDataShareReady(std::atomic<bool> isDataShareReady)837 void AudioPolicyService::SetDataShareReady(std::atomic<bool> isDataShareReady)
838 {
839     audioPolicyManager_.SetDataShareReady(std::atomic_load(&isDataShareReady));
840 }
841 
SetFirstScreenOn()842 void AudioPolicyService::SetFirstScreenOn()
843 {
844     audioDeviceCommon_.SetFirstScreenOn();
845 }
846 
SetVirtualCall(const bool isVirtual)847 int32_t AudioPolicyService::SetVirtualCall(const bool isVirtual)
848 {
849     return audioDeviceCommon_.SetVirtualCall(isVirtual);
850 }
851 
GetAllSinkInputs(std::vector<SinkInput> & sinkInputs)852 void AudioPolicyService::GetAllSinkInputs(std::vector<SinkInput> &sinkInputs)
853 {
854     AudioServerProxy::GetInstance().GetAllSinkInputsProxy(sinkInputs);
855 }
856 
RegisterNameMonitorHelper()857 void AudioPolicyService::RegisterNameMonitorHelper()
858 {
859     std::shared_ptr<DataShare::DataShareHelper> dataShareHelper
860         = AudioPolicyUtils::GetInstance().CreateDataShareHelperInstance();
861     CHECK_AND_RETURN_LOG(dataShareHelper != nullptr, "dataShareHelper is NULL");
862 
863     auto uri = std::make_shared<Uri>(std::string(SETTINGS_DATA_BASE_URI) + "&key=" + PREDICATES_STRING);
864     sptr<AAFwk::DataAbilityObserverStub> settingDataObserver = std::make_unique<DataShareObserverCallBack>().release();
865     dataShareHelper->RegisterObserver(*uri, settingDataObserver);
866 
867     dataShareHelper->Release();
868 }
869 
RegisterAccessibilityMonitorHelper()870 void AudioPolicyService::RegisterAccessibilityMonitorHelper()
871 {
872     RegisterAccessiblilityBalance();
873     RegisterAccessiblilityMono();
874 }
875 
RegisterAccessiblilityBalance()876 void AudioPolicyService::RegisterAccessiblilityBalance()
877 {
878     AudioSettingProvider &settingProvider = AudioSettingProvider::GetInstance(AUDIO_POLICY_SERVICE_ID);
879     AudioSettingObserver::UpdateFunc updateFuncBalance = [&](const std::string &key) {
880         AudioSettingProvider &settingProvider = AudioSettingProvider::GetInstance(AUDIO_POLICY_SERVICE_ID);
881         float balance = 0;
882         int32_t ret = settingProvider.GetFloatValue(CONFIG_AUDIO_BALANACE_KEY, balance, "secure");
883         CHECK_AND_RETURN_LOG(ret == SUCCESS, "get balance value failed");
884         if (balance < -1.0f || balance > 1.0f) {
885             AUDIO_WARNING_LOG("audioBalance value is out of range [-1.0, 1.0]");
886         } else {
887             OnAudioBalanceChanged(balance);
888         }
889     };
890     sptr observer = settingProvider.CreateObserver(CONFIG_AUDIO_BALANACE_KEY, updateFuncBalance);
891     ErrCode ret = settingProvider.RegisterObserver(observer, "secure");
892     if (ret != ERR_OK) {
893         AUDIO_ERR_LOG("RegisterObserver balance failed");
894     }
895     AUDIO_INFO_LOG("Register accessibility balance successfully");
896 }
897 
RegisterAccessiblilityMono()898 void AudioPolicyService::RegisterAccessiblilityMono()
899 {
900     AudioSettingProvider &settingProvider = AudioSettingProvider::GetInstance(AUDIO_POLICY_SERVICE_ID);
901     AudioSettingObserver::UpdateFunc updateFuncMono = [&](const std::string &key) {
902         AudioSettingProvider &settingProvider = AudioSettingProvider::GetInstance(AUDIO_POLICY_SERVICE_ID);
903         int32_t value = 0;
904         ErrCode ret = settingProvider.GetIntValue(CONFIG_AUDIO_MONO_KEY, value, "secure");
905         CHECK_AND_RETURN_LOG(ret == SUCCESS, "get mono value failed");
906         OnMonoAudioConfigChanged(value != 0);
907     };
908     sptr observer = settingProvider.CreateObserver(CONFIG_AUDIO_MONO_KEY, updateFuncMono);
909     ErrCode ret = settingProvider.RegisterObserver(observer, "secure");
910     if (ret != ERR_OK) {
911         AUDIO_ERR_LOG("RegisterObserver mono failed");
912     }
913     AUDIO_INFO_LOG("Register accessibility mono successfully");
914 }
915 
OnDeviceStatusUpdated(DStatusInfo statusInfo,bool isStop)916 void AudioPolicyService::OnDeviceStatusUpdated(DStatusInfo statusInfo, bool isStop)
917 {
918     audioDeviceLock_.OnDeviceStatusUpdated(statusInfo, isStop);
919 }
920 
OnServiceConnected(AudioServiceIndex serviceIndex)921 void AudioPolicyService::OnServiceConnected(AudioServiceIndex serviceIndex)
922 {
923     AUDIO_INFO_LOG("[module_load]::OnServiceConnected for [%{public}d]", serviceIndex);
924     CHECK_AND_RETURN_LOG(serviceIndex >= HDI_SERVICE_INDEX && serviceIndex <= AUDIO_SERVICE_INDEX, "invalid index");
925 
926     // If audio service or hdi service is not ready, donot load default modules
927     lock_guard<mutex> lock(serviceFlagMutex_);
928     serviceFlag_.set(serviceIndex, true);
929     if (serviceFlag_.count() != MIN_SERVICE_COUNT) {
930         AUDIO_INFO_LOG("[module_load]::hdi service or audio service not up. Cannot load default module now");
931         return;
932     }
933 
934     int32_t ret = audioDeviceLock_.OnServiceConnected(serviceIndex);
935     if (ret == SUCCESS) {
936 #ifdef USB_ENABLE
937         AudioUsbManager::GetInstance().Init(this);
938 #endif
939         audioEffectService_.SetMasterSinkAvailable();
940     }
941     // RegisterBluetoothListener() will be called when bluetooth_host is online
942     // load hdi-effect-model
943     LoadHdiEffectModel();
944     AudioServerProxy::GetInstance().NotifyAudioPolicyReady();
945 }
946 
OnServiceDisconnected(AudioServiceIndex serviceIndex)947 void AudioPolicyService::OnServiceDisconnected(AudioServiceIndex serviceIndex)
948 {
949     AUDIO_WARNING_LOG("Start for [%{public}d]", serviceIndex);
950 }
951 
OnForcedDeviceSelected(DeviceType devType,const std::string & macAddress)952 void AudioPolicyService::OnForcedDeviceSelected(DeviceType devType, const std::string &macAddress)
953 {
954     audioDeviceLock_.OnForcedDeviceSelected(devType, macAddress);
955 }
956 
OnMonoAudioConfigChanged(bool audioMono)957 void AudioPolicyService::OnMonoAudioConfigChanged(bool audioMono)
958 {
959     AUDIO_INFO_LOG("audioMono = %{public}s", audioMono? "true": "false");
960     AudioServerProxy::GetInstance().SetAudioMonoStateProxy(audioMono);
961 }
962 
OnAudioBalanceChanged(float audioBalance)963 void AudioPolicyService::OnAudioBalanceChanged(float audioBalance)
964 {
965     AUDIO_INFO_LOG("audioBalance = %{public}f", audioBalance);
966     AudioServerProxy::GetInstance().SetAudioBalanceValueProxy(audioBalance);
967 }
968 
LoadEffectLibrary()969 void AudioPolicyService::LoadEffectLibrary()
970 {
971     // IPC -> audioservice load library
972     OriginalEffectConfig oriEffectConfig = {};
973     audioEffectService_.GetOriginalEffectConfig(oriEffectConfig);
974     vector<Effect> successLoadedEffects;
975 
976     bool loadSuccess = AudioServerProxy::GetInstance().LoadAudioEffectLibrariesProxy(oriEffectConfig.libraries,
977         oriEffectConfig.effects, successLoadedEffects);
978     if (!loadSuccess) {
979         AUDIO_ERR_LOG("Load audio effect failed, please check log");
980     }
981 
982     audioEffectService_.UpdateAvailableEffects(successLoadedEffects);
983     audioEffectService_.BuildAvailableAEConfig();
984 
985     // Initialize EffectChainManager in audio service through IPC
986     SupportedEffectConfig supportedEffectConfig;
987     audioEffectService_.GetSupportedEffectConfig(supportedEffectConfig);
988     EffectChainManagerParam effectChainManagerParam;
989     EffectChainManagerParam enhanceChainManagerParam;
990     audioEffectService_.ConstructEffectChainManagerParam(effectChainManagerParam);
991     audioEffectService_.ConstructEnhanceChainManagerParam(enhanceChainManagerParam);
992 
993     bool ret = AudioServerProxy::GetInstance().CreateEffectChainManagerProxy(supportedEffectConfig.effectChains,
994         effectChainManagerParam, enhanceChainManagerParam);
995     CHECK_AND_RETURN_LOG(ret, "EffectChainManager create failed");
996 
997     audioEffectService_.SetEffectChainManagerAvailable();
998     AudioSpatializationService::GetAudioSpatializationService().Init(supportedEffectConfig.effectChains);
999 }
1000 
AddAudioPolicyClientProxyMap(int32_t clientPid,const sptr<IAudioPolicyClient> & cb)1001 void AudioPolicyService::AddAudioPolicyClientProxyMap(int32_t clientPid, const sptr<IAudioPolicyClient>& cb)
1002 {
1003     if (audioPolicyServerHandler_ != nullptr) {
1004         audioPolicyServerHandler_->AddAudioPolicyClientProxyMap(clientPid, cb);
1005     }
1006 }
1007 
ReduceAudioPolicyClientProxyMap(pid_t clientPid)1008 void AudioPolicyService::ReduceAudioPolicyClientProxyMap(pid_t clientPid)
1009 {
1010     if (audioPolicyServerHandler_ != nullptr) {
1011         audioPolicyServerHandler_->RemoveAudioPolicyClientProxyMap(clientPid);
1012     }
1013 }
1014 
SetAvailableDeviceChangeCallback(const int32_t clientId,const AudioDeviceUsage usage,const sptr<IRemoteObject> & object,bool hasBTPermission)1015 int32_t AudioPolicyService::SetAvailableDeviceChangeCallback(const int32_t clientId, const AudioDeviceUsage usage,
1016     const sptr<IRemoteObject> &object, bool hasBTPermission)
1017 {
1018     sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
1019 
1020     if (callback != nullptr) {
1021         callback->hasBTPermission_ = hasBTPermission;
1022 
1023         if (audioPolicyServerHandler_ != nullptr) {
1024             audioPolicyServerHandler_->AddAvailableDeviceChangeMap(clientId, usage, callback);
1025         }
1026     }
1027 
1028     return SUCCESS;
1029 }
1030 
SetQueryClientTypeCallback(const sptr<IRemoteObject> & object)1031 int32_t AudioPolicyService::SetQueryClientTypeCallback(const sptr<IRemoteObject> &object)
1032 {
1033 #ifdef FEATURE_APPGALLERY
1034     sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
1035 
1036     if (callback != nullptr) {
1037         ClientTypeManager::GetInstance()->SetQueryClientTypeCallback(callback);
1038     } else {
1039         AUDIO_ERR_LOG("Client type callback is null");
1040     }
1041 #endif
1042     return SUCCESS;
1043 }
1044 
SetAudioClientInfoMgrCallback(const sptr<IRemoteObject> & object)1045 int32_t AudioPolicyService::SetAudioClientInfoMgrCallback(const sptr<IRemoteObject> &object)
1046 {
1047     sptr<IStandardAudioPolicyManagerListener> callback = iface_cast<IStandardAudioPolicyManagerListener>(object);
1048 
1049     if (callback != nullptr) {
1050         return audioStateManager_.SetAudioClientInfoMgrCallback(callback);
1051     } else {
1052         AUDIO_ERR_LOG("Client info manager callback is null");
1053     }
1054     return SUCCESS;
1055 }
1056 
UnsetAvailableDeviceChangeCallback(const int32_t clientId,AudioDeviceUsage usage)1057 int32_t AudioPolicyService::UnsetAvailableDeviceChangeCallback(const int32_t clientId, AudioDeviceUsage usage)
1058 {
1059     AUDIO_INFO_LOG("Start");
1060     if (audioPolicyServerHandler_ != nullptr) {
1061         audioPolicyServerHandler_->RemoveAvailableDeviceChangeMap(clientId, usage);
1062     }
1063     return SUCCESS;
1064 }
1065 
UpdateCapturerInfoWhenNoPermission(const shared_ptr<AudioCapturerChangeInfo> & audioCapturerChangeInfos,bool hasSystemPermission)1066 static void UpdateCapturerInfoWhenNoPermission(const shared_ptr<AudioCapturerChangeInfo> &audioCapturerChangeInfos,
1067     bool hasSystemPermission)
1068 {
1069     if (!hasSystemPermission) {
1070         audioCapturerChangeInfos->clientUID = 0;
1071         audioCapturerChangeInfos->capturerState = CAPTURER_INVALID;
1072     }
1073 }
1074 
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object,const int32_t apiVersion)1075 int32_t AudioPolicyService::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
1076     const sptr<IRemoteObject> &object, const int32_t apiVersion)
1077 {
1078     return audioDeviceLock_.RegisterTracker(mode, streamChangeInfo, object, apiVersion);
1079 }
1080 
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)1081 int32_t AudioPolicyService::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
1082 {
1083     return audioDeviceLock_.UpdateTracker(mode, streamChangeInfo);
1084 }
1085 
FetchOutputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo,const AudioStreamDeviceChangeReasonExt reason)1086 void AudioPolicyService::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
1087     const AudioStreamDeviceChangeReasonExt reason)
1088 {
1089     audioDeviceLock_.FetchOutputDeviceForTrack(streamChangeInfo, reason);
1090 }
1091 
FetchInputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo)1092 void AudioPolicyService::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo)
1093 {
1094     audioDeviceLock_.FetchInputDeviceForTrack(streamChangeInfo);
1095 }
1096 
GetCurrentRendererChangeInfos(vector<shared_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos,bool hasBTPermission,bool hasSystemPermission)1097 int32_t AudioPolicyService::GetCurrentRendererChangeInfos(vector<shared_ptr<AudioRendererChangeInfo>>
1098     &audioRendererChangeInfos, bool hasBTPermission, bool hasSystemPermission)
1099 {
1100     return audioDeviceLock_.GetCurrentRendererChangeInfos(audioRendererChangeInfos, hasBTPermission,
1101         hasSystemPermission);
1102 }
1103 
GetCurrentCapturerChangeInfos(vector<shared_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos,bool hasBTPermission,bool hasSystemPermission)1104 int32_t AudioPolicyService::GetCurrentCapturerChangeInfos(vector<shared_ptr<AudioCapturerChangeInfo>>
1105     &audioCapturerChangeInfos, bool hasBTPermission, bool hasSystemPermission)
1106 {
1107     int status = streamCollector_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos);
1108     CHECK_AND_RETURN_RET_LOG(status == SUCCESS, status,
1109         "AudioPolicyServer:: Get capturer change info failed");
1110 
1111     std::vector<std::shared_ptr<AudioDeviceDescriptor>> inputDevices = GetDevicesInner(INPUT_DEVICES_FLAG);
1112     DeviceType activeDeviceType = audioActiveDevice_.GetCurrentInputDeviceType();
1113     DeviceRole activeDeviceRole = INPUT_DEVICE;
1114     for (std::shared_ptr<AudioDeviceDescriptor> desc : inputDevices) {
1115         if ((desc->deviceType_ == activeDeviceType) && (desc->deviceRole_ == activeDeviceRole)) {
1116             size_t capturerInfosSize = audioCapturerChangeInfos.size();
1117             for (size_t i = 0; i < capturerInfosSize; i++) {
1118                 UpdateCapturerInfoWhenNoPermission(audioCapturerChangeInfos[i], hasSystemPermission);
1119                 audioDeviceCommon_.UpdateDeviceInfo(audioCapturerChangeInfos[i]->inputDeviceInfo, desc,
1120                     hasBTPermission, hasSystemPermission);
1121             }
1122             break;
1123         }
1124     }
1125 
1126     return status;
1127 }
1128 
RegisteredTrackerClientDied(pid_t uid)1129 void AudioPolicyService::RegisteredTrackerClientDied(pid_t uid)
1130 {
1131     audioDeviceLock_.RegisteredTrackerClientDied(uid);
1132 }
1133 
ReconfigureAudioChannel(const uint32_t & channelCount,DeviceType deviceType)1134 int32_t AudioPolicyService::ReconfigureAudioChannel(const uint32_t &channelCount, DeviceType deviceType)
1135 {
1136     if (audioActiveDevice_.GetCurrentOutputDeviceType() != DEVICE_TYPE_FILE_SINK) {
1137         AUDIO_INFO_LOG("FILE_SINK_DEVICE is not active. Cannot reconfigure now");
1138         return ERROR;
1139     }
1140 
1141     std::string module = FILE_SINK;
1142 
1143     if (deviceType == DeviceType::DEVICE_TYPE_FILE_SINK) {
1144         CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_8 && channelCount >= MONO, ERROR, "Invalid sink channel");
1145         module = FILE_SINK;
1146     } else if (deviceType == DeviceType::DEVICE_TYPE_FILE_SOURCE) {
1147         CHECK_AND_RETURN_RET_LOG(channelCount <= CHANNEL_6 && channelCount >= MONO, ERROR, "Invalid src channel");
1148         module = FILE_SOURCE;
1149     } else {
1150         AUDIO_ERR_LOG("Invalid DeviceType");
1151         return ERROR;
1152     }
1153 
1154     audioIOHandleMap_.ClosePortAndEraseIOHandle(module);
1155 
1156     std::list<AudioModuleInfo> moduleInfoList;
1157     audioConfigManager_.GetModuleListByType(ClassType::TYPE_FILE_IO, moduleInfoList);
1158     for (auto &moduleInfo : moduleInfoList) {
1159         if (module == moduleInfo.name) {
1160             moduleInfo.channels = to_string(channelCount);
1161             audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
1162             audioPolicyManager_.SetDeviceActive(deviceType, module, true);
1163         }
1164     }
1165     return SUCCESS;
1166 }
1167 
UpdateDescWhenNoBTPermission(vector<std::shared_ptr<AudioDeviceDescriptor>> & deviceDescs)1168 void AudioPolicyService::UpdateDescWhenNoBTPermission(vector<std::shared_ptr<AudioDeviceDescriptor>> &deviceDescs)
1169 {
1170     AUDIO_WARNING_LOG("No bt permission");
1171 
1172     for (std::shared_ptr<AudioDeviceDescriptor> &desc : deviceDescs) {
1173         if ((desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) || (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO)) {
1174             std::shared_ptr<AudioDeviceDescriptor> copyDesc = std::make_shared<AudioDeviceDescriptor>(desc);
1175             copyDesc->deviceName_ = "";
1176             copyDesc->macAddress_ = "";
1177             desc = copyDesc;
1178         }
1179     }
1180 }
1181 
SetDeviceAbsVolumeSupported(const std::string & macAddress,const bool support)1182 int32_t AudioPolicyService::SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support)
1183 {
1184     return audioVolumeManager_.SetDeviceAbsVolumeSupported(macAddress, support);
1185 }
1186 
IsAbsVolumeScene() const1187 bool AudioPolicyService::IsAbsVolumeScene() const
1188 {
1189     return audioPolicyManager_.IsAbsVolumeScene();
1190 }
1191 
SetA2dpDeviceVolume(const std::string & macAddress,const int32_t volumeLevel,bool internalCall)1192 int32_t AudioPolicyService::SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volumeLevel,
1193     bool internalCall)
1194 {
1195     return audioVolumeManager_.SetA2dpDeviceVolume(macAddress, volumeLevel, internalCall);
1196 }
1197 
GetAudioLatencyFromXml() const1198 int32_t AudioPolicyService::GetAudioLatencyFromXml() const
1199 {
1200     return audioConfigManager_.GetAudioLatencyFromXml();
1201 }
1202 
GetSinkLatencyFromXml() const1203 uint32_t AudioPolicyService::GetSinkLatencyFromXml() const
1204 {
1205     return audioConfigManager_.GetSinkLatencyFromXml();
1206 }
1207 
getFastControlParam()1208 bool AudioPolicyService::getFastControlParam()
1209 {
1210     int32_t fastControlFlag = 0; // default 0, set isFastControlled_ false
1211     GetSysPara("persist.multimedia.audioflag.fastcontrolled", fastControlFlag);
1212     if (fastControlFlag == 1) {
1213         isFastControlled_ = true;
1214     }
1215     return isFastControlled_;
1216 }
1217 
GetPreferredOutputStreamType(AudioRendererInfo & rendererInfo,const std::string & bundleName)1218 int32_t AudioPolicyService::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo,
1219     const std::string &bundleName)
1220 {
1221     // Use GetPreferredOutputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream
1222     std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
1223         GetPreferredOutputDeviceDescriptors(rendererInfo);
1224     if (preferredDeviceList.size() == 0) {
1225         return AUDIO_FLAG_NORMAL;
1226     }
1227 
1228     int32_t flag = audioDeviceCommon_.GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage,
1229         preferredDeviceList[0]->deviceType_, rendererInfo.rendererFlags, preferredDeviceList[0]->networkId_,
1230         rendererInfo.samplingRate);
1231     if (isFastControlled_ && (rendererInfo.playerType != PLAYER_TYPE_SOUND_POOL) &&
1232         (flag == AUDIO_FLAG_MMAP || flag == AUDIO_FLAG_VOIP_FAST)) {
1233         std::string bundleNamePre = CHECK_FAST_BLOCK_PREFIX + bundleName;
1234         std::string result = AudioServerProxy::GetInstance().GetAudioParameterProxy(bundleNamePre);
1235         if (result == "true") {
1236             AUDIO_INFO_LOG("%{public}s not in fast list", bundleName.c_str());
1237             return AUDIO_FLAG_NORMAL;
1238         }
1239     }
1240     if (flag == AUDIO_FLAG_VOIP_FAST && audioSceneManager_.GetAudioScene() == AUDIO_SCENE_PHONE_CALL) {
1241         AUDIO_INFO_LOG("Current scene is phone call, concede incoming voip fast output stream");
1242         flag = AUDIO_FLAG_NORMAL;
1243     }
1244     return flag;
1245 }
1246 
SetNormalVoipFlag(const bool & normalVoipFlag)1247 void AudioPolicyService::SetNormalVoipFlag(const bool &normalVoipFlag)
1248 {
1249     audioConfigManager_.SetNormalVoipFlag(normalVoipFlag);
1250 }
1251 
GetPreferredInputStreamType(AudioCapturerInfo & capturerInfo)1252 int32_t AudioPolicyService::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo)
1253 {
1254     // Use GetPreferredInputDeviceDescriptors instead of currentActiveDevice, if prefer != current, recreate stream
1255     std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
1256         GetPreferredInputDeviceDescriptors(capturerInfo);
1257     if (preferredDeviceList.size() == 0) {
1258         return AUDIO_FLAG_NORMAL;
1259     }
1260     int32_t flag = audioDeviceCommon_.GetPreferredInputStreamTypeInner(capturerInfo.sourceType,
1261         preferredDeviceList[0]->deviceType_,
1262         capturerInfo.originalFlag, preferredDeviceList[0]->networkId_, capturerInfo.samplingRate);
1263     if (flag == AUDIO_FLAG_VOIP_FAST && audioSceneManager_.GetAudioScene() == AUDIO_SCENE_PHONE_CALL) {
1264         AUDIO_INFO_LOG("Current scene is phone call, concede incoming voip fast input stream");
1265         flag = AUDIO_FLAG_NORMAL;
1266     }
1267     return flag;
1268 }
1269 
ResumeStreamState()1270 int32_t AudioPolicyService::ResumeStreamState()
1271 {
1272     return streamCollector_.ResumeStreamState();
1273 }
1274 
UpdateStreamState(int32_t clientUid,StreamSetStateEventInternal & streamSetStateEventInternal)1275 int32_t AudioPolicyService::UpdateStreamState(int32_t clientUid,
1276     StreamSetStateEventInternal &streamSetStateEventInternal)
1277 {
1278     return streamCollector_.UpdateStreamState(clientUid, streamSetStateEventInternal);
1279 }
1280 
GetUid(int32_t sessionId)1281 int32_t AudioPolicyService::GetUid(int32_t sessionId)
1282 {
1283     return streamCollector_.GetUid(sessionId);
1284 }
1285 
RemoveDeviceForUid(int32_t uid)1286 void AudioPolicyService::RemoveDeviceForUid(int32_t uid)
1287 {
1288     audioAffinityManager_.DelSelectCapturerDevice(uid);
1289     audioAffinityManager_.DelSelectRendererDevice(uid);
1290 }
1291 
SetDefaultDeviceLoadFlag(bool isLoad)1292 void AudioPolicyService::SetDefaultDeviceLoadFlag(bool isLoad)
1293 {
1294     audioVolumeManager_.SetDefaultDeviceLoadFlag(isLoad);
1295 }
1296 
GetVolumeGroupInfos()1297 std::vector<sptr<VolumeGroupInfo>> AudioPolicyService::GetVolumeGroupInfos()
1298 {
1299     return audioDeviceLock_.GetVolumeGroupInfos();
1300 }
1301 
RegiestPolicy()1302 void AudioPolicyService::RegiestPolicy()
1303 {
1304     AUDIO_INFO_LOG("Start");
1305     const sptr<IStandardAudioService> gsp = AudioServerProxy::GetInstance().GetAudioServerProxy();
1306     CHECK_AND_RETURN_LOG(gsp != nullptr, "RegiestPolicy, Audio Server Proxy is null");
1307     audioPolicyManager_.SetAudioServerProxy(gsp);
1308 
1309     sptr<PolicyProviderWrapper> wrapper = new(std::nothrow) PolicyProviderWrapper(this);
1310     CHECK_AND_RETURN_LOG(wrapper != nullptr, "Get null PolicyProviderWrapper");
1311     sptr<IRemoteObject> object = wrapper->AsObject();
1312     CHECK_AND_RETURN_LOG(object != nullptr, "RegiestPolicy AsObject is nullptr");
1313 
1314     int32_t ret = AudioServerProxy::GetInstance().RegiestPolicyProviderProxy(object);
1315     AUDIO_DEBUG_LOG("result:%{public}d", ret);
1316 }
1317 
1318 /*
1319  * lockFlag is use to determinewhether GetPreferredOutputDeviceDescriptor or
1320 *  GetPreferredOutputDeviceDescInner is invoked.
1321  * If deviceStatusUpdateSharedMutex_ write lock is not invoked at the outer layer, lockFlag can be set to true.
1322  * When deviceStatusUpdateSharedMutex_ write lock has been invoked, lockFlag must be set to false.
1323  */
1324 
GetProcessDeviceInfo(const AudioProcessConfig & config,bool lockFlag,AudioDeviceDescriptor & deviceInfo)1325 int32_t AudioPolicyService::GetProcessDeviceInfo(const AudioProcessConfig &config, bool lockFlag,
1326     AudioDeviceDescriptor &deviceInfo)
1327 {
1328     AUDIO_INFO_LOG("%{public}s", ProcessConfig::DumpProcessConfig(config).c_str());
1329     AudioSamplingRate samplingRate = config.streamInfo.samplingRate;
1330     if (config.audioMode == AUDIO_MODE_PLAYBACK) {
1331         if (config.rendererInfo.streamUsage == STREAM_USAGE_VOICE_COMMUNICATION ||
1332             config.rendererInfo.streamUsage == STREAM_USAGE_VIDEO_COMMUNICATION) {
1333             AudioRendererInfo rendererInfo = config.rendererInfo;
1334             std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
1335                 (lockFlag ? GetPreferredOutputDeviceDescriptors(rendererInfo, LOCAL_NETWORK_ID)
1336                           : audioDeviceCommon_.GetPreferredOutputDeviceDescInner(rendererInfo, LOCAL_NETWORK_ID));
1337             int32_t type = audioDeviceCommon_.GetPreferredOutputStreamTypeInner(rendererInfo.streamUsage,
1338                 preferredDeviceList[0]->deviceType_, rendererInfo.originalFlag, preferredDeviceList[0]->networkId_,
1339                 samplingRate);
1340             deviceInfo.deviceRole_ = OUTPUT_DEVICE;
1341             return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList);
1342         }
1343         AudioDeviceDescriptor curOutputDeviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
1344         deviceInfo.deviceId_ = curOutputDeviceDesc.deviceId_;
1345         deviceInfo.networkId_ = curOutputDeviceDesc.networkId_;
1346         deviceInfo.deviceType_ = curOutputDeviceDesc.deviceType_;
1347         deviceInfo.deviceRole_ = OUTPUT_DEVICE;
1348     } else {
1349         if (config.capturerInfo.sourceType == SOURCE_TYPE_VOICE_COMMUNICATION) {
1350             AudioCapturerInfo capturerInfo = config.capturerInfo;
1351             std::vector<std::shared_ptr<AudioDeviceDescriptor>> preferredDeviceList =
1352                 (lockFlag ? GetPreferredInputDeviceDescriptors(capturerInfo, LOCAL_NETWORK_ID)
1353                           : audioDeviceCommon_.GetPreferredInputDeviceDescInner(capturerInfo, LOCAL_NETWORK_ID));
1354             int32_t type = audioDeviceCommon_.GetPreferredInputStreamTypeInner(capturerInfo.sourceType,
1355                 preferredDeviceList[0]->deviceType_, capturerInfo.originalFlag, preferredDeviceList[0]->networkId_,
1356                 samplingRate);
1357             deviceInfo.deviceRole_ = INPUT_DEVICE;
1358             return GetVoipDeviceInfo(config, deviceInfo, type, preferredDeviceList);
1359         }
1360         deviceInfo.deviceId_ = audioActiveDevice_.GetCurrentInputDevice().deviceId_;
1361         deviceInfo.networkId_ = audioActiveDevice_.GetCurrentInputDevice().networkId_;
1362         deviceInfo.deviceRole_ = INPUT_DEVICE;
1363         deviceInfo.deviceType_ = audioActiveDevice_.GetCurrentInputDeviceType();
1364     }
1365 
1366     // todo
1367     // check process in routerMap, return target device for it
1368     // put the currentActiveDevice_ in deviceinfo, so it can create with current using device.
1369     // genarate the unique deviceid?
1370     AudioStreamInfo targetStreamInfo = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO}; // note: read from xml
1371     deviceInfo.audioStreamInfo_ = targetStreamInfo;
1372     deviceInfo.deviceName_ = "mmap_device";
1373     audioRouteMap_.GetNetworkIDInFastRouterMap(config.appInfo.appUid, deviceInfo.deviceRole_, deviceInfo.networkId_);
1374     deviceInfo.a2dpOffloadFlag_ = GetA2dpOffloadFlag();
1375     return SUCCESS;
1376 }
1377 
GetVoipDeviceInfo(const AudioProcessConfig & config,AudioDeviceDescriptor & deviceInfo,int32_t type,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & preferredDeviceList)1378 int32_t AudioPolicyService::GetVoipDeviceInfo(const AudioProcessConfig &config, AudioDeviceDescriptor &deviceInfo,
1379     int32_t type, std::vector<std::shared_ptr<AudioDeviceDescriptor>> &preferredDeviceList)
1380 {
1381     if (type == AUDIO_FLAG_NORMAL) {
1382         AUDIO_WARNING_LOG("Current device %{public}d not support", type);
1383         return ERROR;
1384     }
1385     deviceInfo.deviceId_ = preferredDeviceList[0]->deviceId_;
1386     deviceInfo.networkId_ = preferredDeviceList[0]->networkId_;
1387     deviceInfo.deviceType_ = preferredDeviceList[0]->deviceType_;
1388     deviceInfo.deviceName_ = preferredDeviceList[0]->deviceName_;
1389     if (config.streamInfo.samplingRate <= SAMPLE_RATE_16000) {
1390         deviceInfo.audioStreamInfo_ = {SAMPLE_RATE_16000, ENCODING_PCM, SAMPLE_S16LE, STEREO};
1391     } else {
1392         deviceInfo.audioStreamInfo_ = {SAMPLE_RATE_48000, ENCODING_PCM, SAMPLE_S16LE, STEREO};
1393     }
1394     if (type == AUDIO_FLAG_VOIP_DIRECT) {
1395         AUDIO_INFO_LOG("Direct VoIP stream, deviceInfo has been updated: deviceInfo.deviceType %{public}d",
1396             deviceInfo.deviceType_);
1397         return SUCCESS;
1398     }
1399     audioRouteMap_.GetNetworkIDInFastRouterMap(config.appInfo.appUid, deviceInfo.deviceRole_, deviceInfo.networkId_);
1400     deviceInfo.a2dpOffloadFlag_ = GetA2dpOffloadFlag();
1401     deviceInfo.isLowLatencyDevice_ = true;
1402     return SUCCESS;
1403 }
1404 
InitSharedVolume(std::shared_ptr<AudioSharedMemory> & buffer)1405 int32_t AudioPolicyService::InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer)
1406 {
1407     return audioVolumeManager_.InitSharedVolume(buffer);
1408 }
1409 
GetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume & vol)1410 bool AudioPolicyService::GetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume &vol)
1411 {
1412     return audioVolumeManager_.GetSharedVolume(streamType, deviceType, vol);
1413 }
1414 
SetParameterCallback(const std::shared_ptr<AudioParameterCallback> & callback)1415 void AudioPolicyService::SetParameterCallback(const std::shared_ptr<AudioParameterCallback>& callback)
1416 {
1417     AUDIO_INFO_LOG("Start");
1418     sptr<AudioManagerListenerStub> parameterChangeCbStub = new(std::nothrow) AudioManagerListenerStub();
1419     CHECK_AND_RETURN_LOG(parameterChangeCbStub != nullptr,
1420         "parameterChangeCbStub null");
1421     parameterChangeCbStub->SetParameterCallback(callback);
1422 
1423     sptr<IRemoteObject> object = parameterChangeCbStub->AsObject();
1424     if (object == nullptr) {
1425         AUDIO_ERR_LOG("listenerStub object is nullptr");
1426         return;
1427     }
1428     AUDIO_DEBUG_LOG("done");
1429     AudioServerProxy::GetInstance().SetParameterCallbackProxy(object);
1430 }
1431 
CheckStreamMode(const int64_t activateSessionId)1432 void AudioPolicyService::CheckStreamMode(const int64_t activateSessionId)
1433 {
1434     audioOffloadStream_.CheckStreamMode(activateSessionId);
1435 }
1436 
MoveToNewPipe(uint32_t sessionId,AudioPipeType pipeType)1437 int32_t AudioPolicyService::MoveToNewPipe(uint32_t sessionId, AudioPipeType pipeType)
1438 {
1439     return audioOffloadStream_.MoveToNewPipe(sessionId, pipeType);
1440 }
1441 
DynamicUnloadModule(const AudioPipeType pipeType)1442 int32_t AudioPolicyService::DynamicUnloadModule(const AudioPipeType pipeType)
1443 {
1444     switch (pipeType) {
1445         case PIPE_TYPE_OFFLOAD:
1446             audioOffloadStream_.DynamicUnloadOffloadModule();
1447             break;
1448         case PIPE_TYPE_MULTICHANNEL:
1449             return audioOffloadStream_.UnloadMchModule();
1450         default:
1451             AUDIO_WARNING_LOG("not supported for pipe type %{public}d", pipeType);
1452             break;
1453     }
1454     return SUCCESS;
1455 }
1456 
GetMaxRendererInstances()1457 int32_t AudioPolicyService::GetMaxRendererInstances()
1458 {
1459     return audioConfigManager_.GetMaxRendererInstances();
1460 }
1461 
1462 #ifdef BLUETOOTH_ENABLE
RegisterBluetoothDeathCallback()1463 void RegisterBluetoothDeathCallback()
1464 {
1465     lock_guard<mutex> lock(g_btProxyMutex);
1466     AUDIO_INFO_LOG("Start RegisterBluetoothDeathCallback");
1467     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1468     CHECK_AND_RETURN_LOG(samgr != nullptr,
1469         "RegisterBluetoothDeathCallback: get sa manager failed");
1470     sptr<IRemoteObject> object = samgr->GetSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
1471     CHECK_AND_RETURN_LOG(object != nullptr,
1472         "RegisterBluetoothDeathCallback: get audio service remote object failed");
1473     // register death recipent
1474     sptr<AudioServerDeathRecipient> asDeathRecipient =
1475         new(std::nothrow) AudioServerDeathRecipient(getpid(), getuid());
1476     if (asDeathRecipient != nullptr) {
1477         asDeathRecipient->SetNotifyCb([] (pid_t pid, pid_t uid) {
1478             AudioPolicyService::BluetoothServiceCrashedCallback(pid, uid);
1479         });
1480         bool result = object->AddDeathRecipient(asDeathRecipient);
1481         if (!result) {
1482             AUDIO_ERR_LOG("RegisterBluetoothDeathCallback: failed to add deathRecipient");
1483         }
1484     }
1485 }
1486 
BluetoothServiceCrashedCallback(pid_t pid,pid_t uid)1487 void AudioPolicyService::BluetoothServiceCrashedCallback(pid_t pid, pid_t uid)
1488 {
1489     AUDIO_INFO_LOG("Bluetooth sa crashed, will restore proxy in next call");
1490     lock_guard<mutex> lock(g_btProxyMutex);
1491     isBtListenerRegistered = false;
1492     isBtCrashed = true;
1493     Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSink();
1494     Bluetooth::AudioA2dpManager::DisconnectBluetoothA2dpSource();
1495     Bluetooth::AudioHfpManager::DisconnectBluetoothHfpSink();
1496 }
1497 #endif
1498 
RegisterBluetoothListener()1499 void AudioPolicyService::RegisterBluetoothListener()
1500 {
1501 #ifdef BLUETOOTH_ENABLE
1502     AUDIO_INFO_LOG("Enter");
1503     Bluetooth::RegisterDeviceObserver(deviceStatusListener_->deviceObserver_);
1504     if (isBtListenerRegistered) {
1505         AUDIO_INFO_LOG("audio policy service already register bt listerer, return");
1506         return;
1507     }
1508 
1509     if (!isBtCrashed) {
1510         Bluetooth::AudioA2dpManager::RegisterBluetoothA2dpListener();
1511         Bluetooth::AudioHfpManager::RegisterBluetoothScoListener();
1512     }
1513 
1514     isBtListenerRegistered = true;
1515     isBtCrashed = false;
1516     RegisterBluetoothDeathCallback();
1517     AudioPolicyUtils::GetInstance().SetBtConnecting(true);
1518     Bluetooth::AudioA2dpManager::CheckA2dpDeviceReconnect();
1519     Bluetooth::AudioHfpManager::CheckHfpDeviceReconnect();
1520     AudioPolicyUtils::GetInstance().SetBtConnecting(false);
1521 #endif
1522 }
1523 
UnregisterBluetoothListener()1524 void AudioPolicyService::UnregisterBluetoothListener()
1525 {
1526 #ifdef BLUETOOTH_ENABLE
1527     AUDIO_INFO_LOG("Enter");
1528     Bluetooth::UnregisterDeviceObserver();
1529     Bluetooth::AudioA2dpManager::UnregisterBluetoothA2dpListener();
1530     Bluetooth::AudioHfpManager::UnregisterBluetoothScoListener();
1531     isBtListenerRegistered = false;
1532 #endif
1533 }
1534 
SubscribeAccessibilityConfigObserver()1535 void AudioPolicyService::SubscribeAccessibilityConfigObserver()
1536 {
1537 #ifdef ACCESSIBILITY_ENABLE
1538     RegisterAccessibilityMonitorHelper();
1539     AUDIO_INFO_LOG("Subscribe accessibility config observer successfully");
1540 #endif
1541 }
1542 
GetMinStreamVolume()1543 float AudioPolicyService::GetMinStreamVolume()
1544 {
1545     return audioPolicyManager_.GetMinStreamVolume();
1546 }
1547 
GetMaxStreamVolume()1548 float AudioPolicyService::GetMaxStreamVolume()
1549 {
1550     return audioPolicyManager_.GetMaxStreamVolume();
1551 }
1552 
IsVolumeUnadjustable()1553 bool AudioPolicyService::IsVolumeUnadjustable()
1554 {
1555     return audioPolicyManager_.IsVolumeUnadjustable();
1556 }
1557 
GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfoMap)1558 void AudioPolicyService::GetStreamVolumeInfoMap(StreamVolumeInfoMap &streamVolumeInfoMap)
1559 {
1560     return audioPolicyManager_.GetStreamVolumeInfoMap(streamVolumeInfoMap);
1561 }
1562 
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType) const1563 float AudioPolicyService::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel,
1564     DeviceType deviceType) const
1565 {
1566     return audioPolicyManager_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType);
1567 }
1568 
QueryEffectManagerSceneMode(SupportedEffectConfig & supportedEffectConfig)1569 int32_t AudioPolicyService::QueryEffectManagerSceneMode(SupportedEffectConfig& supportedEffectConfig)
1570 {
1571     int32_t ret = audioEffectService_.QueryEffectManagerSceneMode(supportedEffectConfig);
1572     return ret;
1573 }
1574 
RegisterDataObserver()1575 void AudioPolicyService::RegisterDataObserver()
1576 {
1577     std::string devicesName = "";
1578     int32_t ret = AudioPolicyUtils::GetInstance().GetDeviceNameFromDataShareHelper(devicesName);
1579     CHECK_AND_RETURN_LOG(ret == SUCCESS, "RegisterDataObserver get devicesName failed");
1580     SetDisplayName(devicesName, true);
1581     RegisterNameMonitorHelper();
1582 }
1583 
GetHardwareOutputSamplingRate(const std::shared_ptr<AudioDeviceDescriptor> & desc)1584 int32_t AudioPolicyService::GetHardwareOutputSamplingRate(const std::shared_ptr<AudioDeviceDescriptor> &desc)
1585 {
1586     int32_t rate = 48000;
1587 
1588     CHECK_AND_RETURN_RET_LOG(desc != nullptr, -1, "desc is null!");
1589 
1590     bool ret = audioConnectedDevice_.IsConnectedOutputDevice(desc);
1591     CHECK_AND_RETURN_RET(ret, -1);
1592 
1593     std::unordered_map<ClassType, std::list<AudioModuleInfo>> deviceClassInfo = {};
1594     audioConfigManager_.GetDeviceClassInfo(deviceClassInfo);
1595     DeviceType clientDevType = desc->deviceType_;
1596     for (const auto &device : deviceClassInfo) {
1597         auto moduleInfoList = device.second;
1598         for (auto &moduleInfo : moduleInfoList) {
1599             auto serverDevType = AudioPolicyUtils::GetInstance().GetDeviceType(moduleInfo.name);
1600             if (clientDevType == serverDevType) {
1601                 rate = atoi(moduleInfo.rate.c_str());
1602                 return rate;
1603             }
1604         }
1605     }
1606 
1607     return rate;
1608 }
1609 
GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)1610 vector<sptr<MicrophoneDescriptor>> AudioPolicyService::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)
1611 {
1612     return audioDeviceLock_.GetAudioCapturerMicrophoneDescriptors(sessionId);
1613 }
1614 
GetAvailableMicrophones()1615 vector<sptr<MicrophoneDescriptor>> AudioPolicyService::GetAvailableMicrophones()
1616 {
1617     return audioDeviceLock_.GetAvailableMicrophones();
1618 }
1619 
OnCapturerSessionRemoved(uint64_t sessionID)1620 void AudioPolicyService::OnCapturerSessionRemoved(uint64_t sessionID)
1621 {
1622     audioDeviceLock_.OnCapturerSessionRemoved(sessionID);
1623 }
1624 
OnCapturerSessionAdded(uint64_t sessionID,SessionInfo sessionInfo,AudioStreamInfo streamInfo)1625 int32_t AudioPolicyService::OnCapturerSessionAdded(uint64_t sessionID, SessionInfo sessionInfo,
1626     AudioStreamInfo streamInfo)
1627 {
1628     return audioDeviceLock_.OnCapturerSessionAdded(sessionID, sessionInfo, streamInfo);
1629 }
1630 
DeviceFilterByUsageInner(AudioDeviceUsage usage,const std::vector<std::shared_ptr<AudioDeviceDescriptor>> & descs)1631 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::DeviceFilterByUsageInner(AudioDeviceUsage usage,
1632     const std::vector<std::shared_ptr<AudioDeviceDescriptor>>& descs)
1633 {
1634     std::vector<shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors;
1635 
1636     unordered_map<AudioDevicePrivacyType, list<DevicePrivacyInfo>> devicePrivacyMaps =
1637         audioDeviceManager_.GetDevicePrivacyMaps();
1638     for (const auto &dev : descs) {
1639         for (const auto &devicePrivacy : devicePrivacyMaps) {
1640             list<DevicePrivacyInfo> deviceInfos = devicePrivacy.second;
1641             audioDeviceManager_.GetAvailableDevicesWithUsage(usage, deviceInfos, dev, audioDeviceDescriptors);
1642         }
1643     }
1644     std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescriptors;
1645     for (const auto &dec : audioDeviceDescriptors) {
1646         std::shared_ptr<AudioDeviceDescriptor> tempDec = std::make_shared<AudioDeviceDescriptor>(*dec);
1647         deviceDescriptors.push_back(move(tempDec));
1648     }
1649     return deviceDescriptors;
1650 }
1651 
GetAvailableDevices(AudioDeviceUsage usage)1652 std::vector<shared_ptr<AudioDeviceDescriptor>> AudioPolicyService::GetAvailableDevices(AudioDeviceUsage usage)
1653 {
1654     return audioDeviceLock_.GetAvailableDevices(usage);
1655 }
1656 
OffloadStartPlaying(const std::vector<int32_t> & sessionIds)1657 int32_t AudioPolicyService::OffloadStartPlaying(const std::vector<int32_t> &sessionIds)
1658 {
1659 #ifdef BLUETOOTH_ENABLE
1660     if (audioA2dpOffloadManager_) {
1661         return audioA2dpOffloadManager_->OffloadStartPlaying(sessionIds);
1662     }
1663     AUDIO_WARNING_LOG("Null audioA2dpOffloadManager");
1664 #endif
1665     return SUCCESS;
1666 }
1667 
OffloadStopPlaying(const std::vector<int32_t> & sessionIds)1668 int32_t AudioPolicyService::OffloadStopPlaying(const std::vector<int32_t> &sessionIds)
1669 {
1670 #ifdef BLUETOOTH_ENABLE
1671     if (audioA2dpOffloadManager_) {
1672         return audioA2dpOffloadManager_->OffloadStopPlaying(sessionIds);
1673     }
1674     AUDIO_WARNING_LOG("Null audioA2dpOffloadManager");
1675 #endif
1676     return SUCCESS;
1677 }
1678 
OffloadGetRenderPosition(uint32_t & delayValue,uint64_t & sendDataSize,uint32_t & timeStamp)1679 int32_t AudioPolicyService::OffloadGetRenderPosition(uint32_t &delayValue, uint64_t &sendDataSize, uint32_t &timeStamp)
1680 {
1681     Trace trace("AudioPolicyService::OffloadGetRenderPosition");
1682 #ifdef BLUETOOTH_ENABLE
1683     DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1684     AUDIO_DEBUG_LOG("GetRenderPosition, deviceType: %{public}d, a2dpOffloadFlag: %{public}d",
1685         GetA2dpOffloadFlag(), curOutputDeviceType);
1686     int32_t ret = SUCCESS;
1687     if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP &&
1688         audioActiveDevice_.GetCurrentOutputDeviceNetworkId() == LOCAL_NETWORK_ID &&
1689         GetA2dpOffloadFlag() == A2DP_OFFLOAD) {
1690         ret = Bluetooth::AudioA2dpManager::GetRenderPosition(delayValue, sendDataSize, timeStamp);
1691     } else {
1692         delayValue = 0;
1693         sendDataSize = 0;
1694         timeStamp = 0;
1695     }
1696     return ret;
1697 #else
1698     return SUCCESS;
1699 #endif
1700 }
1701 
GetAndSaveClientType(uint32_t uid,const std::string & bundleName)1702 int32_t AudioPolicyService::GetAndSaveClientType(uint32_t uid, const std::string &bundleName)
1703 {
1704 #ifdef FEATURE_APPGALLERY
1705     ClientTypeManager::GetInstance()->GetAndSaveClientType(uid, bundleName);
1706 #endif
1707     return SUCCESS;
1708 }
1709 
OnDeviceInfoUpdated(AudioDeviceDescriptor & desc,const DeviceInfoUpdateCommand command)1710 void AudioPolicyService::OnDeviceInfoUpdated(AudioDeviceDescriptor &desc, const DeviceInfoUpdateCommand command)
1711 {
1712     audioDeviceLock_.OnDeviceInfoUpdated(desc, command);
1713 }
1714 
SetCallDeviceActive(InternalDeviceType deviceType,bool active,std::string address,const int32_t uid)1715 int32_t AudioPolicyService::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address,
1716     const int32_t uid)
1717 {
1718     return audioDeviceLock_.SetCallDeviceActive(deviceType, active, address, uid);
1719 }
1720 
GetActiveBluetoothDevice()1721 std::shared_ptr<AudioDeviceDescriptor> AudioPolicyService::GetActiveBluetoothDevice()
1722 {
1723     return audioDeviceLock_.GetActiveBluetoothDevice();
1724 }
1725 
GetConverterConfig()1726 ConverterConfig AudioPolicyService::GetConverterConfig()
1727 {
1728     AudioConverterParser &converterParser = AudioConverterParser::GetInstance();
1729     return converterParser.LoadConfig();
1730 }
1731 
GetMaxAmplitude(const int32_t deviceId,const AudioInterrupt audioInterrupt)1732 float AudioPolicyService::GetMaxAmplitude(const int32_t deviceId, const AudioInterrupt audioInterrupt)
1733 {
1734     return audioActiveDevice_.GetMaxAmplitude(deviceId, audioInterrupt);
1735 }
1736 
TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)1737 int32_t AudioPolicyService::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)
1738 {
1739     return audioDeviceLock_.TriggerFetchDevice(reason);
1740 }
1741 
DisableSafeMediaVolume()1742 int32_t AudioPolicyService::DisableSafeMediaVolume()
1743 {
1744     return audioVolumeManager_.DisableSafeMediaVolume();
1745 }
1746 
NotifyAccountsChanged(const int & id)1747 void AudioPolicyService::NotifyAccountsChanged(const int &id)
1748 {
1749     audioPolicyManager_.NotifyAccountsChanged(id);
1750     RegisterDataObserver();
1751     SubscribeAccessibilityConfigObserver();
1752     AudioServerProxy::GetInstance().NotifyAccountsChanged();
1753 }
1754 
GetCurActivateCount()1755 int32_t AudioPolicyService::GetCurActivateCount()
1756 {
1757     return audioPolicyManager_.GetCurActivateCount();
1758 }
1759 
SetAudioConcurrencyCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)1760 int32_t AudioPolicyService::SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object)
1761 {
1762     return streamCollector_.SetAudioConcurrencyCallback(sessionID, object);
1763 }
1764 
UnsetAudioConcurrencyCallback(const uint32_t sessionID)1765 int32_t AudioPolicyService::UnsetAudioConcurrencyCallback(const uint32_t sessionID)
1766 {
1767     return streamCollector_.UnsetAudioConcurrencyCallback(sessionID);
1768 }
1769 
ActivateAudioConcurrency(const AudioPipeType & pipeType)1770 int32_t AudioPolicyService::ActivateAudioConcurrency(const AudioPipeType &pipeType)
1771 {
1772     return streamCollector_.ActivateAudioConcurrency(pipeType);
1773 }
1774 
ResetRingerModeMute()1775 int32_t AudioPolicyService::ResetRingerModeMute()
1776 {
1777     return audioVolumeManager_.ResetRingerModeMute();
1778 }
1779 
IsRingerModeMute()1780 bool AudioPolicyService::IsRingerModeMute()
1781 {
1782     return audioVolumeManager_.IsRingerModeMute();
1783 }
1784 
OnReceiveBluetoothEvent(const std::string macAddress,const std::string deviceName)1785 void AudioPolicyService::OnReceiveBluetoothEvent(const std::string macAddress, const std::string deviceName)
1786 {
1787     audioDeviceLock_.OnReceiveBluetoothEvent(macAddress, deviceName);
1788 }
1789 
LoadHdiEffectModel()1790 void AudioPolicyService::LoadHdiEffectModel()
1791 {
1792     return AudioServerProxy::GetInstance().LoadHdiEffectModelProxy();
1793 }
1794 
GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)1795 int32_t AudioPolicyService::GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
1796 {
1797     AudioEffectPropertyArrayV3 effectPropertyArray = {};
1798     GetSupportedEffectProperty(effectPropertyArray);
1799     for (auto &effectItem : effectPropertyArray.property) {
1800         effectItem.flag = RENDER_EFFECT_FLAG;
1801         propertyArray.property.push_back(effectItem);
1802     }
1803     AudioEffectPropertyArrayV3 enhancePropertyArray = {};
1804     GetSupportedEnhanceProperty(enhancePropertyArray);
1805     for (auto &enhanceItem : enhancePropertyArray.property) {
1806         enhanceItem.flag = CAPTURE_EFFECT_FLAG;
1807         propertyArray.property.push_back(enhanceItem);
1808     }
1809     return AUDIO_OK;
1810 }
1811 
GetSupportedEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)1812 void AudioPolicyService::GetSupportedEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
1813 {
1814     std::set<std::pair<std::string, std::string>> mergedSet = {};
1815     audioEffectService_.AddSupportedAudioEffectPropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
1816     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(OUTPUT_DEVICES_FLAG);
1817     for (auto &item : descriptor) {
1818         audioEffectService_.AddSupportedAudioEffectPropertyByDevice(item->getType(), mergedSet);
1819     }
1820     propertyArray.property.reserve(mergedSet.size());
1821     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
1822         [](const std::pair<std::string, std::string>& p) {
1823             return AudioEffectPropertyV3{p.first, p.second, RENDER_EFFECT_FLAG};
1824         });
1825     return;
1826 }
1827 
GetSupportedEnhanceProperty(AudioEffectPropertyArrayV3 & propertyArray)1828 void AudioPolicyService::GetSupportedEnhanceProperty(AudioEffectPropertyArrayV3 &propertyArray)
1829 {
1830     std::set<std::pair<std::string, std::string>> mergedSet = {};
1831     audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
1832     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(INPUT_DEVICES_FLAG);
1833     for (auto &item : descriptor) {
1834         audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(item->getType(), mergedSet);
1835     }
1836     propertyArray.property.reserve(mergedSet.size());
1837     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
1838         [](const std::pair<std::string, std::string>& p) {
1839             return AudioEffectPropertyV3{p.first, p.second, CAPTURE_EFFECT_FLAG};
1840         });
1841     return;
1842 }
1843 
CheckSupportedAudioEffectProperty(const AudioEffectPropertyArrayV3 & propertyArray,const EffectFlag & flag)1844 int32_t AudioPolicyService::CheckSupportedAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray,
1845     const EffectFlag& flag)
1846 {
1847     AudioEffectPropertyArrayV3 supportPropertyArray;
1848     if (flag == CAPTURE_EFFECT_FLAG) {
1849         GetSupportedEnhanceProperty(supportPropertyArray);
1850     } else {
1851         GetSupportedEffectProperty(supportPropertyArray);
1852     }
1853     for (auto &item : propertyArray.property) {
1854         auto oIter = std::find(supportPropertyArray.property.begin(), supportPropertyArray.property.end(), item);
1855         CHECK_AND_RETURN_RET_LOG(oIter != supportPropertyArray.property.end(),
1856             ERR_INVALID_PARAM, "set property not valid name:%{public}s,category:%{public}s,flag:%{public}d",
1857             item.name.c_str(), item.category.c_str(), item.flag);
1858     }
1859     return AUDIO_OK;
1860 }
1861 
SetAudioEffectProperty(const AudioEffectPropertyArrayV3 & propertyArray)1862 int32_t AudioPolicyService::SetAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray)
1863 {
1864     int32_t ret = AUDIO_OK;
1865     AudioEffectPropertyArrayV3 effectPropertyArray = {};
1866     AudioEffectPropertyArrayV3 enhancePropertyArray = {};
1867     for (auto &item : propertyArray.property) {
1868         if (item.flag == CAPTURE_EFFECT_FLAG) {
1869             enhancePropertyArray.property.push_back(item);
1870         } else {
1871             effectPropertyArray.property.push_back(item);
1872         }
1873     }
1874     CHECK_AND_RETURN_RET_LOG(CheckSupportedAudioEffectProperty(enhancePropertyArray, CAPTURE_EFFECT_FLAG) == AUDIO_OK,
1875         ERR_INVALID_PARAM, "check Audio Enhance property failed");
1876     CHECK_AND_RETURN_RET_LOG(CheckSupportedAudioEffectProperty(effectPropertyArray, RENDER_EFFECT_FLAG) == AUDIO_OK,
1877         ERR_INVALID_PARAM, "check Audio Effect property failed");
1878     if (enhancePropertyArray.property.size() > 0) {
1879         AudioEffectPropertyArrayV3 oldPropertyArray = {};
1880         ret = GetAudioEnhanceProperty(oldPropertyArray);
1881         CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "get audio enhance property fail");
1882         ret = AudioServerProxy::GetInstance().SetAudioEffectPropertyProxy(enhancePropertyArray,
1883             audioActiveDevice_.GetCurrentInputDeviceType());
1884         CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "set audio enhance property fail");
1885         audioCapturerSession_.ReloadSourceForEffect(oldPropertyArray, enhancePropertyArray);
1886     }
1887     if (effectPropertyArray.property.size() > 0) {
1888         ret = AudioServerProxy::GetInstance().SetAudioEffectPropertyProxy(effectPropertyArray);
1889         CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "set audio effect property fail");
1890     }
1891     return ret;
1892 }
1893 
GetAudioEnhanceProperty(AudioEffectPropertyArrayV3 & propertyArray)1894 int32_t AudioPolicyService::GetAudioEnhanceProperty(AudioEffectPropertyArrayV3 &propertyArray)
1895 {
1896     int32_t ret = AUDIO_OK;
1897     ret = AudioServerProxy::GetInstance().GetAudioEffectPropertyProxy(propertyArray);
1898     CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "get audio enhance property fail");
1899     auto oIter = propertyArray.property.begin();
1900     while (oIter != propertyArray.property.end()) {
1901         if (oIter->flag == RENDER_EFFECT_FLAG) {
1902             oIter = propertyArray.property.erase(oIter);
1903         } else {
1904             oIter++;
1905         }
1906     }
1907     return ret;
1908 }
1909 
GetAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)1910 int32_t AudioPolicyService::GetAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
1911 {
1912     return AudioServerProxy::GetInstance().GetAudioEffectPropertyProxy(propertyArray);
1913 }
1914 
GetSupportedAudioEffectProperty(AudioEffectPropertyArray & propertyArray)1915 int32_t AudioPolicyService::GetSupportedAudioEffectProperty(AudioEffectPropertyArray &propertyArray)
1916 {
1917     std::set<std::pair<std::string, std::string>> mergedSet = {};
1918     audioEffectService_.AddSupportedAudioEffectPropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
1919     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(OUTPUT_DEVICES_FLAG);
1920     for (auto &item : descriptor) {
1921         audioEffectService_.AddSupportedAudioEffectPropertyByDevice(item->getType(), mergedSet);
1922     }
1923     propertyArray.property.reserve(mergedSet.size());
1924     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
1925         [](const std::pair<std::string, std::string>& p) {
1926             return AudioEffectProperty{p.first, p.second};
1927         });
1928     return AUDIO_OK;
1929 }
1930 
GetSupportedAudioEnhanceProperty(AudioEnhancePropertyArray & propertyArray)1931 int32_t AudioPolicyService::GetSupportedAudioEnhanceProperty(AudioEnhancePropertyArray &propertyArray)
1932 {
1933     std::set<std::pair<std::string, std::string>> mergedSet = {};
1934     audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(DEVICE_TYPE_INVALID, mergedSet);
1935     std::vector<std::shared_ptr<AudioDeviceDescriptor>> descriptor = GetDevices(INPUT_DEVICES_FLAG);
1936     for (auto &item : descriptor) {
1937         audioEffectService_.AddSupportedAudioEnhancePropertyByDevice(item->getType(), mergedSet);
1938     }
1939     propertyArray.property.reserve(mergedSet.size());
1940     std::transform(mergedSet.begin(), mergedSet.end(), std::back_inserter(propertyArray.property),
1941         [](const std::pair<std::string, std::string>& p) {
1942             return AudioEnhanceProperty{p.first, p.second};
1943         });
1944     return AUDIO_OK;
1945 }
1946 
SetAudioEffectProperty(const AudioEffectPropertyArray & propertyArray)1947 int32_t AudioPolicyService::SetAudioEffectProperty(const AudioEffectPropertyArray &propertyArray)
1948 {
1949     AudioEffectPropertyArray supportPropertyArray;
1950     std::vector<AudioEffectProperty>::iterator oIter;
1951     (void)GetSupportedAudioEffectProperty(supportPropertyArray);
1952     for (auto &item : propertyArray.property) {
1953         oIter = std::find(supportPropertyArray.property.begin(), supportPropertyArray.property.end(), item);
1954         CHECK_AND_RETURN_RET_LOG(oIter != supportPropertyArray.property.end(),
1955             ERR_INVALID_PARAM, "set audio effect property not valid %{public}s:%{public}s",
1956             item.effectClass.c_str(), item.effectProp.c_str());
1957     }
1958     return AudioServerProxy::GetInstance().SetAudioEffectPropertyProxy(propertyArray);
1959 }
1960 
GetAudioEffectProperty(AudioEffectPropertyArray & propertyArray)1961 int32_t AudioPolicyService::GetAudioEffectProperty(AudioEffectPropertyArray &propertyArray)
1962 {
1963     return AudioServerProxy::GetInstance().GetAudioEffectPropertyProxy(propertyArray);
1964 }
1965 
SetAudioEnhanceProperty(const AudioEnhancePropertyArray & propertyArray)1966 int32_t AudioPolicyService::SetAudioEnhanceProperty(const AudioEnhancePropertyArray &propertyArray)
1967 {
1968     AudioEnhancePropertyArray supportPropertyArray;
1969     std::vector<AudioEnhanceProperty>::iterator oIter;
1970     (void)GetSupportedAudioEnhanceProperty(supportPropertyArray);
1971     for (auto &item : propertyArray.property) {
1972         oIter = std::find(supportPropertyArray.property.begin(), supportPropertyArray.property.end(), item);
1973         CHECK_AND_RETURN_RET_LOG(oIter != supportPropertyArray.property.end(),
1974             ERR_INVALID_PARAM, "set audio enhance property not valid %{public}s:%{public}s",
1975             item.enhanceClass.c_str(), item.enhanceProp.c_str());
1976     }
1977     AudioEnhancePropertyArray oldPropertyArray = {};
1978     int32_t ret = AudioServerProxy::GetInstance().GetAudioEnhancePropertyProxy(oldPropertyArray);
1979     CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "get audio enhance property fail");
1980 
1981     ret = AudioServerProxy::GetInstance().SetAudioEnhancePropertyProxy(propertyArray,
1982         audioActiveDevice_.GetCurrentInputDeviceType());
1983     CHECK_AND_RETURN_RET_LOG(ret == AUDIO_OK, ret, "set audio enhance property fail");
1984 
1985     audioCapturerSession_.ReloadSourceForEffect(oldPropertyArray, propertyArray);
1986     return ret;
1987 }
1988 
GetAudioEnhanceProperty(AudioEnhancePropertyArray & propertyArray)1989 int32_t AudioPolicyService::GetAudioEnhanceProperty(AudioEnhancePropertyArray &propertyArray)
1990 {
1991     return AudioServerProxy::GetInstance().GetAudioEnhancePropertyProxy(propertyArray);
1992 }
1993 
GetAudioEnhancePropertyByDevice(DeviceType deviceType,AudioEnhancePropertyArray & propertyArray)1994 int32_t AudioPolicyService::GetAudioEnhancePropertyByDevice(DeviceType deviceType,
1995     AudioEnhancePropertyArray &propertyArray)
1996 {
1997     return AudioServerProxy::GetInstance().GetAudioEnhancePropertyProxy(propertyArray, deviceType);
1998 }
1999 
UpdateEffectBtOffloadSupported(const bool & isSupported)2000 void AudioPolicyService::UpdateEffectBtOffloadSupported(const bool &isSupported)
2001 {
2002     AudioServerProxy::GetInstance().UpdateEffectBtOffloadSupportedProxy(isSupported);
2003     return;
2004 }
2005 
SetRotationToEffect(const uint32_t rotate)2006 void AudioPolicyService::SetRotationToEffect(const uint32_t rotate)
2007 {
2008     AudioServerProxy::GetInstance().SetRotationToEffectProxy(rotate);
2009 }
2010 
IsA2dpOffloadConnected()2011 bool AudioPolicyService::IsA2dpOffloadConnected()
2012 {
2013     if (audioA2dpOffloadManager_) {
2014         return audioA2dpOffloadManager_->IsA2dpOffloadConnected();
2015     }
2016     AUDIO_WARNING_LOG("Null audioA2dpOffloadManager");
2017     return true;
2018 }
2019 
LoadSplitModule(const std::string & splitArgs,const std::string & networkId)2020 int32_t  AudioPolicyService::LoadSplitModule(const std::string &splitArgs, const std::string &networkId)
2021 {
2022     AUDIO_INFO_LOG("start audio stream split, the split args is %{public}s", splitArgs.c_str());
2023     if (splitArgs.empty() || networkId.empty()) {
2024         std::string anonymousNetworkId = networkId.empty() ? "" : networkId.substr(0, 2) + "***";
2025         AUDIO_ERR_LOG("LoadSplitModule, invalid param, splitArgs:'%{public}s', networkId:'%{public}s'",
2026             splitArgs.c_str(), anonymousNetworkId.c_str());
2027         return ERR_INVALID_PARAM;
2028     }
2029     std::string moduleName = AudioPolicyUtils::GetInstance().GetRemoteModuleName(networkId, OUTPUT_DEVICE);
2030     std::string currentActivePort = REMOTE_CLASS;
2031     audioPolicyManager_.SuspendAudioDevice(currentActivePort, true);
2032     audioIOHandleMap_.ClosePortAndEraseIOHandle(moduleName);
2033 
2034     AudioModuleInfo moudleInfo = AudioPolicyUtils::GetInstance().ConstructRemoteAudioModuleInfo(networkId,
2035         OUTPUT_DEVICE, DEVICE_TYPE_SPEAKER);
2036     moudleInfo.lib = "libmodule-split-stream-sink.z.so";
2037     moudleInfo.extra = splitArgs;
2038 
2039     int32_t openRet = audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleName, moudleInfo);
2040     if (openRet != 0) {
2041         AUDIO_ERR_LOG("open fail, OpenPortAndInsertIOHandle ret: %{public}d", openRet);
2042     }
2043     AudioServerProxy::GetInstance().NotifyDeviceInfoProxy(networkId, true);
2044     return openRet;
2045 }
2046 
IsCurrentActiveDeviceA2dp()2047 bool AudioPolicyService::IsCurrentActiveDeviceA2dp()
2048 {
2049     return audioPolicyManager_.GetActiveDevice() == DEVICE_TYPE_BLUETOOTH_A2DP;
2050 }
2051 
IsAllowedPlayback(const int32_t & uid,const int32_t & pid)2052 bool AudioPolicyService::IsAllowedPlayback(const int32_t &uid, const int32_t &pid)
2053 {
2054 #ifdef AVSESSION_ENABLE
2055     // Temporary solution to avoid performance issues
2056     if (uid == BOOTUP_MUSIC_UID) {
2057         return true;
2058     }
2059     lock_guard<mutex> lock(g_policyMgrListenerMutex);
2060     bool allowed = false;
2061     if (policyManagerListener_ != nullptr) {
2062         allowed = policyManagerListener_->OnQueryAllowedPlayback(uid, pid);
2063     }
2064     if (!allowed) {
2065         usleep(WATI_PLAYBACK_TIME); //wait for 200ms
2066         AUDIO_INFO_LOG("IsAudioPlaybackAllowed Try again after 200ms");
2067         if (policyManagerListener_ != nullptr) {
2068             allowed = policyManagerListener_->OnQueryAllowedPlayback(uid, pid);
2069         }
2070     }
2071     return allowed;
2072 #endif
2073     return true;
2074 }
2075 
SetDefaultOutputDevice(const DeviceType deviceType,const uint32_t sessionID,const StreamUsage streamUsage,bool isRunning)2076 int32_t AudioPolicyService::SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID,
2077     const StreamUsage streamUsage, bool isRunning)
2078 {
2079     CHECK_AND_RETURN_RET_LOG(audioConfigManager_.GetHasEarpiece(), ERR_NOT_SUPPORTED, "the device has no earpiece");
2080     int32_t ret = audioDeviceManager_.SetDefaultOutputDevice(deviceType, sessionID, streamUsage, isRunning);
2081     if (ret == NEED_TO_FETCH) {
2082         audioDeviceCommon_.FetchDevice(true, AudioStreamDeviceChangeReasonExt::ExtEnum::SET_DEFAULT_OUTPUT_DEVICE);
2083         return SUCCESS;
2084     }
2085     return ret;
2086 }
2087 
GetAudioEffectOffloadFlag()2088 bool AudioPolicyService::GetAudioEffectOffloadFlag()
2089 {
2090     // check if audio effect offload
2091     return AudioServerProxy::GetInstance().GetEffectOffloadEnabledProxy();
2092 }
2093 
SetA2dpOffloadFlag(BluetoothOffloadState state)2094 void AudioPolicyService::SetA2dpOffloadFlag(BluetoothOffloadState state)
2095 {
2096     if (audioA2dpOffloadManager_) {
2097         audioA2dpOffloadManager_->SetA2dpOffloadFlag(state);
2098     }
2099 }
2100 
GetA2dpOffloadFlag()2101 BluetoothOffloadState AudioPolicyService::GetA2dpOffloadFlag()
2102 {
2103     if (audioA2dpOffloadManager_) {
2104         return audioA2dpOffloadManager_->GetA2dpOffloadFlag();
2105     }
2106     return NO_A2DP_DEVICE;
2107 }
2108 
SetDefaultAdapterEnable(bool isEnable)2109 void AudioPolicyService::SetDefaultAdapterEnable(bool isEnable)
2110 {
2111     return AudioServerProxy::GetInstance().SetDefaultAdapterEnableProxy(isEnable);
2112 }
2113 
ActivateConcurrencyFromServer(AudioPipeType incomingPipe)2114 int32_t AudioPolicyService::ActivateConcurrencyFromServer(AudioPipeType incomingPipe)
2115 {
2116     return audioOffloadStream_.ActivateConcurrencyFromServer(incomingPipe);
2117 }
2118 
NotifyCapturerRemoved(uint64_t sessionId)2119 int32_t AudioPolicyService::NotifyCapturerRemoved(uint64_t sessionId)
2120 {
2121     CHECK_AND_RETURN_RET_LOG(audioPolicyServerHandler_ != nullptr, ERROR, "audioPolicyServerHandler_ is nullptr");
2122     audioPolicyServerHandler_->SendCapturerRemovedEvent(sessionId, false);
2123     return SUCCESS;
2124 }
2125 
CheckConnectedDevice()2126 void AudioPolicyService::CheckConnectedDevice()
2127 {
2128     bool flag = audioPolicyManager_.GetActiveDevice() == DEVICE_TYPE_USB_ARM_HEADSET ||
2129         audioPolicyManager_.GetActiveDevice() ==  DEVICE_TYPE_USB_HEADSET;
2130     AudioServerProxy::GetInstance().SetDeviceConnectedFlag(flag);
2131 }
2132 
SetDeviceConnectedFlagFalseAfterDuration()2133 void AudioPolicyService::SetDeviceConnectedFlagFalseAfterDuration()
2134 {
2135     usleep(DEVICE_CONNECTED_FLAG_DURATION_MS); // 3s
2136     AudioServerProxy::GetInstance().SetDeviceConnectedFlag(false);
2137 }
2138 
CheckHibernateState(bool hibernate)2139 void AudioPolicyService::CheckHibernateState(bool hibernate)
2140 {
2141     AudioServerProxy::GetInstance().CheckHibernateStateProxy(hibernate);
2142 }
2143 
UpdateSafeVolumeByS4()2144 void AudioPolicyService::UpdateSafeVolumeByS4()
2145 {
2146     return audioVolumeManager_.UpdateSafeVolumeByS4();
2147 }
2148 
UpdateSpatializationSupported(const std::string macAddress,const bool support)2149 void AudioPolicyService::UpdateSpatializationSupported(const std::string macAddress, const bool support)
2150 {
2151     audioDeviceLock_.UpdateSpatializationSupported(macAddress, support);
2152 }
2153 #ifdef HAS_FEATURE_INNERCAPTURER
LoadModernInnerCapSink(int32_t innerCapId)2154 int32_t AudioPolicyService::LoadModernInnerCapSink(int32_t innerCapId)
2155 {
2156     AUDIO_INFO_LOG("Start");
2157     AudioModuleInfo moduleInfo = {};
2158     moduleInfo.lib = "libmodule-inner-capturer-sink.z.so";
2159     std::string name = INNER_CAPTURER_SINK;
2160     moduleInfo.name = name + std::to_string(innerCapId);
2161 
2162     moduleInfo.format = "s16le";
2163     moduleInfo.channels = "2"; // 2 channel
2164     moduleInfo.rate = "48000";
2165     moduleInfo.bufferSize = "3840"; // 20ms
2166 
2167     audioIOHandleMap_.OpenPortAndInsertIOHandle(moduleInfo.name, moduleInfo);
2168     return SUCCESS;
2169 }
2170 
UnloadModernInnerCapSink(int32_t innerCapId)2171 int32_t AudioPolicyService::UnloadModernInnerCapSink(int32_t innerCapId)
2172 {
2173     AUDIO_INFO_LOG("Start");
2174     std::string name = INNER_CAPTURER_SINK;
2175     name += std::to_string(innerCapId);
2176 
2177     audioIOHandleMap_.ClosePortAndEraseIOHandle(name);
2178     return SUCCESS;
2179 }
2180 #endif
2181 
SetQueryAllowedPlaybackCallback(const sptr<IRemoteObject> & object)2182 int32_t AudioPolicyService::SetQueryAllowedPlaybackCallback(const sptr<IRemoteObject> &object)
2183 {
2184     lock_guard<mutex> lock(g_policyMgrListenerMutex);
2185     policyManagerListener_ = iface_cast<IStandardAudioPolicyManagerListener>(object);
2186     return SUCCESS;
2187 }
2188 } // namespace AudioStandard
2189 } // namespace OHOS
2190