• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 "AudioPolicyServer"
17 #endif
18 
19 #include "audio_policy_server.h"
20 
21 #ifdef FEATURE_MULTIMODALINPUT_INPUT
22 #include "input_manager.h"
23 
24 #endif
25 
26 #include "privacy_kit.h"
27 #include "tokenid_kit.h"
28 #include "common_event_manager.h"
29 #include "audio_policy_log.h"
30 #include "audio_utils.h"
31 #include "parameters.h"
32 #include "media_monitor_manager.h"
33 #include "client_type_manager.h"
34 
35 using OHOS::Security::AccessToken::PrivacyKit;
36 using OHOS::Security::AccessToken::TokenIdKit;
37 using namespace std;
38 
39 namespace OHOS {
40 namespace AudioStandard {
41 
42 constexpr int32_t PARAMS_VOLUME_NUM = 5;
43 constexpr int32_t PARAMS_INTERRUPT_NUM = 4;
44 constexpr int32_t PARAMS_RENDER_STATE_NUM = 2;
45 constexpr int32_t EVENT_DES_SIZE = 80;
46 constexpr int32_t ADAPTER_STATE_CONTENT_DES_SIZE = 60;
47 constexpr int32_t API_VERSION_REMAINDER = 1000;
48 constexpr uid_t UID_CAST_ENGINE_SA = 5526;
49 constexpr uid_t UID_AUDIO = 1041;
50 constexpr uid_t UID_FOUNDATION_SA = 5523;
51 constexpr uid_t UID_BLUETOOTH_SA = 1002;
52 constexpr uid_t UID_CAR_DISTRIBUTED_ENGINE_SA = 65872;
53 constexpr uid_t UID_RESOURCE_SCHEDULE_SERVICE = 1096;
54 constexpr int64_t OFFLOAD_NO_SESSION_ID = -1;
55 constexpr unsigned int GET_BUNDLE_TIME_OUT_SECONDS = 10;
56 
57 REGISTER_SYSTEM_ABILITY_BY_ID(AudioPolicyServer, AUDIO_POLICY_SERVICE_ID, true)
58 
59 std::map<PolicyType, uint32_t> POLICY_TYPE_MAP = {
60     {PolicyType::EDM_POLICY_TYPE, 0},
61     {PolicyType::PRIVACY_POLCIY_TYPE, 1},
62     {PolicyType::TEMPORARY_POLCIY_TYPE, 2}
63 };
64 
AudioPolicyServer(int32_t systemAbilityId,bool runOnCreate)65 AudioPolicyServer::AudioPolicyServer(int32_t systemAbilityId, bool runOnCreate)
66     : SystemAbility(systemAbilityId, runOnCreate),
67       audioPolicyService_(AudioPolicyService::GetAudioPolicyService()),
68       audioDeviceManager_(AudioDeviceManager::GetAudioDeviceManager()),
69       audioSpatializationService_(AudioSpatializationService::GetAudioSpatializationService()),
70       audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter())
71 {
72     volumeStep_ = system::GetIntParameter("const.multimedia.audio.volumestep", 1);
73     AUDIO_INFO_LOG("Get volumeStep parameter success %{public}d", volumeStep_);
74 
75     powerStateCallbackRegister_ = false;
76     volumeApplyToAll_ = system::GetBoolParameter("const.audio.volume_apply_to_all", false);
77     if (volumeApplyToAll_) {
78         audioPolicyService_.SetNormalVoipFlag(true);
79     }
80 }
81 
OnDump()82 void AudioPolicyServer::OnDump()
83 {
84     return;
85 }
86 
OnStart()87 void AudioPolicyServer::OnStart()
88 {
89     AUDIO_INFO_LOG("Audio policy server on start");
90 
91     interruptService_ = std::make_shared<AudioInterruptService>();
92     interruptService_->Init(this);
93 
94     audioPolicyServerHandler_ = DelayedSingleton<AudioPolicyServerHandler>::GetInstance();
95     audioPolicyServerHandler_->Init(interruptService_);
96 
97     interruptService_->SetCallbackHandler(audioPolicyServerHandler_);
98 
99     if (audioPolicyService_.SetAudioStreamRemovedCallback(this)) {
100         AUDIO_ERR_LOG("SetAudioStreamRemovedCallback failed");
101     }
102     audioPolicyService_.Init();
103 
104     AddSystemAbilityListener(AUDIO_DISTRIBUTED_SERVICE_ID);
105     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
106 #ifdef FEATURE_MULTIMODALINPUT_INPUT
107     AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
108 #endif
109     AddSystemAbilityListener(BLUETOOTH_HOST_SYS_ABILITY_ID);
110     AddSystemAbilityListener(ACCESSIBILITY_MANAGER_SERVICE_ID);
111     AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
112     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
113 #ifdef SUPPORT_USER_ACCOUNT
114     AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
115 #endif
116     bool res = Publish(this);
117     if (!res) {
118         std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
119             Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_SERVICE_STARTUP_ERROR,
120             Media::MediaMonitor::EventType::FAULT_EVENT);
121         bean->Add("SERVICE_ID", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVICE_ID));
122         bean->Add("ERROR_CODE", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVER));
123         Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
124         AUDIO_INFO_LOG("publish sa err");
125     }
126 
127     Security::AccessToken::PermStateChangeScope scopeInfo;
128     scopeInfo.permList = {"ohos.permission.MICROPHONE"};
129     auto callbackPtr = std::make_shared<PerStateChangeCbCustomizeCallback>(scopeInfo, this);
130     callbackPtr->ready_ = false;
131     int32_t iRes = Security::AccessToken::AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr);
132     if (iRes < 0) {
133         AUDIO_ERR_LOG("fail to call RegisterPermStateChangeCallback.");
134     }
135 #ifdef FEATURE_MULTIMODALINPUT_INPUT
136     SubscribeVolumeKeyEvents();
137 #endif
138     AUDIO_INFO_LOG("Audio policy server start end");
139 }
140 
OnStop()141 void AudioPolicyServer::OnStop()
142 {
143     audioPolicyService_.Deinit();
144     UnRegisterPowerStateListener();
145     UnRegisterSyncHibernateListener();
146     return;
147 }
148 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)149 void AudioPolicyServer::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
150 {
151     AUDIO_INFO_LOG("SA Id is :%{public}d", systemAbilityId);
152     int64_t stamp = ClockTime::GetCurNano();
153     switch (systemAbilityId) {
154 #ifdef FEATURE_MULTIMODALINPUT_INPUT
155         case MULTIMODAL_INPUT_SERVICE_ID:
156             AUDIO_INFO_LOG("OnAddSystemAbility input service start");
157             SubscribeVolumeKeyEvents();
158             break;
159 #endif
160         case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID:
161             HandleKvDataShareEvent();
162             break;
163         case AUDIO_DISTRIBUTED_SERVICE_ID:
164             AUDIO_INFO_LOG("OnAddSystemAbility audio service start");
165             AddAudioServiceOnStart();
166             break;
167         case BLUETOOTH_HOST_SYS_ABILITY_ID:
168             AUDIO_INFO_LOG("OnAddSystemAbility bluetooth service start");
169             RegisterBluetoothListener();
170             break;
171         case ACCESSIBILITY_MANAGER_SERVICE_ID:
172             AUDIO_INFO_LOG("OnAddSystemAbility accessibility service start");
173             SubscribeAccessibilityConfigObserver();
174             InitKVStore();
175             break;
176         case POWER_MANAGER_SERVICE_ID:
177             AUDIO_INFO_LOG("OnAddSystemAbility power manager service start");
178             SubscribePowerStateChangeEvents();
179             RegisterPowerStateListener();
180             RegisterSyncHibernateListener();
181             break;
182         case SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN:
183             AUDIO_INFO_LOG("OnAddSystemAbility os_account service start");
184             SubscribeOsAccountChangeEvents();
185             break;
186         case COMMON_EVENT_SERVICE_ID:
187             SubscribeCommonEvent("usual.event.DATA_SHARE_READY");
188             SubscribeCommonEvent("usual.event.dms.rotation_changed");
189             SubscribeCommonEvent("usual.event.bluetooth.remotedevice.NAME_UPDATE");
190             break;
191         default:
192             AUDIO_WARNING_LOG("OnAddSystemAbility unhandled sysabilityId:%{public}d", systemAbilityId);
193             break;
194     }
195     // eg. done systemAbilityId: [3001] cost 780ms
196     AUDIO_INFO_LOG("done systemAbilityId: [%{public}d] cost %{public}" PRId64 " ms", systemAbilityId,
197         (ClockTime::GetCurNano() - stamp) / AUDIO_US_PER_SECOND);
198 }
199 
HandleKvDataShareEvent()200 void AudioPolicyServer::HandleKvDataShareEvent()
201 {
202     AUDIO_INFO_LOG("OnAddSystemAbility kv data service start");
203     if (isInitMuteState_ == false && audioPolicyService_.IsDataShareReady()) {
204         AUDIO_INFO_LOG("datashare is ready and need init mic mute state");
205         InitMicrophoneMute();
206     }
207     InitKVStore();
208 }
209 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)210 void AudioPolicyServer::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
211 {
212     AUDIO_DEBUG_LOG("AudioPolicyServer::OnRemoveSystemAbility systemAbilityId:%{public}d removed", systemAbilityId);
213 }
214 
215 #ifdef FEATURE_MULTIMODALINPUT_INPUT
MaxOrMinVolumeOption(const int32_t & volLevel,const int32_t keyType,const AudioStreamType & streamInFocus)216 bool AudioPolicyServer::MaxOrMinVolumeOption(const int32_t &volLevel, const int32_t keyType,
217     const AudioStreamType &streamInFocus)
218 {
219     bool volLevelCheck = (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ?
220         volLevel >= GetMaxVolumeLevel(streamInFocus) : volLevel <= GetMinVolumeLevel(streamInFocus);
221     if (volLevelCheck) {
222         VolumeEvent volumeEvent;
223         volumeEvent.volumeType = (streamInFocus == STREAM_ALL) ? STREAM_MUSIC : streamInFocus;
224         volumeEvent.volume = volLevel;
225         volumeEvent.updateUi = true;
226         volumeEvent.volumeGroupId = 0;
227         volumeEvent.networkId = LOCAL_NETWORK_ID;
228         CHECK_AND_RETURN_RET_LOG(audioPolicyServerHandler_ != nullptr, false, "audioPolicyServerHandler_ is nullptr");
229         audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
230         return true;
231     }
232 
233     return false;
234 }
235 #endif
236 
237 #ifdef FEATURE_MULTIMODALINPUT_INPUT
RegisterVolumeKeyEvents(const int32_t keyType)238 int32_t AudioPolicyServer::RegisterVolumeKeyEvents(const int32_t keyType)
239 {
240     if ((keyType != OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) && (keyType != OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN)) {
241         AUDIO_ERR_LOG("VolumeKeyEvents: invalid key type : %{public}d", keyType);
242         return ERR_INVALID_PARAM;
243     }
244     AUDIO_INFO_LOG("RegisterVolumeKeyEvents: volume key: %{public}s.",
245         (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ? "up" : "down");
246 
247     MMI::InputManager *im = MMI::InputManager::GetInstance();
248     CHECK_AND_RETURN_RET_LOG(im != nullptr, ERR_INVALID_PARAM, "Failed to obtain INPUT manager");
249 
250     std::set<int32_t> preKeys;
251     std::shared_ptr<OHOS::MMI::KeyOption> keyOption = std::make_shared<OHOS::MMI::KeyOption>();
252     CHECK_AND_RETURN_RET_LOG(keyOption != nullptr, ERR_INVALID_PARAM, "Invalid key option");
253     WatchTimeout guard("keyOption->SetPreKeys:RegisterVolumeKeyEvents");
254     keyOption->SetPreKeys(preKeys);
255     keyOption->SetFinalKey(keyType);
256     keyOption->SetFinalKeyDown(true);
257     keyOption->SetFinalKeyDownDuration(VOLUME_KEY_DURATION);
258     guard.CheckCurrTimeout();
259     int32_t keySubId = im->SubscribeKeyEvent(keyOption, [=](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
260         AUDIO_PRERELEASE_LOGI("Receive volume key event: %{public}s.",
261             (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ? "up" : "down");
262         std::lock_guard<std::mutex> lock(keyEventMutex_);
263         AudioStreamType streamInFocus = AudioStreamType::STREAM_MUSIC; // use STREAM_MUSIC as default stream type
264         if (volumeApplyToAll_) {
265             streamInFocus = AudioStreamType::STREAM_ALL;
266         } else {
267             streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
268         }
269         if (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP && GetStreamMuteInternal(streamInFocus)) {
270             AUDIO_INFO_LOG("VolumeKeyEvents: volumeKey: Up. volumeType %{public}d is mute. Unmute.", streamInFocus);
271             SetStreamMuteInternal(streamInFocus, false, true);
272             return;
273         }
274         int32_t volumeLevelInInt = GetSystemVolumeLevelInternal(streamInFocus);
275         if (MaxOrMinVolumeOption(volumeLevelInInt, keyType, streamInFocus)) {
276             return;
277         }
278 
279         volumeLevelInInt = (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ?
280             ++volumeLevelInInt : --volumeLevelInInt;
281         SetSystemVolumeLevelInternal(streamInFocus, volumeLevelInInt, true);
282     });
283     if (keySubId < 0) {
284         AUDIO_ERR_LOG("SubscribeKeyEvent: subscribing for volume key: %{public}s option failed",
285             (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ? "up" : "down");
286     }
287     return keySubId;
288 }
289 #endif
290 
291 #ifdef FEATURE_MULTIMODALINPUT_INPUT
RegisterVolumeKeyMuteEvents()292 int32_t AudioPolicyServer::RegisterVolumeKeyMuteEvents()
293 {
294     AUDIO_INFO_LOG("RegisterVolumeKeyMuteEvents: volume key: mute");
295     MMI::InputManager *im = MMI::InputManager::GetInstance();
296     CHECK_AND_RETURN_RET_LOG(im != nullptr, ERR_INVALID_PARAM, "Failed to obtain INPUT manager");
297 
298     std::shared_ptr<OHOS::MMI::KeyOption> keyOptionMute = std::make_shared<OHOS::MMI::KeyOption>();
299     CHECK_AND_RETURN_RET_LOG(keyOptionMute != nullptr, ERR_INVALID_PARAM, "keyOptionMute: Invalid key option");
300     std::set<int32_t> preKeys;
301     WatchTimeout guard("keyOption->SetPreKeys:RegisterVolumeKeyMuteEvents");
302     keyOptionMute->SetPreKeys(preKeys);
303     keyOptionMute->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_MUTE);
304     keyOptionMute->SetFinalKeyDown(true);
305     keyOptionMute->SetFinalKeyDownDuration(VOLUME_MUTE_KEY_DURATION);
306     guard.CheckCurrTimeout();
307     int32_t muteKeySubId = im->SubscribeKeyEvent(keyOptionMute,
308         [this](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
309             AUDIO_INFO_LOG("Receive volume key event: mute");
310             std::lock_guard<std::mutex> lock(keyEventMutex_);
311             AudioStreamType streamInFocus = AudioStreamType::STREAM_MUSIC; // use STREAM_MUSIC as default stream type
312             if (volumeApplyToAll_) {
313                 streamInFocus = AudioStreamType::STREAM_ALL;
314             } else {
315                 streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
316             }
317             bool isMuted = GetStreamMuteInternal(streamInFocus);
318             SetStreamMuteInternal(streamInFocus, !isMuted, true);
319         });
320     if (muteKeySubId < 0) {
321         AUDIO_ERR_LOG("SubscribeKeyEvent: subscribing for mute failed ");
322     }
323     return muteKeySubId;
324 }
325 #endif
326 
327 #ifdef FEATURE_MULTIMODALINPUT_INPUT
SubscribeVolumeKeyEvents()328 void AudioPolicyServer::SubscribeVolumeKeyEvents()
329 {
330     if (hasSubscribedVolumeKeyEvents_.load()) {
331         AUDIO_INFO_LOG("SubscribeVolumeKeyEvents: volume key events has been sunscirbed!");
332         return;
333     }
334 
335     AUDIO_INFO_LOG("SubscribeVolumeKeyEvents: first time.");
336     int32_t resultOfVolumeUp = RegisterVolumeKeyEvents(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP);
337     int32_t resultOfVolumeDown = RegisterVolumeKeyEvents(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN);
338     int32_t resultOfMute = RegisterVolumeKeyMuteEvents();
339     if (resultOfVolumeUp >= 0 && resultOfVolumeDown >= 0 && resultOfMute >= 0) {
340         hasSubscribedVolumeKeyEvents_.store(true);
341     } else {
342         AUDIO_ERR_LOG("SubscribeVolumeKeyEvents: failed to subscribe key events.");
343         hasSubscribedVolumeKeyEvents_.store(false);
344     }
345 }
346 #endif
347 
IsVolumeTypeValid(AudioStreamType streamType)348 bool AudioPolicyServer::IsVolumeTypeValid(AudioStreamType streamType)
349 {
350     bool result = false;
351     switch (streamType) {
352         case STREAM_MUSIC:
353         case STREAM_RING:
354         case STREAM_NOTIFICATION:
355         case STREAM_VOICE_CALL:
356         case STREAM_VOICE_COMMUNICATION:
357         case STREAM_VOICE_ASSISTANT:
358         case STREAM_ALARM:
359         case STREAM_ACCESSIBILITY:
360         case STREAM_ULTRASONIC:
361         case STREAM_ALL:
362         case STREAM_VOICE_RING:
363         case STREAM_CAMCORDER:
364             result = true;
365             break;
366         default:
367             result = false;
368             AUDIO_ERR_LOG("IsVolumeTypeValid: streamType[%{public}d] is not supported", streamType);
369             break;
370     }
371     return result;
372 }
373 
IsVolumeLevelValid(AudioStreamType streamType,int32_t volumeLevel)374 bool AudioPolicyServer::IsVolumeLevelValid(AudioStreamType streamType, int32_t volumeLevel)
375 {
376     bool result = true;
377     if (volumeLevel < audioPolicyService_.GetMinVolumeLevel(streamType) ||
378         volumeLevel > audioPolicyService_.GetMaxVolumeLevel(streamType)) {
379         AUDIO_ERR_LOG("IsVolumeLevelValid: volumeLevel[%{public}d] is out of valid range for streamType[%{public}d]",
380             volumeLevel, streamType);
381         result = false;
382     }
383     return result;
384 }
385 
SubscribeOsAccountChangeEvents()386 void AudioPolicyServer::SubscribeOsAccountChangeEvents()
387 {
388     if (accountObserver_ == nullptr) {
389         AccountSA::OsAccountSubscribeInfo osAccountSubscribeInfo;
390         osAccountSubscribeInfo.SetOsAccountSubscribeType(AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHED);
391         accountObserver_ = std::make_shared<AudioOsAccountInfo>(osAccountSubscribeInfo, this);
392         ErrCode errCode = AccountSA::OsAccountManager::SubscribeOsAccount(accountObserver_);
393         CHECK_AND_RETURN_LOG(errCode == ERR_OK, "account observer register fail");
394         AUDIO_INFO_LOG("account observer register success");
395     } else {
396         AUDIO_ERR_LOG("account observer register already");
397     }
398 }
399 
AddAudioServiceOnStart()400 void AudioPolicyServer::AddAudioServiceOnStart()
401 {
402     if (!isFirstAudioServiceStart_) {
403         ConnectServiceAdapter();
404         sessionProcessor_.Start();
405         RegisterParamCallback();
406         LoadEffectLibrary();
407         isFirstAudioServiceStart_ = true;
408     } else {
409         AUDIO_WARNING_LOG("OnAddSystemAbility audio service is not first start");
410     }
411 }
412 
SubscribePowerStateChangeEvents()413 void AudioPolicyServer::SubscribePowerStateChangeEvents()
414 {
415     sptr<PowerMgr::IPowerStateCallback> powerStateCallback_;
416 
417     if (powerStateCallback_ == nullptr) {
418         powerStateCallback_ = new (std::nothrow) AudioPolicyServerPowerStateCallback(this);
419     }
420 
421     if (powerStateCallback_ == nullptr) {
422         AUDIO_ERR_LOG("subscribe create power state callback Create Error");
423         return;
424     }
425 
426     WatchTimeout guard("PowerMgr::PowerMgrClient::GetInstance().RegisterPowerStateCallback:AddRemoteDevstatus");
427     bool RegisterSuccess = PowerMgr::PowerMgrClient::GetInstance().RegisterPowerStateCallback(powerStateCallback_,
428         false);
429     guard.CheckCurrTimeout();
430     if (!RegisterSuccess) {
431         AUDIO_ERR_LOG("register power state callback failed");
432     } else {
433         AUDIO_INFO_LOG("register power state callback success");
434         powerStateCallbackRegister_ = true;
435     }
436 }
437 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)438 void AudioCommonEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
439 {
440     if (eventReceiver_ == nullptr) {
441         AUDIO_ERR_LOG("eventReceiver_ is nullptr");
442         return;
443     }
444     AUDIO_INFO_LOG("receive DATA_SHARE_READY action success");
445     eventReceiver_(eventData);
446 }
447 
SubscribeCommonEvent(const std::string event)448 void AudioPolicyServer::SubscribeCommonEvent(const std::string event)
449 {
450     EventFwk::MatchingSkills matchingSkills;
451     matchingSkills.AddEvent(event);
452     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
453     if (event == "usual.event.dms.rotation_changed") {
454         subscribeInfo.SetPermission("ohos.permission.PUBLISH_DISPLAY_ROTATION_EVENT");
455     }
456     auto commonSubscribePtr = std::make_shared<AudioCommonEventSubscriber>(subscribeInfo,
457         std::bind(&AudioPolicyServer::OnReceiveEvent, this, std::placeholders::_1));
458     if (commonSubscribePtr == nullptr) {
459         AUDIO_ERR_LOG("commonSubscribePtr is nullptr");
460         return;
461     }
462     AUDIO_INFO_LOG("subscribe event: %s action", event.c_str());
463     EventFwk::CommonEventManager::SubscribeCommonEvent(commonSubscribePtr);
464 }
465 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)466 void AudioPolicyServer::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
467 {
468     const AAFwk::Want& want = eventData.GetWant();
469     std::string action = want.GetAction();
470     if (action == "usual.event.DATA_SHARE_READY") {
471         RegisterDataObserver();
472         if (isInitMuteState_ == false) {
473             AUDIO_INFO_LOG("receive DATA_SHARE_READY action and need init mic mute state");
474             InitMicrophoneMute();
475         }
476         audioPolicyService_.SetDataShareReady(true);
477     } else if (action == "usual.event.dms.rotation_changed") {
478         uint32_t rotate = static_cast<uint32_t>(want.GetIntParam("rotation", 0));
479         AUDIO_INFO_LOG("Set rotation to audioeffectchainmanager is %{public}d", rotate);
480         audioPolicyService_.SetRotationToEffect(rotate);
481     } else if (action == "usual.event.bluetooth.remotedevice.NAME_UPDATE") {
482         std::string deviceName  = want.GetStringParam("remoteName");
483         std::string macAddress = want.GetStringParam("deviceAddr");
484         audioPolicyService_.OnReceiveBluetoothEvent(macAddress, deviceName);
485     }
486 }
487 
CheckSubscribePowerStateChange()488 void AudioPolicyServer::CheckSubscribePowerStateChange()
489 {
490     if (powerStateCallbackRegister_) {
491         return;
492     }
493 
494     SubscribePowerStateChangeEvents();
495 
496     if (powerStateCallbackRegister_) {
497         AUDIO_DEBUG_LOG("PowerState CallBack Register Success");
498     } else {
499         AUDIO_ERR_LOG("PowerState CallBack Register Failed");
500     }
501 }
502 
OffloadStreamCheck(int64_t activateSessionId,int64_t deactivateSessionId)503 void AudioPolicyServer::OffloadStreamCheck(int64_t activateSessionId, int64_t deactivateSessionId)
504 {
505     CheckSubscribePowerStateChange();
506     if (deactivateSessionId != OFFLOAD_NO_SESSION_ID) {
507         audioPolicyService_.OffloadStreamReleaseCheck(deactivateSessionId);
508     }
509     if (activateSessionId != OFFLOAD_NO_SESSION_ID) {
510         audioPolicyService_.OffloadStreamSetCheck(activateSessionId);
511     }
512 }
513 
AudioPolicyServerPowerStateCallback(AudioPolicyServer * policyServer)514 AudioPolicyServer::AudioPolicyServerPowerStateCallback::AudioPolicyServerPowerStateCallback(
515     AudioPolicyServer* policyServer) : PowerMgr::PowerStateCallbackStub(), policyServer_(policyServer)
516 {}
517 
CheckStreamMode(const int64_t activateSessionId)518 void AudioPolicyServer::CheckStreamMode(const int64_t activateSessionId)
519 {
520     audioPolicyService_.CheckStreamMode(activateSessionId);
521 }
522 
OnAsyncPowerStateChanged(PowerMgr::PowerState state)523 void AudioPolicyServer::AudioPolicyServerPowerStateCallback::OnAsyncPowerStateChanged(PowerMgr::PowerState state)
524 {
525     policyServer_->audioPolicyService_.HandlePowerStateChanged(state);
526 }
527 
InitKVStore()528 void AudioPolicyServer::InitKVStore()
529 {
530     audioPolicyService_.InitKVStore();
531 }
532 
ConnectServiceAdapter()533 void AudioPolicyServer::ConnectServiceAdapter()
534 {
535     if (!audioPolicyService_.ConnectServiceAdapter()) {
536         AUDIO_ERR_LOG("ConnectServiceAdapter Error in connecting to audio service adapter");
537         return;
538     }
539 }
540 
LoadEffectLibrary()541 void AudioPolicyServer::LoadEffectLibrary()
542 {
543     audioPolicyService_.LoadEffectLibrary();
544 }
545 
GetMaxVolumeLevel(AudioVolumeType volumeType)546 int32_t AudioPolicyServer::GetMaxVolumeLevel(AudioVolumeType volumeType)
547 {
548     return audioPolicyService_.GetMaxVolumeLevel(volumeType);
549 }
550 
GetMinVolumeLevel(AudioVolumeType volumeType)551 int32_t AudioPolicyServer::GetMinVolumeLevel(AudioVolumeType volumeType)
552 {
553     return audioPolicyService_.GetMinVolumeLevel(volumeType);
554 }
555 
556 // deprecated since api 9.
SetSystemVolumeLevelLegacy(AudioStreamType streamType,int32_t volumeLevel)557 int32_t AudioPolicyServer::SetSystemVolumeLevelLegacy(AudioStreamType streamType, int32_t volumeLevel)
558 {
559     if (!IsVolumeTypeValid(streamType)) {
560         return ERR_NOT_SUPPORTED;
561     }
562     if (!IsVolumeLevelValid(streamType, volumeLevel)) {
563         return ERR_NOT_SUPPORTED;
564     }
565 
566     return SetSystemVolumeLevelInternal(streamType, volumeLevel, false);
567 }
568 
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel,int32_t volumeFlag)569 int32_t AudioPolicyServer::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel, int32_t volumeFlag)
570 {
571     if (!PermissionUtil::VerifySystemPermission()) {
572         AUDIO_ERR_LOG("SetSystemVolumeLevel: No system permission");
573         return ERR_PERMISSION_DENIED;
574     }
575 
576     if (!IsVolumeTypeValid(streamType)) {
577         return ERR_NOT_SUPPORTED;
578     }
579     if (!IsVolumeLevelValid(streamType, volumeLevel)) {
580         return ERR_NOT_SUPPORTED;
581     }
582 
583     return SetSystemVolumeLevelInternal(streamType, volumeLevel, volumeFlag == VolumeFlag::FLAG_SHOW_SYSTEM_UI);
584 }
585 
GetSystemActiveVolumeType(const int32_t clientUid)586 AudioStreamType AudioPolicyServer::GetSystemActiveVolumeType(const int32_t clientUid)
587 {
588     return GetSystemActiveVolumeTypeInternal(clientUid);
589 }
590 
GetSystemActiveVolumeTypeInternal(const int32_t clientUid)591 AudioStreamType AudioPolicyServer::GetSystemActiveVolumeTypeInternal(const int32_t clientUid)
592 {
593     if (!PermissionUtil::VerifySystemPermission()) {
594         AUDIO_ERR_LOG("No system permission");
595         return AudioStreamType::STREAM_MUSIC;
596     }
597     AudioStreamType streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
598     if (clientUid != 0) {
599         streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus(clientUid));
600     }
601 
602     AUDIO_INFO_LOG("Get active volume type success:= %{public}d", streamInFocus);
603     return streamInFocus;
604 }
605 
GetSystemVolumeLevel(AudioStreamType streamType)606 int32_t AudioPolicyServer::GetSystemVolumeLevel(AudioStreamType streamType)
607 {
608     return GetSystemVolumeLevelInternal(streamType);
609 }
610 
GetSystemVolumeLevelInternal(AudioStreamType streamType)611 int32_t AudioPolicyServer::GetSystemVolumeLevelInternal(AudioStreamType streamType)
612 {
613     if (streamType == STREAM_ALL) {
614         streamType = STREAM_MUSIC;
615         AUDIO_DEBUG_LOG("GetVolume of STREAM_ALL for streamType = %{public}d ", streamType);
616     }
617     return audioPolicyService_.GetSystemVolumeLevel(streamType);
618 }
619 
SetLowPowerVolume(int32_t streamId,float volume)620 int32_t AudioPolicyServer::SetLowPowerVolume(int32_t streamId, float volume)
621 {
622     auto callerUid = IPCSkeleton::GetCallingUid();
623     if (callerUid != UID_FOUNDATION_SA && callerUid != UID_RESOURCE_SCHEDULE_SERVICE) {
624         AUDIO_ERR_LOG("SetLowPowerVolume callerUid Error: not foundation or resource_schedule_service");
625         return ERROR;
626     }
627     return audioPolicyService_.SetLowPowerVolume(streamId, volume);
628 }
629 
GetLowPowerVolume(int32_t streamId)630 float AudioPolicyServer::GetLowPowerVolume(int32_t streamId)
631 {
632     return audioPolicyService_.GetLowPowerVolume(streamId);
633 }
634 
GetSingleStreamVolume(int32_t streamId)635 float AudioPolicyServer::GetSingleStreamVolume(int32_t streamId)
636 {
637     return audioPolicyService_.GetSingleStreamVolume(streamId);
638 }
639 
IsVolumeUnadjustable()640 bool AudioPolicyServer::IsVolumeUnadjustable()
641 {
642     return audioPolicyService_.IsVolumeUnadjustable();
643 }
644 
AdjustVolumeByStep(VolumeAdjustType adjustType)645 int32_t AudioPolicyServer::AdjustVolumeByStep(VolumeAdjustType adjustType)
646 {
647     if (!PermissionUtil::VerifySystemPermission()) {
648         AUDIO_ERR_LOG("AdjustVolumeByStep: No system permission");
649         return ERR_PERMISSION_DENIED;
650     }
651 
652     AudioStreamType streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
653     if (streamInFocus == AudioStreamType::STREAM_DEFAULT) {
654         streamInFocus = AudioStreamType::STREAM_MUSIC;
655     }
656 
657     int32_t volumeLevelInInt = GetSystemVolumeLevel(streamInFocus);
658     int32_t ret = ERROR;
659     if (adjustType == VolumeAdjustType::VOLUME_UP) {
660         ret = SetSystemVolumeLevelInternal(streamInFocus, volumeLevelInInt + volumeStep_, false);
661         AUDIO_INFO_LOG("AdjustVolumeByStep Up, VolumeLevel is %{public}d", GetSystemVolumeLevel(streamInFocus));
662     }
663 
664     if (adjustType == VolumeAdjustType::VOLUME_DOWN) {
665         ret = SetSystemVolumeLevelInternal(streamInFocus, volumeLevelInInt - volumeStep_, false);
666         AUDIO_INFO_LOG("AdjustVolumeByStep Down, VolumeLevel is %{public}d", GetSystemVolumeLevel(streamInFocus));
667     }
668     return ret;
669 }
670 
AdjustSystemVolumeByStep(AudioVolumeType volumeType,VolumeAdjustType adjustType)671 int32_t AudioPolicyServer::AdjustSystemVolumeByStep(AudioVolumeType volumeType, VolumeAdjustType adjustType)
672 {
673     if (!PermissionUtil::VerifySystemPermission()) {
674         AUDIO_ERR_LOG("AdjustSystemVolumeByStep: No system permission");
675         return ERR_PERMISSION_DENIED;
676     }
677 
678     int32_t volumeLevelInInt = GetSystemVolumeLevel(volumeType);
679     int32_t ret = ERROR;
680 
681     if (adjustType == VolumeAdjustType::VOLUME_UP) {
682         ret = SetSystemVolumeLevelInternal(volumeType, volumeLevelInInt + volumeStep_, false);
683         AUDIO_INFO_LOG("AdjustSystemVolumeByStep Up, VolumeLevel:%{public}d", GetSystemVolumeLevel(volumeType));
684     }
685 
686     if (adjustType == VolumeAdjustType::VOLUME_DOWN) {
687         ret = SetSystemVolumeLevelInternal(volumeType, volumeLevelInInt - volumeStep_, false);
688         AUDIO_INFO_LOG("AdjustSystemVolumeByStep Down, VolumeLevel:%{public}d", GetSystemVolumeLevel(volumeType));
689     }
690     return ret;
691 }
692 
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType)693 float AudioPolicyServer::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, DeviceType deviceType)
694 {
695     if (!IsVolumeTypeValid(volumeType)) {
696         return static_cast<float>(ERR_INVALID_PARAM);
697     }
698     if (!IsVolumeLevelValid(volumeType, volumeLevel)) {
699         return static_cast<float>(ERR_INVALID_PARAM);
700     }
701 
702     return audioPolicyService_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType);
703 }
704 
705 // deprecated since api 9.
SetStreamMuteLegacy(AudioStreamType streamType,bool mute)706 int32_t AudioPolicyServer::SetStreamMuteLegacy(AudioStreamType streamType, bool mute)
707 {
708     return SetStreamMuteInternal(streamType, mute, false);
709 }
710 
SetStreamMute(AudioStreamType streamType,bool mute)711 int32_t AudioPolicyServer::SetStreamMute(AudioStreamType streamType, bool mute)
712 {
713     if (!PermissionUtil::VerifySystemPermission()) {
714         AUDIO_ERR_LOG("No system permission");
715         return ERR_PERMISSION_DENIED;
716     }
717 
718     return SetStreamMuteInternal(streamType, mute, false);
719 }
720 
SetStreamMuteInternal(AudioStreamType streamType,bool mute,bool isUpdateUi)721 int32_t AudioPolicyServer::SetStreamMuteInternal(AudioStreamType streamType, bool mute, bool isUpdateUi)
722 {
723     AUDIO_INFO_LOG("SetStreamMuteInternal streamType: %{public}d, mute: %{public}d, updateUi: %{public}d",
724         streamType, mute, isUpdateUi);
725 
726     if (streamType == STREAM_ALL) {
727         for (auto audioStreamType : GET_STREAM_ALL_VOLUME_TYPES) {
728             AUDIO_INFO_LOG("SetMute of STREAM_ALL for StreamType = %{public}d ", audioStreamType);
729             int32_t setResult = SetSingleStreamMute(audioStreamType, mute, isUpdateUi);
730             if (setResult != SUCCESS) {
731                 return setResult;
732             }
733         }
734         return SUCCESS;
735     }
736 
737     return SetSingleStreamMute(streamType, mute, isUpdateUi);
738 }
739 
SetSingleStreamMute(AudioStreamType streamType,bool mute,bool isUpdateUi)740 int32_t AudioPolicyServer::SetSingleStreamMute(AudioStreamType streamType, bool mute, bool isUpdateUi)
741 {
742     bool updateRingerMode = false;
743     if (streamType == AudioStreamType::STREAM_RING || streamType == AudioStreamType::STREAM_VOICE_RING) {
744         // Check whether the currentRingerMode is suitable for the ringtone mute state.
745         AudioRingerMode currentRingerMode = GetRingerMode();
746         if ((currentRingerMode == RINGER_MODE_NORMAL && mute) || (currentRingerMode != RINGER_MODE_NORMAL && !mute)) {
747             // When isUpdateUi is false, the func is called by others. Need to verify permission.
748             if (!isUpdateUi && !VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
749                 AUDIO_ERR_LOG("ACCESS_NOTIFICATION_POLICY_PERMISSION permission denied for ringtone mute state!");
750                 return ERR_PERMISSION_DENIED;
751             }
752             updateRingerMode = true;
753         }
754     }
755 
756     int32_t result = audioPolicyService_.SetStreamMute(streamType, mute);
757     CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Fail to set stream mute!");
758 
759     if (!mute && GetSystemVolumeLevelInternal(streamType) == 0) {
760         // If mute state is set to false but volume is 0, set volume to 1
761         audioPolicyService_.SetSystemVolumeLevel(streamType, 1);
762     }
763 
764     if (updateRingerMode) {
765         AudioRingerMode ringerMode = mute ? RINGER_MODE_VIBRATE : RINGER_MODE_NORMAL;
766         AUDIO_INFO_LOG("RingerMode should be set to %{public}d because of ring mute state", ringerMode);
767         // Update ringer mode but no need to update mute state again.
768         SetRingerModeInternal(ringerMode, true);
769     }
770 
771     VolumeEvent volumeEvent;
772     volumeEvent.volumeType = streamType;
773     volumeEvent.volume = GetSystemVolumeLevelInternal(streamType);
774     volumeEvent.updateUi = isUpdateUi;
775     volumeEvent.volumeGroupId = 0;
776     volumeEvent.networkId = LOCAL_NETWORK_ID;
777     if (audioPolicyServerHandler_ != nullptr) {
778         audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
779     }
780     return result;
781 }
782 
GetSystemVolumeDb(AudioStreamType streamType)783 float AudioPolicyServer::GetSystemVolumeDb(AudioStreamType streamType)
784 {
785     return audioPolicyService_.GetSystemVolumeDb(streamType);
786 }
787 
SetSystemVolumeLevelInternal(AudioStreamType streamType,int32_t volumeLevel,bool isUpdateUi)788 int32_t AudioPolicyServer::SetSystemVolumeLevelInternal(AudioStreamType streamType, int32_t volumeLevel,
789     bool isUpdateUi)
790 {
791     AUDIO_INFO_LOG("SetSystemVolumeLevelInternal streamType: %{public}d, volumeLevel: %{public}d, updateUi: %{public}d",
792         streamType, volumeLevel, isUpdateUi);
793     if (IsVolumeUnadjustable()) {
794         AUDIO_ERR_LOG("Unadjustable device, not allow set volume");
795         return ERR_OPERATION_FAILED;
796     }
797     bool mute = GetStreamMuteInternal(streamType);
798     if (streamType == STREAM_ALL) {
799         for (auto audioStreamType : GET_STREAM_ALL_VOLUME_TYPES) {
800             AUDIO_INFO_LOG("SetVolume of STREAM_ALL, SteamType = %{public}d, mute = %{public}d, level = %{public}d",
801                 audioStreamType, mute, volumeLevel);
802             int32_t setResult = SetSingleStreamVolume(audioStreamType, volumeLevel, isUpdateUi, mute);
803             if (setResult != SUCCESS) {
804                 return setResult;
805             }
806         }
807         return SUCCESS;
808     }
809     return SetSingleStreamVolume(streamType, volumeLevel, isUpdateUi, mute);
810 }
811 
SetSingleStreamVolume(AudioStreamType streamType,int32_t volumeLevel,bool isUpdateUi,bool mute)812 int32_t AudioPolicyServer::SetSingleStreamVolume(AudioStreamType streamType, int32_t volumeLevel, bool isUpdateUi,
813     bool mute)
814 {
815     bool updateRingerMode = false;
816     if (streamType == AudioStreamType::STREAM_RING || streamType == AudioStreamType::STREAM_VOICE_RING) {
817         // Check whether the currentRingerMode is suitable for the ringtone volume level.
818         AudioRingerMode currentRingerMode = GetRingerMode();
819         if ((currentRingerMode == RINGER_MODE_NORMAL && volumeLevel == 0) ||
820             (currentRingerMode != RINGER_MODE_NORMAL && volumeLevel > 0)) {
821             // When isUpdateUi is false, the func is called by others. Need to verify permission.
822             if (!isUpdateUi && !VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
823                 AUDIO_ERR_LOG("ACCESS_NOTIFICATION_POLICY_PERMISSION permission denied for ringtone volume!");
824                 return ERR_PERMISSION_DENIED;
825             }
826             updateRingerMode = true;
827         }
828     }
829 
830     int32_t ret = audioPolicyService_.SetSystemVolumeLevel(streamType, volumeLevel);
831     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fail to set system volume level!");
832 
833     // Update mute state according to volume level
834     if (volumeLevel == 0 && !mute) {
835         audioPolicyService_.SetStreamMute(streamType, true);
836     } else if (volumeLevel > 0 && mute) {
837         audioPolicyService_.SetStreamMute(streamType, false);
838     }
839 
840     if (updateRingerMode) {
841         int32_t curRingVolumeLevel = GetSystemVolumeLevelInternal(STREAM_RING);
842         AudioRingerMode ringerMode = (curRingVolumeLevel > 0) ? RINGER_MODE_NORMAL : RINGER_MODE_VIBRATE;
843         AUDIO_INFO_LOG("RingerMode should be set to %{public}d because of ring volume level", ringerMode);
844         // Update ringer mode but no need to update volume again.
845         SetRingerModeInternal(ringerMode, true);
846     }
847 
848     VolumeEvent volumeEvent;
849     volumeEvent.volumeType = streamType;
850     volumeEvent.volume = GetSystemVolumeLevelInternal(streamType);
851     volumeEvent.updateUi = isUpdateUi;
852     volumeEvent.volumeGroupId = 0;
853     volumeEvent.networkId = LOCAL_NETWORK_ID;
854     bool ringerModeMute = audioPolicyService_.IsRingerModeMute();
855     if (audioPolicyServerHandler_ != nullptr && ringerModeMute) {
856         audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
857     }
858     return ret;
859 }
860 
GetStreamMute(AudioStreamType streamType)861 bool AudioPolicyServer::GetStreamMute(AudioStreamType streamType)
862 {
863     if (streamType == AudioStreamType::STREAM_RING || streamType == AudioStreamType::STREAM_VOICE_RING) {
864         bool ret = VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION);
865         CHECK_AND_RETURN_RET_LOG(ret, false,
866             "GetStreamMute permission denied for stream type : %{public}d", streamType);
867     }
868 
869     return GetStreamMuteInternal(streamType);
870 }
871 
GetStreamMuteInternal(AudioStreamType streamType)872 bool AudioPolicyServer::GetStreamMuteInternal(AudioStreamType streamType)
873 {
874     if (streamType == STREAM_ALL) {
875         streamType = STREAM_MUSIC;
876         AUDIO_INFO_LOG("GetStreamMute of STREAM_ALL for streamType = %{public}d ", streamType);
877     }
878     return audioPolicyService_.GetStreamMute(streamType);
879 }
880 
IsArmUsbDevice(const AudioDeviceDescriptor & desc)881 bool AudioPolicyServer::IsArmUsbDevice(const AudioDeviceDescriptor &desc)
882 {
883     if (desc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) return true;
884     if (desc.deviceType_ != DEVICE_TYPE_USB_HEADSET) return false;
885 
886     return audioPolicyService_.IsArmUsbDevice(desc);
887 }
888 
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)889 int32_t AudioPolicyServer::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
890     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
891 {
892     CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED,
893         "SelectOutputDevice: No system permission");
894 
895     return audioPolicyService_.SelectOutputDevice(audioRendererFilter, audioDeviceDescriptors);
896 }
897 
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)898 std::string AudioPolicyServer::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
899 {
900     return audioPolicyService_.GetSelectedDeviceInfo(uid, pid, streamType);
901 }
902 
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)903 int32_t AudioPolicyServer::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
904     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
905 {
906     CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED,
907         "SelectInputDevice: No system permission");
908     int32_t ret = audioPolicyService_.SelectInputDevice(audioCapturerFilter, audioDeviceDescriptors);
909     return ret;
910 }
911 
GetDevices(DeviceFlag deviceFlag)912 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyServer::GetDevices(DeviceFlag deviceFlag)
913 {
914     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
915     switch (deviceFlag) {
916         case NONE_DEVICES_FLAG:
917         case DISTRIBUTED_OUTPUT_DEVICES_FLAG:
918         case DISTRIBUTED_INPUT_DEVICES_FLAG:
919         case ALL_DISTRIBUTED_DEVICES_FLAG:
920         case ALL_L_D_DEVICES_FLAG:
921             if (!hasSystemPermission) {
922                 AUDIO_ERR_LOG("GetDevices: No system permission");
923                 std::vector<sptr<AudioDeviceDescriptor>> info = {};
924                 return info;
925             }
926             break;
927         default:
928             break;
929     }
930 
931     std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = audioPolicyService_.GetDevices(deviceFlag);
932 
933     if (!hasSystemPermission) {
934         for (sptr<AudioDeviceDescriptor> desc : deviceDescs) {
935             desc->networkId_ = "";
936             desc->interruptGroupId_ = GROUP_ID_NONE;
937             desc->volumeGroupId_ = GROUP_ID_NONE;
938         }
939     }
940 
941     bool hasBTPermission = VerifyBluetoothPermission();
942     if (!hasBTPermission) {
943         audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDescs);
944     }
945 
946     return deviceDescs;
947 }
948 
GetDevicesInner(DeviceFlag deviceFlag)949 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyServer::GetDevicesInner(DeviceFlag deviceFlag)
950 {
951     auto callerUid = IPCSkeleton::GetCallingUid();
952     if (callerUid != UID_AUDIO) {
953         AUDIO_ERR_LOG("only for audioUid");
954         return {};
955     }
956     std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = audioPolicyService_.GetDevicesInner(deviceFlag);
957 
958     return deviceDescs;
959 }
960 
NotifyCapturerAdded(AudioCapturerInfo capturerInfo,AudioStreamInfo streamInfo,uint32_t sessionId)961 int32_t AudioPolicyServer::NotifyCapturerAdded(AudioCapturerInfo capturerInfo, AudioStreamInfo streamInfo,
962     uint32_t sessionId)
963 {
964     auto callerUid = IPCSkeleton::GetCallingUid();
965     // Temporarily allow only media service to use non-IPC route
966     CHECK_AND_RETURN_RET_LOG(callerUid == MEDIA_SERVICE_UID, ERR_PERMISSION_DENIED, "No permission");
967 
968     return audioPolicyService_.NotifyCapturerAdded(capturerInfo, streamInfo, sessionId);
969 }
970 
VerifyVoiceCallPermission(uint64_t fullTokenId,Security::AccessToken::AccessTokenID tokenId)971 int32_t AudioPolicyServer::VerifyVoiceCallPermission(uint64_t fullTokenId, Security::AccessToken::AccessTokenID tokenId)
972 {
973     bool hasSystemPermission = TokenIdKit::IsSystemAppByFullTokenID(fullTokenId);
974     CHECK_AND_RETURN_RET_LOG(hasSystemPermission, ERR_PERMISSION_DENIED, "No system permission");
975 
976     bool hasRecordVoiceCallPermission = VerifyPermission(RECORD_VOICE_CALL_PERMISSION, tokenId, true);
977     CHECK_AND_RETURN_RET_LOG(hasRecordVoiceCallPermission, ERR_PERMISSION_DENIED, "No permission");
978     return SUCCESS;
979 }
980 
GetPreferredOutputDeviceDescriptors(AudioRendererInfo & rendererInfo)981 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyServer::GetPreferredOutputDeviceDescriptors(
982     AudioRendererInfo &rendererInfo)
983 {
984     std::vector<sptr<AudioDeviceDescriptor>> deviceDescs =
985         audioPolicyService_.GetPreferredOutputDeviceDescriptors(rendererInfo);
986     bool hasBTPermission = VerifyBluetoothPermission();
987     if (!hasBTPermission) {
988         audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDescs);
989     }
990 
991     return deviceDescs;
992 }
993 
GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo)994 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyServer::GetPreferredInputDeviceDescriptors(
995     AudioCapturerInfo &captureInfo)
996 {
997     std::vector<sptr<AudioDeviceDescriptor>> deviceDescs =
998         audioPolicyService_.GetPreferredInputDeviceDescriptors(captureInfo);
999     bool hasBTPermission = VerifyBluetoothPermission();
1000     if (!hasBTPermission) {
1001         audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDescs);
1002     }
1003 
1004     return deviceDescs;
1005 }
1006 
SetClientCallbacksEnable(const CallbackChange & callbackchange,const bool & enable)1007 int32_t AudioPolicyServer::SetClientCallbacksEnable(const CallbackChange &callbackchange, const bool &enable)
1008 {
1009     return audioPolicyService_.SetClientCallbacksEnable(callbackchange, enable);
1010 }
1011 
IsStreamActive(AudioStreamType streamType)1012 bool AudioPolicyServer::IsStreamActive(AudioStreamType streamType)
1013 {
1014     return audioPolicyService_.IsStreamActive(streamType);
1015 }
1016 
SetDeviceActive(InternalDeviceType deviceType,bool active)1017 int32_t AudioPolicyServer::SetDeviceActive(InternalDeviceType deviceType, bool active)
1018 {
1019     return audioPolicyService_.SetDeviceActive(deviceType, active);
1020 }
1021 
IsDeviceActive(InternalDeviceType deviceType)1022 bool AudioPolicyServer::IsDeviceActive(InternalDeviceType deviceType)
1023 {
1024     return audioPolicyService_.IsDeviceActive(deviceType);
1025 }
1026 
GetActiveOutputDevice()1027 InternalDeviceType AudioPolicyServer::GetActiveOutputDevice()
1028 {
1029     return audioPolicyService_.GetActiveOutputDevice();
1030 }
1031 
GetActiveInputDevice()1032 InternalDeviceType AudioPolicyServer::GetActiveInputDevice()
1033 {
1034     return audioPolicyService_.GetActiveInputDevice();
1035 }
1036 
1037 // deprecated since api 9.
SetRingerModeLegacy(AudioRingerMode ringMode)1038 int32_t AudioPolicyServer::SetRingerModeLegacy(AudioRingerMode ringMode)
1039 {
1040     AUDIO_INFO_LOG("Set ringer mode to %{public}d in legacy", ringMode);
1041     return SetRingerModeInner(ringMode);
1042 }
1043 
SetRingerMode(AudioRingerMode ringMode)1044 int32_t AudioPolicyServer::SetRingerMode(AudioRingerMode ringMode)
1045 {
1046     AUDIO_INFO_LOG("Set ringer mode to %{public}d", ringMode);
1047     if (!PermissionUtil::VerifySystemPermission()) {
1048         AUDIO_ERR_LOG("No system permission");
1049         return ERR_PERMISSION_DENIED;
1050     }
1051 
1052     return SetRingerModeInner(ringMode);
1053 }
1054 
SetRingerModeInner(AudioRingerMode ringMode)1055 int32_t AudioPolicyServer::SetRingerModeInner(AudioRingerMode ringMode)
1056 {
1057     bool isPermissionRequired = false;
1058 
1059     if (ringMode == AudioRingerMode::RINGER_MODE_SILENT) {
1060         isPermissionRequired = true;
1061     } else {
1062         AudioRingerMode currentRingerMode = GetRingerMode();
1063         if (currentRingerMode == AudioRingerMode::RINGER_MODE_SILENT) {
1064             isPermissionRequired = true;
1065         }
1066     }
1067 
1068     // only switch to silent need check NOTIFICATION.
1069     if (isPermissionRequired) {
1070         bool result = VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION);
1071         CHECK_AND_RETURN_RET_LOG(result, ERR_PERMISSION_DENIED,
1072             "Access policy permission denied for ringerMode : %{public}d", ringMode);
1073     }
1074 
1075     return SetRingerModeInternal(ringMode);
1076 }
1077 
SetRingerModeInternal(AudioRingerMode ringerMode,bool hasUpdatedVolume)1078 int32_t AudioPolicyServer::SetRingerModeInternal(AudioRingerMode ringerMode, bool hasUpdatedVolume)
1079 {
1080     AUDIO_INFO_LOG("Set ringer mode to %{public}d. hasUpdatedVolume %{public}d", ringerMode, hasUpdatedVolume);
1081     int32_t ret = audioPolicyService_.SetRingerMode(ringerMode);
1082     CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fail to set ringer mode!");
1083 
1084     if (!hasUpdatedVolume) {
1085         // need to set volume according to ringermode
1086         bool muteState = (ringerMode == RINGER_MODE_NORMAL) ? false : true;
1087         AudioInterrupt audioInterrupt;
1088         GetSessionInfoInFocus(audioInterrupt);
1089         audioPolicyService_.SetStreamMute(STREAM_RING, muteState, audioInterrupt.streamUsage);
1090         if (!muteState && GetSystemVolumeLevelInternal(STREAM_RING) == 0) {
1091             // if mute state is false but volume is 0, set volume to 1. Send volumeChange callback.
1092             SetSystemVolumeLevelInternal(STREAM_RING, 1, false);
1093         }
1094     }
1095 
1096     if (audioPolicyServerHandler_ != nullptr) {
1097         audioPolicyServerHandler_->SendRingerModeUpdatedCallback(ringerMode);
1098     }
1099     return ret;
1100 }
1101 
1102 #ifdef FEATURE_DTMF_TONE
GetToneConfig(int32_t ltonetype)1103 std::shared_ptr<ToneInfo> AudioPolicyServer::GetToneConfig(int32_t ltonetype)
1104 {
1105     return audioPolicyService_.GetToneConfig(ltonetype);
1106 }
1107 
GetSupportedTones()1108 std::vector<int32_t> AudioPolicyServer::GetSupportedTones()
1109 {
1110     return audioPolicyService_.GetSupportedTones();
1111 }
1112 #endif
1113 
InitMicrophoneMute()1114 void AudioPolicyServer::InitMicrophoneMute()
1115 {
1116     AUDIO_INFO_LOG("Entered %{public}s", __func__);
1117     if (isInitMuteState_) {
1118         AUDIO_ERR_LOG("mic mutestate has already been initialized");
1119         return;
1120     }
1121     bool isMute = false;
1122     int32_t ret = audioPolicyService_.InitPersistentMicrophoneMuteState(isMute);
1123     AUDIO_INFO_LOG("Get persistent mic ismute: %{public}d  state from setting db", isMute);
1124     if (ret != SUCCESS) {
1125         AUDIO_ERR_LOG("InitMicrophoneMute InitPersistentMicrophoneMuteState result %{public}d", ret);
1126         return;
1127     }
1128     isInitMuteState_ = true;
1129     if (audioPolicyServerHandler_ != nullptr) {
1130         MicStateChangeEvent micStateChangeEvent;
1131         micStateChangeEvent.mute = isMute;
1132         audioPolicyServerHandler_->SendMicStateUpdatedCallback(micStateChangeEvent);
1133     }
1134 }
1135 
SetMicrophoneMuteCommon(bool isMute,bool isLegacy)1136 int32_t AudioPolicyServer::SetMicrophoneMuteCommon(bool isMute, bool isLegacy)
1137 {
1138     std::lock_guard<std::mutex> lock(micStateChangeMutex_);
1139     bool isMicrophoneMute = isLegacy ? IsMicrophoneMuteLegacy() : IsMicrophoneMute();
1140     int32_t ret = audioPolicyService_.SetMicrophoneMute(isMute);
1141     if (ret == SUCCESS && isMicrophoneMute != isMute && audioPolicyServerHandler_ != nullptr) {
1142         MicStateChangeEvent micStateChangeEvent;
1143         micStateChangeEvent.mute = audioPolicyService_.IsMicrophoneMute();
1144         audioPolicyServerHandler_->SendMicStateUpdatedCallback(micStateChangeEvent);
1145     }
1146     return ret;
1147 }
1148 
SetMicrophoneMute(bool isMute)1149 int32_t AudioPolicyServer::SetMicrophoneMute(bool isMute)
1150 {
1151     AUDIO_INFO_LOG("[%{public}d] set to %{public}s", IPCSkeleton::GetCallingPid(), (isMute ? "true" : "false"));
1152     bool ret = VerifyPermission(MICROPHONE_PERMISSION);
1153     CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED,
1154         "MICROPHONE permission denied");
1155     return SetMicrophoneMuteCommon(isMute, true);
1156 }
1157 
SetMicrophoneMuteAudioConfig(bool isMute)1158 int32_t AudioPolicyServer::SetMicrophoneMuteAudioConfig(bool isMute)
1159 {
1160     AUDIO_INFO_LOG("[%{public}d] set to %{public}s", IPCSkeleton::GetCallingPid(), (isMute ? "true" : "false"));
1161     bool ret = VerifyPermission(MANAGE_AUDIO_CONFIG);
1162     CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED,
1163         "MANAGE_AUDIO_CONFIG permission denied");
1164     lastMicMuteSettingPid_ = IPCSkeleton::GetCallingPid();
1165     WatchTimeout guard("PrivacyKit::SetMutePolicy:SetMicrophoneMuteAudioConfig");
1166     PrivacyKit::SetMutePolicy(POLICY_TYPE_MAP[TEMPORARY_POLCIY_TYPE], MICPHONE_CALLER, isMute,
1167         IPCSkeleton::GetCallingTokenID());
1168     guard.CheckCurrTimeout();
1169     return SetMicrophoneMuteCommon(isMute, false);
1170 }
1171 
SetMicrophoneMutePersistent(const bool isMute,const PolicyType type)1172 int32_t AudioPolicyServer::SetMicrophoneMutePersistent(const bool isMute, const PolicyType type)
1173 {
1174     AUDIO_INFO_LOG("Entered %{public}s isMute:%{public}d, type:%{public}d", __func__, isMute, type);
1175     bool hasPermission = VerifyPermission(MICROPHONE_CONTROL_PERMISSION);
1176     CHECK_AND_RETURN_RET_LOG(hasPermission, ERR_PERMISSION_DENIED,
1177         "MICROPHONE_CONTROL_PERMISSION permission denied");
1178     WatchTimeout guard("PrivacyKit::SetMutePolicy:SetMicrophoneMutePersistent");
1179     int32_t ret = PrivacyKit::SetMutePolicy(POLICY_TYPE_MAP[type], MICPHONE_CALLER, isMute,
1180         IPCSkeleton::GetCallingTokenID());
1181     guard.CheckCurrTimeout();
1182     if (ret != SUCCESS) {
1183         AUDIO_ERR_LOG("PrivacyKit SetMutePolicy failed ret is %{public}d", ret);
1184         return ret;
1185     }
1186     ret = audioPolicyService_.SetMicrophoneMutePersistent(isMute);
1187     if (ret == SUCCESS && audioPolicyServerHandler_ != nullptr) {
1188         MicStateChangeEvent micStateChangeEvent;
1189         micStateChangeEvent.mute = audioPolicyService_.IsMicrophoneMute();
1190         AUDIO_INFO_LOG("SendMicStateUpdatedCallback when set mic mute state persistent.");
1191         audioPolicyServerHandler_->SendMicStateUpdatedCallback(micStateChangeEvent);
1192     }
1193     return ret;
1194 }
1195 
GetPersistentMicMuteState()1196 bool AudioPolicyServer::GetPersistentMicMuteState()
1197 {
1198     bool hasPermission = VerifyPermission(MICROPHONE_CONTROL_PERMISSION);
1199     CHECK_AND_RETURN_RET_LOG(hasPermission, ERR_PERMISSION_DENIED,
1200         "MICROPHONE_CONTROL_PERMISSION permission denied");
1201 
1202     return audioPolicyService_.GetPersistentMicMuteState();
1203 }
1204 
1205 // deprecated since 9.
IsMicrophoneMuteLegacy()1206 bool AudioPolicyServer::IsMicrophoneMuteLegacy()
1207 {
1208     // AudioManager.IsMicrophoneMute check micphone right.
1209     if (!VerifyPermission(MICROPHONE_PERMISSION)) {
1210         AUDIO_ERR_LOG("MICROPHONE permission denied");
1211         return false;
1212     }
1213     return audioPolicyService_.IsMicrophoneMute();
1214 }
1215 
IsMicrophoneMute()1216 bool AudioPolicyServer::IsMicrophoneMute()
1217 {
1218     // AudioVolumeGroupManager.IsMicrophoneMute didn't check micphone right.
1219     return audioPolicyService_.IsMicrophoneMute();
1220 }
1221 
GetRingerMode()1222 AudioRingerMode AudioPolicyServer::GetRingerMode()
1223 {
1224     return audioPolicyService_.GetRingerMode();
1225 }
1226 
SetAudioScene(AudioScene audioScene)1227 int32_t AudioPolicyServer::SetAudioScene(AudioScene audioScene)
1228 {
1229     CHECK_AND_RETURN_RET_LOG(audioScene > AUDIO_SCENE_INVALID && audioScene < AUDIO_SCENE_MAX,
1230         ERR_INVALID_PARAM, "param is invalid");
1231     bool ret = PermissionUtil::VerifySystemPermission();
1232     CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED, "No system permission");
1233     if (audioScene == AUDIO_SCENE_CALL_START || audioScene == AUDIO_SCENE_CALL_END) {
1234         AUDIO_ERR_LOG("param is invalid");
1235         return ERR_INVALID_PARAM;
1236     }
1237     return audioPolicyService_.SetAudioScene(audioScene);
1238 }
1239 
SetAudioSceneInternal(AudioScene audioScene)1240 int32_t AudioPolicyServer::SetAudioSceneInternal(AudioScene audioScene)
1241 {
1242     return audioPolicyService_.SetAudioScene(audioScene);
1243 }
1244 
GetAudioScene()1245 AudioScene AudioPolicyServer::GetAudioScene()
1246 {
1247     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1248     return audioPolicyService_.GetAudioScene(hasSystemPermission);
1249 }
1250 
SetAudioInterruptCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object,uint32_t clientUid,const int32_t zoneID)1251 int32_t AudioPolicyServer::SetAudioInterruptCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object,
1252     uint32_t clientUid, const int32_t zoneID)
1253 {
1254     if (interruptService_ != nullptr) {
1255         return interruptService_->SetAudioInterruptCallback(zoneID, sessionID, object, clientUid);
1256     }
1257     return ERR_UNKNOWN;
1258 }
1259 
UnsetAudioInterruptCallback(const uint32_t sessionID,const int32_t zoneID)1260 int32_t AudioPolicyServer::UnsetAudioInterruptCallback(const uint32_t sessionID, const int32_t zoneID)
1261 {
1262     if (interruptService_ != nullptr) {
1263         return interruptService_->UnsetAudioInterruptCallback(zoneID, sessionID);
1264     }
1265     return ERR_UNKNOWN;
1266 }
1267 
SetAudioManagerInterruptCallback(const int32_t,const sptr<IRemoteObject> & object)1268 int32_t AudioPolicyServer::SetAudioManagerInterruptCallback(const int32_t /* clientId */,
1269                                                             const sptr<IRemoteObject> &object)
1270 {
1271     if (interruptService_ != nullptr) {
1272         return interruptService_->SetAudioManagerInterruptCallback(object);
1273     }
1274     return ERR_UNKNOWN;
1275 }
1276 
UnsetAudioManagerInterruptCallback(const int32_t)1277 int32_t AudioPolicyServer::UnsetAudioManagerInterruptCallback(const int32_t /* clientId */)
1278 {
1279     if (interruptService_ != nullptr) {
1280         return interruptService_->UnsetAudioManagerInterruptCallback();
1281     }
1282     return ERR_UNKNOWN;
1283 }
1284 
SetQueryClientTypeCallback(const sptr<IRemoteObject> & object)1285 int32_t AudioPolicyServer::SetQueryClientTypeCallback(const sptr<IRemoteObject> &object)
1286 {
1287     return audioPolicyService_.SetQueryClientTypeCallback(object);
1288 }
1289 
RequestAudioFocus(const int32_t clientId,const AudioInterrupt & audioInterrupt)1290 int32_t AudioPolicyServer::RequestAudioFocus(const int32_t clientId, const AudioInterrupt &audioInterrupt)
1291 {
1292     if (interruptService_ != nullptr) {
1293         return interruptService_->RequestAudioFocus(clientId, audioInterrupt);
1294     }
1295     return ERR_UNKNOWN;
1296 }
1297 
AbandonAudioFocus(const int32_t clientId,const AudioInterrupt & audioInterrupt)1298 int32_t AudioPolicyServer::AbandonAudioFocus(const int32_t clientId, const AudioInterrupt &audioInterrupt)
1299 {
1300     if (interruptService_ != nullptr) {
1301         return interruptService_->AbandonAudioFocus(clientId, audioInterrupt);
1302     }
1303     return ERR_UNKNOWN;
1304 }
1305 
ProcessRemoteInterrupt(std::set<int32_t> sessionIds,InterruptEventInternal interruptEvent)1306 void AudioPolicyServer::ProcessRemoteInterrupt(std::set<int32_t> sessionIds, InterruptEventInternal interruptEvent)
1307 {
1308     if (interruptService_ != nullptr) {
1309         interruptService_->ProcessRemoteInterrupt(sessionIds, interruptEvent);
1310     }
1311 }
1312 
ActivateAudioInterrupt(const AudioInterrupt & audioInterrupt,const int32_t zoneID,const bool isUpdatedAudioStrategy)1313 int32_t AudioPolicyServer::ActivateAudioInterrupt(
1314     const AudioInterrupt &audioInterrupt, const int32_t zoneID, const bool isUpdatedAudioStrategy)
1315 {
1316     if (interruptService_ != nullptr) {
1317         return interruptService_->ActivateAudioInterrupt(zoneID, audioInterrupt, isUpdatedAudioStrategy);
1318     }
1319     return ERR_UNKNOWN;
1320 }
1321 
DeactivateAudioInterrupt(const AudioInterrupt & audioInterrupt,const int32_t zoneID)1322 int32_t AudioPolicyServer::DeactivateAudioInterrupt(const AudioInterrupt &audioInterrupt, const int32_t zoneID)
1323 {
1324     if (interruptService_ != nullptr) {
1325         return interruptService_->DeactivateAudioInterrupt(zoneID, audioInterrupt);
1326     }
1327     return ERR_UNKNOWN;
1328 }
1329 
OnAudioStreamRemoved(const uint64_t sessionID)1330 void AudioPolicyServer::OnAudioStreamRemoved(const uint64_t sessionID)
1331 {
1332     CHECK_AND_RETURN_LOG(audioPolicyServerHandler_ != nullptr, "audioPolicyServerHandler_ is nullptr");
1333     audioPolicyServerHandler_->SendCapturerRemovedEvent(sessionID, false);
1334 }
1335 
ProcessSessionRemoved(const uint64_t sessionID,const int32_t zoneID)1336 void AudioPolicyServer::ProcessSessionRemoved(const uint64_t sessionID, const int32_t zoneID)
1337 {
1338     AUDIO_DEBUG_LOG("Removed SessionId: %{public}" PRIu64, sessionID);
1339 }
1340 
ProcessSessionAdded(SessionEvent sessionEvent)1341 void AudioPolicyServer::ProcessSessionAdded(SessionEvent sessionEvent)
1342 {
1343     AUDIO_DEBUG_LOG("Added Session");
1344 }
1345 
ProcessorCloseWakeupSource(const uint64_t sessionID)1346 void AudioPolicyServer::ProcessorCloseWakeupSource(const uint64_t sessionID)
1347 {
1348     audioPolicyService_.CloseWakeUpAudioCapturer();
1349 }
1350 
GetStreamInFocus(const int32_t zoneID)1351 AudioStreamType AudioPolicyServer::GetStreamInFocus(const int32_t zoneID)
1352 {
1353     if (interruptService_ != nullptr) {
1354         return interruptService_->GetStreamInFocus(zoneID);
1355     }
1356     return STREAM_MUSIC;
1357 }
1358 
GetSessionInfoInFocus(AudioInterrupt & audioInterrupt,const int32_t zoneID)1359 int32_t AudioPolicyServer::GetSessionInfoInFocus(AudioInterrupt &audioInterrupt, const int32_t zoneID)
1360 {
1361     if (interruptService_ != nullptr) {
1362         return interruptService_->GetSessionInfoInFocus(audioInterrupt, zoneID);
1363     }
1364     return ERR_UNKNOWN;
1365 }
1366 
GetAudioFocusInfoList(std::list<std::pair<AudioInterrupt,AudioFocuState>> & focusInfoList,const int32_t zoneID)1367 int32_t AudioPolicyServer::GetAudioFocusInfoList(std::list<std::pair<AudioInterrupt, AudioFocuState>> &focusInfoList,
1368     const int32_t zoneID)
1369 {
1370     if (interruptService_ != nullptr) {
1371         return interruptService_->GetAudioFocusInfoList(zoneID, focusInfoList);
1372     }
1373     return ERR_UNKNOWN;
1374 }
1375 
CheckRecordingCreate(uint32_t appTokenId,uint64_t appFullTokenId,int32_t appUid,SourceType sourceType)1376 bool AudioPolicyServer::CheckRecordingCreate(uint32_t appTokenId, uint64_t appFullTokenId, int32_t appUid,
1377     SourceType sourceType)
1378 {
1379     return false;
1380 }
1381 
VerifyPermission(const std::string & permissionName,uint32_t tokenId,bool isRecording)1382 bool AudioPolicyServer::VerifyPermission(const std::string &permissionName, uint32_t tokenId, bool isRecording)
1383 {
1384     AUDIO_DEBUG_LOG("Verify permission [%{public}s]", permissionName.c_str());
1385 
1386     if (!isRecording) {
1387 #ifdef AUDIO_BUILD_VARIANT_ROOT
1388         // root user case for auto test
1389         uid_t callingUid = static_cast<uid_t>(IPCSkeleton::GetCallingUid());
1390         if (callingUid == ROOT_UID) {
1391             return true;
1392         }
1393 #endif
1394         tokenId = IPCSkeleton::GetCallingTokenID();
1395     }
1396 
1397     int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, permissionName);
1398     CHECK_AND_RETURN_RET_LOG(res == Security::AccessToken::PermissionState::PERMISSION_GRANTED,
1399         false, "Permission denied [%{public}s]", permissionName.c_str());
1400 
1401     return true;
1402 }
1403 
VerifyBluetoothPermission()1404 bool AudioPolicyServer::VerifyBluetoothPermission()
1405 {
1406 #ifdef AUDIO_BUILD_VARIANT_ROOT
1407     // root user case for auto test
1408     uid_t callingUid = static_cast<uid_t>(IPCSkeleton::GetCallingUid());
1409     if (callingUid == ROOT_UID) {
1410         return true;
1411     }
1412 #endif
1413     uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
1414 
1415     int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, USE_BLUETOOTH_PERMISSION);
1416     CHECK_AND_RETURN_RET(res == Security::AccessToken::PermissionState::PERMISSION_GRANTED, false);
1417 
1418     return true;
1419 }
1420 
CheckRecordingStateChange(uint32_t appTokenId,uint64_t appFullTokenId,int32_t appUid,AudioPermissionState state)1421 bool AudioPolicyServer::CheckRecordingStateChange(uint32_t appTokenId, uint64_t appFullTokenId, int32_t appUid,
1422     AudioPermissionState state)
1423 {
1424     return false;
1425 }
1426 
ReconfigureAudioChannel(const uint32_t & count,DeviceType deviceType)1427 int32_t AudioPolicyServer::ReconfigureAudioChannel(const uint32_t &count, DeviceType deviceType)
1428 {
1429 #ifdef AUDIO_BUILD_VARIANT_ROOT
1430     // Only root users should have access to this api
1431     if (ROOT_UID != IPCSkeleton::GetCallingUid()) {
1432         AUDIO_INFO_LOG("Unautorized user. Cannot modify channel");
1433         return ERR_PERMISSION_DENIED;
1434     }
1435 
1436     return audioPolicyService_.ReconfigureAudioChannel(count, deviceType);
1437 #else
1438     // this api is not supported
1439     return ERR_NOT_SUPPORTED;
1440 #endif
1441 }
1442 
GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfos)1443 void AudioPolicyServer::GetStreamVolumeInfoMap(StreamVolumeInfoMap& streamVolumeInfos)
1444 {
1445     audioPolicyService_.GetStreamVolumeInfoMap(streamVolumeInfos);
1446 }
1447 
Dump(int32_t fd,const std::vector<std::u16string> & args)1448 int32_t AudioPolicyServer::Dump(int32_t fd, const std::vector<std::u16string> &args)
1449 {
1450     AUDIO_DEBUG_LOG("Dump Process Invoked");
1451     std::queue<std::u16string> argQue;
1452     for (decltype(args.size()) index = 0; index < args.size(); ++index) {
1453         argQue.push(args[index]);
1454     }
1455     std::string dumpString;
1456     InitPolicyDumpMap();
1457     ArgInfoDump(dumpString, argQue);
1458 
1459     return write(fd, dumpString.c_str(), dumpString.size());
1460 }
1461 
InitPolicyDumpMap()1462 void AudioPolicyServer::InitPolicyDumpMap()
1463 {
1464     dumpFuncMap[u"-h"] = &AudioPolicyServer::InfoDumpHelp;
1465     dumpFuncMap[u"-d"] = &AudioPolicyServer::AudioDevicesDump;
1466     dumpFuncMap[u"-m"] = &AudioPolicyServer::AudioModeDump;
1467     dumpFuncMap[u"-v"] = &AudioPolicyServer::AudioVolumeDump;
1468     dumpFuncMap[u"-az"] = &AudioPolicyServer::AudioInterruptZoneDump;
1469     dumpFuncMap[u"-apc"] = &AudioPolicyServer::AudioPolicyParserDump;
1470     dumpFuncMap[u"-s"] = &AudioPolicyServer::AudioStreamDump;
1471     dumpFuncMap[u"-xp"] = &AudioPolicyServer::XmlParsedDataMapDump;
1472     dumpFuncMap[u"-e"] = &AudioPolicyServer::EffectManagerInfoDump;
1473     dumpFuncMap[u"-ms"] = &AudioPolicyServer::MicrophoneMuteInfoDump;
1474 }
1475 
PolicyDataDump(std::string & dumpString)1476 void AudioPolicyServer::PolicyDataDump(std::string &dumpString)
1477 {
1478     AudioDevicesDump(dumpString);
1479     AudioModeDump(dumpString);
1480     AudioVolumeDump(dumpString);
1481     AudioInterruptZoneDump(dumpString);
1482     AudioPolicyParserDump(dumpString);
1483     AudioStreamDump(dumpString);
1484     XmlParsedDataMapDump(dumpString);
1485     EffectManagerInfoDump(dumpString);
1486     MicrophoneMuteInfoDump(dumpString);
1487 }
1488 
AudioDevicesDump(std::string & dumpString)1489 void AudioPolicyServer::AudioDevicesDump(std::string &dumpString)
1490 {
1491     audioPolicyService_.DevicesInfoDump(dumpString);
1492 }
1493 
AudioModeDump(std::string & dumpString)1494 void AudioPolicyServer::AudioModeDump(std::string &dumpString)
1495 {
1496     audioPolicyService_.AudioModeDump(dumpString);
1497 }
1498 
AudioInterruptZoneDump(std::string & dumpString)1499 void AudioPolicyServer::AudioInterruptZoneDump(std::string &dumpString)
1500 {
1501     interruptService_->AudioInterruptZoneDump(dumpString);
1502 }
1503 
AudioPolicyParserDump(std::string & dumpString)1504 void AudioPolicyServer::AudioPolicyParserDump(std::string &dumpString)
1505 {
1506     audioPolicyService_.AudioPolicyParserDump(dumpString);
1507 }
1508 
AudioVolumeDump(std::string & dumpString)1509 void AudioPolicyServer::AudioVolumeDump(std::string &dumpString)
1510 {
1511     audioPolicyService_.StreamVolumesDump(dumpString);
1512 }
1513 
AudioStreamDump(std::string & dumpString)1514 void AudioPolicyServer::AudioStreamDump(std::string &dumpString)
1515 {
1516     audioPolicyService_.AudioStreamDump(dumpString);
1517 }
1518 
XmlParsedDataMapDump(std::string & dumpString)1519 void AudioPolicyServer::XmlParsedDataMapDump(std::string &dumpString)
1520 {
1521     audioPolicyService_.XmlParsedDataMapDump(dumpString);
1522 }
1523 
EffectManagerInfoDump(std::string & dumpString)1524 void AudioPolicyServer::EffectManagerInfoDump(std::string &dumpString)
1525 {
1526     audioPolicyService_.EffectManagerInfoDump(dumpString);
1527 }
1528 
MicrophoneMuteInfoDump(std::string & dumpString)1529 void AudioPolicyServer::MicrophoneMuteInfoDump(std::string &dumpString)
1530 {
1531     audioPolicyService_.MicrophoneMuteInfoDump(dumpString);
1532 }
1533 
ArgInfoDump(std::string & dumpString,std::queue<std::u16string> & argQue)1534 void AudioPolicyServer::ArgInfoDump(std::string &dumpString, std::queue<std::u16string> &argQue)
1535 {
1536     dumpString += "AudioPolicyServer Data Dump:\n\n";
1537     if (argQue.empty()) {
1538         PolicyDataDump(dumpString);
1539         return;
1540     }
1541     while (!argQue.empty()) {
1542         std::u16string para = argQue.front();
1543         if (para == u"-h") {
1544             dumpString.clear();
1545             (this->*dumpFuncMap[para])(dumpString);
1546             return;
1547         } else if (dumpFuncMap.count(para) == 0) {
1548             dumpString.clear();
1549             AppendFormat(dumpString, "Please input correct param:\n");
1550             InfoDumpHelp(dumpString);
1551             return;
1552         } else {
1553             (this->*dumpFuncMap[para])(dumpString);
1554         }
1555         argQue.pop();
1556     }
1557 }
1558 
InfoDumpHelp(std::string & dumpString)1559 void AudioPolicyServer::InfoDumpHelp(std::string &dumpString)
1560 {
1561     AppendFormat(dumpString, "usage:\n");
1562     AppendFormat(dumpString, "  -h\t\t\t|help text for hidumper audio\n");
1563     AppendFormat(dumpString, "  -d\t\t\t|dump devices info\n");
1564     AppendFormat(dumpString, "  -m\t\t\t|dump ringer mode and call status\n");
1565     AppendFormat(dumpString, "  -v\t\t\t|dump stream volume info\n");
1566     AppendFormat(dumpString, "  -az\t\t\t|dump audio in interrupt zone info\n");
1567     AppendFormat(dumpString, "  -apc\t\t\t|dump audio policy config xml parser info\n");
1568     AppendFormat(dumpString, "  -s\t\t\t|dump stream info\n");
1569     AppendFormat(dumpString, "  -xp\t\t\t|dump xml data map\n");
1570     AppendFormat(dumpString, "  -e\t\t\t|dump audio effect manager Info\n");
1571 }
1572 
GetAudioLatencyFromXml()1573 int32_t AudioPolicyServer::GetAudioLatencyFromXml()
1574 {
1575     return audioPolicyService_.GetAudioLatencyFromXml();
1576 }
1577 
GetSinkLatencyFromXml()1578 uint32_t AudioPolicyServer::GetSinkLatencyFromXml()
1579 {
1580     return audioPolicyService_.GetSinkLatencyFromXml();
1581 }
1582 
GetPreferredOutputStreamType(AudioRendererInfo & rendererInfo)1583 int32_t AudioPolicyServer::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo)
1584 {
1585     std::string bundleName = "";
1586     bool isFastControlled = audioPolicyService_.getFastControlParam();
1587     if (isFastControlled && rendererInfo.rendererFlags == AUDIO_FLAG_MMAP) {
1588         bundleName = GetBundleName();
1589         AUDIO_INFO_LOG("bundleName %{public}s", bundleName.c_str());
1590         return audioPolicyService_.GetPreferredOutputStreamType(rendererInfo, bundleName);
1591     }
1592     return audioPolicyService_.GetPreferredOutputStreamType(rendererInfo, "");
1593 }
1594 
GetPreferredInputStreamType(AudioCapturerInfo & capturerInfo)1595 int32_t AudioPolicyServer::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo)
1596 {
1597     return audioPolicyService_.GetPreferredInputStreamType(capturerInfo);
1598 }
1599 
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object)1600 int32_t AudioPolicyServer::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
1601     const sptr<IRemoteObject> &object)
1602 {
1603     auto callerPid = IPCSkeleton::GetCallingPid();
1604     streamChangeInfo.audioRendererChangeInfo.callerPid = callerPid;
1605     streamChangeInfo.audioCapturerChangeInfo.callerPid = callerPid;
1606 
1607     // update the clientUid
1608     auto callerUid = IPCSkeleton::GetCallingUid();
1609     streamChangeInfo.audioRendererChangeInfo.createrUID = callerUid;
1610     streamChangeInfo.audioCapturerChangeInfo.createrUID = callerUid;
1611     AUDIO_DEBUG_LOG("RegisterTracker: [caller uid: %{public}d]", callerUid);
1612     if (callerUid != MEDIA_SERVICE_UID) {
1613         if (mode == AUDIO_MODE_PLAYBACK) {
1614             streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
1615             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1616                 streamChangeInfo.audioRendererChangeInfo.clientUID);
1617         } else {
1618             streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
1619             streamChangeInfo.audioCapturerChangeInfo.appTokenId = IPCSkeleton::GetCallingTokenID();
1620 
1621             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1622                 streamChangeInfo.audioCapturerChangeInfo.clientUID);
1623         }
1624     }
1625     RegisterClientDeathRecipient(object, TRACKER_CLIENT);
1626     int32_t apiVersion = GetApiTargerVersion();
1627     return audioPolicyService_.RegisterTracker(mode, streamChangeInfo, object, apiVersion);
1628 }
1629 
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)1630 int32_t AudioPolicyServer::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
1631 {
1632     auto callerPid = IPCSkeleton::GetCallingPid();
1633     streamChangeInfo.audioRendererChangeInfo.callerPid = callerPid;
1634     streamChangeInfo.audioCapturerChangeInfo.callerPid = callerPid;
1635 
1636     // update the clientUid
1637     auto callerUid = IPCSkeleton::GetCallingUid();
1638     streamChangeInfo.audioRendererChangeInfo.createrUID = callerUid;
1639     streamChangeInfo.audioCapturerChangeInfo.createrUID = callerUid;
1640     AUDIO_DEBUG_LOG("UpdateTracker: [caller uid: %{public}d]", callerUid);
1641     if (callerUid != MEDIA_SERVICE_UID) {
1642         if (mode == AUDIO_MODE_PLAYBACK) {
1643             streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
1644             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1645                 streamChangeInfo.audioRendererChangeInfo.clientUID);
1646         } else {
1647             streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
1648             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1649                 streamChangeInfo.audioCapturerChangeInfo.clientUID);
1650         }
1651     }
1652     int32_t ret = audioPolicyService_.UpdateTracker(mode, streamChangeInfo);
1653     if (streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_PAUSED ||
1654         streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_STOPPED ||
1655         streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_RELEASED) {
1656         OffloadStreamCheck(OFFLOAD_NO_SESSION_ID, streamChangeInfo.audioRendererChangeInfo.sessionId);
1657     }
1658     if (streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_RUNNING) {
1659         OffloadStreamCheck(streamChangeInfo.audioRendererChangeInfo.sessionId, OFFLOAD_NO_SESSION_ID);
1660     }
1661     return ret;
1662 }
1663 
FetchOutputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo,const AudioStreamDeviceChangeReasonExt reason)1664 void AudioPolicyServer::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
1665     const AudioStreamDeviceChangeReasonExt reason)
1666 {
1667     auto callerPid = IPCSkeleton::GetCallingPid();
1668     streamChangeInfo.audioRendererChangeInfo.callerPid = callerPid;
1669 
1670     // update the clientUid
1671     auto callerUid = IPCSkeleton::GetCallingUid();
1672     streamChangeInfo.audioRendererChangeInfo.createrUID = callerUid;
1673     AUDIO_DEBUG_LOG("[caller uid: %{public}d]", callerUid);
1674     if (callerUid != MEDIA_SERVICE_UID) {
1675         streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
1676         AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1677             streamChangeInfo.audioRendererChangeInfo.clientUID);
1678     }
1679     audioPolicyService_.FetchOutputDeviceForTrack(streamChangeInfo, reason);
1680 }
1681 
FetchInputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo)1682 void AudioPolicyServer::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo)
1683 {
1684     auto callerPid = IPCSkeleton::GetCallingPid();
1685     streamChangeInfo.audioCapturerChangeInfo.callerPid = callerPid;
1686 
1687     // update the clientUid
1688     auto callerUid = IPCSkeleton::GetCallingUid();
1689     streamChangeInfo.audioCapturerChangeInfo.createrUID = callerUid;
1690     AUDIO_DEBUG_LOG("[caller uid: %{public}d]", callerUid);
1691     if (callerUid != MEDIA_SERVICE_UID) {
1692         streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
1693         AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1694             streamChangeInfo.audioCapturerChangeInfo.clientUID);
1695     }
1696     audioPolicyService_.FetchInputDeviceForTrack(streamChangeInfo);
1697 }
1698 
GetCurrentRendererChangeInfos(std::vector<unique_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos)1699 int32_t AudioPolicyServer::GetCurrentRendererChangeInfos(
1700     std::vector<unique_ptr<AudioRendererChangeInfo>> &audioRendererChangeInfos)
1701 {
1702     bool hasBTPermission = VerifyBluetoothPermission();
1703     AUDIO_DEBUG_LOG("GetCurrentRendererChangeInfos: BT use permission: %{public}d", hasBTPermission);
1704     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1705     AUDIO_DEBUG_LOG("GetCurrentRendererChangeInfos: System use permission: %{public}d", hasSystemPermission);
1706 
1707     return audioPolicyService_.GetCurrentRendererChangeInfos(audioRendererChangeInfos,
1708         hasBTPermission, hasSystemPermission);
1709 }
1710 
GetCurrentCapturerChangeInfos(std::vector<unique_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos)1711 int32_t AudioPolicyServer::GetCurrentCapturerChangeInfos(
1712     std::vector<unique_ptr<AudioCapturerChangeInfo>> &audioCapturerChangeInfos)
1713 {
1714     bool hasBTPermission = VerifyBluetoothPermission();
1715     AUDIO_DEBUG_LOG("GetCurrentCapturerChangeInfos: BT use permission: %{public}d", hasBTPermission);
1716     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1717     AUDIO_DEBUG_LOG("GetCurrentCapturerChangeInfos: System use permission: %{public}d", hasSystemPermission);
1718 
1719     return audioPolicyService_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos,
1720         hasBTPermission, hasSystemPermission);
1721 }
1722 
RegisterClientDeathRecipient(const sptr<IRemoteObject> & object,DeathRecipientId id)1723 void AudioPolicyServer::RegisterClientDeathRecipient(const sptr<IRemoteObject> &object, DeathRecipientId id)
1724 {
1725     AUDIO_DEBUG_LOG("Register clients death recipient!! RecipientId: %{public}d", id);
1726     std::lock_guard<std::mutex> lock(clientDiedListenerStateMutex_);
1727     CHECK_AND_RETURN_LOG(object != nullptr, "Client proxy obj NULL!!");
1728 
1729     pid_t uid = 0;
1730     if (id == TRACKER_CLIENT) {
1731         // Deliberately casting UID to pid_t
1732         uid = static_cast<pid_t>(IPCSkeleton::GetCallingUid());
1733     } else {
1734         uid = IPCSkeleton::GetCallingPid();
1735     }
1736     if (id == TRACKER_CLIENT && std::find(clientDiedListenerState_.begin(), clientDiedListenerState_.end(), uid)
1737         != clientDiedListenerState_.end()) {
1738         AUDIO_INFO_LOG("Tracker has been registered for %{public}d!", uid);
1739         return;
1740     }
1741     sptr<AudioServerDeathRecipient> deathRecipient_ = new(std::nothrow) AudioServerDeathRecipient(uid);
1742     if (deathRecipient_ != nullptr) {
1743         if (id == TRACKER_CLIENT) {
1744             deathRecipient_->SetNotifyCb([this] (int uid) { this->RegisteredTrackerClientDied(uid); });
1745         } else {
1746             AUDIO_PRERELEASE_LOGI("RegisteredStreamListenerClientDied register!!");
1747             deathRecipient_->SetNotifyCb([this] (pid_t pid) { this->RegisteredStreamListenerClientDied(pid); });
1748         }
1749         bool result = object->AddDeathRecipient(deathRecipient_);
1750         if (result && id == TRACKER_CLIENT) {
1751             clientDiedListenerState_.push_back(uid);
1752         }
1753         if (!result) {
1754             AUDIO_WARNING_LOG("failed to add deathRecipient");
1755         }
1756     }
1757 }
1758 
RegisteredTrackerClientDied(pid_t uid)1759 void AudioPolicyServer::RegisteredTrackerClientDied(pid_t uid)
1760 {
1761     AUDIO_INFO_LOG("RegisteredTrackerClient died: remove entry, uid %{public}d", uid);
1762     std::lock_guard<std::mutex> lock(clientDiedListenerStateMutex_);
1763     audioPolicyService_.RegisteredTrackerClientDied(uid);
1764 
1765     auto filter = [&uid](int val) {
1766         return uid == val;
1767     };
1768     clientDiedListenerState_.erase(std::remove_if(clientDiedListenerState_.begin(), clientDiedListenerState_.end(),
1769         filter), clientDiedListenerState_.end());
1770 }
1771 
RegisteredStreamListenerClientDied(pid_t pid)1772 void AudioPolicyServer::RegisteredStreamListenerClientDied(pid_t pid)
1773 {
1774     AUDIO_INFO_LOG("RegisteredStreamListenerClient died: remove entry, uid %{public}d", pid);
1775     if (pid == lastMicMuteSettingPid_) {
1776         // The last app with the non-persistent microphone setting died, restore the default non-persistent value
1777         AUDIO_INFO_LOG("Cliet died and reset non-persist mute state");
1778         audioPolicyService_.SetMicrophoneMute(false);
1779     }
1780     if (interruptService_ != nullptr && interruptService_->IsAudioSessionActivated(pid)) {
1781         interruptService_->DeactivateAudioSession(pid);
1782     }
1783     audioPolicyService_.ReduceAudioPolicyClientProxyMap(pid);
1784 }
1785 
UpdateStreamState(const int32_t clientUid,StreamSetState streamSetState,StreamUsage streamUsage)1786 int32_t AudioPolicyServer::UpdateStreamState(const int32_t clientUid,
1787     StreamSetState streamSetState, StreamUsage streamUsage)
1788 {
1789     constexpr int32_t avSessionUid = 6700; // "uid" : "av_session"
1790     auto callerUid = IPCSkeleton::GetCallingUid();
1791     // This function can only be used by av_session
1792     CHECK_AND_RETURN_RET_LOG(callerUid == avSessionUid, ERROR,
1793         "UpdateStreamState callerUid is error: not av_session");
1794 
1795     AUDIO_INFO_LOG("UpdateStreamState::uid:%{public}d streamSetState:%{public}d audioStreamUsage:%{public}d",
1796         clientUid, streamSetState, streamUsage);
1797     StreamSetState setState = StreamSetState::STREAM_PAUSE;
1798     if (streamSetState == StreamSetState::STREAM_RESUME) {
1799         setState  = StreamSetState::STREAM_RESUME;
1800     } else if (streamSetState != StreamSetState::STREAM_PAUSE) {
1801         AUDIO_ERR_LOG("UpdateStreamState streamSetState value is error");
1802         return ERROR;
1803     }
1804     StreamSetStateEventInternal setStateEvent = {};
1805     setStateEvent.streamSetState = setState;
1806     setStateEvent.streamUsage = streamUsage;
1807 
1808     return audioPolicyService_.UpdateStreamState(clientUid, setStateEvent);
1809 }
1810 
GetVolumeGroupInfos(std::string networkId,std::vector<sptr<VolumeGroupInfo>> & infos)1811 int32_t AudioPolicyServer::GetVolumeGroupInfos(std::string networkId, std::vector<sptr<VolumeGroupInfo>> &infos)
1812 {
1813     bool ret = PermissionUtil::VerifySystemPermission();
1814     CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED,
1815         "No system permission");
1816 
1817     infos = audioPolicyService_.GetVolumeGroupInfos();
1818     auto filter = [&networkId](const sptr<VolumeGroupInfo>& info) {
1819         return networkId != info->networkId_;
1820     };
1821     infos.erase(std::remove_if(infos.begin(), infos.end(), filter), infos.end());
1822 
1823     return SUCCESS;
1824 }
1825 
GetNetworkIdByGroupId(int32_t groupId,std::string & networkId)1826 int32_t AudioPolicyServer::GetNetworkIdByGroupId(int32_t groupId, std::string &networkId)
1827 {
1828     auto volumeGroupInfos = audioPolicyService_.GetVolumeGroupInfos();
1829 
1830     auto filter = [&groupId](const sptr<VolumeGroupInfo>& info) {
1831         return groupId != info->volumeGroupId_;
1832     };
1833     volumeGroupInfos.erase(std::remove_if(volumeGroupInfos.begin(), volumeGroupInfos.end(), filter),
1834         volumeGroupInfos.end());
1835     if (volumeGroupInfos.size() > 0) {
1836         networkId = volumeGroupInfos[0]->networkId_;
1837         AUDIO_INFO_LOG("GetNetworkIdByGroupId: get networkId %{public}s.", networkId.c_str());
1838     } else {
1839         AUDIO_ERR_LOG("GetNetworkIdByGroupId: has no valid group");
1840         return ERROR;
1841     }
1842 
1843     return SUCCESS;
1844 }
1845 
RemoteParameterCallback(sptr<AudioPolicyServer> server)1846 AudioPolicyServer::RemoteParameterCallback::RemoteParameterCallback(sptr<AudioPolicyServer> server)
1847 {
1848     server_ = server;
1849 }
1850 
OnAudioParameterChange(const std::string networkId,const AudioParamKey key,const std::string & condition,const std::string & value)1851 void AudioPolicyServer::RemoteParameterCallback::OnAudioParameterChange(const std::string networkId,
1852     const AudioParamKey key, const std::string& condition, const std::string& value)
1853 {
1854     AUDIO_INFO_LOG("key:%{public}d, condition:%{public}s, value:%{public}s",
1855         key, condition.c_str(), value.c_str());
1856     CHECK_AND_RETURN_LOG(server_ != nullptr, "AudioPolicyServer is nullptr");
1857     switch (key) {
1858         case VOLUME:
1859             VolumeOnChange(networkId, condition);
1860             break;
1861         case INTERRUPT:
1862             InterruptOnChange(networkId, condition);
1863             break;
1864         case PARAM_KEY_STATE:
1865             StateOnChange(networkId, condition, value);
1866             break;
1867         default:
1868             AUDIO_DEBUG_LOG("[AudioPolicyServer]: No processing");
1869             break;
1870     }
1871 }
1872 
VolumeOnChange(const std::string networkId,const std::string & condition)1873 void AudioPolicyServer::RemoteParameterCallback::VolumeOnChange(const std::string networkId,
1874     const std::string& condition)
1875 {
1876     VolumeEvent volumeEvent;
1877     volumeEvent.networkId = networkId;
1878     char eventDes[EVENT_DES_SIZE];
1879     if (sscanf_s(condition.c_str(), "%[^;];AUDIO_STREAM_TYPE=%d;VOLUME_LEVEL=%d;IS_UPDATEUI=%d;VOLUME_GROUP_ID=%d;",
1880         eventDes, EVENT_DES_SIZE, &(volumeEvent.volumeType), &(volumeEvent.volume), &(volumeEvent.updateUi),
1881         &(volumeEvent.volumeGroupId)) < PARAMS_VOLUME_NUM) {
1882         AUDIO_ERR_LOG("[VolumeOnChange]: Failed parse condition");
1883         return;
1884     }
1885 
1886     volumeEvent.updateUi = false;
1887     CHECK_AND_RETURN_LOG(server_->audioPolicyServerHandler_ != nullptr, "audioPolicyServerHandler_ is nullptr");
1888     server_->audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
1889 }
1890 
InterruptOnChange(const std::string networkId,const std::string & condition)1891 void AudioPolicyServer::RemoteParameterCallback::InterruptOnChange(const std::string networkId,
1892     const std::string& condition)
1893 {
1894     AUDIO_INFO_LOG("InterruptOnChange : networkId: %{public}s, condition: %{public}s.", networkId.c_str(),
1895         condition.c_str());
1896     char eventDes[EVENT_DES_SIZE];
1897     InterruptType type = INTERRUPT_TYPE_BEGIN;
1898     InterruptForceType forceType = INTERRUPT_SHARE;
1899     InterruptHint hint = INTERRUPT_HINT_NONE;
1900     int32_t audioCategory = 0;
1901 
1902     int ret = sscanf_s(condition.c_str(), "%[^;];EVENT_TYPE=%d;FORCE_TYPE=%d;HINT_TYPE=%d;AUDIOCATEGORY=%d;",
1903         eventDes, EVENT_DES_SIZE, &type, &forceType, &hint, &audioCategory);
1904     CHECK_AND_RETURN_LOG(ret >= PARAMS_INTERRUPT_NUM, "[InterruptOnChange]: Failed parse condition");
1905 
1906     std::set<int32_t> sessionIdMedia = AudioStreamCollector::GetAudioStreamCollector().
1907         GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_MUSIC);
1908     std::set<int32_t> sessionIdMovie = AudioStreamCollector::GetAudioStreamCollector().
1909         GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_MOVIE);
1910     std::set<int32_t> sessionIdGame = AudioStreamCollector::GetAudioStreamCollector().
1911         GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_GAME);
1912     std::set<int32_t> sessionIdAudioBook = AudioStreamCollector::GetAudioStreamCollector().
1913         GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_AUDIOBOOK);
1914     std::set<int32_t> sessionIds = {};
1915     sessionIds.insert(sessionIdMedia.begin(), sessionIdMedia.end());
1916     sessionIds.insert(sessionIdMovie.begin(), sessionIdMovie.end());
1917     sessionIds.insert(sessionIdGame.begin(), sessionIdGame.end());
1918     sessionIds.insert(sessionIdAudioBook.begin(), sessionIdAudioBook.end());
1919 
1920     InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
1921     if (server_ != nullptr) {
1922         server_->ProcessRemoteInterrupt(sessionIds, interruptEvent);
1923     }
1924 }
1925 
StateOnChange(const std::string networkId,const std::string & condition,const std::string & value)1926 void AudioPolicyServer::RemoteParameterCallback::StateOnChange(const std::string networkId,
1927     const std::string& condition, const std::string& value)
1928 {
1929     char eventDes[EVENT_DES_SIZE];
1930     char contentDes[ADAPTER_STATE_CONTENT_DES_SIZE];
1931     int ret = sscanf_s(condition.c_str(), "%[^;];%s", eventDes, EVENT_DES_SIZE, contentDes,
1932         ADAPTER_STATE_CONTENT_DES_SIZE);
1933     CHECK_AND_RETURN_LOG(ret >= PARAMS_RENDER_STATE_NUM, "StateOnChange: Failed parse condition");
1934     CHECK_AND_RETURN_LOG(strcmp(eventDes, "ERR_EVENT") == 0,
1935         "StateOnChange: Event %{public}s is not supported.", eventDes);
1936 
1937     std::string devTypeKey = "DEVICE_TYPE=";
1938     std::string contentDesStr = std::string(contentDes);
1939     auto devTypeKeyPos =  contentDesStr.find(devTypeKey);
1940     CHECK_AND_RETURN_LOG(devTypeKeyPos != std::string::npos,
1941         "StateOnChange: Not find daudio device type info, contentDes %{public}s.", contentDesStr.c_str());
1942     size_t devTypeValPos = devTypeKeyPos + devTypeKey.length();
1943     CHECK_AND_RETURN_LOG(devTypeValPos < contentDesStr.length(),
1944         "StateOnChange: Not find daudio device type value, contentDes %{public}s.", contentDesStr.c_str());
1945 
1946     if (contentDesStr[devTypeValPos] == DAUDIO_DEV_TYPE_SPK) {
1947         server_->audioPolicyService_.NotifyRemoteRenderState(networkId, contentDesStr, value);
1948     } else if (contentDesStr[devTypeValPos] == DAUDIO_DEV_TYPE_MIC) {
1949         AUDIO_INFO_LOG("StateOnChange: ERR_EVENT of DAUDIO_DEV_TYPE_MIC.");
1950     } else {
1951         AUDIO_ERR_LOG("StateOnChange: Device type is not supported, contentDes %{public}s.", contentDesStr.c_str());
1952     }
1953 }
1954 
PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo & result)1955 void AudioPolicyServer::PerStateChangeCbCustomizeCallback::PermStateChangeCallback(
1956     Security::AccessToken::PermStateChangeInfo& result)
1957 {
1958     ready_ = true;
1959     Security::AccessToken::HapTokenInfo hapTokenInfo;
1960     int32_t res = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(result.tokenID, hapTokenInfo);
1961     if (res < 0) {
1962         AUDIO_ERR_LOG("Call GetHapTokenInfo fail.");
1963     }
1964 
1965     bool targetMuteState = (result.permStateChangeType > 0) ? false : true;
1966     int32_t appUid = getUidByBundleName(hapTokenInfo.bundleName, hapTokenInfo.userID);
1967     if (appUid < 0) {
1968         AUDIO_ERR_LOG("fail to get uid.");
1969     } else {
1970         int32_t streamSet = server_->audioPolicyService_.SetSourceOutputStreamMute(appUid, targetMuteState);
1971         if (streamSet > 0) {
1972             UpdateMicPrivacyByCapturerState(targetMuteState, result.tokenID, appUid);
1973         }
1974     }
1975 }
1976 
UpdateMicPrivacyByCapturerState(bool targetMuteState,uint32_t targetTokenId,int32_t appUid)1977 void AudioPolicyServer::PerStateChangeCbCustomizeCallback::UpdateMicPrivacyByCapturerState(
1978     bool targetMuteState, uint32_t targetTokenId, int32_t appUid)
1979 {
1980     std::vector<std::unique_ptr<AudioCapturerChangeInfo>> capturerChangeInfos;
1981     server_->audioPolicyService_.GetCurrentCapturerChangeInfos(capturerChangeInfos, true, true);
1982     for (auto &info : capturerChangeInfos) {
1983         if (info->appTokenId == targetTokenId && info->capturerState == CAPTURER_RUNNING) {
1984             AUDIO_INFO_LOG("update using mic %{public}d for uid: %{public}d because permission changed",
1985                 targetMuteState, appUid);
1986             int32_t res = SUCCESS;
1987             if (targetMuteState) {
1988                 WatchTimeout guard("PrivacyKit::StopUsingPermission:UpdateMicPrivacyByCapturerState");
1989                 res = PrivacyKit::StopUsingPermission(targetTokenId, MICROPHONE_PERMISSION);
1990                 guard.CheckCurrTimeout();
1991             } else {
1992                 WatchTimeout guard("PrivacyKit::StartUsingPermission:UpdateMicPrivacyByCapturerState");
1993                 res = PrivacyKit::StartUsingPermission(targetTokenId, MICROPHONE_PERMISSION);
1994                 guard.CheckCurrTimeout();
1995             }
1996             if (res != SUCCESS) {
1997                 AUDIO_ERR_LOG("update using permission failed, error code %{public}d", res);
1998             }
1999         }
2000     }
2001 }
2002 
getUidByBundleName(std::string bundle_name,int user_id)2003 int32_t AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName(std::string bundle_name, int user_id)
2004 {
2005     AudioXCollie audioXCollie("AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName",
2006         GET_BUNDLE_TIME_OUT_SECONDS);
2007     WatchTimeout guard("SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager():getUidByBundleName");
2008     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2009     if (systemAbilityManager == nullptr) {
2010         return ERR_INVALID_PARAM;
2011     }
2012     guard.CheckCurrTimeout();
2013 
2014     sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2015     if (remoteObject == nullptr) {
2016         return ERR_INVALID_PARAM;
2017     }
2018 
2019     sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
2020     if (bundleMgrProxy == nullptr) {
2021         return ERR_INVALID_PARAM;
2022     }
2023     WatchTimeout reguard("bundleMgrProxy->GetUidByBundleName:getUidByBundleName");
2024     int32_t iUid = bundleMgrProxy->GetUidByBundleName(bundle_name, user_id);
2025     reguard.CheckCurrTimeout();
2026 
2027     return iUid;
2028 }
2029 
RegisterParamCallback()2030 void AudioPolicyServer::RegisterParamCallback()
2031 {
2032     AUDIO_INFO_LOG("RegisterParamCallback");
2033     remoteParameterCallback_ = std::make_shared<RemoteParameterCallback>(this);
2034     audioPolicyService_.SetParameterCallback(remoteParameterCallback_);
2035     // regiest policy provider in audio server
2036     audioPolicyService_.RegiestPolicy();
2037 }
2038 
RegisterBluetoothListener()2039 void AudioPolicyServer::RegisterBluetoothListener()
2040 {
2041     AUDIO_INFO_LOG("RegisterBluetoothListener");
2042     audioPolicyService_.RegisterBluetoothListener();
2043 }
2044 
SubscribeAccessibilityConfigObserver()2045 void AudioPolicyServer::SubscribeAccessibilityConfigObserver()
2046 {
2047     AUDIO_INFO_LOG("SubscribeAccessibilityConfigObserver");
2048     audioPolicyService_.SubscribeAccessibilityConfigObserver();
2049 }
2050 
IsAudioRendererLowLatencySupported(const AudioStreamInfo & audioStreamInfo)2051 bool AudioPolicyServer::IsAudioRendererLowLatencySupported(const AudioStreamInfo &audioStreamInfo)
2052 {
2053     AUDIO_INFO_LOG("IsAudioRendererLowLatencySupported server call");
2054     return true;
2055 }
2056 
SetSystemSoundUri(const std::string & key,const std::string & uri)2057 int32_t AudioPolicyServer::SetSystemSoundUri(const std::string &key, const std::string &uri)
2058 {
2059     if (!PermissionUtil::VerifySystemPermission()) {
2060         AUDIO_ERR_LOG("GetVolumeGroupInfos: No system permission");
2061         return ERR_PERMISSION_DENIED;
2062     }
2063     AUDIO_INFO_LOG("key: %{public}s, uri: %{public}s", key.c_str(), uri.c_str());
2064     return audioPolicyService_.SetSystemSoundUri(key, uri);
2065 }
2066 
GetSystemSoundUri(const std::string & key)2067 std::string AudioPolicyServer::GetSystemSoundUri(const std::string &key)
2068 {
2069     if (!PermissionUtil::VerifySystemPermission()) {
2070         AUDIO_ERR_LOG("GetVolumeGroupInfos: No system permission");
2071         return "";
2072     }
2073     AUDIO_INFO_LOG("key: %{public}s", key.c_str());
2074     return audioPolicyService_.GetSystemSoundUri(key);
2075 }
2076 
GetMinStreamVolume()2077 float AudioPolicyServer::GetMinStreamVolume()
2078 {
2079     return audioPolicyService_.GetMinStreamVolume();
2080 }
2081 
GetMaxStreamVolume()2082 float AudioPolicyServer::GetMaxStreamVolume()
2083 {
2084     return audioPolicyService_.GetMaxStreamVolume();
2085 }
2086 
CheckMaxRendererInstances()2087 int32_t AudioPolicyServer::CheckMaxRendererInstances()
2088 {
2089     AUDIO_INFO_LOG("CheckMaxRendererInstances");
2090     int32_t retryCount = 20; // 20 * 200000us = 4s, wait up to 4s
2091     while (!isFirstAudioServiceStart_) {
2092         retryCount--;
2093         if (retryCount > 0) {
2094             AUDIO_WARNING_LOG("Audio server is not start");
2095             usleep(200000); // Wait 200000us when audio server is not started
2096         } else {
2097             break;
2098         }
2099     }
2100     return audioPolicyService_.CheckMaxRendererInstances();
2101 }
2102 
RegisterDataObserver()2103 void AudioPolicyServer::RegisterDataObserver()
2104 {
2105     audioPolicyService_.RegisterDataObserver();
2106 }
2107 
QueryEffectSceneMode(SupportedEffectConfig & supportedEffectConfig)2108 int32_t AudioPolicyServer::QueryEffectSceneMode(SupportedEffectConfig &supportedEffectConfig)
2109 {
2110     int32_t ret = audioPolicyService_.QueryEffectManagerSceneMode(supportedEffectConfig);
2111     return ret;
2112 }
2113 
GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> & desc)2114 int32_t AudioPolicyServer::GetHardwareOutputSamplingRate(const sptr<AudioDeviceDescriptor> &desc)
2115 {
2116     return audioPolicyService_.GetHardwareOutputSamplingRate(desc);
2117 }
2118 
GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)2119 vector<sptr<MicrophoneDescriptor>> AudioPolicyServer::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)
2120 {
2121     std::vector<sptr<MicrophoneDescriptor>> micDescs =
2122         audioPolicyService_.GetAudioCapturerMicrophoneDescriptors(sessionId);
2123     return micDescs;
2124 }
2125 
GetAvailableMicrophones()2126 vector<sptr<MicrophoneDescriptor>> AudioPolicyServer::GetAvailableMicrophones()
2127 {
2128     std::vector<sptr<MicrophoneDescriptor>> micDescs = audioPolicyService_.GetAvailableMicrophones();
2129     return micDescs;
2130 }
2131 
SetDeviceAbsVolumeSupported(const std::string & macAddress,const bool support)2132 int32_t AudioPolicyServer::SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support)
2133 {
2134     auto callerUid = IPCSkeleton::GetCallingUid();
2135     if (callerUid != UID_BLUETOOTH_SA) {
2136         AUDIO_ERR_LOG("SetDeviceAbsVolumeSupported: Error caller uid: %{public}d", callerUid);
2137         return ERROR;
2138     }
2139     return audioPolicyService_.SetDeviceAbsVolumeSupported(macAddress, support);
2140 }
2141 
IsAbsVolumeScene()2142 bool AudioPolicyServer::IsAbsVolumeScene()
2143 {
2144     return audioPolicyService_.IsAbsVolumeScene();
2145 }
2146 
IsVgsVolumeSupported()2147 bool AudioPolicyServer::IsVgsVolumeSupported()
2148 {
2149     return audioPolicyService_.IsVgsVolumeSupported();
2150 }
2151 
SetA2dpDeviceVolume(const std::string & macAddress,const int32_t volume,const bool updateUi)2152 int32_t AudioPolicyServer::SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volume,
2153     const bool updateUi)
2154 {
2155     auto callerUid = IPCSkeleton::GetCallingUid();
2156     if (callerUid != UID_BLUETOOTH_SA) {
2157         AUDIO_ERR_LOG("SetA2dpDeviceVolume: Error caller uid: %{public}d", callerUid);
2158         return ERROR;
2159     }
2160 
2161     AudioStreamType streamInFocus = AudioStreamType::STREAM_MUSIC; // use STREAM_MUSIC as default stream type
2162 
2163     if (!IsVolumeLevelValid(streamInFocus, volume)) {
2164         return ERR_NOT_SUPPORTED;
2165     }
2166     int32_t ret = audioPolicyService_.SetA2dpDeviceVolume(macAddress, volume);
2167 
2168     VolumeEvent volumeEvent;
2169     volumeEvent.volumeType = streamInFocus;
2170     volumeEvent.volume = volume;
2171     volumeEvent.updateUi = updateUi;
2172     volumeEvent.volumeGroupId = 0;
2173     volumeEvent.networkId = LOCAL_NETWORK_ID;
2174 
2175     if (ret == SUCCESS && audioPolicyServerHandler_!= nullptr) {
2176         audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
2177     }
2178     return ret;
2179 }
2180 
GetAvailableDevices(AudioDeviceUsage usage)2181 std::vector<std::unique_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetAvailableDevices(AudioDeviceUsage usage)
2182 {
2183     std::vector<unique_ptr<AudioDeviceDescriptor>> deviceDescs = {};
2184     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2185     switch (usage) {
2186         case MEDIA_OUTPUT_DEVICES:
2187         case MEDIA_INPUT_DEVICES:
2188         case ALL_MEDIA_DEVICES:
2189         case CALL_OUTPUT_DEVICES:
2190         case CALL_INPUT_DEVICES:
2191         case ALL_CALL_DEVICES:
2192         case D_ALL_DEVICES:
2193             break;
2194         default:
2195             AUDIO_ERR_LOG("Invalid device usage:%{public}d", usage);
2196             return deviceDescs;
2197     }
2198 
2199     deviceDescs = audioPolicyService_.GetAvailableDevices(usage);
2200     if (!hasSystemPermission) {
2201         for (auto &desc : deviceDescs) {
2202             desc->networkId_ = "";
2203             desc->interruptGroupId_ = GROUP_ID_NONE;
2204             desc->volumeGroupId_ = GROUP_ID_NONE;
2205         }
2206     }
2207 
2208     std::vector<sptr<AudioDeviceDescriptor>> deviceDevices = {};
2209     for (auto &desc : deviceDescs) {
2210         deviceDevices.push_back(new(std::nothrow) AudioDeviceDescriptor(*desc));
2211     }
2212 
2213     bool hasBTPermission = VerifyBluetoothPermission();
2214     if (!hasBTPermission) {
2215         audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDevices);
2216         deviceDescs.clear();
2217         for (auto &dec : deviceDevices) {
2218             deviceDescs.push_back(make_unique<AudioDeviceDescriptor>(*dec));
2219         }
2220     }
2221 
2222     return deviceDescs;
2223 }
2224 
SetAvailableDeviceChangeCallback(const int32_t,const AudioDeviceUsage usage,const sptr<IRemoteObject> & object)2225 int32_t AudioPolicyServer::SetAvailableDeviceChangeCallback(const int32_t /*clientId*/, const AudioDeviceUsage usage,
2226     const sptr<IRemoteObject> &object)
2227 {
2228     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
2229         "SetAvailableDeviceChangeCallback set listener object is nullptr");
2230     switch (usage) {
2231         case MEDIA_OUTPUT_DEVICES:
2232         case MEDIA_INPUT_DEVICES:
2233         case ALL_MEDIA_DEVICES:
2234         case CALL_OUTPUT_DEVICES:
2235         case CALL_INPUT_DEVICES:
2236         case ALL_CALL_DEVICES:
2237         case D_ALL_DEVICES:
2238             break;
2239         default:
2240             AUDIO_ERR_LOG("Invalid AudioDeviceUsage");
2241             return ERR_INVALID_PARAM;
2242     }
2243 
2244     int32_t clientPid = IPCSkeleton::GetCallingPid();
2245     bool hasBTPermission = VerifyBluetoothPermission();
2246     return audioPolicyService_.SetAvailableDeviceChangeCallback(clientPid, usage, object, hasBTPermission);
2247 }
2248 
UnsetAvailableDeviceChangeCallback(const int32_t,AudioDeviceUsage usage)2249 int32_t AudioPolicyServer::UnsetAvailableDeviceChangeCallback(const int32_t /*clientId*/, AudioDeviceUsage usage)
2250 {
2251     int32_t clientPid = IPCSkeleton::GetCallingPid();
2252     return audioPolicyService_.UnsetAvailableDeviceChangeCallback(clientPid, usage);
2253 }
2254 
OffloadStopPlaying(const AudioInterrupt & audioInterrupt)2255 int32_t AudioPolicyServer::OffloadStopPlaying(const AudioInterrupt &audioInterrupt)
2256 {
2257     return audioPolicyService_.OffloadStopPlaying(std::vector<int32_t>(1, audioInterrupt.sessionId));
2258 }
2259 
ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor,CastType type)2260 int32_t AudioPolicyServer::ConfigDistributedRoutingRole(const sptr<AudioDeviceDescriptor> descriptor, CastType type)
2261 {
2262     if (!PermissionUtil::VerifySystemPermission()) {
2263         AUDIO_ERR_LOG("No system permission");
2264         return ERR_PERMISSION_DENIED;
2265     }
2266     std::lock_guard<std::mutex> lock(descLock_);
2267     audioPolicyService_.ConfigDistributedRoutingRole(descriptor, type);
2268     OnDistributedRoutingRoleChange(descriptor, type);
2269     return SUCCESS;
2270 }
2271 
SetDistributedRoutingRoleCallback(const sptr<IRemoteObject> & object)2272 int32_t AudioPolicyServer::SetDistributedRoutingRoleCallback(const sptr<IRemoteObject> &object)
2273 {
2274     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
2275         "SetDistributedRoutingRoleCallback set listener object is nullptr");
2276     int32_t clientPid = IPCSkeleton::GetCallingPid();
2277     bool hasBTPermission = VerifyBluetoothPermission();
2278     AUDIO_INFO_LOG("Entered %{public}s", __func__);
2279     sptr<IStandardAudioRoutingManagerListener> listener = iface_cast<IStandardAudioRoutingManagerListener>(object);
2280     if (listener != nullptr && audioPolicyServerHandler_ != nullptr) {
2281         listener->hasBTPermission_ = hasBTPermission;
2282         audioPolicyServerHandler_->AddDistributedRoutingRoleChangeCbsMap(clientPid, listener);
2283     }
2284     return SUCCESS;
2285 }
2286 
UnsetDistributedRoutingRoleCallback()2287 int32_t AudioPolicyServer::UnsetDistributedRoutingRoleCallback()
2288 {
2289     int32_t clientPid = IPCSkeleton::GetCallingPid();
2290     AUDIO_INFO_LOG("Entered %{public}s", __func__);
2291     if (audioPolicyServerHandler_ != nullptr) {
2292         return audioPolicyServerHandler_->RemoveDistributedRoutingRoleChangeCbsMap(clientPid);
2293     }
2294     return SUCCESS;
2295 }
2296 
OnDistributedRoutingRoleChange(const sptr<AudioDeviceDescriptor> descriptor,const CastType type)2297 void AudioPolicyServer::OnDistributedRoutingRoleChange(const sptr<AudioDeviceDescriptor> descriptor,
2298     const CastType type)
2299 {
2300     CHECK_AND_RETURN_LOG(audioPolicyServerHandler_ != nullptr, "audioPolicyServerHandler_ is nullptr");
2301     audioPolicyServerHandler_->SendDistributedRoutingRoleChange(descriptor, type);
2302 }
2303 
RegisterPowerStateListener()2304 void AudioPolicyServer::RegisterPowerStateListener()
2305 {
2306     if (powerStateListener_ == nullptr) {
2307         powerStateListener_ = new (std::nothrow) PowerStateListener(this);
2308     }
2309 
2310     if (powerStateListener_ == nullptr) {
2311         AUDIO_ERR_LOG("create power state listener failed");
2312         return;
2313     }
2314 
2315     auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
2316     WatchTimeout guard("powerMgrClient.RegisterSyncSleepCallback:RegisterPowerStateListener");
2317     bool ret = powerMgrClient.RegisterSyncSleepCallback(powerStateListener_, SleepPriority::HIGH);
2318     guard.CheckCurrTimeout();
2319     if (!ret) {
2320         AUDIO_ERR_LOG("register sync sleep callback failed");
2321     } else {
2322         AUDIO_INFO_LOG("register sync sleep callback success");
2323     }
2324 }
2325 
UnRegisterPowerStateListener()2326 void AudioPolicyServer::UnRegisterPowerStateListener()
2327 {
2328     if (powerStateListener_ == nullptr) {
2329         AUDIO_ERR_LOG("power state listener is null");
2330         return;
2331     }
2332 
2333     auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
2334     WatchTimeout guard("powerMgrClient.UnRegisterSyncSleepCallback:UnRegisterPowerStateListener");
2335     bool ret = powerMgrClient.UnRegisterSyncSleepCallback(powerStateListener_);
2336     guard.CheckCurrTimeout();
2337     if (!ret) {
2338         AUDIO_WARNING_LOG("unregister sync sleep callback failed");
2339     } else {
2340         powerStateListener_ = nullptr;
2341         AUDIO_INFO_LOG("unregister sync sleep callback success");
2342     }
2343 }
2344 
RegisterSyncHibernateListener()2345 void AudioPolicyServer::RegisterSyncHibernateListener()
2346 {
2347     if (syncHibernateListener_ == nullptr) {
2348         syncHibernateListener_ = new (std::nothrow) SyncHibernateListener(this);
2349     }
2350 
2351     if (syncHibernateListener_ == nullptr) {
2352         AUDIO_ERR_LOG("create sync hibernate listener failed");
2353         return;
2354     }
2355 
2356     auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
2357     WatchTimeout guard("powerMgrClient.RegisterSyncHibernateCallback:RegisterSyncHibernateListener");
2358     bool ret = powerMgrClient.RegisterSyncHibernateCallback(syncHibernateListener_);
2359     guard.CheckCurrTimeout();
2360     if (!ret) {
2361         AUDIO_ERR_LOG("register sync hibernate callback failed");
2362     } else {
2363         AUDIO_INFO_LOG("register sync hibernate callback success");
2364     }
2365 }
2366 
UnRegisterSyncHibernateListener()2367 void AudioPolicyServer::UnRegisterSyncHibernateListener()
2368 {
2369     if (syncHibernateListener_ == nullptr) {
2370         AUDIO_ERR_LOG("sync hibernate listener is null");
2371         return;
2372     }
2373 
2374     auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
2375     WatchTimeout guard("powerMgrClient.UnRegisterSyncHibernateCallback:UnRegisterSyncHibernateListener");
2376     bool ret = powerMgrClient.UnRegisterSyncHibernateCallback(syncHibernateListener_);
2377     guard.CheckCurrTimeout();
2378     if (!ret) {
2379         AUDIO_WARNING_LOG("unregister sync hibernate callback failed");
2380     } else {
2381         syncHibernateListener_ = nullptr;
2382         AUDIO_INFO_LOG("unregister sync hibernate callback success");
2383     }
2384 }
2385 
IsSpatializationEnabled()2386 bool AudioPolicyServer::IsSpatializationEnabled()
2387 {
2388     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2389     if (!hasSystemPermission) {
2390         return false;
2391     }
2392     return audioSpatializationService_.IsSpatializationEnabled();
2393 }
2394 
IsSpatializationEnabled(const std::string address)2395 bool AudioPolicyServer::IsSpatializationEnabled(const std::string address)
2396 {
2397     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2398     if (!hasSystemPermission) {
2399         return false;
2400     }
2401     return audioSpatializationService_.IsSpatializationEnabled(address);
2402 }
2403 
SetSpatializationEnabled(const bool enable)2404 int32_t AudioPolicyServer::SetSpatializationEnabled(const bool enable)
2405 {
2406     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2407         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2408         return ERR_PERMISSION_DENIED;
2409     }
2410     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2411     if (!hasSystemPermission) {
2412         return ERR_PERMISSION_DENIED;
2413     }
2414     return audioSpatializationService_.SetSpatializationEnabled(enable);
2415 }
2416 
SetSpatializationEnabled(const sptr<AudioDeviceDescriptor> & selectedAudioDevice,const bool enable)2417 int32_t AudioPolicyServer::SetSpatializationEnabled(const sptr<AudioDeviceDescriptor> &selectedAudioDevice,
2418     const bool enable)
2419 {
2420     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2421         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2422         return ERR_PERMISSION_DENIED;
2423     }
2424     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2425     if (!hasSystemPermission) {
2426         return ERR_PERMISSION_DENIED;
2427     }
2428     return audioSpatializationService_.SetSpatializationEnabled(selectedAudioDevice, enable);
2429 }
2430 
IsHeadTrackingEnabled()2431 bool AudioPolicyServer::IsHeadTrackingEnabled()
2432 {
2433     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2434     if (!hasSystemPermission) {
2435         return false;
2436     }
2437     return audioSpatializationService_.IsHeadTrackingEnabled();
2438 }
2439 
IsHeadTrackingEnabled(const std::string address)2440 bool AudioPolicyServer::IsHeadTrackingEnabled(const std::string address)
2441 {
2442     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2443     if (!hasSystemPermission) {
2444         return false;
2445     }
2446     return audioSpatializationService_.IsHeadTrackingEnabled(address);
2447 }
2448 
SetHeadTrackingEnabled(const bool enable)2449 int32_t AudioPolicyServer::SetHeadTrackingEnabled(const bool enable)
2450 {
2451     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2452         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2453         return ERR_PERMISSION_DENIED;
2454     }
2455     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2456     if (!hasSystemPermission) {
2457         return ERR_PERMISSION_DENIED;
2458     }
2459     return audioSpatializationService_.SetHeadTrackingEnabled(enable);
2460 }
2461 
SetHeadTrackingEnabled(const sptr<AudioDeviceDescriptor> & selectedAudioDevice,const bool enable)2462 int32_t AudioPolicyServer::SetHeadTrackingEnabled(const sptr<AudioDeviceDescriptor> &selectedAudioDevice,
2463     const bool enable)
2464 {
2465     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2466         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2467         return ERR_PERMISSION_DENIED;
2468     }
2469     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2470     if (!hasSystemPermission) {
2471         return ERR_PERMISSION_DENIED;
2472     }
2473     return audioSpatializationService_.SetHeadTrackingEnabled(selectedAudioDevice, enable);
2474 }
2475 
GetSpatializationState(const StreamUsage streamUsage)2476 AudioSpatializationState AudioPolicyServer::GetSpatializationState(const StreamUsage streamUsage)
2477 {
2478     return audioSpatializationService_.GetSpatializationState(streamUsage);
2479 }
2480 
IsSpatializationSupported()2481 bool AudioPolicyServer::IsSpatializationSupported()
2482 {
2483     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2484     if (!hasSystemPermission) {
2485         return false;
2486     }
2487     return audioSpatializationService_.IsSpatializationSupported();
2488 }
2489 
IsSpatializationSupportedForDevice(const std::string address)2490 bool AudioPolicyServer::IsSpatializationSupportedForDevice(const std::string address)
2491 {
2492     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2493     if (!hasSystemPermission) {
2494         return false;
2495     }
2496     return audioSpatializationService_.IsSpatializationSupportedForDevice(address);
2497 }
2498 
IsHeadTrackingSupported()2499 bool AudioPolicyServer::IsHeadTrackingSupported()
2500 {
2501     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2502     if (!hasSystemPermission) {
2503         return false;
2504     }
2505     return audioSpatializationService_.IsHeadTrackingSupported();
2506 }
2507 
IsHeadTrackingSupportedForDevice(const std::string address)2508 bool AudioPolicyServer::IsHeadTrackingSupportedForDevice(const std::string address)
2509 {
2510     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2511     if (!hasSystemPermission) {
2512         return false;
2513     }
2514     return audioSpatializationService_.IsHeadTrackingSupportedForDevice(address);
2515 }
2516 
UpdateSpatialDeviceState(const AudioSpatialDeviceState audioSpatialDeviceState)2517 int32_t AudioPolicyServer::UpdateSpatialDeviceState(const AudioSpatialDeviceState audioSpatialDeviceState)
2518 {
2519     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2520         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2521         return ERR_PERMISSION_DENIED;
2522     }
2523     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2524     if (!hasSystemPermission) {
2525         return ERR_PERMISSION_DENIED;
2526     }
2527     return audioSpatializationService_.UpdateSpatialDeviceState(audioSpatialDeviceState);
2528 }
2529 
RegisterSpatializationStateEventListener(const uint32_t sessionID,const StreamUsage streamUsage,const sptr<IRemoteObject> & object)2530 int32_t AudioPolicyServer::RegisterSpatializationStateEventListener(const uint32_t sessionID,
2531     const StreamUsage streamUsage, const sptr<IRemoteObject> &object)
2532 {
2533     return audioSpatializationService_.RegisterSpatializationStateEventListener(sessionID, streamUsage, object);
2534 }
2535 
UnregisterSpatializationStateEventListener(const uint32_t sessionID)2536 int32_t AudioPolicyServer::UnregisterSpatializationStateEventListener(const uint32_t sessionID)
2537 {
2538     return audioSpatializationService_.UnregisterSpatializationStateEventListener(sessionID);
2539 }
2540 
RegisterPolicyCallbackClient(const sptr<IRemoteObject> & object,const int32_t zoneID)2541 int32_t AudioPolicyServer::RegisterPolicyCallbackClient(const sptr<IRemoteObject> &object, const int32_t zoneID)
2542 {
2543     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
2544         "RegisterPolicyCallbackClient listener object is nullptr");
2545 
2546     sptr<IAudioPolicyClient> callback = iface_cast<IAudioPolicyClient>(object);
2547     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM,
2548         "RegisterPolicyCallbackClient listener obj cast failed");
2549 
2550     int32_t clientPid = IPCSkeleton::GetCallingPid();
2551     AUDIO_DEBUG_LOG("register clientPid: %{public}d", clientPid);
2552 
2553     bool hasBTPermission = VerifyBluetoothPermission();
2554     bool hasSysPermission = PermissionUtil::VerifySystemPermission();
2555     callback->hasBTPermission_ = hasBTPermission;
2556     callback->hasSystemPermission_ = hasSysPermission;
2557     callback->apiVersion_ = GetApiTargerVersion();
2558     audioPolicyService_.AddAudioPolicyClientProxyMap(clientPid, callback);
2559 
2560     RegisterClientDeathRecipient(object, LISTENER_CLIENT);
2561     return SUCCESS;
2562 }
2563 
CreateAudioInterruptZone(const std::set<int32_t> & pids,const int32_t zoneID)2564 int32_t AudioPolicyServer::CreateAudioInterruptZone(const std::set<int32_t> &pids, const int32_t zoneID)
2565 {
2566     if (interruptService_ != nullptr) {
2567         return interruptService_->CreateAudioInterruptZone(zoneID, pids);
2568     }
2569     return ERR_UNKNOWN;
2570 }
2571 
AddAudioInterruptZonePids(const std::set<int32_t> & pids,const int32_t zoneID)2572 int32_t AudioPolicyServer::AddAudioInterruptZonePids(const std::set<int32_t> &pids, const int32_t zoneID)
2573 {
2574     if (interruptService_ != nullptr) {
2575         return interruptService_->AddAudioInterruptZonePids(zoneID, pids);
2576     }
2577     return ERR_UNKNOWN;
2578 }
2579 
RemoveAudioInterruptZonePids(const std::set<int32_t> & pids,const int32_t zoneID)2580 int32_t AudioPolicyServer::RemoveAudioInterruptZonePids(const std::set<int32_t> &pids, const int32_t zoneID)
2581 {
2582     if (interruptService_ != nullptr) {
2583         return interruptService_->RemoveAudioInterruptZonePids(zoneID, pids);
2584     }
2585     return ERR_UNKNOWN;
2586 }
2587 
ReleaseAudioInterruptZone(const int32_t zoneID)2588 int32_t AudioPolicyServer::ReleaseAudioInterruptZone(const int32_t zoneID)
2589 {
2590     if (interruptService_ != nullptr) {
2591         return interruptService_->ReleaseAudioInterruptZone(zoneID);
2592     }
2593     return ERR_UNKNOWN;
2594 }
2595 
SetCallDeviceActive(InternalDeviceType deviceType,bool active,std::string address)2596 int32_t AudioPolicyServer::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address)
2597 {
2598     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2599     if (!hasSystemPermission) {
2600         AUDIO_ERR_LOG("No system permission");
2601         return ERR_SYSTEM_PERMISSION_DENIED;
2602     }
2603     switch (deviceType) {
2604         case DeviceType::DEVICE_TYPE_EARPIECE:
2605         case DeviceType::DEVICE_TYPE_SPEAKER:
2606         case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
2607             break;
2608         default:
2609             AUDIO_ERR_LOG("device=%{public}d not supported", deviceType);
2610             return ERR_NOT_SUPPORTED;
2611     }
2612     return audioPolicyService_.SetCallDeviceActive(deviceType, active, address);
2613 }
2614 
GetActiveBluetoothDevice()2615 std::unique_ptr<AudioDeviceDescriptor> AudioPolicyServer::GetActiveBluetoothDevice()
2616 {
2617     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2618     if (!hasSystemPermission) {
2619         AUDIO_ERR_LOG("No system permission");
2620         return make_unique<AudioDeviceDescriptor>();
2621     }
2622 
2623     auto btdevice = audioPolicyService_.GetActiveBluetoothDevice();
2624 
2625     bool hasBTPermission = VerifyBluetoothPermission();
2626     if (!hasBTPermission) {
2627         btdevice->deviceName_ = "";
2628         btdevice->macAddress_ = "";
2629     }
2630 
2631     return btdevice;
2632 }
2633 
GetBundleName()2634 std::string AudioPolicyServer::GetBundleName()
2635 {
2636     AppExecFwk::BundleInfo bundleInfo = GetBundleInfoFromUid();
2637     return bundleInfo.name;
2638 }
2639 
GetSpatializationSceneType()2640 AudioSpatializationSceneType AudioPolicyServer::GetSpatializationSceneType()
2641 {
2642     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2643     if (!hasSystemPermission) {
2644         return SPATIALIZATION_SCENE_TYPE_DEFAULT;
2645     }
2646     return audioSpatializationService_.GetSpatializationSceneType();
2647 }
2648 
SetSpatializationSceneType(const AudioSpatializationSceneType spatializationSceneType)2649 int32_t AudioPolicyServer::SetSpatializationSceneType(const AudioSpatializationSceneType spatializationSceneType)
2650 {
2651     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2652         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2653         return ERR_PERMISSION_DENIED;
2654     }
2655     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2656     if (!hasSystemPermission) {
2657         return ERR_PERMISSION_DENIED;
2658     }
2659     return audioSpatializationService_.SetSpatializationSceneType(spatializationSceneType);
2660 }
2661 
DisableSafeMediaVolume()2662 int32_t AudioPolicyServer::DisableSafeMediaVolume()
2663 {
2664     if (!VerifyPermission(MODIFY_AUDIO_SETTINGS_PERMISSION)) {
2665         AUDIO_ERR_LOG("MODIFY_AUDIO_SETTINGS_PERMISSION permission check failed");
2666         return ERR_PERMISSION_DENIED;
2667     }
2668     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2669     if (!hasSystemPermission) {
2670         return ERR_SYSTEM_PERMISSION_DENIED;
2671     }
2672     return audioPolicyService_.DisableSafeMediaVolume();
2673 }
2674 
GetBundleInfoFromUid()2675 AppExecFwk::BundleInfo AudioPolicyServer::GetBundleInfoFromUid()
2676 {
2677     AudioXCollie audioXCollie("AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName",
2678         GET_BUNDLE_TIME_OUT_SECONDS);
2679     std::string bundleName {""};
2680     AppExecFwk::BundleInfo bundleInfo;
2681     WatchTimeout guard("SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager():GetBundleInfoFromUid");
2682     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2683     CHECK_AND_RETURN_RET_LOG(systemAbilityManager != nullptr, bundleInfo, "systemAbilityManager is nullptr");
2684     guard.CheckCurrTimeout();
2685 
2686     sptr<IRemoteObject> remoteObject = systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2687     CHECK_AND_RETURN_RET_PRELOG(remoteObject != nullptr, bundleInfo, "remoteObject is nullptr");
2688 
2689     sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
2690     CHECK_AND_RETURN_RET_LOG(bundleMgrProxy != nullptr, bundleInfo, "bundleMgrProxy is nullptr");
2691 
2692     int32_t callingUid = IPCSkeleton::GetCallingUid();
2693     WatchTimeout reguard("bundleMgrProxy->GetNameForUid:GetBundleInfoFromUid");
2694     bundleMgrProxy->GetNameForUid(callingUid, bundleName);
2695 
2696     bundleMgrProxy->GetBundleInfoV9(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT |
2697         AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES |
2698         AppExecFwk::BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION |
2699         AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO |
2700         AppExecFwk::BundleFlag::GET_BUNDLE_WITH_HASH_VALUE,
2701         bundleInfo,
2702         AppExecFwk::Constants::ALL_USERID);
2703     reguard.CheckCurrTimeout();
2704 
2705     return bundleInfo;
2706 }
2707 
GetApiTargerVersion()2708 int32_t AudioPolicyServer::GetApiTargerVersion()
2709 {
2710     AppExecFwk::BundleInfo bundleInfo = GetBundleInfoFromUid();
2711 
2712     // Taking remainder of large integers
2713     int32_t apiTargetversion = bundleInfo.applicationInfo.apiTargetVersion % API_VERSION_REMAINDER;
2714     return apiTargetversion;
2715 }
2716 
GetConverterConfig()2717 ConverterConfig AudioPolicyServer::GetConverterConfig()
2718 {
2719     return audioPolicyService_.GetConverterConfig();
2720 }
2721 
IsHighResolutionExist()2722 bool AudioPolicyServer::IsHighResolutionExist()
2723 {
2724     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2725     if (!hasSystemPermission) {
2726         AUDIO_ERR_LOG("No system permission");
2727         return false;
2728     }
2729     return isHighResolutionExist_;
2730 }
2731 
SetHighResolutionExist(bool highResExist)2732 int32_t AudioPolicyServer::SetHighResolutionExist(bool highResExist)
2733 {
2734     bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2735     if (!hasSystemPermission) {
2736         AUDIO_ERR_LOG("No system permission");
2737         return ERR_PERMISSION_DENIED;
2738     }
2739     isHighResolutionExist_ = highResExist;
2740     return SUCCESS;
2741 }
2742 
GetMaxAmplitude(int32_t deviceId)2743 float AudioPolicyServer::GetMaxAmplitude(int32_t deviceId)
2744 {
2745     return audioPolicyService_.GetMaxAmplitude(deviceId);
2746 }
2747 
IsHeadTrackingDataRequested(const std::string & macAddress)2748 bool AudioPolicyServer::IsHeadTrackingDataRequested(const std::string &macAddress)
2749 {
2750     return audioSpatializationService_.IsHeadTrackingDataRequested(macAddress);
2751 }
2752 
SetAudioDeviceRefinerCallback(const sptr<IRemoteObject> & object)2753 int32_t AudioPolicyServer::SetAudioDeviceRefinerCallback(const sptr<IRemoteObject> &object)
2754 {
2755     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "SetAudioDeviceRefinerCallback object is nullptr");
2756     auto callerUid = IPCSkeleton::GetCallingUid();
2757     if (callerUid != UID_AUDIO) {
2758         return ERROR;
2759     }
2760     return audioRouterCenter_.SetAudioDeviceRefinerCallback(object);
2761 }
2762 
UnsetAudioDeviceRefinerCallback()2763 int32_t AudioPolicyServer::UnsetAudioDeviceRefinerCallback()
2764 {
2765     auto callerUid = IPCSkeleton::GetCallingUid();
2766     if (callerUid != UID_AUDIO) {
2767         return ERROR;
2768     }
2769     return audioRouterCenter_.UnsetAudioDeviceRefinerCallback();
2770 }
2771 
TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)2772 int32_t AudioPolicyServer::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)
2773 {
2774     auto callerUid = IPCSkeleton::GetCallingUid();
2775     if (callerUid != UID_AUDIO) {
2776         return ERROR;
2777     }
2778     return audioPolicyService_.TriggerFetchDevice(reason);
2779 }
2780 
SetPreferredDevice(const PreferredType preferredType,const sptr<AudioDeviceDescriptor> & desc)2781 int32_t AudioPolicyServer::SetPreferredDevice(const PreferredType preferredType,
2782     const sptr<AudioDeviceDescriptor> &desc)
2783 {
2784     auto callerUid = IPCSkeleton::GetCallingUid();
2785     if (callerUid != UID_AUDIO) {
2786         AUDIO_ERR_LOG("No permission");
2787         return ERROR;
2788     }
2789     return audioPolicyService_.SetPreferredDevice(preferredType, desc);
2790 }
2791 
SaveRemoteInfo(const std::string & networkId,DeviceType deviceType)2792 void AudioPolicyServer::SaveRemoteInfo(const std::string &networkId, DeviceType deviceType)
2793 {
2794     auto callerUid = IPCSkeleton::GetCallingUid();
2795     if (callerUid != UID_AUDIO) {
2796         AUDIO_ERR_LOG("No permission");
2797         return;
2798     }
2799     std::unique_ptr<AudioDeviceDescriptor> newMediaDescriptor = std::move(
2800         audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1, ROUTER_TYPE_USER_SELECT).front());
2801     std::unique_ptr<AudioDeviceDescriptor> newCallDescriptor = std::move(
2802         audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_COMMUNICATION, -1,
2803         ROUTER_TYPE_USER_SELECT).front());
2804     if (networkId == newMediaDescriptor->networkId_ && deviceType == newMediaDescriptor->deviceType_) {
2805         audioPolicyService_.SetPreferredDevice(AUDIO_MEDIA_RENDER,
2806             new(std::nothrow) AudioDeviceDescriptor());
2807     }
2808     if (networkId == newCallDescriptor->networkId_ && deviceType == newCallDescriptor->deviceType_) {
2809         audioPolicyService_.SetPreferredDevice(AUDIO_CALL_RENDER,
2810             new(std::nothrow) AudioDeviceDescriptor());
2811     }
2812     audioDeviceManager_.SaveRemoteInfo(networkId, deviceType);
2813 }
2814 
NotifyAccountsChanged(const int & id)2815 void AudioPolicyServer::NotifyAccountsChanged(const int &id)
2816 {
2817     audioPolicyService_.NotifyAccountsChanged(id);
2818     CHECK_AND_RETURN_LOG(interruptService_ != nullptr, "interruptService_ is nullptr");
2819     interruptService_->ClearAudioFocusInfoListOnAccountsChanged(id);
2820 }
2821 
MoveToNewPipe(const uint32_t sessionId,const AudioPipeType pipeType)2822 int32_t AudioPolicyServer::MoveToNewPipe(const uint32_t sessionId, const AudioPipeType pipeType)
2823 {
2824     return audioPolicyService_.MoveToNewPipe(sessionId, pipeType);
2825 }
2826 
SetAudioConcurrencyCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)2827 int32_t AudioPolicyServer::SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object)
2828 {
2829     return audioPolicyService_.SetAudioConcurrencyCallback(sessionID, object);
2830 }
2831 
UnsetAudioConcurrencyCallback(const uint32_t sessionID)2832 int32_t AudioPolicyServer::UnsetAudioConcurrencyCallback(const uint32_t sessionID)
2833 {
2834     return audioPolicyService_.UnsetAudioConcurrencyCallback(sessionID);
2835 }
2836 
ActivateAudioConcurrency(const AudioPipeType & pipeType)2837 int32_t AudioPolicyServer::ActivateAudioConcurrency(const AudioPipeType &pipeType)
2838 {
2839     return audioPolicyService_.ActivateAudioConcurrency(pipeType);
2840 }
2841 
GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)2842 int32_t AudioPolicyServer::GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
2843 {
2844     bool ret = PermissionUtil::VerifySystemPermission();
2845     CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
2846     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2847         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2848         return ERR_PERMISSION_DENIED;
2849     }
2850     audioPolicyService_.GetSupportedAudioEffectProperty(propertyArray);
2851     return AUDIO_OK;
2852 }
2853 
SetAudioEffectProperty(const AudioEffectPropertyArrayV3 & propertyArray)2854 int32_t AudioPolicyServer::SetAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray)
2855 {
2856     bool ret = PermissionUtil::VerifySystemPermission();
2857     CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
2858     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2859         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2860         return ERR_PERMISSION_DENIED;
2861     }
2862     return audioPolicyService_.SetAudioEffectProperty(propertyArray);
2863 }
2864 
GetAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)2865 int32_t AudioPolicyServer::GetAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
2866 {
2867     bool ret = PermissionUtil::VerifySystemPermission();
2868     CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
2869     if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
2870         AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
2871         return ERR_PERMISSION_DENIED;
2872     }
2873     return audioPolicyService_.GetAudioEffectProperty(propertyArray);
2874 }
2875 
InjectInterruption(const std::string networkId,InterruptEvent & event)2876 int32_t AudioPolicyServer::InjectInterruption(const std::string networkId, InterruptEvent &event)
2877 {
2878     auto callerUid = IPCSkeleton::GetCallingUid();
2879     if (callerUid != UID_CAST_ENGINE_SA) {
2880         AUDIO_ERR_LOG("InjectInterruption callerUid is Error: not cast_engine");
2881         return ERROR;
2882     }
2883     CHECK_AND_RETURN_RET_LOG(audioPolicyServerHandler_ != nullptr, ERROR, "audioPolicyServerHandler_ is nullptr");
2884     std::set<int32_t> sessionIds =
2885         AudioStreamCollector::GetAudioStreamCollector().GetSessionIdsOnRemoteDeviceByDeviceType(
2886             DEVICE_TYPE_REMOTE_CAST);
2887     InterruptEventInternal interruptEvent { event.eventType, event.forceType, event.hintType, 0.2f};
2888     ProcessRemoteInterrupt(sessionIds, interruptEvent);
2889     return SUCCESS;
2890 }
2891 
CheckAudioSessionStrategy(const AudioSessionStrategy & sessionStrategy)2892 bool AudioPolicyServer::CheckAudioSessionStrategy(const AudioSessionStrategy &sessionStrategy)
2893 {
2894     bool result = false;
2895     switch (sessionStrategy.concurrencyMode) {
2896         case AudioConcurrencyMode::DEFAULT:
2897         case AudioConcurrencyMode::MIX_WITH_OTHERS:
2898         case AudioConcurrencyMode::DUCK_OTHERS:
2899         case AudioConcurrencyMode::PAUSE_OTHERS:
2900             result = true;
2901             break;
2902         default:
2903             AUDIO_ERR_LOG("Invalid concurrency mode: %{public}d!",
2904                 static_cast<int32_t>(sessionStrategy.concurrencyMode));
2905             result = false;
2906             break;
2907     }
2908     return result;
2909 }
2910 
ActivateAudioSession(const AudioSessionStrategy & strategy)2911 int32_t AudioPolicyServer::ActivateAudioSession(const AudioSessionStrategy &strategy)
2912 {
2913     if (interruptService_ == nullptr) {
2914         AUDIO_ERR_LOG("interruptService_ is nullptr!");
2915         return ERR_UNKNOWN;
2916     }
2917     if (!CheckAudioSessionStrategy(strategy)) {
2918         AUDIO_ERR_LOG("The audio session strategy is invalid!");
2919         return ERR_INVALID_PARAM;
2920     }
2921     int32_t callerPid = IPCSkeleton::GetCallingPid();
2922     AUDIO_INFO_LOG("activate audio session with concurrencyMode %{public}d for pid %{public}d",
2923         static_cast<int32_t>(strategy.concurrencyMode), callerPid);
2924     return interruptService_->ActivateAudioSession(callerPid, strategy);
2925 }
2926 
DeactivateAudioSession()2927 int32_t AudioPolicyServer::DeactivateAudioSession()
2928 {
2929     if (interruptService_ == nullptr) {
2930         AUDIO_ERR_LOG("interruptService_ is nullptr!");
2931         return ERR_UNKNOWN;
2932     }
2933     int32_t callerPid = IPCSkeleton::GetCallingPid();
2934     AUDIO_INFO_LOG("deactivate audio session for pid %{public}d", callerPid);
2935     return interruptService_->DeactivateAudioSession(callerPid);
2936 }
2937 
IsAudioSessionActivated()2938 bool AudioPolicyServer::IsAudioSessionActivated()
2939 {
2940     if (interruptService_ == nullptr) {
2941         AUDIO_ERR_LOG("interruptService_ is nullptr!");
2942         return false;
2943     }
2944     int32_t callerPid = IPCSkeleton::GetCallingPid();
2945     bool isActive = interruptService_->IsAudioSessionActivated(callerPid);
2946     AUDIO_INFO_LOG("callerPid %{public}d, isSessionActive: %{public}d.", callerPid, isActive);
2947     return isActive;
2948 }
2949 
LoadSplitModule(const std::string & splitArgs,const std::string & networkId)2950 int32_t AudioPolicyServer::LoadSplitModule(const std::string &splitArgs, const std::string &networkId)
2951 {
2952     auto callerUid = IPCSkeleton::GetCallingUid();
2953     if (callerUid != UID_CAR_DISTRIBUTED_ENGINE_SA) {
2954         AUDIO_ERR_LOG("callerUid %{public}d is not allow LoadSplitModule", callerUid);
2955         return ERR_PERMISSION_DENIED;
2956     }
2957     return audioPolicyService_.LoadSplitModule(splitArgs, networkId);
2958 }
2959 
SetVoiceRingtoneMute(bool isMute)2960 int32_t AudioPolicyServer::SetVoiceRingtoneMute(bool isMute)
2961 {
2962     constexpr int32_t foundationUid = 5523; // "uid" : "foundation"
2963     auto callerUid = IPCSkeleton::GetCallingUid();
2964     // This function can only be used by foundation
2965     CHECK_AND_RETURN_RET_LOG(callerUid == foundationUid, ERROR,
2966         "SetVoiceRingtoneMute callerUid is error: not foundation");
2967     AUDIO_INFO_LOG("Set VoiceRingtone is %{public}d", isMute);
2968     return audioPolicyService_.SetVoiceRingtoneMute(isMute);
2969 }
2970 
SetDefaultOutputDevice(const DeviceType deviceType,const uint32_t sessionID,const StreamUsage streamUsage,bool isRunning)2971 int32_t AudioPolicyServer::SetDefaultOutputDevice(const DeviceType deviceType, const uint32_t sessionID,
2972     const StreamUsage streamUsage, bool isRunning)
2973 {
2974     return audioPolicyService_.SetDefaultOutputDevice(deviceType, sessionID, streamUsage, isRunning);
2975 }
2976 
UpdateDefaultOutputDeviceWhenStarting(const uint32_t sessionID)2977 void AudioPolicyServer::UpdateDefaultOutputDeviceWhenStarting(const uint32_t sessionID)
2978 {
2979     audioDeviceManager_.UpdateDefaultOutputDeviceWhenStarting(sessionID);
2980 }
2981 
UpdateDefaultOutputDeviceWhenStopping(const uint32_t sessionID)2982 void AudioPolicyServer::UpdateDefaultOutputDeviceWhenStopping(const uint32_t sessionID)
2983 {
2984     audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(sessionID);
2985 }
2986 } // namespace AudioStandard
2987 } // namespace OHOS
2988