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