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