1 /*
2 * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef LOG_TAG
16 #define LOG_TAG "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 "parameters.h"
31 #include "media_monitor_manager.h"
32 #include "client_type_manager.h"
33 #include "dfx_msg_manager.h"
34 #ifdef USB_ENABLE
35 #include "audio_usb_manager.h"
36 #endif
37
38 using OHOS::Security::AccessToken::PrivacyKit;
39 using OHOS::Security::AccessToken::TokenIdKit;
40 using namespace std;
41
42 namespace OHOS {
43 namespace AudioStandard {
44
45 // for phone
46 const std::vector<AudioStreamType> GET_STREAM_ALL_VOLUME_TYPES {
47 STREAM_MUSIC,
48 STREAM_VOICE_CALL,
49 STREAM_RING,
50 STREAM_VOICE_ASSISTANT,
51 STREAM_ALARM,
52 STREAM_ACCESSIBILITY,
53 STREAM_ULTRASONIC
54 };
55
56 const std::vector<AudioStreamType> GET_PC_STREAM_ALL_VOLUME_TYPES {
57 STREAM_VOICE_CALL,
58 STREAM_VOICE_ASSISTANT,
59 STREAM_ACCESSIBILITY,
60 STREAM_RING,
61 STREAM_ALARM,
62 STREAM_VOICE_RING,
63 STREAM_ULTRASONIC,
64 // adjust the type of music from the head of list to end, make sure music is updated last.
65 // avoid interference from ring updates on special platform.
66 // when the device is switched to headset,ring and alarm is dualtone type.
67 // dualtone type use fixed volume curve of speaker.
68 // the ring and alarm are classified into the music group.
69 // the music volume becomes abnormal when the db value of music is modified.
70 STREAM_MUSIC
71 };
72
73 const std::list<AudioStreamType> CAN_MIX_MUTED_STREAM = {
74 STREAM_NOTIFICATION
75 };
76
77 constexpr int32_t PARAMS_VOLUME_NUM = 5;
78 constexpr int32_t PARAMS_INTERRUPT_NUM = 4;
79 constexpr int32_t PARAMS_RENDER_STATE_NUM = 2;
80 constexpr int32_t EVENT_DES_SIZE = 80;
81 constexpr int32_t ADAPTER_STATE_CONTENT_DES_SIZE = 60;
82 constexpr int32_t API_VERSION_REMAINDER = 1000;
83 constexpr pid_t FIRST_SCREEN_ON_PID = 1000;
84 constexpr uid_t UID_CAST_ENGINE_SA = 5526;
85 constexpr uid_t UID_AUDIO = 1041;
86 constexpr uid_t UID_FOUNDATION_SA = 5523;
87 constexpr uid_t UID_BLUETOOTH_SA = 1002;
88 constexpr uid_t UID_CAR_DISTRIBUTED_ENGINE_SA = 65872;
89 constexpr uid_t UID_TV_PROCESS_SA = 7501;
90 constexpr uid_t UID_RESOURCE_SCHEDULE_SERVICE = 1096;
91 constexpr int64_t OFFLOAD_NO_SESSION_ID = -1;
92 constexpr unsigned int GET_BUNDLE_TIME_OUT_SECONDS = 10;
93 const char* MANAGE_SYSTEM_AUDIO_EFFECTS = "ohos.permission.MANAGE_SYSTEM_AUDIO_EFFECTS";
94 const char* MANAGE_AUDIO_CONFIG = "ohos.permission.MANAGE_AUDIO_CONFIG";
95 const char* USE_BLUETOOTH_PERMISSION = "ohos.permission.USE_BLUETOOTH";
96 const char* MICROPHONE_CONTROL_PERMISSION = "ohos.permission.MICROPHONE_CONTROL";
97
98 REGISTER_SYSTEM_ABILITY_BY_ID(AudioPolicyServer, AUDIO_POLICY_SERVICE_ID, true)
99
100 std::map<PolicyType, uint32_t> POLICY_TYPE_MAP = {
101 {PolicyType::EDM_POLICY_TYPE, 0},
102 {PolicyType::PRIVACY_POLCIY_TYPE, 1},
103 {PolicyType::TEMPORARY_POLCIY_TYPE, 2}
104 };
105
AudioPolicyServer(int32_t systemAbilityId,bool runOnCreate)106 AudioPolicyServer::AudioPolicyServer(int32_t systemAbilityId, bool runOnCreate)
107 : SystemAbility(systemAbilityId, runOnCreate),
108 audioPolicyService_(AudioPolicyService::GetAudioPolicyService()),
109 audioPolicyUtils_(AudioPolicyUtils::GetInstance()),
110 audioDeviceManager_(AudioDeviceManager::GetAudioDeviceManager()),
111 audioSpatializationService_(AudioSpatializationService::GetAudioSpatializationService()),
112 audioRouterCenter_(AudioRouterCenter::GetAudioRouterCenter()),
113 audioPolicyDump_(AudioPolicyDump::GetInstance()),
114 audioActiveDevice_(AudioActiveDevice::GetInstance())
115 {
116 volumeStep_ = system::GetIntParameter("const.multimedia.audio.volumestep", 1);
117 AUDIO_INFO_LOG("Get volumeStep parameter success %{public}d", volumeStep_);
118
119 powerStateCallbackRegister_ = false;
120 supportVibrator_ = system::GetBoolParameter("const.vibrator.support_vibrator", true);
121 volumeApplyToAll_ = system::GetBoolParameter("const.audio.volume_apply_to_all", false);
122 if (volumeApplyToAll_) {
123 audioPolicyService_.SetNormalVoipFlag(true);
124 }
125 }
126
TranslateKeyEvent(const int32_t keyType)127 static std::string TranslateKeyEvent(const int32_t keyType)
128 {
129 string event = "KEYCODE_UNKNOWN";
130
131 if (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) {
132 event = "KEYCODE_VOLUME_UP";
133 } else if (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN) {
134 event = "KEYCODE_VOLUME_DOWN";
135 } else if (keyType == OHOS::MMI::KeyEvent::KEYCODE_MUTE) {
136 event = "KEYCODE_MUTE";
137 }
138 return event;
139 }
140
TranslateErrorCode(int32_t result)141 uint32_t AudioPolicyServer::TranslateErrorCode(int32_t result)
142 {
143 uint32_t resultForMonitor = 0;
144 switch (result) {
145 case ERR_INVALID_PARAM:
146 resultForMonitor = ERR_SUBSCRIBE_INVALID_PARAM;
147 break;
148 case ERR_NULL_POINTER:
149 resultForMonitor = ERR_SUBSCRIBE_KEY_OPTION_NULL;
150 break;
151 case ERR_MMI_CREATION:
152 resultForMonitor = ERR_SUBSCRIBE_MMI_NULL;
153 break;
154 case ERR_MMI_SUBSCRIBE:
155 resultForMonitor = ERR_MODE_SUBSCRIBE;
156 break;
157 default:
158 break;
159 }
160 return resultForMonitor;
161 }
162
OnDump()163 void AudioPolicyServer::OnDump()
164 {
165 return;
166 }
167
OnStart()168 void AudioPolicyServer::OnStart()
169 {
170 AUDIO_INFO_LOG("Audio policy server on start");
171 DlopenUtils::Init();
172 interruptService_ = std::make_shared<AudioInterruptService>();
173 interruptService_->Init(this);
174
175 audioPolicyServerHandler_ = DelayedSingleton<AudioPolicyServerHandler>::GetInstance();
176 audioPolicyServerHandler_->Init(interruptService_);
177
178 interruptService_->SetCallbackHandler(audioPolicyServerHandler_);
179
180 if (audioPolicyService_.SetAudioStreamRemovedCallback(this)) {
181 AUDIO_ERR_LOG("SetAudioStreamRemovedCallback failed");
182 }
183 audioPolicyService_.Init();
184
185 AddSystemAbilityListeners();
186 bool res = Publish(this);
187 if (!res) {
188 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
189 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::AUDIO_SERVICE_STARTUP_ERROR,
190 Media::MediaMonitor::EventType::FAULT_EVENT);
191 bean->Add("SERVICE_ID", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVICE_ID));
192 bean->Add("ERROR_CODE", static_cast<int32_t>(Media::MediaMonitor::AUDIO_POLICY_SERVER));
193 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
194 AUDIO_INFO_LOG("publish sa err");
195 }
196
197 Security::AccessToken::PermStateChangeScope scopeInfo;
198 scopeInfo.permList = {"ohos.permission.MICROPHONE"};
199 auto callbackPtr = std::make_shared<PerStateChangeCbCustomizeCallback>(scopeInfo, this);
200 callbackPtr->ready_ = false;
201 int32_t iRes = Security::AccessToken::AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr);
202 if (iRes < 0) {
203 AUDIO_ERR_LOG("fail to call RegisterPermStateChangeCallback.");
204 }
205 #ifdef FEATURE_MULTIMODALINPUT_INPUT
206 SubscribeVolumeKeyEvents();
207 #endif
208 if (getpid() > FIRST_SCREEN_ON_PID) {
209 audioPolicyService_.SetFirstScreenOn();
210 }
211 // Restart to reload the volume.
212 InitKVStore();
213 isScreenOffOrLock_ = !PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(true);
214 DlopenUtils::DeInit();
215 DfxMsgManager::GetInstance().Init();
216 AUDIO_INFO_LOG("Audio policy server start end");
217 }
218
AddSystemAbilityListeners()219 void AudioPolicyServer::AddSystemAbilityListeners()
220 {
221 AddSystemAbilityListener(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
222 AddSystemAbilityListener(AUDIO_DISTRIBUTED_SERVICE_ID);
223 AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
224 AddSystemAbilityListener(APP_MGR_SERVICE_ID);
225 #ifdef FEATURE_MULTIMODALINPUT_INPUT
226 AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
227 #endif
228 AddSystemAbilityListener(BLUETOOTH_HOST_SYS_ABILITY_ID);
229 AddSystemAbilityListener(ACCESSIBILITY_MANAGER_SERVICE_ID);
230 AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
231 #ifdef USB_ENABLE
232 AddSystemAbilityListener(USB_SYSTEM_ABILITY_ID);
233 #endif
234 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
235 #ifdef SUPPORT_USER_ACCOUNT
236 AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
237 #endif
238 }
239
OnStop()240 void AudioPolicyServer::OnStop()
241 {
242 audioPolicyService_.Deinit();
243 #ifdef USB_ENABLE
244 AudioUsbManager::GetInstance().Deinit();
245 #endif
246 UnRegisterPowerStateListener();
247 UnRegisterSyncHibernateListener();
248 return;
249 }
250
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)251 void AudioPolicyServer::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
252 {
253 AUDIO_INFO_LOG("SA Id is :%{public}d", systemAbilityId);
254 int64_t stamp = ClockTime::GetCurNano();
255 switch (systemAbilityId) {
256 #ifdef FEATURE_MULTIMODALINPUT_INPUT
257 case MULTIMODAL_INPUT_SERVICE_ID:
258 SubscribeVolumeKeyEvents();
259 break;
260 #endif
261 case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID:
262 HandleKvDataShareEvent();
263 break;
264 case DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID:
265 AddRemoteDevstatusCallback();
266 break;
267 case AUDIO_DISTRIBUTED_SERVICE_ID:
268 AddAudioServiceOnStart();
269 break;
270 case BLUETOOTH_HOST_SYS_ABILITY_ID:
271 RegisterBluetoothListener();
272 break;
273 case ACCESSIBILITY_MANAGER_SERVICE_ID:
274 SubscribeAccessibilityConfigObserver();
275 break;
276 case POWER_MANAGER_SERVICE_ID:
277 SubscribePowerStateChangeEvents();
278 RegisterPowerStateListener();
279 RegisterSyncHibernateListener();
280 break;
281 case SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN:
282 SubscribeOsAccountChangeEvents();
283 break;
284 case COMMON_EVENT_SERVICE_ID:
285 SubscribeCommonEventExecute();
286 break;
287 #ifdef USB_ENABLE
288 case USB_SYSTEM_ABILITY_ID:
289 AudioUsbManager::GetInstance().Init(&audioPolicyService_);
290 break;
291 #endif
292 default:
293 OnAddSystemAbilityExtract(systemAbilityId, deviceId);
294 break;
295 }
296 // eg. done systemAbilityId: [3001] cost 780ms
297 AUDIO_INFO_LOG("done systemAbilityId: [%{public}d] cost %{public}" PRId64 " ms", systemAbilityId,
298 (ClockTime::GetCurNano() - stamp) / AUDIO_US_PER_SECOND);
299 }
300
OnAddSystemAbilityExtract(int32_t systemAbilityId,const std::string & deviceId)301 void AudioPolicyServer::OnAddSystemAbilityExtract(int32_t systemAbilityId, const std::string& deviceId)
302 {
303 switch (systemAbilityId) {
304 case APP_MGR_SERVICE_ID:
305 RegisterAppStateListener();
306 break;
307 default:
308 AUDIO_WARNING_LOG("OnAddSystemAbility unhandled sysabilityId:%{public}d", systemAbilityId);
309 break;
310 }
311 }
312
HandleKvDataShareEvent()313 void AudioPolicyServer::HandleKvDataShareEvent()
314 {
315 AUDIO_INFO_LOG("OnAddSystemAbility kv data service start");
316 if (isInitMuteState_ == false && audioPolicyService_.IsDataShareReady()) {
317 AUDIO_INFO_LOG("datashare is ready and need init mic mute state");
318 InitMicrophoneMute();
319 }
320 }
321
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)322 void AudioPolicyServer::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
323 {
324 AUDIO_DEBUG_LOG("AudioPolicyServer::OnRemoveSystemAbility systemAbilityId:%{public}d removed", systemAbilityId);
325 }
326
327 #ifdef FEATURE_MULTIMODALINPUT_INPUT
MaxOrMinVolumeOption(const int32_t & volLevel,const int32_t keyType,const AudioStreamType & streamInFocus)328 bool AudioPolicyServer::MaxOrMinVolumeOption(const int32_t &volLevel, const int32_t keyType,
329 const AudioStreamType &streamInFocus)
330 {
331 bool volLevelCheck = (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ?
332 volLevel >= GetMaxVolumeLevel(streamInFocus) : volLevel <= GetMinVolumeLevel(streamInFocus);
333 if (volLevelCheck) {
334 VolumeEvent volumeEvent;
335 volumeEvent.volumeType = (streamInFocus == STREAM_ALL) ? STREAM_MUSIC : streamInFocus;
336 volumeEvent.volume = volLevel;
337 volumeEvent.updateUi = true;
338 volumeEvent.volumeGroupId = 0;
339 volumeEvent.networkId = LOCAL_NETWORK_ID;
340 CHECK_AND_RETURN_RET_LOG(audioPolicyServerHandler_ != nullptr, false, "audioPolicyServerHandler_ is nullptr");
341 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
342 return true;
343 }
344
345 return false;
346 }
347 #endif
348
ChangeVolumeOnVoiceAssistant(AudioStreamType & streamInFocus)349 void AudioPolicyServer::ChangeVolumeOnVoiceAssistant(AudioStreamType &streamInFocus)
350 {
351 if (streamInFocus == AudioStreamType::STREAM_VOICE_ASSISTANT &&
352 audioPolicyService_.GetActiveOutputDevice() == DEVICE_TYPE_BLUETOOTH_A2DP) {
353 streamInFocus = AudioStreamType::STREAM_MUSIC;
354 }
355 }
356
357 #ifdef FEATURE_MULTIMODALINPUT_INPUT
RegisterVolumeKeyEvents(const int32_t keyType)358 int32_t AudioPolicyServer::RegisterVolumeKeyEvents(const int32_t keyType)
359 {
360 if ((keyType != OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) && (keyType != OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN)) {
361 AUDIO_ERR_LOG("VolumeKeyEvents: invalid key type : %{public}d", keyType);
362 return ERR_INVALID_PARAM;
363 }
364 AUDIO_INFO_LOG("RegisterVolumeKeyEvents: volume key: %{public}s.",
365 (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ? "up" : "down");
366
367 MMI::InputManager *im = MMI::InputManager::GetInstance();
368 CHECK_AND_RETURN_RET_LOG(im != nullptr, ERR_MMI_CREATION, "Failed to obtain INPUT manager");
369
370 std::set<int32_t> preKeys;
371 std::shared_ptr<OHOS::MMI::KeyOption> keyOption = std::make_shared<OHOS::MMI::KeyOption>();
372 CHECK_AND_RETURN_RET_LOG(keyOption != nullptr, ERR_NULL_POINTER, "Invalid key option");
373 WatchTimeout guard("keyOption->SetPreKeys:RegisterVolumeKeyEvents");
374 keyOption->SetPreKeys(preKeys);
375 keyOption->SetFinalKey(keyType);
376 keyOption->SetFinalKeyDown(true);
377 keyOption->SetFinalKeyDownDuration(VOLUME_KEY_DURATION);
378 guard.CheckCurrTimeout();
379 int32_t keySubId = im->SubscribeKeyEvent(keyOption, [=](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
380 AUDIO_PRERELEASE_LOGI("Receive volume key event: %{public}s.",
381 (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ? "up" : "down");
382 int32_t ret = ProcessVolumeKeyMuteEvents(keyType);
383 if (ret != AUDIO_OK) {
384 AUDIO_DEBUG_LOG("process volume key mute events need return[%{public}d]", ret);
385 return;
386 }
387 });
388 if (keySubId < 0) {
389 AUDIO_ERR_LOG("key: %{public}s failed", (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ? "up" : "down");
390 return ERR_MMI_SUBSCRIBE;
391 }
392 return keySubId;
393 }
394
ProcessVolumeKeyMuteEvents(const int32_t keyType)395 int32_t AudioPolicyServer::ProcessVolumeKeyMuteEvents(const int32_t keyType)
396 {
397 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
398 AudioStreamType streamInFocus = AudioStreamType::STREAM_MUSIC; // use STREAM_MUSIC as default stream type
399 if (volumeApplyToAll_) {
400 streamInFocus = AudioStreamType::STREAM_ALL;
401 } else {
402 streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
403 ChangeVolumeOnVoiceAssistant(streamInFocus);
404 }
405 if (isScreenOffOrLock_ && !IsStreamActive(streamInFocus)) {
406 AUDIO_INFO_LOG("screen off or screen lock, this stream is not active, not change volume.");
407 return AUDIO_OK;
408 }
409 if (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP && GetStreamMuteInternal(streamInFocus)) {
410 AUDIO_INFO_LOG("VolumeKeyEvents: volumeKey: Up. volumeType %{public}d is mute. Unmute.", streamInFocus);
411 SetStreamMuteInternal(streamInFocus, false, true);
412 if (!VolumeUtils::IsPCVolumeEnable()) {
413 AUDIO_DEBUG_LOG("phone need return");
414 return ERROR_UNSUPPORTED;
415 }
416 }
417 if (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP && GetStreamMuteInternal(STREAM_SYSTEM) &&
418 VolumeUtils::IsPCVolumeEnable()) {
419 SetStreamMuteInternal(STREAM_SYSTEM, false, true);
420 }
421 int32_t volumeLevelInInt = GetSystemVolumeLevelInternal(streamInFocus);
422 if (MaxOrMinVolumeOption(volumeLevelInInt, keyType, streamInFocus)) {
423 AUDIO_ERR_LOG("volumelevel[%{public}d] invalid", volumeLevelInInt);
424 return ERROR_INVALID_PARAM;
425 }
426
427 volumeLevelInInt = (keyType == OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP) ? ++volumeLevelInInt : --volumeLevelInInt;
428 SetSystemVolumeLevelInternal(streamInFocus, volumeLevelInInt, true);
429 if (volumeLevelInInt <= 0 && VolumeUtils::IsPCVolumeEnable()) {
430 SetStreamMuteInternal(STREAM_SYSTEM, true, true);
431 }
432 return AUDIO_OK;
433 }
434 #endif
435
436 #ifdef FEATURE_MULTIMODALINPUT_INPUT
RegisterVolumeKeyMuteEvents()437 int32_t AudioPolicyServer::RegisterVolumeKeyMuteEvents()
438 {
439 AUDIO_INFO_LOG("RegisterVolumeKeyMuteEvents: volume key: mute");
440 MMI::InputManager *im = MMI::InputManager::GetInstance();
441 CHECK_AND_RETURN_RET_LOG(im != nullptr, ERR_MMI_CREATION, "Failed to obtain INPUT manager");
442
443 std::shared_ptr<OHOS::MMI::KeyOption> keyOptionMute = std::make_shared<OHOS::MMI::KeyOption>();
444 CHECK_AND_RETURN_RET_LOG(keyOptionMute != nullptr, ERR_NULL_POINTER, "keyOptionMute: Invalid key option");
445 std::set<int32_t> preKeys;
446 WatchTimeout guard("keyOption->SetPreKeys:RegisterVolumeKeyMuteEvents");
447 keyOptionMute->SetPreKeys(preKeys);
448 keyOptionMute->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_MUTE);
449 keyOptionMute->SetFinalKeyDown(true);
450 keyOptionMute->SetFinalKeyDownDuration(VOLUME_MUTE_KEY_DURATION);
451 keyOptionMute->SetRepeat(false);
452 guard.CheckCurrTimeout();
453 int32_t muteKeySubId = im->SubscribeKeyEvent(keyOptionMute,
454 [this](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
455 AUDIO_INFO_LOG("Receive volume key event: mute");
456 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
457 AudioStreamType streamInFocus = AudioStreamType::STREAM_MUSIC; // use STREAM_MUSIC as default stream type
458 if (volumeApplyToAll_) {
459 bool isStreamMuted = GetStreamMuteInternal(STREAM_ALL);
460 SetStreamMuteInternal(STREAM_ALL, !isStreamMuted, true);
461 } else {
462 streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
463 bool isMuted = GetStreamMuteInternal(streamInFocus);
464 SetStreamMuteInternal(streamInFocus, !isMuted, true);
465 }
466 });
467 if (muteKeySubId < 0) {
468 AUDIO_ERR_LOG("SubscribeKeyEvent: subscribing for mute failed ");
469 return ERR_MMI_SUBSCRIBE;
470 }
471 return muteKeySubId;
472 }
473 #endif
474
475 #ifdef FEATURE_MULTIMODALINPUT_INPUT
SubscribeVolumeKeyEvents()476 void AudioPolicyServer::SubscribeVolumeKeyEvents()
477 {
478 std::lock_guard<std::mutex> lock(subscribeVolumeKey_);
479 if (hasSubscribedVolumeKeyEvents_.load()) {
480 AUDIO_INFO_LOG("SubscribeVolumeKeyEvents: volume key events has been sunscirbed!");
481 return;
482 }
483
484 AUDIO_INFO_LOG("SubscribeVolumeKeyEvents: first time.");
485 int32_t resultOfVolumeUp = RegisterVolumeKeyEvents(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP);
486 SendMonitrtEvent(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP, resultOfVolumeUp);
487 int32_t resultOfVolumeDown = RegisterVolumeKeyEvents(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN);
488 SendMonitrtEvent(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN, resultOfVolumeDown);
489 int32_t resultOfMute = RegisterVolumeKeyMuteEvents();
490 SendMonitrtEvent(OHOS::MMI::KeyEvent::KEYCODE_MUTE, resultOfMute);
491 if (resultOfVolumeUp >= 0 && resultOfVolumeDown >= 0 && resultOfMute >= 0) {
492 hasSubscribedVolumeKeyEvents_.store(true);
493 } else {
494 AUDIO_ERR_LOG("SubscribeVolumeKeyEvents: failed to subscribe key events.");
495 hasSubscribedVolumeKeyEvents_.store(false);
496 }
497 }
498 #endif
499
SendMonitrtEvent(const int32_t keyType,int32_t resultOfVolumeKey)500 void AudioPolicyServer::SendMonitrtEvent(const int32_t keyType, int32_t resultOfVolumeKey)
501 {
502 std::shared_ptr<Media::MediaMonitor::EventBean> bean = std::make_shared<Media::MediaMonitor::EventBean>(
503 Media::MediaMonitor::ModuleId::AUDIO, Media::MediaMonitor::EventId::VOLUME_SUBSCRIBE,
504 Media::MediaMonitor::EventType::BEHAVIOR_EVENT);
505 bean->Add("SUBSCRIBE_KEY", TranslateKeyEvent(keyType));
506 bean->Add("SUBSCRIBE_RESULT", static_cast<int32_t>(TranslateErrorCode(resultOfVolumeKey)));
507 Media::MediaMonitor::MediaMonitorManager::GetInstance().WriteLogMsg(bean);
508 }
509
SubscribeSafeVolumeEvent()510 void AudioPolicyServer::SubscribeSafeVolumeEvent()
511 {
512 AUDIO_INFO_LOG("SubscribeSafeVolumeEvent enter");
513 audioPolicyService_.SubscribeSafeVolumeEvent();
514 }
515
IsVolumeTypeValid(AudioStreamType streamType)516 bool AudioPolicyServer::IsVolumeTypeValid(AudioStreamType streamType)
517 {
518 bool result = false;
519 switch (streamType) {
520 case STREAM_MUSIC:
521 case STREAM_RING:
522 case STREAM_NOTIFICATION:
523 case STREAM_VOICE_CALL:
524 case STREAM_VOICE_COMMUNICATION:
525 case STREAM_VOICE_ASSISTANT:
526 case STREAM_ALARM:
527 case STREAM_SYSTEM:
528 case STREAM_ACCESSIBILITY:
529 case STREAM_ULTRASONIC:
530 case STREAM_ALL:
531 case STREAM_VOICE_RING:
532 case STREAM_CAMCORDER:
533 result = true;
534 break;
535 default:
536 result = false;
537 AUDIO_ERR_LOG("IsVolumeTypeValid: streamType[%{public}d] is not supported", streamType);
538 break;
539 }
540 return result;
541 }
542
IsVolumeLevelValid(AudioStreamType streamType,int32_t volumeLevel)543 bool AudioPolicyServer::IsVolumeLevelValid(AudioStreamType streamType, int32_t volumeLevel)
544 {
545 bool result = true;
546 if (volumeLevel < audioPolicyService_.GetMinVolumeLevel(streamType) ||
547 volumeLevel > audioPolicyService_.GetMaxVolumeLevel(streamType)) {
548 AUDIO_ERR_LOG("IsVolumeLevelValid: volumeLevel[%{public}d] is out of valid range for streamType[%{public}d]",
549 volumeLevel, streamType);
550 result = false;
551 }
552 return result;
553 }
554
SubscribeOsAccountChangeEvents()555 void AudioPolicyServer::SubscribeOsAccountChangeEvents()
556 {
557 AUDIO_INFO_LOG("OnAddSystemAbility os_account service start");
558 if (accountObserver_ == nullptr) {
559 AccountSA::OsAccountSubscribeInfo osAccountSubscribeInfo;
560 osAccountSubscribeInfo.SetOsAccountSubscribeType(AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHED);
561 accountObserver_ = std::make_shared<AudioOsAccountInfo>(osAccountSubscribeInfo, this);
562 ErrCode errCode = AccountSA::OsAccountManager::SubscribeOsAccount(accountObserver_);
563 CHECK_AND_RETURN_LOG(errCode == ERR_OK, "account observer register fail");
564 AUDIO_INFO_LOG("account observer register success");
565 } else {
566 AUDIO_ERR_LOG("account observer register already");
567 }
568 }
569
AddAudioServiceOnStart()570 void AudioPolicyServer::AddAudioServiceOnStart()
571 {
572 AUDIO_INFO_LOG("OnAddSystemAbility audio service start");
573 if (!isFirstAudioServiceStart_) {
574 ConnectServiceAdapter();
575 sessionProcessor_.Start();
576 RegisterParamCallback();
577 LoadEffectLibrary();
578 isFirstAudioServiceStart_ = true;
579 } else {
580 AUDIO_WARNING_LOG("OnAddSystemAbility audio service is not first start");
581 }
582 }
583
AddRemoteDevstatusCallback()584 void AudioPolicyServer::AddRemoteDevstatusCallback()
585 {
586 AUDIO_INFO_LOG("add remote dev status callback start");
587 audioPolicyService_.RegisterRemoteDevStatusCallback();
588 }
589
SubscribePowerStateChangeEvents()590 void AudioPolicyServer::SubscribePowerStateChangeEvents()
591 {
592 sptr<PowerMgr::IPowerStateCallback> powerStateCallback_;
593
594 if (powerStateCallback_ == nullptr) {
595 powerStateCallback_ = new (std::nothrow) AudioPolicyServerPowerStateCallback(this);
596 }
597
598 if (powerStateCallback_ == nullptr) {
599 AUDIO_ERR_LOG("subscribe create power state callback Create Error");
600 return;
601 }
602
603 WatchTimeout guard("PowerMgr::PowerMgrClient::GetInstance().RegisterPowerStateCallback:AddRemoteDevstatus");
604 bool RegisterSuccess = PowerMgr::PowerMgrClient::GetInstance().RegisterPowerStateCallback(powerStateCallback_,
605 false);
606 guard.CheckCurrTimeout();
607 if (!RegisterSuccess) {
608 AUDIO_ERR_LOG("register power state callback failed");
609 } else {
610 AUDIO_INFO_LOG("register power state callback success");
611 powerStateCallbackRegister_ = true;
612 }
613 }
614
OnReceiveEvent(const EventFwk::CommonEventData & eventData)615 void AudioCommonEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
616 {
617 if (eventReceiver_ == nullptr) {
618 AUDIO_ERR_LOG("eventReceiver_ is nullptr");
619 return;
620 }
621 AUDIO_INFO_LOG("receive DATA_SHARE_READY action success");
622 eventReceiver_(eventData);
623 }
624
SubscribeCommonEventExecute()625 void AudioPolicyServer::SubscribeCommonEventExecute()
626 {
627 SubscribeCommonEvent("usual.event.DATA_SHARE_READY");
628 SubscribeCommonEvent("usual.event.dms.rotation_changed");
629 SubscribeCommonEvent("usual.event.bluetooth.remotedevice.NAME_UPDATE");
630 SubscribeCommonEvent("usual.event.SCREEN_ON");
631 SubscribeCommonEvent("usual.event.SCREEN_OFF");
632 SubscribeCommonEvent("usual.event.SCREEN_LOCKED");
633 SubscribeCommonEvent("usual.event.SCREEN_UNLOCKED");
634 #ifdef USB_ENABLE
635 AudioUsbManager::GetInstance().Init(&audioPolicyService_);
636 AudioUsbManager::GetInstance().SubscribeEvent();
637 #endif
638 SubscribeSafeVolumeEvent();
639 }
640
SubscribeCommonEvent(const std::string event)641 void AudioPolicyServer::SubscribeCommonEvent(const std::string event)
642 {
643 EventFwk::MatchingSkills matchingSkills;
644 matchingSkills.AddEvent(event);
645 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
646 if (event == "usual.event.dms.rotation_changed") {
647 subscribeInfo.SetPermission("ohos.permission.PUBLISH_DISPLAY_ROTATION_EVENT");
648 }
649 auto commonSubscribePtr = std::make_shared<AudioCommonEventSubscriber>(subscribeInfo,
650 std::bind(&AudioPolicyServer::OnReceiveEvent, this, std::placeholders::_1));
651 if (commonSubscribePtr == nullptr) {
652 AUDIO_ERR_LOG("commonSubscribePtr is nullptr");
653 return;
654 }
655 AUDIO_INFO_LOG("subscribe event: %s action", event.c_str());
656 EventFwk::CommonEventManager::SubscribeCommonEvent(commonSubscribePtr);
657 }
658
OnReceiveEvent(const EventFwk::CommonEventData & eventData)659 void AudioPolicyServer::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
660 {
661 const AAFwk::Want& want = eventData.GetWant();
662 std::string action = want.GetAction();
663 if (action == "usual.event.DATA_SHARE_READY") {
664 audioPolicyService_.SetDataShareReady(true);
665 RegisterDataObserver();
666 if (isInitMuteState_ == false) {
667 AUDIO_INFO_LOG("receive DATA_SHARE_READY action and need init mic mute state");
668 InitMicrophoneMute();
669 }
670 if (isInitSettingsData_ == false) {
671 AUDIO_INFO_LOG("First receive DATA_SHARE_READY action and need init SettingsData");
672 InitKVStore();
673 SettingsDataReady();
674 isInitSettingsData_ = true;
675 }
676 } else if (action == "usual.event.dms.rotation_changed") {
677 uint32_t rotate = static_cast<uint32_t>(want.GetIntParam("rotation", 0));
678 AUDIO_INFO_LOG("Set rotation to audioeffectchainmanager is %{public}d", rotate);
679 audioPolicyService_.SetRotationToEffect(rotate);
680 } else if (action == "usual.event.bluetooth.remotedevice.NAME_UPDATE") {
681 std::string deviceName = want.GetStringParam("remoteName");
682 std::string macAddress = want.GetStringParam("deviceAddr");
683 audioPolicyService_.OnReceiveBluetoothEvent(macAddress, deviceName);
684 } else if (action == "usual.event.SCREEN_ON") {
685 AUDIO_INFO_LOG("receive SCREEN_ON action, control audio focus if need");
686 audioPolicyService_.SetFirstScreenOn();
687 if (powerStateListener_ == nullptr) {
688 AUDIO_ERR_LOG("powerStateListener_ is nullptr");
689 return;
690 }
691 powerStateListener_->ControlAudioFocus(false);
692 } else if (action == "usual.event.SCREEN_LOCKED") {
693 AUDIO_INFO_LOG("receive SCREEN_OFF or SCREEN_LOCKED action, control audio volume change if stream is active");
694 isScreenOffOrLock_ = true;
695 } else if (action == "usual.event.SCREEN_UNLOCKED") {
696 AUDIO_INFO_LOG("receive SCREEN_UNLOCKED action, can change volume");
697 isScreenOffOrLock_ = false;
698 }
699 }
700
CheckSubscribePowerStateChange()701 void AudioPolicyServer::CheckSubscribePowerStateChange()
702 {
703 if (powerStateCallbackRegister_) {
704 return;
705 }
706
707 SubscribePowerStateChangeEvents();
708
709 if (powerStateCallbackRegister_) {
710 AUDIO_DEBUG_LOG("PowerState CallBack Register Success");
711 } else {
712 AUDIO_ERR_LOG("PowerState CallBack Register Failed");
713 }
714 }
715
OffloadStreamCheck(int64_t activateSessionId,int64_t deactivateSessionId)716 void AudioPolicyServer::OffloadStreamCheck(int64_t activateSessionId, int64_t deactivateSessionId)
717 {
718 CheckSubscribePowerStateChange();
719 if (deactivateSessionId != OFFLOAD_NO_SESSION_ID) {
720 audioPolicyService_.OffloadStreamReleaseCheck(deactivateSessionId);
721 }
722 if (activateSessionId != OFFLOAD_NO_SESSION_ID) {
723 audioPolicyService_.OffloadStreamSetCheck(activateSessionId);
724 }
725 }
726
AudioPolicyServerPowerStateCallback(AudioPolicyServer * policyServer)727 AudioPolicyServer::AudioPolicyServerPowerStateCallback::AudioPolicyServerPowerStateCallback(
728 AudioPolicyServer* policyServer) : PowerMgr::PowerStateCallbackStub(), policyServer_(policyServer)
729 {}
730
CheckStreamMode(const int64_t activateSessionId)731 void AudioPolicyServer::CheckStreamMode(const int64_t activateSessionId)
732 {
733 audioPolicyService_.CheckStreamMode(activateSessionId);
734 }
735
OnAsyncPowerStateChanged(PowerMgr::PowerState state)736 void AudioPolicyServer::AudioPolicyServerPowerStateCallback::OnAsyncPowerStateChanged(PowerMgr::PowerState state)
737 {
738 policyServer_->audioPolicyService_.HandlePowerStateChanged(state);
739 }
740
InitKVStore()741 void AudioPolicyServer::InitKVStore()
742 {
743 audioPolicyService_.InitKVStore();
744 }
745
SettingsDataReady()746 void AudioPolicyServer::SettingsDataReady()
747 {
748 audioPolicyService_.SettingsDataReady();
749 }
750
ConnectServiceAdapter()751 void AudioPolicyServer::ConnectServiceAdapter()
752 {
753 if (!audioPolicyService_.ConnectServiceAdapter()) {
754 AUDIO_ERR_LOG("ConnectServiceAdapter Error in connecting to audio service adapter");
755 return;
756 }
757 }
758
LoadEffectLibrary()759 void AudioPolicyServer::LoadEffectLibrary()
760 {
761 audioPolicyService_.LoadEffectLibrary();
762 }
763
GetMaxVolumeLevel(AudioVolumeType volumeType)764 int32_t AudioPolicyServer::GetMaxVolumeLevel(AudioVolumeType volumeType)
765 {
766 return audioPolicyService_.GetMaxVolumeLevel(volumeType);
767 }
768
GetMinVolumeLevel(AudioVolumeType volumeType)769 int32_t AudioPolicyServer::GetMinVolumeLevel(AudioVolumeType volumeType)
770 {
771 return audioPolicyService_.GetMinVolumeLevel(volumeType);
772 }
773
774 // deprecated since api 9.
SetSystemVolumeLevelLegacy(AudioStreamType streamType,int32_t volumeLevel)775 int32_t AudioPolicyServer::SetSystemVolumeLevelLegacy(AudioStreamType streamType, int32_t volumeLevel)
776 {
777 if (!IsVolumeTypeValid(streamType)) {
778 return ERR_NOT_SUPPORTED;
779 }
780 if (!IsVolumeLevelValid(streamType, volumeLevel)) {
781 return ERR_NOT_SUPPORTED;
782 }
783
784 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
785 return SetSystemVolumeLevelInternal(streamType, volumeLevel, false);
786 }
787
SetAppVolumeMuted(int32_t appUid,bool muted,int32_t volumeFlag)788 int32_t AudioPolicyServer::SetAppVolumeMuted(int32_t appUid, bool muted, int32_t volumeFlag)
789 {
790 if (!PermissionUtil::VerifySystemPermission()) {
791 AUDIO_ERR_LOG("SetAppVolumeLevel: No system permission");
792 return ERR_PERMISSION_DENIED;
793 }
794 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
795 return SetAppVolumeMutedInternal(appUid, muted, volumeFlag == VolumeFlag::FLAG_SHOW_SYSTEM_UI);
796 }
797
SetAppVolumeLevel(int32_t appUid,int32_t volumeLevel,int32_t volumeFlag)798 int32_t AudioPolicyServer::SetAppVolumeLevel(int32_t appUid, int32_t volumeLevel, int32_t volumeFlag)
799 {
800 if (!PermissionUtil::VerifySystemPermission()) {
801 AUDIO_ERR_LOG("SetAppVolumeLevel: No system permission");
802 return ERR_PERMISSION_DENIED;
803 }
804 if (!IsVolumeLevelValid(STREAM_APP, volumeLevel)) {
805 return ERR_NOT_SUPPORTED;
806 }
807 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
808 return SetAppVolumeLevelInternal(appUid, volumeLevel, volumeFlag == VolumeFlag::FLAG_SHOW_SYSTEM_UI);
809 }
810
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel,int32_t volumeFlag)811 int32_t AudioPolicyServer::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel, int32_t volumeFlag)
812 {
813 if (!PermissionUtil::VerifySystemPermission()) {
814 AUDIO_ERR_LOG("SetSystemVolumeLevel: No system permission");
815 return ERR_PERMISSION_DENIED;
816 }
817
818 if (!IsVolumeTypeValid(streamType)) {
819 return ERR_NOT_SUPPORTED;
820 }
821 if (!IsVolumeLevelValid(streamType, volumeLevel)) {
822 return ERR_NOT_SUPPORTED;
823 }
824
825 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
826 return SetSystemVolumeLevelInternal(streamType, volumeLevel, volumeFlag == VolumeFlag::FLAG_SHOW_SYSTEM_UI);
827 }
828
SetSystemVolumeLevelWithDevice(AudioStreamType streamType,int32_t volumeLevel,DeviceType deviceType,int32_t volumeFlag)829 int32_t AudioPolicyServer::SetSystemVolumeLevelWithDevice(AudioStreamType streamType, int32_t volumeLevel,
830 DeviceType deviceType, int32_t volumeFlag)
831 {
832 if (!PermissionUtil::VerifySystemPermission()) {
833 AUDIO_ERR_LOG("SetSystemVolumeLevelWithDevice: No system permission");
834 return ERR_PERMISSION_DENIED;
835 }
836
837 if (!IsVolumeTypeValid(streamType)) {
838 return ERR_NOT_SUPPORTED;
839 }
840 if (!IsVolumeLevelValid(streamType, volumeLevel)) {
841 return ERR_NOT_SUPPORTED;
842 }
843
844 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
845 return SetSystemVolumeLevelWithDeviceInternal(streamType, volumeLevel,
846 volumeFlag == VolumeFlag::FLAG_SHOW_SYSTEM_UI, deviceType);
847 }
848
GetSystemActiveVolumeType(const int32_t clientUid)849 AudioStreamType AudioPolicyServer::GetSystemActiveVolumeType(const int32_t clientUid)
850 {
851 return GetSystemActiveVolumeTypeInternal(clientUid);
852 }
853
GetSystemActiveVolumeTypeInternal(const int32_t clientUid)854 AudioStreamType AudioPolicyServer::GetSystemActiveVolumeTypeInternal(const int32_t clientUid)
855 {
856 if (!PermissionUtil::VerifySystemPermission()) {
857 AUDIO_ERR_LOG("No system permission");
858 return AudioStreamType::STREAM_MUSIC;
859 }
860 AudioStreamType streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
861 if (clientUid != 0) {
862 streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocusByUid(clientUid));
863 }
864
865 AUDIO_INFO_LOG("Get active volume type success:= %{public}d", streamInFocus);
866 return streamInFocus;
867 }
868
GetAppVolumeLevel(int32_t appUid)869 int32_t AudioPolicyServer::GetAppVolumeLevel(int32_t appUid)
870 {
871 AUDIO_INFO_LOG("GetAppVolumeLevel appUid : %{public}d", appUid);
872 if (!PermissionUtil::VerifySystemPermission()) {
873 AUDIO_ERR_LOG("only for system app");
874 return ERR_PERMISSION_DENIED;
875 }
876 return GetAppVolumeLevelInternal(appUid);
877 }
878
GetSelfAppVolumeLevel()879 int32_t AudioPolicyServer::GetSelfAppVolumeLevel()
880 {
881 AUDIO_INFO_LOG("GetSelfAppVolumeLevel enter");
882 int32_t appUid = IPCSkeleton::GetCallingUid();
883 return GetAppVolumeLevelInternal(appUid);
884 }
885
GetSystemVolumeLevel(AudioStreamType streamType)886 int32_t AudioPolicyServer::GetSystemVolumeLevel(AudioStreamType streamType)
887 {
888 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
889 return GetSystemVolumeLevelInternal(streamType);
890 }
891
GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)892 int32_t AudioPolicyServer::GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)
893 {
894 if (streamType == STREAM_ALL) {
895 streamType = STREAM_MUSIC;
896 }
897 int32_t volumeLevel = audioPolicyService_.GetSystemVolumeLevelNoMuteState(streamType);
898 AUDIO_DEBUG_LOG("GetVolumeNoMute streamType[%{public}d],volumeLevel[%{public}d]", streamType, volumeLevel);
899 return volumeLevel;
900 }
901
GetSystemVolumeLevelInternal(AudioStreamType streamType)902 int32_t AudioPolicyServer::GetSystemVolumeLevelInternal(AudioStreamType streamType)
903 {
904 if (streamType == STREAM_ALL) {
905 streamType = STREAM_MUSIC;
906 }
907 int32_t volumeLevel = audioPolicyService_.GetSystemVolumeLevel(streamType);
908 AUDIO_DEBUG_LOG("GetVolume streamType[%{public}d],volumeLevel[%{public}d]", streamType, volumeLevel);
909 return volumeLevel;
910 }
911
GetAppVolumeLevelInternal(int32_t appUid)912 int32_t AudioPolicyServer::GetAppVolumeLevelInternal(int32_t appUid)
913 {
914 int32_t volumeLevel = audioPolicyService_.GetAppVolumeLevel(appUid);
915 AUDIO_DEBUG_LOG("GetAppVolume appUid[%{public}d],volumeLevel[%{public}d]", appUid, volumeLevel);
916 return volumeLevel;
917 }
918
SetLowPowerVolume(int32_t streamId,float volume)919 int32_t AudioPolicyServer::SetLowPowerVolume(int32_t streamId, float volume)
920 {
921 auto callerUid = IPCSkeleton::GetCallingUid();
922 if (callerUid != UID_FOUNDATION_SA && callerUid != UID_RESOURCE_SCHEDULE_SERVICE) {
923 AUDIO_ERR_LOG("SetLowPowerVolume callerUid Error: not foundation or resource_schedule_service");
924 return ERROR;
925 }
926 return audioPolicyService_.SetLowPowerVolume(streamId, volume);
927 }
928
GetLowPowerVolume(int32_t streamId)929 float AudioPolicyServer::GetLowPowerVolume(int32_t streamId)
930 {
931 return audioPolicyService_.GetLowPowerVolume(streamId);
932 }
933
GetSingleStreamVolume(int32_t streamId)934 float AudioPolicyServer::GetSingleStreamVolume(int32_t streamId)
935 {
936 return audioPolicyService_.GetSingleStreamVolume(streamId);
937 }
938
IsVolumeUnadjustable()939 bool AudioPolicyServer::IsVolumeUnadjustable()
940 {
941 return audioPolicyService_.IsVolumeUnadjustable();
942 }
943
CheckCanMuteVolumeTypeByStep(AudioVolumeType volumeType,int32_t volumeLevel)944 bool AudioPolicyServer::CheckCanMuteVolumeTypeByStep(AudioVolumeType volumeType, int32_t volumeLevel)
945 {
946 if ((volumeLevel - volumeStep_) == 0 && !VolumeUtils::IsPCVolumeEnable() && (volumeType == STREAM_VOICE_ASSISTANT
947 || volumeType == STREAM_VOICE_CALL || volumeType == STREAM_ALARM || volumeType == STREAM_ACCESSIBILITY ||
948 volumeType == STREAM_VOICE_COMMUNICATION)) {
949 return false;
950 }
951 return true;
952 }
953
AdjustVolumeByStep(VolumeAdjustType adjustType)954 int32_t AudioPolicyServer::AdjustVolumeByStep(VolumeAdjustType adjustType)
955 {
956 auto callerUid = IPCSkeleton::GetCallingUid();
957 AUDIO_INFO_LOG("Uid %{public}d send AdjustVolumeByStep volume key: %{public}s.", callerUid,
958 (adjustType == VolumeAdjustType::VOLUME_UP) ? "up" : "down");
959 if (!PermissionUtil::VerifySystemPermission()) {
960 AUDIO_ERR_LOG("AdjustVolumeByStep: No system permission");
961 return ERR_PERMISSION_DENIED;
962 }
963
964 AudioStreamType streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(GetStreamInFocus());
965 if (streamInFocus == AudioStreamType::STREAM_DEFAULT) {
966 streamInFocus = AudioStreamType::STREAM_MUSIC;
967 }
968
969 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
970 int32_t volumeLevelInInt = 0;
971 if (GetStreamMuteInternal(streamInFocus)) {
972 SetStreamMuteInternal(streamInFocus, false, false);
973 }
974 volumeLevelInInt = GetSystemVolumeLevelInternal(streamInFocus);
975 int32_t minRet = GetMinVolumeLevel(streamInFocus);
976 int32_t maxRet = GetMaxVolumeLevel(streamInFocus);
977 if (adjustType == VolumeAdjustType::VOLUME_UP) {
978 CHECK_AND_RETURN_RET_LOG(volumeLevelInInt < maxRet, ERR_OPERATION_FAILED, "volumeLevelInInt is biggest");
979 volumeLevelInInt = volumeLevelInInt + volumeStep_;
980 } else {
981 if (!CheckCanMuteVolumeTypeByStep(streamInFocus, volumeLevelInInt)) {
982 // This type can not set to mute, but don't return error
983 AUDIO_INFO_LOG("SetSystemVolumeLevel this type can not set mute");
984 return SUCCESS;
985 }
986 CHECK_AND_RETURN_RET_LOG(volumeLevelInInt > minRet, ERR_OPERATION_FAILED, "volumeLevelInInt is smallest");
987 volumeLevelInInt = volumeLevelInInt - volumeStep_;
988 }
989 volumeLevelInInt = volumeLevelInInt > GetMaxVolumeLevel(streamInFocus) ? GetMaxVolumeLevel(streamInFocus) :
990 volumeLevelInInt;
991 volumeLevelInInt = volumeLevelInInt < GetMinVolumeLevel(streamInFocus) ? GetMinVolumeLevel(streamInFocus) :
992 volumeLevelInInt;
993 int32_t ret = SetSystemVolumeLevelInternal(streamInFocus, volumeLevelInInt, false);
994 return ret;
995 }
996
AdjustSystemVolumeByStep(AudioVolumeType volumeType,VolumeAdjustType adjustType)997 int32_t AudioPolicyServer::AdjustSystemVolumeByStep(AudioVolumeType volumeType, VolumeAdjustType adjustType)
998 {
999 auto callerUid = IPCSkeleton::GetCallingUid();
1000 AUDIO_INFO_LOG("Uid %{public}d send AdjustSystemVolumeByStep VolumeType: %{public}d volume key: %{public}s.",
1001 callerUid, volumeType, (adjustType == VolumeAdjustType::VOLUME_UP) ? "up" : "down");
1002 if (!PermissionUtil::VerifySystemPermission()) {
1003 AUDIO_ERR_LOG("AdjustSystemVolumeByStep: No system permission");
1004 return ERR_PERMISSION_DENIED;
1005 }
1006
1007 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1008 int32_t volumeLevelInInt = GetSystemVolumeLevelInternal(volumeType);
1009 int32_t minRet = GetMinVolumeLevel(volumeType);
1010 int32_t maxRet = GetMaxVolumeLevel(volumeType);
1011 if (adjustType == VolumeAdjustType::VOLUME_UP) {
1012 CHECK_AND_RETURN_RET_LOG(volumeLevelInInt < maxRet, ERR_OPERATION_FAILED, "volumeLevelInInt is biggest");
1013 volumeLevelInInt = volumeLevelInInt + volumeStep_;
1014 } else {
1015 if (!CheckCanMuteVolumeTypeByStep(volumeType, volumeLevelInInt)) {
1016 // This type can not set to mute, but don't return error
1017 AUDIO_INFO_LOG("SetSystemVolumeLevel this type can not set mute");
1018 return SUCCESS;
1019 }
1020 CHECK_AND_RETURN_RET_LOG(volumeLevelInInt > minRet, ERR_OPERATION_FAILED, "volumeLevelInInt is smallest");
1021 volumeLevelInInt = volumeLevelInInt - volumeStep_;
1022 }
1023 volumeLevelInInt = volumeLevelInInt > GetMaxVolumeLevel(volumeType) ? GetMaxVolumeLevel(volumeType) :
1024 volumeLevelInInt;
1025 volumeLevelInInt = volumeLevelInInt < GetMinVolumeLevel(volumeType) ? GetMinVolumeLevel(volumeType) :
1026 volumeLevelInInt;
1027 int32_t ret = SetSystemVolumeLevelInternal(volumeType, volumeLevelInInt, false);
1028 return ret;
1029 }
1030
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType)1031 float AudioPolicyServer::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, DeviceType deviceType)
1032 {
1033 if (!IsVolumeTypeValid(volumeType)) {
1034 return static_cast<float>(ERR_INVALID_PARAM);
1035 }
1036 if (!IsVolumeLevelValid(volumeType, volumeLevel)) {
1037 return static_cast<float>(ERR_INVALID_PARAM);
1038 }
1039
1040 return audioPolicyService_.GetSystemVolumeInDb(volumeType, volumeLevel, deviceType);
1041 }
1042
1043 // deprecated since api 9.
SetStreamMuteLegacy(AudioStreamType streamType,bool mute,const DeviceType & deviceType)1044 int32_t AudioPolicyServer::SetStreamMuteLegacy(AudioStreamType streamType, bool mute, const DeviceType &deviceType)
1045 {
1046 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1047 return SetStreamMuteInternal(streamType, mute, false, deviceType);
1048 }
1049
SetStreamMute(AudioStreamType streamType,bool mute,const DeviceType & deviceType)1050 int32_t AudioPolicyServer::SetStreamMute(AudioStreamType streamType, bool mute, const DeviceType &deviceType)
1051 {
1052 if (!PermissionUtil::VerifySystemPermission()) {
1053 AUDIO_ERR_LOG("No system permission");
1054 return ERR_PERMISSION_DENIED;
1055 }
1056
1057 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1058 return SetStreamMuteInternal(streamType, mute, false, deviceType);
1059 }
1060
SetStreamMuteInternal(AudioStreamType streamType,bool mute,bool isUpdateUi,const DeviceType & deviceType)1061 int32_t AudioPolicyServer::SetStreamMuteInternal(AudioStreamType streamType, bool mute, bool isUpdateUi,
1062 const DeviceType &deviceType)
1063 {
1064 AUDIO_INFO_LOG("SetStreamMuteInternal streamType: %{public}d, mute: %{public}d, updateUi: %{public}d",
1065 streamType, mute, isUpdateUi);
1066
1067 if (streamType == STREAM_ALL) {
1068 const std::vector<AudioStreamType> &streamTypeArray =
1069 (VolumeUtils::IsPCVolumeEnable())? GET_PC_STREAM_ALL_VOLUME_TYPES : GET_STREAM_ALL_VOLUME_TYPES;
1070 for (auto audioStreamType : streamTypeArray) {
1071 AUDIO_INFO_LOG("SetMute of STREAM_ALL for StreamType = %{public}d ", audioStreamType);
1072 int32_t setResult = SetSingleStreamMute(audioStreamType, mute, isUpdateUi, deviceType);
1073 if (setResult != SUCCESS) {
1074 return setResult;
1075 }
1076 }
1077 return SUCCESS;
1078 }
1079
1080 return SetSingleStreamMute(streamType, mute, isUpdateUi, deviceType);
1081 }
1082
UpdateSystemMuteStateAccordingMusicState(AudioStreamType streamType,bool mute,bool isUpdateUi)1083 void AudioPolicyServer::UpdateSystemMuteStateAccordingMusicState(AudioStreamType streamType, bool mute, bool isUpdateUi)
1084 {
1085 // This function only applies to mute/unmute scenarios where the input type is music on the PC platform
1086 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) != AudioStreamType::STREAM_MUSIC ||
1087 !VolumeUtils::IsPCVolumeEnable()) {
1088 return;
1089 }
1090 if (mute && !GetStreamMuteInternal(STREAM_SYSTEM)) {
1091 // If the STREAM_MUSIC wants mute, synchronize the mute STREAM_SYSTEM
1092 audioPolicyService_.SetStreamMute(STREAM_SYSTEM, mute);
1093 SendMuteKeyEventCbWithUpdateUiOrNot(STREAM_SYSTEM, isUpdateUi);
1094 AUDIO_WARNING_LOG("music is mute or volume change to 0 and need mute system stream");
1095 } else if (!mute && GetStreamMuteInternal(STREAM_SYSTEM)) {
1096 // If you STREAM_MUSIC unmute, you need to determine whether the volume is 0
1097 // if it is 0, the prompt sound will continue to be mute, and if it is not 0
1098 // you need to synchronize the unmute prompt sound
1099 bool isMute = (GetSystemVolumeLevelInternal(STREAM_MUSIC) == 0) ? true : false;
1100 audioPolicyService_.SetStreamMute(STREAM_SYSTEM, isMute);
1101 SendMuteKeyEventCbWithUpdateUiOrNot(STREAM_SYSTEM, isUpdateUi);
1102 AUDIO_WARNING_LOG("music is unmute and volume is 0 and need %{public}d system stream", isMute);
1103 }
1104 }
1105
SendMuteKeyEventCbWithUpdateUiOrNot(AudioStreamType streamType,const bool & isUpdateUi)1106 void AudioPolicyServer::SendMuteKeyEventCbWithUpdateUiOrNot(AudioStreamType streamType, const bool& isUpdateUi)
1107 {
1108 VolumeEvent volumeEvent;
1109 volumeEvent.volumeType = streamType;
1110 volumeEvent.volume = GetSystemVolumeLevelInternal(streamType);
1111 volumeEvent.updateUi = isUpdateUi;
1112 volumeEvent.volumeGroupId = 0;
1113 volumeEvent.networkId = LOCAL_NETWORK_ID;
1114 if (audioPolicyServerHandler_ != nullptr) {
1115 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
1116 }
1117 }
1118
SetSingleStreamMute(AudioStreamType streamType,bool mute,bool isUpdateUi,const DeviceType & deviceType)1119 int32_t AudioPolicyServer::SetSingleStreamMute(AudioStreamType streamType, bool mute, bool isUpdateUi,
1120 const DeviceType &deviceType)
1121 {
1122 bool updateRingerMode = false;
1123 if ((streamType == AudioStreamType::STREAM_RING || streamType == AudioStreamType::STREAM_VOICE_RING) &&
1124 VolumeUtils::GetVolumeTypeFromStreamType(streamType) == AudioStreamType::STREAM_RING) {
1125 // Check whether the currentRingerMode is suitable for the ringtone mute state.
1126 AudioRingerMode currentRingerMode = audioPolicyService_.GetRingerMode();
1127 if ((currentRingerMode == RINGER_MODE_NORMAL && mute) || (currentRingerMode != RINGER_MODE_NORMAL && !mute)) {
1128 // When isUpdateUi is false, the func is called by others. Need to verify permission.
1129 if (!isUpdateUi && !VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
1130 AUDIO_ERR_LOG("ACCESS_NOTIFICATION_POLICY_PERMISSION permission denied for ringtone mute state!");
1131 return ERR_PERMISSION_DENIED;
1132 }
1133 updateRingerMode = true;
1134 }
1135 }
1136
1137 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == AudioStreamType::STREAM_SYSTEM &&
1138 !mute && (GetSystemVolumeLevelNoMuteState(STREAM_MUSIC) == 0 || GetStreamMuteInternal(STREAM_MUSIC))) {
1139 // when music type volume is not mute,system type volume can be muted separately.
1140 // but when trying to mute system type volume while the volume for music type is mute
1141 // or volume level is 0,system type volume can not be muted.
1142 AUDIO_WARNING_LOG("music volume is 0 or mute and no need unmute system stream!");
1143 } else {
1144 int32_t result = audioPolicyService_.SetStreamMute(streamType, mute, STREAM_USAGE_UNKNOWN, deviceType);
1145 CHECK_AND_RETURN_RET_LOG(result == SUCCESS, result, "Fail to set stream mute!");
1146 }
1147
1148 if (!mute && GetSystemVolumeLevelInternal(streamType) == 0 && !VolumeUtils::IsPCVolumeEnable()) {
1149 // If mute state is set to false but volume is 0, set volume to 1
1150 audioPolicyService_.SetSystemVolumeLevel(streamType, 1);
1151 }
1152
1153 ProcUpdateRingerModeForMute(updateRingerMode, mute);
1154 SendMuteKeyEventCbWithUpdateUiOrNot(streamType, isUpdateUi);
1155 UpdateSystemMuteStateAccordingMusicState(streamType, mute, isUpdateUi);
1156 return SUCCESS;
1157 }
1158
ProcUpdateRingerModeForMute(bool updateRingerMode,bool mute)1159 void AudioPolicyServer::ProcUpdateRingerModeForMute(bool updateRingerMode, bool mute)
1160 {
1161 if (updateRingerMode) {
1162 AudioRingerMode ringerMode = mute ? (supportVibrator_ ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT) :
1163 RINGER_MODE_NORMAL;
1164 if (!supportVibrator_) {
1165 AUDIO_INFO_LOG("The device does not support vibration");
1166 }
1167 AUDIO_INFO_LOG("RingerMode should be set to %{public}d because of ring mute state", ringerMode);
1168 // Update ringer mode but no need to update mute state again.
1169 SetRingerModeInternal(ringerMode, true);
1170 }
1171 }
1172
GetSystemVolumeDb(AudioStreamType streamType)1173 float AudioPolicyServer::GetSystemVolumeDb(AudioStreamType streamType)
1174 {
1175 return audioPolicyService_.GetSystemVolumeDb(streamType);
1176 }
1177
SetSelfAppVolumeLevel(int32_t volumeLevel,int32_t volumeFlag)1178 int32_t AudioPolicyServer::SetSelfAppVolumeLevel(int32_t volumeLevel, int32_t volumeFlag)
1179 {
1180 AUDIO_INFO_LOG("SetSelfAppVolumeLevel volumeLevel: %{public}d, volumeFlag: %{public}d",
1181 volumeLevel, volumeFlag);
1182 if (!IsVolumeLevelValid(STREAM_APP, volumeLevel)) {
1183 return ERR_NOT_SUPPORTED;
1184 }
1185 int32_t appUid = IPCSkeleton::GetCallingUid();
1186 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1187 return SetAppVolumeLevelInternal(appUid, volumeLevel, volumeFlag == VolumeFlag::FLAG_SHOW_SYSTEM_UI);
1188 }
1189
SetAppVolumeLevelInternal(int32_t appUid,int32_t volumeLevel,bool isUpdateUi)1190 int32_t AudioPolicyServer::SetAppVolumeLevelInternal(int32_t appUid, int32_t volumeLevel, bool isUpdateUi)
1191 {
1192 AUDIO_INFO_LOG("SetAppVolumeLevelInternal appUid: %{public}d, volumeLevel: %{public}d, updateUi: %{public}d",
1193 appUid, volumeLevel, isUpdateUi);
1194 return SetAppSingleStreamVolume(appUid, volumeLevel, isUpdateUi);
1195 }
1196
SetAppVolumeMutedInternal(int32_t appUid,bool muted,bool isUpdateUi)1197 int32_t AudioPolicyServer::SetAppVolumeMutedInternal(int32_t appUid, bool muted, bool isUpdateUi)
1198 {
1199 AUDIO_INFO_LOG("SetAppVolumeLevelInternal appUid: %{public}d, muted: %{public}d, updateUi: %{public}d",
1200 appUid, muted, isUpdateUi);
1201 int32_t ret = audioPolicyService_.SetAppVolumeMuted(appUid, muted);
1202 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fail to set App Volume mute");
1203 return ret;
1204 }
1205
IsAppVolumeMute(int32_t appUid,bool owned)1206 bool AudioPolicyServer::IsAppVolumeMute(int32_t appUid, bool owned)
1207 {
1208 AUDIO_INFO_LOG("IsAppVolumeMute appUid: %{public}d, owned: %{public}d", appUid, owned);
1209 if (!PermissionUtil::VerifySystemPermission()) {
1210 AUDIO_ERR_LOG("only for system app");
1211 return ERR_PERMISSION_DENIED;
1212 }
1213 bool ret = audioPolicyService_.IsAppVolumeMute(appUid, owned);
1214 return ret;
1215 }
1216
SetSystemVolumeLevelInternal(AudioStreamType streamType,int32_t volumeLevel,bool isUpdateUi)1217 int32_t AudioPolicyServer::SetSystemVolumeLevelInternal(AudioStreamType streamType, int32_t volumeLevel,
1218 bool isUpdateUi)
1219 {
1220 AUDIO_INFO_LOG("SetSystemVolumeLevelInternal streamType: %{public}d, volumeLevel: %{public}d, updateUi: %{public}d",
1221 streamType, volumeLevel, isUpdateUi);
1222 if (IsVolumeUnadjustable()) {
1223 AUDIO_ERR_LOG("Unadjustable device, not allow set volume");
1224 return ERR_OPERATION_FAILED;
1225 }
1226 bool mute = GetStreamMuteInternal(streamType);
1227 if (streamType == STREAM_ALL) {
1228 const std::vector<AudioStreamType> &streamTypeArray =
1229 (VolumeUtils::IsPCVolumeEnable()) ? GET_PC_STREAM_ALL_VOLUME_TYPES : GET_STREAM_ALL_VOLUME_TYPES;
1230 for (auto audioStreamType : streamTypeArray) {
1231 AUDIO_INFO_LOG("SetVolume of STREAM_ALL, SteamType = %{public}d, mute = %{public}d, level = %{public}d",
1232 audioStreamType, mute, volumeLevel);
1233 int32_t setResult = SetSingleStreamVolume(audioStreamType, volumeLevel, isUpdateUi, mute);
1234 if (setResult != SUCCESS && setResult != ERR_SET_VOL_FAILED_BY_SAFE_VOL) {
1235 return setResult;
1236 }
1237 }
1238 return SUCCESS;
1239 }
1240 return SetSingleStreamVolume(streamType, volumeLevel, isUpdateUi, mute);
1241 }
1242
SetSystemVolumeLevelWithDeviceInternal(AudioStreamType streamType,int32_t volumeLevel,bool isUpdateUi,DeviceType deviceType)1243 int32_t AudioPolicyServer::SetSystemVolumeLevelWithDeviceInternal(AudioStreamType streamType, int32_t volumeLevel,
1244 bool isUpdateUi, DeviceType deviceType)
1245 {
1246 AUDIO_INFO_LOG("SetSystemVolumeLevelWithDeviceInternal streamType: %{public}d, volumeLevel: %{public}d, "
1247 "updateUi: %{public}d, deviceType: %{public}d", streamType, volumeLevel, isUpdateUi, deviceType);
1248 if (IsVolumeUnadjustable()) {
1249 AUDIO_ERR_LOG("Unadjustable device, not allow set volume");
1250 return ERR_OPERATION_FAILED;
1251 }
1252 bool mute = GetStreamMuteInternal(streamType);
1253 return SetSingleStreamVolumeWithDevice(streamType, volumeLevel, isUpdateUi, mute, deviceType);
1254 }
1255
SendVolumeKeyEventCbWithUpdateUiOrNot(AudioStreamType streamType,const bool & isUpdateUi)1256 void AudioPolicyServer::SendVolumeKeyEventCbWithUpdateUiOrNot(AudioStreamType streamType, const bool& isUpdateUi)
1257 {
1258 VolumeEvent volumeEvent;
1259 volumeEvent.volumeType = streamType;
1260 volumeEvent.volume = GetSystemVolumeLevelInternal(streamType);
1261 volumeEvent.updateUi = isUpdateUi;
1262 volumeEvent.volumeGroupId = 0;
1263 volumeEvent.networkId = LOCAL_NETWORK_ID;
1264 bool ringerModeMute = audioPolicyService_.IsRingerModeMute();
1265 if (audioPolicyServerHandler_ != nullptr && ringerModeMute) {
1266 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
1267 }
1268 }
1269
UpdateMuteStateAccordingToVolLevel(AudioStreamType streamType,int32_t volumeLevel,bool mute,const bool & isUpdateUi)1270 void AudioPolicyServer::UpdateMuteStateAccordingToVolLevel(AudioStreamType streamType, int32_t volumeLevel,
1271 bool mute, const bool& isUpdateUi)
1272 {
1273 bool muteStatus = mute;
1274 if (volumeLevel == 0 && !mute) {
1275 muteStatus = true;
1276 audioPolicyService_.SetStreamMute(streamType, true);
1277 } else if (volumeLevel > 0 && mute) {
1278 muteStatus = false;
1279 audioPolicyService_.SetStreamMute(streamType, false);
1280 }
1281 SendVolumeKeyEventCbWithUpdateUiOrNot(streamType, isUpdateUi);
1282 if (VolumeUtils::IsPCVolumeEnable()) {
1283 // system mute status should be aligned with music mute status.
1284 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
1285 muteStatus != GetStreamMuteInternal(STREAM_SYSTEM)) {
1286 AUDIO_DEBUG_LOG("set system mute to %{public}d when STREAM_MUSIC.", muteStatus);
1287 audioPolicyService_.SetStreamMute(STREAM_SYSTEM, muteStatus);
1288 SendVolumeKeyEventCbWithUpdateUiOrNot(STREAM_SYSTEM);
1289 } else if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_SYSTEM &&
1290 muteStatus != GetStreamMuteInternal(STREAM_MUSIC)) {
1291 bool isMute = (GetSystemVolumeLevelInternal(STREAM_MUSIC) == 0) ? true : false;
1292 AUDIO_DEBUG_LOG("set system same to music muted or level is zero to %{public}d.", isMute);
1293 audioPolicyService_.SetStreamMute(STREAM_SYSTEM, isMute);
1294 SendVolumeKeyEventCbWithUpdateUiOrNot(STREAM_SYSTEM);
1295 }
1296 }
1297 }
1298
ProcUpdateRingerMode()1299 void AudioPolicyServer::ProcUpdateRingerMode()
1300 {
1301 int32_t curRingVolumeLevel = GetSystemVolumeLevelNoMuteState(STREAM_RING);
1302 AudioRingerMode ringerMode = (curRingVolumeLevel > 0) ? RINGER_MODE_NORMAL :
1303 (supportVibrator_ ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT);
1304 if (!supportVibrator_) {
1305 AUDIO_INFO_LOG("The device does not support vibration");
1306 }
1307 AUDIO_INFO_LOG("RingerMode should be set to %{public}d because of ring volume level", ringerMode);
1308 // Update ringer mode but no need to update volume again.
1309 SetRingerModeInternal(ringerMode, true);
1310 }
1311
SetAppSingleStreamVolume(int32_t appUid,int32_t volumeLevel,bool isUpdateUi)1312 int32_t AudioPolicyServer::SetAppSingleStreamVolume(int32_t appUid, int32_t volumeLevel, bool isUpdateUi)
1313 {
1314 int32_t ret = audioPolicyService_.SetAppVolumeLevel(appUid, volumeLevel);
1315 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fail to set App Volume level");
1316
1317 VolumeEvent volumeEvent;
1318 volumeEvent.volumeType = STREAM_APP;
1319 volumeEvent.volume = volumeLevel;
1320 volumeEvent.updateUi = isUpdateUi;
1321 volumeEvent.volumeGroupId = 0;
1322 volumeEvent.networkId = LOCAL_NETWORK_ID;
1323 volumeEvent.volumeMode = AUDIOSTREAM_VOLUMEMODE_APP_INDIVIDUAL;
1324 if (audioPolicyServerHandler_ != nullptr) {
1325 audioPolicyServerHandler_->SendAppVolumeChangeCallback(appUid, volumeEvent);
1326 }
1327 return ret;
1328 }
1329
SetSingleStreamVolume(AudioStreamType streamType,int32_t volumeLevel,bool isUpdateUi,bool mute)1330 int32_t AudioPolicyServer::SetSingleStreamVolume(AudioStreamType streamType, int32_t volumeLevel, bool isUpdateUi,
1331 bool mute)
1332 {
1333 bool updateRingerMode = false;
1334 if ((streamType == AudioStreamType::STREAM_RING || streamType == AudioStreamType::STREAM_VOICE_RING) &&
1335 VolumeUtils::GetVolumeTypeFromStreamType(streamType) == AudioStreamType::STREAM_RING) {
1336 // Check whether the currentRingerMode is suitable for the ringtone volume level.
1337 AudioRingerMode currentRingerMode = audioPolicyService_.GetRingerMode();
1338 if ((currentRingerMode == RINGER_MODE_NORMAL && volumeLevel == 0) ||
1339 (currentRingerMode != RINGER_MODE_NORMAL && volumeLevel > 0)) {
1340 // When isUpdateUi is false, the func is called by others. Need to verify permission.
1341 if (!isUpdateUi && !VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
1342 AUDIO_ERR_LOG("ACCESS_NOTIFICATION_POLICY_PERMISSION permission denied for ringtone volume!");
1343 return ERR_PERMISSION_DENIED;
1344 }
1345 updateRingerMode = true;
1346 }
1347 }
1348
1349 int32_t ret = audioPolicyService_.SetSystemVolumeLevel(streamType, volumeLevel);
1350 if (ret == SUCCESS) {
1351 if (updateRingerMode) {
1352 ProcUpdateRingerMode();
1353 }
1354 UpdateMuteStateAccordingToVolLevel(streamType, volumeLevel, mute, isUpdateUi);
1355 } else if (ret == ERR_SET_VOL_FAILED_BY_SAFE_VOL) {
1356 SendVolumeKeyEventCbWithUpdateUiOrNot(streamType, isUpdateUi);
1357 AUDIO_ERR_LOG("fail to set system volume level by safe vol");
1358 } else {
1359 AUDIO_ERR_LOG("fail to set system volume level, ret is %{public}d", ret);
1360 }
1361
1362 return ret;
1363 }
1364
SetSingleStreamVolumeWithDevice(AudioStreamType streamType,int32_t volumeLevel,bool isUpdateUi,bool mute,DeviceType deviceType)1365 int32_t AudioPolicyServer::SetSingleStreamVolumeWithDevice(AudioStreamType streamType, int32_t volumeLevel,
1366 bool isUpdateUi, bool mute, DeviceType deviceType)
1367 {
1368 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1369 int32_t ret = SUCCESS;
1370 if (curOutputDeviceType != deviceType) {
1371 ret = audioPolicyService_.SetSystemVolumeLevelWithDevice(streamType, volumeLevel, deviceType);
1372 } else {
1373 ret = SetSingleStreamVolume(streamType, volumeLevel, isUpdateUi, mute);
1374 }
1375 return ret;
1376 }
1377
GetStreamMute(AudioStreamType streamType)1378 bool AudioPolicyServer::GetStreamMute(AudioStreamType streamType)
1379 {
1380 if (streamType == AudioStreamType::STREAM_RING || streamType == AudioStreamType::STREAM_VOICE_RING) {
1381 bool ret = VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION);
1382 CHECK_AND_RETURN_RET_LOG(ret, false,
1383 "GetStreamMute permission denied for stream type : %{public}d", streamType);
1384 }
1385 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1386 return GetStreamMuteInternal(streamType);
1387 }
1388
GetStreamMuteInternal(AudioStreamType streamType)1389 bool AudioPolicyServer::GetStreamMuteInternal(AudioStreamType streamType)
1390 {
1391 if (streamType == STREAM_ALL) {
1392 streamType = STREAM_MUSIC;
1393 }
1394 bool isMuted = audioPolicyService_.GetStreamMute(streamType);
1395 AUDIO_DEBUG_LOG("GetMute streamType[%{public}d],mute[%{public}d]", streamType, isMuted);
1396 return isMuted;
1397 }
1398
IsArmUsbDevice(const AudioDeviceDescriptor & desc)1399 bool AudioPolicyServer::IsArmUsbDevice(const AudioDeviceDescriptor &desc)
1400 {
1401 if (desc.deviceType_ == DEVICE_TYPE_USB_ARM_HEADSET) return true;
1402 if (desc.deviceType_ != DEVICE_TYPE_USB_HEADSET) return false;
1403
1404 return audioPolicyService_.IsArmUsbDevice(desc);
1405 }
1406
MapExternalToInternalDeviceType(AudioDeviceDescriptor & desc)1407 void AudioPolicyServer::MapExternalToInternalDeviceType(AudioDeviceDescriptor &desc)
1408 {
1409 if (desc.deviceType_ == DEVICE_TYPE_USB_HEADSET || desc.deviceType_ == DEVICE_TYPE_USB_DEVICE) {
1410 auto item = audioDeviceManager_.FindConnectedDeviceById(desc.deviceId_);
1411 if (item && IsUsb(item->deviceType_)) {
1412 desc.deviceType_ = item->deviceType_;
1413 }
1414 } else if (desc.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && desc.deviceRole_ == INPUT_DEVICE) {
1415 desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP_IN;
1416 }
1417 }
1418
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors)1419 int32_t AudioPolicyServer::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
1420 std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
1421 {
1422 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED,
1423 "SelectOutputDevice: No system permission");
1424
1425 return audioPolicyService_.SelectOutputDevice(audioRendererFilter, audioDeviceDescriptors);
1426 }
1427
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)1428 std::string AudioPolicyServer::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
1429 {
1430 return audioPolicyService_.GetSelectedDeviceInfo(uid, pid, streamType);
1431 }
1432
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors)1433 int32_t AudioPolicyServer::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
1434 std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
1435 {
1436 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED,
1437 "SelectInputDevice: No system permission");
1438 int32_t ret = audioPolicyService_.SelectInputDevice(audioCapturerFilter, audioDeviceDescriptors);
1439 return ret;
1440 }
1441
ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,vector<shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)1442 int32_t AudioPolicyServer::ExcludeOutputDevices(AudioDeviceUsage audioDevUsage,
1443 vector<shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
1444 {
1445 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED,
1446 "No system permission");
1447
1448 return audioPolicyService_.ExcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
1449 }
1450
UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,vector<shared_ptr<AudioDeviceDescriptor>> & audioDeviceDescriptors)1451 int32_t AudioPolicyServer::UnexcludeOutputDevices(AudioDeviceUsage audioDevUsage,
1452 vector<shared_ptr<AudioDeviceDescriptor>> &audioDeviceDescriptors)
1453 {
1454 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), ERR_PERMISSION_DENIED,
1455 "No system permission");
1456
1457 return audioPolicyService_.UnexcludeOutputDevices(audioDevUsage, audioDeviceDescriptors);
1458 }
1459
GetExcludedDevices(AudioDeviceUsage audioDevUsage)1460 vector<shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetExcludedDevices(AudioDeviceUsage audioDevUsage)
1461 {
1462 CHECK_AND_RETURN_RET_LOG(PermissionUtil::VerifySystemPermission(), vector<shared_ptr<AudioDeviceDescriptor>>(),
1463 "No system permission");
1464
1465 return audioPolicyService_.GetExcludedDevices(audioDevUsage);
1466 }
1467
GetDevices(DeviceFlag deviceFlag)1468 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetDevices(DeviceFlag deviceFlag)
1469 {
1470 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1471 switch (deviceFlag) {
1472 case NONE_DEVICES_FLAG:
1473 case DISTRIBUTED_OUTPUT_DEVICES_FLAG:
1474 case DISTRIBUTED_INPUT_DEVICES_FLAG:
1475 case ALL_DISTRIBUTED_DEVICES_FLAG:
1476 case ALL_L_D_DEVICES_FLAG:
1477 if (!hasSystemPermission) {
1478 AUDIO_ERR_LOG("GetDevices: No system permission");
1479 std::vector<std::shared_ptr<AudioDeviceDescriptor>> info = {};
1480 return info;
1481 }
1482 break;
1483 default:
1484 break;
1485 }
1486
1487 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescs = audioPolicyService_.GetDevices(deviceFlag);
1488
1489 if (!hasSystemPermission) {
1490 for (std::shared_ptr<AudioDeviceDescriptor> desc : deviceDescs) {
1491 desc->networkId_ = "";
1492 desc->interruptGroupId_ = GROUP_ID_NONE;
1493 desc->volumeGroupId_ = GROUP_ID_NONE;
1494 }
1495 }
1496
1497 bool hasBTPermission = VerifyBluetoothPermission();
1498 if (!hasBTPermission) {
1499 audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDescs);
1500 }
1501
1502 return deviceDescs;
1503 }
1504
GetDevicesInner(DeviceFlag deviceFlag)1505 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetDevicesInner(DeviceFlag deviceFlag)
1506 {
1507 auto callerUid = IPCSkeleton::GetCallingUid();
1508 if (callerUid != UID_AUDIO) {
1509 return {};
1510 }
1511 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescs = audioPolicyService_.GetDevicesInner(deviceFlag);
1512
1513 return deviceDescs;
1514 }
1515
GetOutputDevice(sptr<AudioRendererFilter> audioRendererFilter)1516 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetOutputDevice(
1517 sptr<AudioRendererFilter> audioRendererFilter)
1518 {
1519 if (!PermissionUtil::VerifySystemPermission()) {
1520 AUDIO_ERR_LOG("only for system app");
1521 return {};
1522 }
1523 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescs =
1524 audioPolicyService_.GetOutputDevice(audioRendererFilter);
1525 return deviceDescs;
1526 }
1527
GetInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter)1528 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetInputDevice(
1529 sptr<AudioCapturerFilter> audioCapturerFilter)
1530 {
1531 if (!PermissionUtil::VerifySystemPermission()) {
1532 AUDIO_ERR_LOG("only for system app");
1533 return {};
1534 }
1535 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescs =
1536 audioPolicyService_.GetInputDevice(audioCapturerFilter);
1537 return deviceDescs;
1538 }
1539
VerifyVoiceCallPermission(uint64_t fullTokenId,Security::AccessToken::AccessTokenID tokenId)1540 int32_t AudioPolicyServer::VerifyVoiceCallPermission(
1541 uint64_t fullTokenId, Security::AccessToken::AccessTokenID tokenId)
1542 {
1543 bool hasSystemPermission = TokenIdKit::IsSystemAppByFullTokenID(fullTokenId);
1544 CHECK_AND_RETURN_RET_LOG(hasSystemPermission, ERR_PERMISSION_DENIED, "No system permission");
1545
1546 bool hasRecordVoiceCallPermission = VerifyPermission(RECORD_VOICE_CALL_PERMISSION, tokenId, true);
1547 CHECK_AND_RETURN_RET_LOG(hasRecordVoiceCallPermission, ERR_PERMISSION_DENIED, "No permission");
1548 return SUCCESS;
1549 }
1550
GetPreferredOutputDeviceDescriptors(AudioRendererInfo & rendererInfo,bool forceNoBTPermission)1551 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetPreferredOutputDeviceDescriptors(
1552 AudioRendererInfo &rendererInfo, bool forceNoBTPermission)
1553 {
1554 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescs =
1555 audioPolicyService_.GetPreferredOutputDeviceDescriptors(rendererInfo);
1556
1557 bool hasBTPermission = false;
1558 if (!forceNoBTPermission) {
1559 hasBTPermission = VerifyBluetoothPermission();
1560 }
1561
1562 if (!hasBTPermission) {
1563 audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDescs);
1564 }
1565
1566 return deviceDescs;
1567 }
1568
GetPreferredInputDeviceDescriptors(AudioCapturerInfo & captureInfo)1569 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetPreferredInputDeviceDescriptors(
1570 AudioCapturerInfo &captureInfo)
1571 {
1572 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDescs =
1573 audioPolicyService_.GetPreferredInputDeviceDescriptors(captureInfo);
1574 bool hasBTPermission = VerifyBluetoothPermission();
1575 if (!hasBTPermission) {
1576 audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDescs);
1577 }
1578
1579 return deviceDescs;
1580 }
1581
SetClientCallbacksEnable(const CallbackChange & callbackchange,const bool & enable)1582 int32_t AudioPolicyServer::SetClientCallbacksEnable(const CallbackChange &callbackchange, const bool &enable)
1583 {
1584 return audioPolicyService_.SetClientCallbacksEnable(callbackchange, enable);
1585 }
1586
SetCallbackRendererInfo(const AudioRendererInfo & rendererInfo)1587 int32_t AudioPolicyServer::SetCallbackRendererInfo(const AudioRendererInfo &rendererInfo)
1588 {
1589 if (audioPolicyServerHandler_ != nullptr) {
1590 audioPolicyServerHandler_->SetCallbackRendererInfo(rendererInfo);
1591 }
1592 return SUCCESS;
1593 }
1594
SetCallbackCapturerInfo(const AudioCapturerInfo & capturerInfo)1595 int32_t AudioPolicyServer::SetCallbackCapturerInfo(const AudioCapturerInfo &capturerInfo)
1596 {
1597 if (audioPolicyServerHandler_ != nullptr) {
1598 audioPolicyServerHandler_->SetCallbackCapturerInfo(capturerInfo);
1599 }
1600 return SUCCESS;
1601 }
1602
IsStreamActive(AudioStreamType streamType)1603 bool AudioPolicyServer::IsStreamActive(AudioStreamType streamType)
1604 {
1605 return audioPolicyService_.IsStreamActive(streamType);
1606 }
1607
SetDeviceActive(InternalDeviceType deviceType,bool active,const int32_t uid)1608 int32_t AudioPolicyServer::SetDeviceActive(InternalDeviceType deviceType, bool active, const int32_t uid)
1609 {
1610 return audioPolicyService_.SetDeviceActive(deviceType, active, uid);
1611 }
1612
IsDeviceActive(InternalDeviceType deviceType)1613 bool AudioPolicyServer::IsDeviceActive(InternalDeviceType deviceType)
1614 {
1615 return audioPolicyService_.IsDeviceActive(deviceType);
1616 }
1617
GetActiveOutputDevice()1618 InternalDeviceType AudioPolicyServer::GetActiveOutputDevice()
1619 {
1620 return audioPolicyService_.GetActiveOutputDevice();
1621 }
1622
GetActiveInputDevice()1623 InternalDeviceType AudioPolicyServer::GetActiveInputDevice()
1624 {
1625 return audioPolicyService_.GetActiveInputDevice();
1626 }
1627
1628 // deprecated since api 9.
SetRingerModeLegacy(AudioRingerMode ringMode)1629 int32_t AudioPolicyServer::SetRingerModeLegacy(AudioRingerMode ringMode)
1630 {
1631 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1632 return SetRingerModeInner(ringMode);
1633 }
1634
SetRingerMode(AudioRingerMode ringMode)1635 int32_t AudioPolicyServer::SetRingerMode(AudioRingerMode ringMode)
1636 {
1637 AUDIO_INFO_LOG("Set ringer mode to %{public}d", ringMode);
1638 if (!PermissionUtil::VerifySystemPermission()) {
1639 AUDIO_ERR_LOG("No system permission");
1640 return ERR_PERMISSION_DENIED;
1641 }
1642
1643 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1644 return SetRingerModeInner(ringMode);
1645 }
1646
SetRingerModeInner(AudioRingerMode ringMode)1647 int32_t AudioPolicyServer::SetRingerModeInner(AudioRingerMode ringMode)
1648 {
1649 bool isPermissionRequired = false;
1650
1651 if (ringMode == AudioRingerMode::RINGER_MODE_SILENT) {
1652 isPermissionRequired = true;
1653 } else {
1654 AudioRingerMode currentRingerMode = audioPolicyService_.GetRingerMode();
1655 if (currentRingerMode == AudioRingerMode::RINGER_MODE_SILENT) {
1656 isPermissionRequired = true;
1657 }
1658 }
1659
1660 // only switch to silent need check NOTIFICATION.
1661 if (isPermissionRequired) {
1662 bool result = VerifyPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION);
1663 CHECK_AND_RETURN_RET_LOG(result, ERR_PERMISSION_DENIED,
1664 "Access policy permission denied for ringerMode : %{public}d", ringMode);
1665 }
1666
1667 return SetRingerModeInternal(ringMode);
1668 }
1669
SetRingerModeInternal(AudioRingerMode inputRingerMode,bool hasUpdatedVolume)1670 int32_t AudioPolicyServer::SetRingerModeInternal(AudioRingerMode inputRingerMode, bool hasUpdatedVolume)
1671 {
1672 // PC ringmode not support silent or vibrate
1673 AudioRingerMode ringerMode = VolumeUtils::IsPCVolumeEnable() ? RINGER_MODE_NORMAL : inputRingerMode;
1674 AUDIO_INFO_LOG("Set ringer mode to %{public}d. hasUpdatedVolume %{public}d", ringerMode, hasUpdatedVolume);
1675 int32_t ret = audioPolicyService_.SetRingerMode(ringerMode);
1676 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ret, "Fail to set ringer mode!");
1677
1678 if (!hasUpdatedVolume) {
1679 // need to set volume according to ringermode
1680 bool muteState = (ringerMode == RINGER_MODE_NORMAL) ? false : true;
1681 AudioInterrupt audioInterrupt;
1682 GetSessionInfoInFocus(audioInterrupt);
1683 audioPolicyService_.SetStreamMute(STREAM_RING, muteState, audioInterrupt.streamUsage);
1684 if (!muteState && GetSystemVolumeLevelInternal(STREAM_RING) == 0) {
1685 // if mute state is false but volume is 0, set volume to 1. Send volumeChange callback.
1686 SetSystemVolumeLevelInternal(STREAM_RING, 1, false);
1687 }
1688 }
1689
1690 if (audioPolicyServerHandler_ != nullptr) {
1691 audioPolicyServerHandler_->SendRingerModeUpdatedCallback(ringerMode);
1692 }
1693 return ret;
1694 }
1695
1696 #ifdef FEATURE_DTMF_TONE
GetToneConfig(int32_t ltonetype,const std::string & countryCode)1697 std::shared_ptr<ToneInfo> AudioPolicyServer::GetToneConfig(int32_t ltonetype, const std::string &countryCode)
1698 {
1699 return audioPolicyService_.GetToneConfig(ltonetype, countryCode);
1700 }
1701
GetSupportedTones(const std::string & countryCode)1702 std::vector<int32_t> AudioPolicyServer::GetSupportedTones(const std::string &countryCode)
1703 {
1704 return audioPolicyService_.GetSupportedTones(countryCode);
1705 }
1706 #endif
1707
InitMicrophoneMute()1708 void AudioPolicyServer::InitMicrophoneMute()
1709 {
1710 AUDIO_INFO_LOG("Entered %{public}s", __func__);
1711 if (isInitMuteState_) {
1712 AUDIO_ERR_LOG("mic mutestate has already been initialized");
1713 return;
1714 }
1715 bool isMute = false;
1716 int32_t ret = audioPolicyService_.InitPersistentMicrophoneMuteState(isMute);
1717 AUDIO_INFO_LOG("Get persistent mic ismute: %{public}d state from setting db", isMute);
1718 if (ret != SUCCESS) {
1719 AUDIO_ERR_LOG("InitMicrophoneMute InitPersistentMicrophoneMuteState result %{public}d", ret);
1720 return;
1721 }
1722 isInitMuteState_ = true;
1723 if (audioPolicyServerHandler_ != nullptr) {
1724 MicStateChangeEvent micStateChangeEvent;
1725 micStateChangeEvent.mute = isMute;
1726 audioPolicyServerHandler_->SendMicStateUpdatedCallback(micStateChangeEvent);
1727 }
1728 }
1729
SetMicrophoneMuteCommon(bool isMute,bool isLegacy)1730 int32_t AudioPolicyServer::SetMicrophoneMuteCommon(bool isMute, bool isLegacy)
1731 {
1732 std::lock_guard<std::mutex> lock(micStateChangeMutex_);
1733 bool originalMicrophoneMute = IsMicrophoneMute();
1734 int32_t ret = audioPolicyService_.SetMicrophoneMute(isMute);
1735 bool newMicrophoneMute = IsMicrophoneMute();
1736 if (ret == SUCCESS && originalMicrophoneMute != newMicrophoneMute && audioPolicyServerHandler_ != nullptr) {
1737 MicStateChangeEvent micStateChangeEvent;
1738 micStateChangeEvent.mute = newMicrophoneMute;
1739 AUDIO_INFO_LOG("SendMicStateUpdatedCallback when set common mic mute state:%{public}d, isLegacy:%{public}d",
1740 newMicrophoneMute, isLegacy);
1741 audioPolicyServerHandler_->SendMicStateUpdatedCallback(micStateChangeEvent);
1742 }
1743 return ret;
1744 }
1745
SetMicrophoneMute(bool isMute)1746 int32_t AudioPolicyServer::SetMicrophoneMute(bool isMute)
1747 {
1748 AUDIO_INFO_LOG("[%{public}d] set to %{public}s", IPCSkeleton::GetCallingPid(), (isMute ? "true" : "false"));
1749 bool ret = VerifyPermission(MICROPHONE_PERMISSION);
1750 CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED,
1751 "MICROPHONE permission denied");
1752 return SetMicrophoneMuteCommon(isMute, true);
1753 }
1754
SetMicrophoneMuteAudioConfig(bool isMute)1755 int32_t AudioPolicyServer::SetMicrophoneMuteAudioConfig(bool isMute)
1756 {
1757 AUDIO_INFO_LOG("[%{public}d] set to %{public}s", IPCSkeleton::GetCallingPid(), (isMute ? "true" : "false"));
1758 const char* MANAGE_AUDIO_CONFIG = "ohos.permission.MANAGE_AUDIO_CONFIG";
1759 bool ret = VerifyPermission(MANAGE_AUDIO_CONFIG);
1760 CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED,
1761 "MANAGE_AUDIO_CONFIG permission denied");
1762 lastMicMuteSettingPid_ = IPCSkeleton::GetCallingPid();
1763 WatchTimeout guard("PrivacyKit::SetMutePolicy:SetMicrophoneMuteAudioConfig");
1764 PrivacyKit::SetMutePolicy(POLICY_TYPE_MAP[TEMPORARY_POLCIY_TYPE], MICPHONE_CALLER, isMute,
1765 IPCSkeleton::GetCallingTokenID());
1766 guard.CheckCurrTimeout();
1767 return SetMicrophoneMuteCommon(isMute, false);
1768 }
1769
SetMicrophoneMutePersistent(const bool isMute,const PolicyType type)1770 int32_t AudioPolicyServer::SetMicrophoneMutePersistent(const bool isMute, const PolicyType type)
1771 {
1772 AUDIO_INFO_LOG("Entered %{public}s isMute:%{public}d, type:%{public}d", __func__, isMute, type);
1773 bool hasPermission = VerifyPermission(MICROPHONE_CONTROL_PERMISSION);
1774 CHECK_AND_RETURN_RET_LOG(hasPermission, ERR_PERMISSION_DENIED,
1775 "MICROPHONE_CONTROL_PERMISSION permission denied");
1776 WatchTimeout guard("PrivacyKit::SetMutePolicy:SetMicrophoneMutePersistent");
1777 bool originalMicrophoneMute = IsMicrophoneMute();
1778 int32_t ret = PrivacyKit::SetMutePolicy(POLICY_TYPE_MAP[type], MICPHONE_CALLER, isMute,
1779 IPCSkeleton::GetCallingTokenID());
1780 guard.CheckCurrTimeout();
1781 if (ret != SUCCESS) {
1782 AUDIO_ERR_LOG("PrivacyKit SetMutePolicy failed ret is %{public}d", ret);
1783 return ret;
1784 }
1785 ret = audioPolicyService_.SetMicrophoneMutePersistent(isMute);
1786 bool newMicrophoneMute = IsMicrophoneMute();
1787 if (ret == SUCCESS && originalMicrophoneMute != newMicrophoneMute && audioPolicyServerHandler_ != nullptr) {
1788 MicStateChangeEvent micStateChangeEvent;
1789 micStateChangeEvent.mute = newMicrophoneMute;
1790 AUDIO_INFO_LOG("SendMicStateUpdatedCallback when set persistent mic mute state:%{public}d", newMicrophoneMute);
1791 audioPolicyServerHandler_->SendMicStateUpdatedCallback(micStateChangeEvent);
1792 }
1793 return ret;
1794 }
1795
GetPersistentMicMuteState()1796 bool AudioPolicyServer::GetPersistentMicMuteState()
1797 {
1798 bool hasPermission = VerifyPermission(MICROPHONE_CONTROL_PERMISSION);
1799 CHECK_AND_RETURN_RET_LOG(hasPermission, ERR_PERMISSION_DENIED,
1800 "MICROPHONE_CONTROL_PERMISSION permission denied");
1801
1802 return audioPolicyService_.GetPersistentMicMuteState();
1803 }
1804
1805 // deprecated since 9.
IsMicrophoneMuteLegacy()1806 bool AudioPolicyServer::IsMicrophoneMuteLegacy()
1807 {
1808 // AudioManager.IsMicrophoneMute check micphone right.
1809 if (!VerifyPermission(MICROPHONE_PERMISSION)) {
1810 AUDIO_ERR_LOG("MICROPHONE permission denied");
1811 return false;
1812 }
1813 return audioPolicyService_.IsMicrophoneMute();
1814 }
1815
IsMicrophoneMute()1816 bool AudioPolicyServer::IsMicrophoneMute()
1817 {
1818 // AudioVolumeGroupManager.IsMicrophoneMute didn't check micphone right.
1819 return audioPolicyService_.IsMicrophoneMute();
1820 }
1821
GetRingerMode()1822 AudioRingerMode AudioPolicyServer::GetRingerMode()
1823 {
1824 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
1825 return audioPolicyService_.GetRingerMode();
1826 }
1827
SetAudioScene(AudioScene audioScene)1828 int32_t AudioPolicyServer::SetAudioScene(AudioScene audioScene)
1829 {
1830 CHECK_AND_RETURN_RET_LOG(audioScene > AUDIO_SCENE_INVALID && audioScene < AUDIO_SCENE_MAX,
1831 ERR_INVALID_PARAM, "param is invalid");
1832 bool ret = PermissionUtil::VerifySystemPermission();
1833 CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED, "No system permission");
1834 switch (audioScene) {
1835 case AUDIO_SCENE_DEFAULT:
1836 case AUDIO_SCENE_RINGING:
1837 case AUDIO_SCENE_PHONE_CALL:
1838 case AUDIO_SCENE_PHONE_CHAT:
1839 return audioPolicyService_.SetAudioScene(audioScene);
1840
1841 default:
1842 AUDIO_ERR_LOG("param is invalid: %{public}d", audioScene);
1843 return ERR_INVALID_PARAM;
1844 }
1845 }
1846
SetAudioSceneInternal(AudioScene audioScene,const int32_t uid,const int32_t pid)1847 int32_t AudioPolicyServer::SetAudioSceneInternal(AudioScene audioScene, const int32_t uid, const int32_t pid)
1848 {
1849 return audioPolicyService_.SetAudioScene(audioScene, uid, pid);
1850 }
1851
GetAudioScene()1852 AudioScene AudioPolicyServer::GetAudioScene()
1853 {
1854 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
1855 return audioPolicyService_.GetAudioScene(hasSystemPermission);
1856 }
1857
SetAudioInterruptCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object,uint32_t clientUid,const int32_t zoneID)1858 int32_t AudioPolicyServer::SetAudioInterruptCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object,
1859 uint32_t clientUid, const int32_t zoneID)
1860 {
1861 if (interruptService_ != nullptr) {
1862 return interruptService_->SetAudioInterruptCallback(zoneID, sessionID, object, clientUid);
1863 }
1864 return ERR_UNKNOWN;
1865 }
1866
UnsetAudioInterruptCallback(const uint32_t sessionID,const int32_t zoneID)1867 int32_t AudioPolicyServer::UnsetAudioInterruptCallback(const uint32_t sessionID, const int32_t zoneID)
1868 {
1869 if (interruptService_ != nullptr) {
1870 return interruptService_->UnsetAudioInterruptCallback(zoneID, sessionID);
1871 }
1872 return ERR_UNKNOWN;
1873 }
1874
SetAudioManagerInterruptCallback(const int32_t,const sptr<IRemoteObject> & object)1875 int32_t AudioPolicyServer::SetAudioManagerInterruptCallback(const int32_t /* clientId */,
1876 const sptr<IRemoteObject> &object)
1877 {
1878 if (interruptService_ != nullptr) {
1879 return interruptService_->SetAudioManagerInterruptCallback(object);
1880 }
1881 return ERR_UNKNOWN;
1882 }
1883
UnsetAudioManagerInterruptCallback(const int32_t)1884 int32_t AudioPolicyServer::UnsetAudioManagerInterruptCallback(const int32_t /* clientId */)
1885 {
1886 if (interruptService_ != nullptr) {
1887 return interruptService_->UnsetAudioManagerInterruptCallback();
1888 }
1889 return ERR_UNKNOWN;
1890 }
1891
SetQueryClientTypeCallback(const sptr<IRemoteObject> & object)1892 int32_t AudioPolicyServer::SetQueryClientTypeCallback(const sptr<IRemoteObject> &object)
1893 {
1894 if (!PermissionUtil::VerifyIsAudio()) {
1895 AUDIO_ERR_LOG("not audio calling!");
1896 return ERR_OPERATION_FAILED;
1897 }
1898 return audioPolicyService_.SetQueryClientTypeCallback(object);
1899 }
1900
SetAudioClientInfoMgrCallback(const sptr<IRemoteObject> & object)1901 int32_t AudioPolicyServer::SetAudioClientInfoMgrCallback(const sptr<IRemoteObject> &object)
1902 {
1903 if (!PermissionUtil::VerifyIsAudio()) {
1904 AUDIO_ERR_LOG("not audio calling!");
1905 return ERR_OPERATION_FAILED;
1906 }
1907 return audioPolicyService_.SetAudioClientInfoMgrCallback(object);
1908 }
1909
RequestAudioFocus(const int32_t clientId,const AudioInterrupt & audioInterrupt)1910 int32_t AudioPolicyServer::RequestAudioFocus(const int32_t clientId, const AudioInterrupt &audioInterrupt)
1911 {
1912 if (interruptService_ != nullptr) {
1913 return interruptService_->RequestAudioFocus(clientId, audioInterrupt);
1914 }
1915 return ERR_UNKNOWN;
1916 }
1917
AbandonAudioFocus(const int32_t clientId,const AudioInterrupt & audioInterrupt)1918 int32_t AudioPolicyServer::AbandonAudioFocus(const int32_t clientId, const AudioInterrupt &audioInterrupt)
1919 {
1920 if (interruptService_ != nullptr) {
1921 return interruptService_->AbandonAudioFocus(clientId, audioInterrupt);
1922 }
1923 return ERR_UNKNOWN;
1924 }
1925
ProcessRemoteInterrupt(std::set<int32_t> sessionIds,InterruptEventInternal interruptEvent)1926 void AudioPolicyServer::ProcessRemoteInterrupt(std::set<int32_t> sessionIds, InterruptEventInternal interruptEvent)
1927 {
1928 if (interruptService_ != nullptr) {
1929 interruptService_->ProcessRemoteInterrupt(sessionIds, interruptEvent);
1930 }
1931 }
1932
ActivateAudioInterrupt(AudioInterrupt & audioInterrupt,const int32_t zoneID,const bool isUpdatedAudioStrategy)1933 int32_t AudioPolicyServer::ActivateAudioInterrupt(
1934 AudioInterrupt &audioInterrupt, const int32_t zoneID, const bool isUpdatedAudioStrategy)
1935 {
1936 if (interruptService_ != nullptr) {
1937 auto it = std::find(CAN_MIX_MUTED_STREAM.begin(), CAN_MIX_MUTED_STREAM.end(),
1938 audioInterrupt.audioFocusType.streamType);
1939 if (it != CAN_MIX_MUTED_STREAM.end()) {
1940 AudioStreamType streamInFocus = VolumeUtils::GetVolumeTypeFromStreamType(
1941 audioInterrupt.audioFocusType.streamType);
1942 int32_t volumeLevel = GetSystemVolumeLevelInternal(streamInFocus);
1943 if (volumeLevel == 0) {
1944 audioInterrupt.sessionStrategy.concurrencyMode = AudioConcurrencyMode::SILENT;
1945 }
1946 }
1947 return interruptService_->ActivateAudioInterrupt(zoneID, audioInterrupt, isUpdatedAudioStrategy);
1948 }
1949 return ERR_UNKNOWN;
1950 }
1951
DeactivateAudioInterrupt(const AudioInterrupt & audioInterrupt,const int32_t zoneID)1952 int32_t AudioPolicyServer::DeactivateAudioInterrupt(const AudioInterrupt &audioInterrupt, const int32_t zoneID)
1953 {
1954 if (interruptService_ != nullptr) {
1955 return interruptService_->DeactivateAudioInterrupt(zoneID, audioInterrupt);
1956 }
1957 return ERR_UNKNOWN;
1958 }
1959
OnAudioStreamRemoved(const uint64_t sessionID)1960 void AudioPolicyServer::OnAudioStreamRemoved(const uint64_t sessionID)
1961 {
1962 CHECK_AND_RETURN_LOG(audioPolicyServerHandler_ != nullptr, "audioPolicyServerHandler_ is nullptr");
1963 audioPolicyServerHandler_->SendCapturerRemovedEvent(sessionID, false);
1964 }
1965
ProcessSessionRemoved(const uint64_t sessionID,const int32_t zoneID)1966 void AudioPolicyServer::ProcessSessionRemoved(const uint64_t sessionID, const int32_t zoneID)
1967 {
1968 AUDIO_DEBUG_LOG("Removed SessionId: %{public}" PRIu64, sessionID);
1969 }
1970
ProcessSessionAdded(SessionEvent sessionEvent)1971 void AudioPolicyServer::ProcessSessionAdded(SessionEvent sessionEvent)
1972 {
1973 AUDIO_DEBUG_LOG("Added Session");
1974 }
1975
ProcessorCloseWakeupSource(const uint64_t sessionID)1976 void AudioPolicyServer::ProcessorCloseWakeupSource(const uint64_t sessionID)
1977 {
1978 audioPolicyService_.CloseWakeUpAudioCapturer();
1979 }
1980
GetStreamInFocus(const int32_t zoneID)1981 AudioStreamType AudioPolicyServer::GetStreamInFocus(const int32_t zoneID)
1982 {
1983 if (interruptService_ != nullptr) {
1984 return interruptService_->GetStreamInFocus(zoneID);
1985 }
1986 return STREAM_MUSIC;
1987 }
1988
GetStreamInFocusByUid(const int32_t uid,const int32_t zoneID)1989 AudioStreamType AudioPolicyServer::GetStreamInFocusByUid(const int32_t uid, const int32_t zoneID)
1990 {
1991 if (!PermissionUtil::VerifySystemPermission()) {
1992 AUDIO_ERR_LOG("No system permission");
1993 return STREAM_MUSIC;
1994 }
1995
1996 if (interruptService_ != nullptr) {
1997 return interruptService_->GetStreamInFocusByUid(uid, zoneID);
1998 }
1999 return STREAM_MUSIC;
2000 }
2001
GetSessionInfoInFocus(AudioInterrupt & audioInterrupt,const int32_t zoneID)2002 int32_t AudioPolicyServer::GetSessionInfoInFocus(AudioInterrupt &audioInterrupt, const int32_t zoneID)
2003 {
2004 if (interruptService_ != nullptr) {
2005 return interruptService_->GetSessionInfoInFocus(audioInterrupt, zoneID);
2006 }
2007 return ERR_UNKNOWN;
2008 }
2009
GetAudioFocusInfoList(std::list<std::pair<AudioInterrupt,AudioFocuState>> & focusInfoList,const int32_t zoneID)2010 int32_t AudioPolicyServer::GetAudioFocusInfoList(std::list<std::pair<AudioInterrupt, AudioFocuState>> &focusInfoList,
2011 const int32_t zoneID)
2012 {
2013 if (interruptService_ != nullptr) {
2014 return interruptService_->GetAudioFocusInfoList(zoneID, focusInfoList);
2015 }
2016 return ERR_UNKNOWN;
2017 }
2018
VerifyPermission(const std::string & permissionName,uint32_t tokenId,bool isRecording)2019 bool AudioPolicyServer::VerifyPermission(const std::string &permissionName, uint32_t tokenId, bool isRecording)
2020 {
2021 AUDIO_DEBUG_LOG("Verify permission [%{public}s]", permissionName.c_str());
2022
2023 if (!isRecording) {
2024 #ifdef AUDIO_BUILD_VARIANT_ROOT
2025 // root user case for auto test
2026 uid_t callingUid = static_cast<uid_t>(IPCSkeleton::GetCallingUid());
2027 if (callingUid == ROOT_UID) {
2028 return true;
2029 }
2030 #endif
2031 tokenId = IPCSkeleton::GetCallingTokenID();
2032 }
2033
2034 int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, permissionName);
2035 CHECK_AND_RETURN_RET_LOG(res == Security::AccessToken::PermissionState::PERMISSION_GRANTED,
2036 false, "Permission denied [%{public}s]", permissionName.c_str());
2037
2038 return true;
2039 }
2040
VerifyBluetoothPermission()2041 bool AudioPolicyServer::VerifyBluetoothPermission()
2042 {
2043 #ifdef AUDIO_BUILD_VARIANT_ROOT
2044 // root user case for auto test
2045 uid_t callingUid = static_cast<uid_t>(IPCSkeleton::GetCallingUid());
2046 if (callingUid == ROOT_UID) {
2047 return true;
2048 }
2049 #endif
2050 uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
2051
2052 int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, USE_BLUETOOTH_PERMISSION);
2053 CHECK_AND_RETURN_RET(res == Security::AccessToken::PermissionState::PERMISSION_GRANTED, false);
2054
2055 return true;
2056 }
2057
ReconfigureAudioChannel(const uint32_t & count,DeviceType deviceType)2058 int32_t AudioPolicyServer::ReconfigureAudioChannel(const uint32_t &count, DeviceType deviceType)
2059 {
2060 #ifdef AUDIO_BUILD_VARIANT_ROOT
2061 // Only root users should have access to this api
2062 if (ROOT_UID != IPCSkeleton::GetCallingUid()) {
2063 AUDIO_INFO_LOG("Unautorized user. Cannot modify channel");
2064 return ERR_PERMISSION_DENIED;
2065 }
2066
2067 return audioPolicyService_.ReconfigureAudioChannel(count, deviceType);
2068 #else
2069 // this api is not supported
2070 return ERR_NOT_SUPPORTED;
2071 #endif
2072 }
2073
GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfos)2074 void AudioPolicyServer::GetStreamVolumeInfoMap(StreamVolumeInfoMap& streamVolumeInfos)
2075 {
2076 audioPolicyService_.GetStreamVolumeInfoMap(streamVolumeInfos);
2077 }
2078
Dump(int32_t fd,const std::vector<std::u16string> & args)2079 int32_t AudioPolicyServer::Dump(int32_t fd, const std::vector<std::u16string> &args)
2080 {
2081 AUDIO_DEBUG_LOG("Dump Process Invoked");
2082 std::queue<std::u16string> argQue;
2083 for (decltype(args.size()) index = 0; index < args.size(); ++index) {
2084 argQue.push(args[index]);
2085 }
2086 std::string dumpString;
2087 InitPolicyDumpMap();
2088 ArgInfoDump(dumpString, argQue);
2089
2090 return write(fd, dumpString.c_str(), dumpString.size());
2091 }
2092
InitPolicyDumpMap()2093 void AudioPolicyServer::InitPolicyDumpMap()
2094 {
2095 dumpFuncMap[u"-h"] = &AudioPolicyServer::InfoDumpHelp;
2096 dumpFuncMap[u"-d"] = &AudioPolicyServer::AudioDevicesDump;
2097 dumpFuncMap[u"-m"] = &AudioPolicyServer::AudioModeDump;
2098 dumpFuncMap[u"-v"] = &AudioPolicyServer::AudioVolumeDump;
2099 dumpFuncMap[u"-az"] = &AudioPolicyServer::AudioInterruptZoneDump;
2100 dumpFuncMap[u"-apc"] = &AudioPolicyServer::AudioPolicyParserDump;
2101 dumpFuncMap[u"-s"] = &AudioPolicyServer::AudioStreamDump;
2102 dumpFuncMap[u"-xp"] = &AudioPolicyServer::XmlParsedDataMapDump;
2103 dumpFuncMap[u"-e"] = &AudioPolicyServer::EffectManagerInfoDump;
2104 dumpFuncMap[u"-ms"] = &AudioPolicyServer::MicrophoneMuteInfoDump;
2105 dumpFuncMap[u"-as"] = &AudioPolicyServer::AudioSessionInfoDump;
2106 }
2107
PolicyDataDump(std::string & dumpString)2108 void AudioPolicyServer::PolicyDataDump(std::string &dumpString)
2109 {
2110 AudioDevicesDump(dumpString);
2111 AudioModeDump(dumpString);
2112 AudioVolumeDump(dumpString);
2113 AudioInterruptZoneDump(dumpString);
2114 AudioPolicyParserDump(dumpString);
2115 AudioStreamDump(dumpString);
2116 XmlParsedDataMapDump(dumpString);
2117 EffectManagerInfoDump(dumpString);
2118 MicrophoneMuteInfoDump(dumpString);
2119 AudioSessionInfoDump(dumpString);
2120 }
2121
AudioDevicesDump(std::string & dumpString)2122 void AudioPolicyServer::AudioDevicesDump(std::string &dumpString)
2123 {
2124 audioPolicyDump_.DevicesInfoDump(dumpString);
2125 }
2126
AudioModeDump(std::string & dumpString)2127 void AudioPolicyServer::AudioModeDump(std::string &dumpString)
2128 {
2129 audioPolicyDump_.AudioModeDump(dumpString);
2130 }
2131
AudioInterruptZoneDump(std::string & dumpString)2132 void AudioPolicyServer::AudioInterruptZoneDump(std::string &dumpString)
2133 {
2134 interruptService_->AudioInterruptZoneDump(dumpString);
2135 }
2136
AudioPolicyParserDump(std::string & dumpString)2137 void AudioPolicyServer::AudioPolicyParserDump(std::string &dumpString)
2138 {
2139 audioPolicyDump_.AudioPolicyParserDump(dumpString);
2140 }
2141
AudioVolumeDump(std::string & dumpString)2142 void AudioPolicyServer::AudioVolumeDump(std::string &dumpString)
2143 {
2144 audioPolicyDump_.StreamVolumesDump(dumpString);
2145 }
2146
AudioStreamDump(std::string & dumpString)2147 void AudioPolicyServer::AudioStreamDump(std::string &dumpString)
2148 {
2149 audioPolicyDump_.AudioStreamDump(dumpString);
2150 }
2151
XmlParsedDataMapDump(std::string & dumpString)2152 void AudioPolicyServer::XmlParsedDataMapDump(std::string &dumpString)
2153 {
2154 audioPolicyDump_.XmlParsedDataMapDump(dumpString);
2155 }
2156
EffectManagerInfoDump(std::string & dumpString)2157 void AudioPolicyServer::EffectManagerInfoDump(std::string &dumpString)
2158 {
2159 audioPolicyDump_.EffectManagerInfoDump(dumpString);
2160 }
2161
MicrophoneMuteInfoDump(std::string & dumpString)2162 void AudioPolicyServer::MicrophoneMuteInfoDump(std::string &dumpString)
2163 {
2164 audioPolicyDump_.MicrophoneMuteInfoDump(dumpString);
2165 }
2166
AudioSessionInfoDump(std::string & dumpString)2167 void AudioPolicyServer::AudioSessionInfoDump(std::string &dumpString)
2168 {
2169 interruptService_->AudioSessionInfoDump(dumpString);
2170 }
2171
ArgInfoDump(std::string & dumpString,std::queue<std::u16string> & argQue)2172 void AudioPolicyServer::ArgInfoDump(std::string &dumpString, std::queue<std::u16string> &argQue)
2173 {
2174 dumpString += "AudioPolicyServer Data Dump:\n\n";
2175 if (argQue.empty()) {
2176 PolicyDataDump(dumpString);
2177 return;
2178 }
2179 while (!argQue.empty()) {
2180 std::u16string para = argQue.front();
2181 if (para == u"-h") {
2182 dumpString.clear();
2183 (this->*dumpFuncMap[para])(dumpString);
2184 return;
2185 } else if (dumpFuncMap.count(para) == 0) {
2186 dumpString.clear();
2187 AppendFormat(dumpString, "Please input correct param:\n");
2188 InfoDumpHelp(dumpString);
2189 return;
2190 } else {
2191 (this->*dumpFuncMap[para])(dumpString);
2192 }
2193 argQue.pop();
2194 }
2195 }
2196
InfoDumpHelp(std::string & dumpString)2197 void AudioPolicyServer::InfoDumpHelp(std::string &dumpString)
2198 {
2199 AppendFormat(dumpString, "usage:\n");
2200 AppendFormat(dumpString, " -h\t\t\t|help text for hidumper audio\n");
2201 AppendFormat(dumpString, " -d\t\t\t|dump devices info\n");
2202 AppendFormat(dumpString, " -m\t\t\t|dump ringer mode and call status\n");
2203 AppendFormat(dumpString, " -v\t\t\t|dump stream volume info\n");
2204 AppendFormat(dumpString, " -az\t\t\t|dump audio in interrupt zone info\n");
2205 AppendFormat(dumpString, " -apc\t\t\t|dump audio policy config xml parser info\n");
2206 AppendFormat(dumpString, " -s\t\t\t|dump stream info\n");
2207 AppendFormat(dumpString, " -xp\t\t\t|dump xml data map\n");
2208 AppendFormat(dumpString, " -e\t\t\t|dump audio effect manager Info\n");
2209 AppendFormat(dumpString, " -as\t\t\t|dump audio session info\n");
2210 }
2211
GetPreferredOutputStreamType(AudioRendererInfo & rendererInfo)2212 int32_t AudioPolicyServer::GetPreferredOutputStreamType(AudioRendererInfo &rendererInfo)
2213 {
2214 std::string bundleName = "";
2215 bool isFastControlled = audioPolicyService_.getFastControlParam();
2216 if (isFastControlled && rendererInfo.rendererFlags == AUDIO_FLAG_MMAP) {
2217 bundleName = GetBundleName();
2218 AUDIO_INFO_LOG("bundleName %{public}s", bundleName.c_str());
2219 return audioPolicyService_.GetPreferredOutputStreamType(rendererInfo, bundleName);
2220 }
2221 return audioPolicyService_.GetPreferredOutputStreamType(rendererInfo, "");
2222 }
2223
GetPreferredInputStreamType(AudioCapturerInfo & capturerInfo)2224 int32_t AudioPolicyServer::GetPreferredInputStreamType(AudioCapturerInfo &capturerInfo)
2225 {
2226 return audioPolicyService_.GetPreferredInputStreamType(capturerInfo);
2227 }
2228
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object)2229 int32_t AudioPolicyServer::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
2230 const sptr<IRemoteObject> &object)
2231 {
2232 auto callerPid = IPCSkeleton::GetCallingPid();
2233 streamChangeInfo.audioRendererChangeInfo.callerPid = callerPid;
2234 streamChangeInfo.audioCapturerChangeInfo.callerPid = callerPid;
2235
2236 // update the clientUid
2237 auto callerUid = IPCSkeleton::GetCallingUid();
2238 streamChangeInfo.audioRendererChangeInfo.createrUID = callerUid;
2239 streamChangeInfo.audioCapturerChangeInfo.createrUID = callerUid;
2240 int appVolume = GetAppVolumeLevel(callerUid);
2241 streamChangeInfo.audioRendererChangeInfo.appVolume = appVolume;
2242 AUDIO_DEBUG_LOG("RegisterTracker: [caller uid: %{public}d]", callerUid);
2243 if (callerUid != MEDIA_SERVICE_UID) {
2244 if (mode == AUDIO_MODE_PLAYBACK) {
2245 streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
2246 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
2247 streamChangeInfo.audioRendererChangeInfo.clientUID);
2248 } else {
2249 streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
2250 streamChangeInfo.audioCapturerChangeInfo.appTokenId = IPCSkeleton::GetCallingTokenID();
2251
2252 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
2253 streamChangeInfo.audioCapturerChangeInfo.clientUID);
2254 }
2255 }
2256 RegisterClientDeathRecipient(object, TRACKER_CLIENT);
2257 int32_t apiVersion = GetApiTargerVersion();
2258 return audioPolicyService_.RegisterTracker(mode, streamChangeInfo, object, apiVersion);
2259 }
2260
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)2261 int32_t AudioPolicyServer::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
2262 {
2263 auto callerPid = IPCSkeleton::GetCallingPid();
2264 streamChangeInfo.audioRendererChangeInfo.callerPid = callerPid;
2265 streamChangeInfo.audioCapturerChangeInfo.callerPid = callerPid;
2266
2267 // update the clientUid
2268 auto callerUid = IPCSkeleton::GetCallingUid();
2269 streamChangeInfo.audioRendererChangeInfo.createrUID = callerUid;
2270 streamChangeInfo.audioCapturerChangeInfo.createrUID = callerUid;
2271 AUDIO_DEBUG_LOG("UpdateTracker: [caller uid: %{public}d]", callerUid);
2272 if (callerUid != MEDIA_SERVICE_UID) {
2273 if (mode == AUDIO_MODE_PLAYBACK) {
2274 streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
2275 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
2276 streamChangeInfo.audioRendererChangeInfo.clientUID);
2277 } else {
2278 streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
2279 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
2280 streamChangeInfo.audioCapturerChangeInfo.clientUID);
2281 }
2282 }
2283 int appVolume = GetAppVolumeLevel(streamChangeInfo.audioRendererChangeInfo.clientUID);
2284 streamChangeInfo.audioRendererChangeInfo.appVolume = appVolume;
2285 int32_t ret = audioPolicyService_.UpdateTracker(mode, streamChangeInfo);
2286 if (streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_PAUSED ||
2287 streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_STOPPED ||
2288 streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_RELEASED) {
2289 OffloadStreamCheck(OFFLOAD_NO_SESSION_ID, streamChangeInfo.audioRendererChangeInfo.sessionId);
2290 }
2291 if (streamChangeInfo.audioRendererChangeInfo.rendererState == RENDERER_RUNNING) {
2292 OffloadStreamCheck(streamChangeInfo.audioRendererChangeInfo.sessionId, OFFLOAD_NO_SESSION_ID);
2293 }
2294 return ret;
2295 }
2296
FetchOutputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo,const AudioStreamDeviceChangeReasonExt reason)2297 void AudioPolicyServer::FetchOutputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo,
2298 const AudioStreamDeviceChangeReasonExt reason)
2299 {
2300 auto callerPid = IPCSkeleton::GetCallingPid();
2301 streamChangeInfo.audioRendererChangeInfo.callerPid = callerPid;
2302
2303 // update the clientUid
2304 auto callerUid = IPCSkeleton::GetCallingUid();
2305 streamChangeInfo.audioRendererChangeInfo.createrUID = callerUid;
2306 AUDIO_DEBUG_LOG("[caller uid: %{public}d]", callerUid);
2307 if (callerUid != MEDIA_SERVICE_UID) {
2308 streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
2309 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
2310 streamChangeInfo.audioRendererChangeInfo.clientUID);
2311 }
2312 audioPolicyService_.FetchOutputDeviceForTrack(streamChangeInfo, reason);
2313 }
2314
FetchInputDeviceForTrack(AudioStreamChangeInfo & streamChangeInfo)2315 void AudioPolicyServer::FetchInputDeviceForTrack(AudioStreamChangeInfo &streamChangeInfo)
2316 {
2317 auto callerPid = IPCSkeleton::GetCallingPid();
2318 streamChangeInfo.audioCapturerChangeInfo.callerPid = callerPid;
2319
2320 // update the clientUid
2321 auto callerUid = IPCSkeleton::GetCallingUid();
2322 streamChangeInfo.audioCapturerChangeInfo.createrUID = callerUid;
2323 AUDIO_DEBUG_LOG("[caller uid: %{public}d]", callerUid);
2324 if (callerUid != MEDIA_SERVICE_UID) {
2325 streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
2326 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
2327 streamChangeInfo.audioCapturerChangeInfo.clientUID);
2328 }
2329 audioPolicyService_.FetchInputDeviceForTrack(streamChangeInfo);
2330 }
2331
GetCurrentRendererChangeInfos(std::vector<shared_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos)2332 int32_t AudioPolicyServer::GetCurrentRendererChangeInfos(
2333 std::vector<shared_ptr<AudioRendererChangeInfo>> &audioRendererChangeInfos)
2334 {
2335 bool hasBTPermission = VerifyBluetoothPermission();
2336 AUDIO_DEBUG_LOG("GetCurrentRendererChangeInfos: BT use permission: %{public}d", hasBTPermission);
2337 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2338 AUDIO_DEBUG_LOG("GetCurrentRendererChangeInfos: System use permission: %{public}d", hasSystemPermission);
2339
2340 return audioPolicyService_.GetCurrentRendererChangeInfos(audioRendererChangeInfos,
2341 hasBTPermission, hasSystemPermission);
2342 }
2343
GetCurrentCapturerChangeInfos(std::vector<shared_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos)2344 int32_t AudioPolicyServer::GetCurrentCapturerChangeInfos(
2345 std::vector<shared_ptr<AudioCapturerChangeInfo>> &audioCapturerChangeInfos)
2346 {
2347 bool hasBTPermission = VerifyBluetoothPermission();
2348 AUDIO_DEBUG_LOG("GetCurrentCapturerChangeInfos: BT use permission: %{public}d", hasBTPermission);
2349 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2350 AUDIO_DEBUG_LOG("GetCurrentCapturerChangeInfos: System use permission: %{public}d", hasSystemPermission);
2351
2352 return audioPolicyService_.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos,
2353 hasBTPermission, hasSystemPermission);
2354 }
2355
RegisterClientDeathRecipient(const sptr<IRemoteObject> & object,DeathRecipientId id)2356 void AudioPolicyServer::RegisterClientDeathRecipient(const sptr<IRemoteObject> &object, DeathRecipientId id)
2357 {
2358 AUDIO_DEBUG_LOG("Register clients death recipient!! RecipientId: %{public}d", id);
2359 std::lock_guard<std::mutex> lock(clientDiedListenerStateMutex_);
2360 CHECK_AND_RETURN_LOG(object != nullptr, "Client proxy obj NULL!!");
2361
2362 pid_t pid = IPCSkeleton::GetCallingPid();
2363 pid_t uid = IPCSkeleton::GetCallingUid();
2364 if (id == TRACKER_CLIENT && std::find(clientDiedListenerState_.begin(), clientDiedListenerState_.end(), uid)
2365 != clientDiedListenerState_.end()) {
2366 AUDIO_INFO_LOG("Tracker has been registered for %{public}d!", uid);
2367 return;
2368 }
2369 sptr<AudioServerDeathRecipient> deathRecipient_ = new(std::nothrow) AudioServerDeathRecipient(pid, uid);
2370 if (deathRecipient_ != nullptr) {
2371 if (id == TRACKER_CLIENT) {
2372 deathRecipient_->SetNotifyCb(
2373 [this] (pid_t pid, pid_t uid) { this->RegisteredTrackerClientDied(pid, uid); });
2374 } else {
2375 AUDIO_PRERELEASE_LOGI("RegisteredStreamListenerClientDied register!!");
2376 deathRecipient_->SetNotifyCb(
2377 [this] (pid_t pid, pid_t uid) { this->RegisteredStreamListenerClientDied(pid, uid); });
2378 }
2379 bool result = object->AddDeathRecipient(deathRecipient_);
2380 if (result && id == TRACKER_CLIENT) {
2381 clientDiedListenerState_.push_back(uid);
2382 }
2383 if (!result) {
2384 AUDIO_WARNING_LOG("failed to add deathRecipient");
2385 }
2386 }
2387 }
2388
RegisteredTrackerClientDied(pid_t pid,pid_t uid)2389 void AudioPolicyServer::RegisteredTrackerClientDied(pid_t pid, pid_t uid)
2390 {
2391 AUDIO_INFO_LOG("RegisteredTrackerClient died: remove entry, pid %{public}d uid %{public}d", pid, uid);
2392 audioPolicyService_.RemoveDeviceForUid(uid);
2393 std::lock_guard<std::mutex> lock(clientDiedListenerStateMutex_);
2394 audioPolicyService_.RegisteredTrackerClientDied(uid);
2395
2396 auto filter = [&uid](int val) {
2397 return uid == val;
2398 };
2399 clientDiedListenerState_.erase(std::remove_if(clientDiedListenerState_.begin(), clientDiedListenerState_.end(),
2400 filter), clientDiedListenerState_.end());
2401 }
2402
RegisteredStreamListenerClientDied(pid_t pid,pid_t uid)2403 void AudioPolicyServer::RegisteredStreamListenerClientDied(pid_t pid, pid_t uid)
2404 {
2405 AUDIO_INFO_LOG("RegisteredStreamListenerClient died: remove entry, pid %{public}d uid %{public}d", pid, uid);
2406 audioPolicyService_.RemoveDeviceForUid(uid);
2407 if (pid == lastMicMuteSettingPid_) {
2408 // The last app with the non-persistent microphone setting died, restore the default non-persistent value
2409 AUDIO_INFO_LOG("Cliet died and reset non-persist mute state");
2410 audioPolicyService_.SetMicrophoneMute(false);
2411 }
2412 if (interruptService_ != nullptr && interruptService_->IsAudioSessionActivated(pid)) {
2413 interruptService_->DeactivateAudioSession(pid);
2414 }
2415 audioPolicyService_.ReduceAudioPolicyClientProxyMap(pid);
2416 }
2417
ResumeStreamState()2418 int32_t AudioPolicyServer::ResumeStreamState()
2419 {
2420 AUDIO_INFO_LOG("AVSession is not alive.");
2421 return audioPolicyService_.ResumeStreamState();
2422 }
2423
2424 // LCOV_EXCL_START
UpdateStreamState(const int32_t clientUid,StreamSetState streamSetState,StreamUsage streamUsage)2425 int32_t AudioPolicyServer::UpdateStreamState(const int32_t clientUid,
2426 StreamSetState streamSetState, StreamUsage streamUsage)
2427 {
2428 constexpr int32_t avSessionUid = 6700; // "uid" : "av_session"
2429 auto callerUid = IPCSkeleton::GetCallingUid();
2430 // This function can only be used by av_session
2431 CHECK_AND_RETURN_RET_LOG(callerUid == avSessionUid, ERROR,
2432 "UpdateStreamState callerUid is error: not av_session");
2433
2434 AUDIO_INFO_LOG("UpdateStreamState::uid:%{public}d streamSetState:%{public}d audioStreamUsage:%{public}d",
2435 clientUid, streamSetState, streamUsage);
2436 StreamSetState setState = StreamSetState::STREAM_PAUSE;
2437 switch (streamSetState) {
2438 case StreamSetState::STREAM_PAUSE:
2439 setState = StreamSetState::STREAM_PAUSE;
2440 break;
2441 case StreamSetState::STREAM_RESUME:
2442 setState = StreamSetState::STREAM_RESUME;
2443 break;
2444 case StreamSetState::STREAM_MUTE:
2445 setState = StreamSetState::STREAM_MUTE;
2446 break;
2447 case StreamSetState::STREAM_UNMUTE:
2448 setState = StreamSetState::STREAM_UNMUTE;
2449 break;
2450 default:
2451 AUDIO_INFO_LOG("UpdateStreamState::streamSetState value is error");
2452 break;
2453 }
2454 StreamSetStateEventInternal setStateEvent = {};
2455 setStateEvent.streamSetState = setState;
2456 setStateEvent.streamUsage = streamUsage;
2457
2458 return audioPolicyService_.UpdateStreamState(clientUid, setStateEvent);
2459 }
2460 // LCOV_EXCL_STOP
2461
GetVolumeGroupInfos(std::string networkId,std::vector<sptr<VolumeGroupInfo>> & infos)2462 int32_t AudioPolicyServer::GetVolumeGroupInfos(std::string networkId, std::vector<sptr<VolumeGroupInfo>> &infos)
2463 {
2464 bool ret = PermissionUtil::VerifySystemPermission();
2465 CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED,
2466 "No system permission");
2467
2468 infos = audioPolicyService_.GetVolumeGroupInfos();
2469 auto filter = [&networkId](const sptr<VolumeGroupInfo>& info) {
2470 return networkId != info->networkId_;
2471 };
2472 infos.erase(std::remove_if(infos.begin(), infos.end(), filter), infos.end());
2473
2474 return SUCCESS;
2475 }
2476
GetNetworkIdByGroupId(int32_t groupId,std::string & networkId)2477 int32_t AudioPolicyServer::GetNetworkIdByGroupId(int32_t groupId, std::string &networkId)
2478 {
2479 auto volumeGroupInfos = audioPolicyService_.GetVolumeGroupInfos();
2480
2481 auto filter = [&groupId](const sptr<VolumeGroupInfo>& info) {
2482 return groupId != info->volumeGroupId_;
2483 };
2484 volumeGroupInfos.erase(std::remove_if(volumeGroupInfos.begin(), volumeGroupInfos.end(), filter),
2485 volumeGroupInfos.end());
2486 if (volumeGroupInfos.size() > 0) {
2487 networkId = volumeGroupInfos[0]->networkId_;
2488 AUDIO_INFO_LOG("GetNetworkIdByGroupId: get networkId %{public}s.", networkId.c_str());
2489 } else {
2490 AUDIO_ERR_LOG("GetNetworkIdByGroupId: has no valid group");
2491 return ERROR;
2492 }
2493
2494 return SUCCESS;
2495 }
2496
RemoteParameterCallback(sptr<AudioPolicyServer> server)2497 AudioPolicyServer::RemoteParameterCallback::RemoteParameterCallback(sptr<AudioPolicyServer> server)
2498 {
2499 server_ = server;
2500 }
2501
OnAudioParameterChange(const std::string networkId,const AudioParamKey key,const std::string & condition,const std::string & value)2502 void AudioPolicyServer::RemoteParameterCallback::OnAudioParameterChange(const std::string networkId,
2503 const AudioParamKey key, const std::string& condition, const std::string& value)
2504 {
2505 AUDIO_INFO_LOG("key:%{public}d, condition:%{public}s, value:%{public}s",
2506 key, condition.c_str(), value.c_str());
2507 CHECK_AND_RETURN_LOG(server_ != nullptr, "AudioPolicyServer is nullptr");
2508 switch (key) {
2509 case VOLUME:
2510 VolumeOnChange(networkId, condition);
2511 break;
2512 case INTERRUPT:
2513 InterruptOnChange(networkId, condition);
2514 break;
2515 case PARAM_KEY_STATE:
2516 StateOnChange(networkId, condition, value);
2517 break;
2518 default:
2519 AUDIO_DEBUG_LOG("[AudioPolicyServer]: No processing");
2520 break;
2521 }
2522 }
2523
VolumeOnChange(const std::string networkId,const std::string & condition)2524 void AudioPolicyServer::RemoteParameterCallback::VolumeOnChange(const std::string networkId,
2525 const std::string& condition)
2526 {
2527 VolumeEvent volumeEvent;
2528 volumeEvent.networkId = networkId;
2529 char eventDes[EVENT_DES_SIZE];
2530 if (sscanf_s(condition.c_str(), "%[^;];AUDIO_STREAM_TYPE=%d;VOLUME_LEVEL=%d;IS_UPDATEUI=%d;VOLUME_GROUP_ID=%d;",
2531 eventDes, EVENT_DES_SIZE, &(volumeEvent.volumeType), &(volumeEvent.volume), &(volumeEvent.updateUi),
2532 &(volumeEvent.volumeGroupId)) < PARAMS_VOLUME_NUM) {
2533 AUDIO_ERR_LOG("[VolumeOnChange]: Failed parse condition");
2534 return;
2535 }
2536
2537 volumeEvent.updateUi = false;
2538 CHECK_AND_RETURN_LOG(server_->audioPolicyServerHandler_ != nullptr, "audioPolicyServerHandler_ is nullptr");
2539 server_->audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
2540 }
2541
InterruptOnChange(const std::string networkId,const std::string & condition)2542 void AudioPolicyServer::RemoteParameterCallback::InterruptOnChange(const std::string networkId,
2543 const std::string& condition)
2544 {
2545 AUDIO_INFO_LOG("InterruptOnChange : networkId: %{public}s, condition: %{public}s.", networkId.c_str(),
2546 condition.c_str());
2547 char eventDes[EVENT_DES_SIZE];
2548 InterruptType type = INTERRUPT_TYPE_BEGIN;
2549 InterruptForceType forceType = INTERRUPT_SHARE;
2550 InterruptHint hint = INTERRUPT_HINT_NONE;
2551 int32_t audioCategory = 0;
2552
2553 int ret = sscanf_s(condition.c_str(), "%[^;];EVENT_TYPE=%d;FORCE_TYPE=%d;HINT_TYPE=%d;AUDIOCATEGORY=%d;",
2554 eventDes, EVENT_DES_SIZE, &type, &forceType, &hint, &audioCategory);
2555 CHECK_AND_RETURN_LOG(ret >= PARAMS_INTERRUPT_NUM, "[InterruptOnChange]: Failed parse condition");
2556
2557 std::set<int32_t> sessionIdMedia = AudioStreamCollector::GetAudioStreamCollector().
2558 GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_MUSIC);
2559 std::set<int32_t> sessionIdMovie = AudioStreamCollector::GetAudioStreamCollector().
2560 GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_MOVIE);
2561 std::set<int32_t> sessionIdGame = AudioStreamCollector::GetAudioStreamCollector().
2562 GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_GAME);
2563 std::set<int32_t> sessionIdAudioBook = AudioStreamCollector::GetAudioStreamCollector().
2564 GetSessionIdsOnRemoteDeviceByStreamUsage(StreamUsage::STREAM_USAGE_AUDIOBOOK);
2565 std::set<int32_t> sessionIds = {};
2566 sessionIds.insert(sessionIdMedia.begin(), sessionIdMedia.end());
2567 sessionIds.insert(sessionIdMovie.begin(), sessionIdMovie.end());
2568 sessionIds.insert(sessionIdGame.begin(), sessionIdGame.end());
2569 sessionIds.insert(sessionIdAudioBook.begin(), sessionIdAudioBook.end());
2570
2571 InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
2572 if (server_ != nullptr) {
2573 server_->ProcessRemoteInterrupt(sessionIds, interruptEvent);
2574 }
2575 }
2576
StateOnChange(const std::string networkId,const std::string & condition,const std::string & value)2577 void AudioPolicyServer::RemoteParameterCallback::StateOnChange(const std::string networkId,
2578 const std::string& condition, const std::string& value)
2579 {
2580 char eventDes[EVENT_DES_SIZE];
2581 char contentDes[ADAPTER_STATE_CONTENT_DES_SIZE];
2582 int ret = sscanf_s(condition.c_str(), "%[^;];%s", eventDes, EVENT_DES_SIZE, contentDes,
2583 ADAPTER_STATE_CONTENT_DES_SIZE);
2584 CHECK_AND_RETURN_LOG(ret >= PARAMS_RENDER_STATE_NUM, "StateOnChange: Failed parse condition");
2585 CHECK_AND_RETURN_LOG(strcmp(eventDes, "ERR_EVENT") == 0,
2586 "StateOnChange: Event %{public}s is not supported.", eventDes);
2587
2588 std::string devTypeKey = "DEVICE_TYPE=";
2589 std::string contentDesStr = std::string(contentDes);
2590 auto devTypeKeyPos = contentDesStr.find(devTypeKey);
2591 CHECK_AND_RETURN_LOG(devTypeKeyPos != std::string::npos,
2592 "StateOnChange: Not find daudio device type info, contentDes %{public}s.", contentDesStr.c_str());
2593 size_t devTypeValPos = devTypeKeyPos + devTypeKey.length();
2594 CHECK_AND_RETURN_LOG(devTypeValPos < contentDesStr.length(),
2595 "StateOnChange: Not find daudio device type value, contentDes %{public}s.", contentDesStr.c_str());
2596
2597 if (contentDesStr[devTypeValPos] == DAUDIO_DEV_TYPE_SPK) {
2598 server_->audioPolicyService_.NotifyRemoteRenderState(networkId, contentDesStr, value);
2599 } else if (contentDesStr[devTypeValPos] == DAUDIO_DEV_TYPE_MIC) {
2600 AUDIO_INFO_LOG("StateOnChange: ERR_EVENT of DAUDIO_DEV_TYPE_MIC.");
2601 } else {
2602 AUDIO_ERR_LOG("StateOnChange: Device type is not supported, contentDes %{public}s.", contentDesStr.c_str());
2603 }
2604 }
2605
PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo & result)2606 void AudioPolicyServer::PerStateChangeCbCustomizeCallback::PermStateChangeCallback(
2607 Security::AccessToken::PermStateChangeInfo& result)
2608 {
2609 ready_ = true;
2610 Security::AccessToken::HapTokenInfo hapTokenInfo;
2611 int32_t res = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(result.tokenID, hapTokenInfo);
2612 if (res < 0) {
2613 AUDIO_ERR_LOG("Call GetHapTokenInfo fail.");
2614 }
2615
2616 bool targetMuteState = (result.permStateChangeType > 0) ? false : true;
2617 int32_t appUid = getUidByBundleName(hapTokenInfo.bundleName, hapTokenInfo.userID);
2618 if (appUid < 0) {
2619 AUDIO_ERR_LOG("fail to get uid.");
2620 } else {
2621 int32_t streamSet = server_->audioPolicyService_.SetSourceOutputStreamMute(appUid, targetMuteState);
2622 if (streamSet > 0) {
2623 UpdateMicPrivacyByCapturerState(targetMuteState, result.tokenID, appUid);
2624 }
2625 }
2626 }
2627
UpdateMicPrivacyByCapturerState(bool targetMuteState,uint32_t targetTokenId,int32_t appUid)2628 void AudioPolicyServer::PerStateChangeCbCustomizeCallback::UpdateMicPrivacyByCapturerState(
2629 bool targetMuteState, uint32_t targetTokenId, int32_t appUid)
2630 {
2631 std::vector<std::shared_ptr<AudioCapturerChangeInfo>> capturerChangeInfos;
2632 server_->audioPolicyService_.GetCurrentCapturerChangeInfos(capturerChangeInfos, true, true);
2633 for (auto &info : capturerChangeInfos) {
2634 if (info->appTokenId == targetTokenId && info->capturerState == CAPTURER_RUNNING) {
2635 AUDIO_INFO_LOG("update using mic %{public}d for uid: %{public}d because permission changed",
2636 targetMuteState, appUid);
2637 int32_t res = SUCCESS;
2638 if (targetMuteState) {
2639 res = PermissionUtil::StopUsingPermission(targetTokenId, MICROPHONE_PERMISSION);
2640 } else {
2641 res = PermissionUtil::StartUsingPermission(targetTokenId, MICROPHONE_PERMISSION);
2642 }
2643 if (res != SUCCESS) {
2644 AUDIO_ERR_LOG("update using permission failed, error code %{public}d", res);
2645 }
2646 }
2647 }
2648 }
2649
getUidByBundleName(std::string bundle_name,int user_id)2650 int32_t AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName(std::string bundle_name, int user_id)
2651 {
2652 AudioXCollie audioXCollie("AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName",
2653 GET_BUNDLE_TIME_OUT_SECONDS);
2654 WatchTimeout guard("SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager():getUidByBundleName");
2655 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2656 if (systemAbilityManager == nullptr) {
2657 return ERR_INVALID_PARAM;
2658 }
2659 guard.CheckCurrTimeout();
2660
2661 sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2662 if (remoteObject == nullptr) {
2663 return ERR_INVALID_PARAM;
2664 }
2665
2666 sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
2667 if (bundleMgrProxy == nullptr) {
2668 return ERR_INVALID_PARAM;
2669 }
2670 WatchTimeout reguard("bundleMgrProxy->GetUidByBundleName:getUidByBundleName");
2671 int32_t iUid = bundleMgrProxy->GetUidByBundleName(bundle_name, user_id);
2672 reguard.CheckCurrTimeout();
2673
2674 return iUid;
2675 }
2676
RegisterParamCallback()2677 void AudioPolicyServer::RegisterParamCallback()
2678 {
2679 AUDIO_INFO_LOG("RegisterParamCallback");
2680 remoteParameterCallback_ = std::make_shared<RemoteParameterCallback>(this);
2681 audioPolicyService_.SetParameterCallback(remoteParameterCallback_);
2682 // regiest policy provider in audio server
2683 audioPolicyService_.RegiestPolicy();
2684 }
2685
RegisterBluetoothListener()2686 void AudioPolicyServer::RegisterBluetoothListener()
2687 {
2688 AUDIO_INFO_LOG("OnAddSystemAbility bluetooth service start");
2689 audioPolicyService_.RegisterBluetoothListener();
2690 }
2691
SubscribeAccessibilityConfigObserver()2692 void AudioPolicyServer::SubscribeAccessibilityConfigObserver()
2693 {
2694 AUDIO_INFO_LOG("SubscribeAccessibilityConfigObserver");
2695 audioPolicyService_.SubscribeAccessibilityConfigObserver();
2696 }
2697
SetSystemSoundUri(const std::string & key,const std::string & uri)2698 int32_t AudioPolicyServer::SetSystemSoundUri(const std::string &key, const std::string &uri)
2699 {
2700 if (!PermissionUtil::VerifySystemPermission()) {
2701 AUDIO_ERR_LOG("GetVolumeGroupInfos: No system permission");
2702 return ERR_PERMISSION_DENIED;
2703 }
2704 AUDIO_INFO_LOG("key: %{public}s, uri: %{public}s", key.c_str(), uri.c_str());
2705 return audioPolicyService_.SetSystemSoundUri(key, uri);
2706 }
2707
GetSystemSoundUri(const std::string & key)2708 std::string AudioPolicyServer::GetSystemSoundUri(const std::string &key)
2709 {
2710 if (!PermissionUtil::VerifySystemPermission()) {
2711 AUDIO_ERR_LOG("GetVolumeGroupInfos: No system permission");
2712 return "";
2713 }
2714 AUDIO_INFO_LOG("key: %{public}s", key.c_str());
2715 return audioPolicyService_.GetSystemSoundUri(key);
2716 }
2717
GetMinStreamVolume()2718 float AudioPolicyServer::GetMinStreamVolume()
2719 {
2720 return audioPolicyService_.GetMinStreamVolume();
2721 }
2722
GetMaxStreamVolume()2723 float AudioPolicyServer::GetMaxStreamVolume()
2724 {
2725 return audioPolicyService_.GetMaxStreamVolume();
2726 }
2727
GetMaxRendererInstances()2728 int32_t AudioPolicyServer::GetMaxRendererInstances()
2729 {
2730 AUDIO_INFO_LOG("GetMaxRendererInstances");
2731 int32_t retryCount = 20; // 20 * 200000us = 4s, wait up to 4s
2732 while (!isFirstAudioServiceStart_) {
2733 retryCount--;
2734 if (retryCount > 0) {
2735 AUDIO_WARNING_LOG("Audio server is not start");
2736 usleep(200000); // Wait 200000us when audio server is not started
2737 } else {
2738 break;
2739 }
2740 }
2741 return audioPolicyService_.GetMaxRendererInstances();
2742 }
2743
RegisterDataObserver()2744 void AudioPolicyServer::RegisterDataObserver()
2745 {
2746 audioPolicyService_.RegisterDataObserver();
2747 }
2748
QueryEffectSceneMode(SupportedEffectConfig & supportedEffectConfig)2749 int32_t AudioPolicyServer::QueryEffectSceneMode(SupportedEffectConfig &supportedEffectConfig)
2750 {
2751 int32_t ret = audioPolicyService_.QueryEffectManagerSceneMode(supportedEffectConfig);
2752 return ret;
2753 }
2754
GetHardwareOutputSamplingRate(const std::shared_ptr<AudioDeviceDescriptor> & desc)2755 int32_t AudioPolicyServer::GetHardwareOutputSamplingRate(const std::shared_ptr<AudioDeviceDescriptor> &desc)
2756 {
2757 return audioPolicyService_.GetHardwareOutputSamplingRate(desc);
2758 }
2759
GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)2760 vector<sptr<MicrophoneDescriptor>> AudioPolicyServer::GetAudioCapturerMicrophoneDescriptors(int32_t sessionId)
2761 {
2762 std::vector<sptr<MicrophoneDescriptor>> micDescs =
2763 audioPolicyService_.GetAudioCapturerMicrophoneDescriptors(sessionId);
2764 return micDescs;
2765 }
2766
GetAvailableMicrophones()2767 vector<sptr<MicrophoneDescriptor>> AudioPolicyServer::GetAvailableMicrophones()
2768 {
2769 std::vector<sptr<MicrophoneDescriptor>> micDescs = audioPolicyService_.GetAvailableMicrophones();
2770 return micDescs;
2771 }
2772
SetDeviceAbsVolumeSupported(const std::string & macAddress,const bool support)2773 int32_t AudioPolicyServer::SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support)
2774 {
2775 auto callerUid = IPCSkeleton::GetCallingUid();
2776 if (callerUid != UID_BLUETOOTH_SA) {
2777 AUDIO_ERR_LOG("SetDeviceAbsVolumeSupported: Error caller uid: %{public}d", callerUid);
2778 return ERROR;
2779 }
2780 return audioPolicyService_.SetDeviceAbsVolumeSupported(macAddress, support);
2781 }
2782
IsAbsVolumeScene()2783 bool AudioPolicyServer::IsAbsVolumeScene()
2784 {
2785 return audioPolicyService_.IsAbsVolumeScene();
2786 }
2787
SetA2dpDeviceVolume(const std::string & macAddress,const int32_t volume,const bool updateUi)2788 int32_t AudioPolicyServer::SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volume,
2789 const bool updateUi)
2790 {
2791 auto callerUid = IPCSkeleton::GetCallingUid();
2792 if (callerUid != UID_BLUETOOTH_SA) {
2793 AUDIO_ERR_LOG("SetA2dpDeviceVolume: Error caller uid: %{public}d", callerUid);
2794 return ERROR;
2795 }
2796
2797 AudioStreamType streamInFocus = AudioStreamType::STREAM_MUSIC; // use STREAM_MUSIC as default stream type
2798
2799 if (!IsVolumeLevelValid(streamInFocus, volume)) {
2800 return ERR_NOT_SUPPORTED;
2801 }
2802 std::lock_guard<std::mutex> lock(systemVolumeMutex_);
2803 int32_t ret = audioPolicyService_.SetA2dpDeviceVolume(macAddress, volume);
2804
2805 VolumeEvent volumeEvent;
2806 volumeEvent.volumeType = streamInFocus;
2807 volumeEvent.volume = volume;
2808 volumeEvent.updateUi = updateUi;
2809 volumeEvent.volumeGroupId = 0;
2810 volumeEvent.networkId = LOCAL_NETWORK_ID;
2811
2812 if (ret == SUCCESS && audioPolicyServerHandler_!= nullptr && audioPolicyService_.IsCurrentActiveDeviceA2dp()) {
2813 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
2814 }
2815 return ret;
2816 }
2817
GetAvailableDevices(AudioDeviceUsage usage)2818 std::vector<std::shared_ptr<AudioDeviceDescriptor>> AudioPolicyServer::GetAvailableDevices(AudioDeviceUsage usage)
2819 {
2820 std::vector<shared_ptr<AudioDeviceDescriptor>> deviceDescs = {};
2821 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
2822 switch (usage) {
2823 case MEDIA_OUTPUT_DEVICES:
2824 case MEDIA_INPUT_DEVICES:
2825 case ALL_MEDIA_DEVICES:
2826 case CALL_OUTPUT_DEVICES:
2827 case CALL_INPUT_DEVICES:
2828 case ALL_CALL_DEVICES:
2829 case D_ALL_DEVICES:
2830 break;
2831 default:
2832 AUDIO_ERR_LOG("Invalid device usage:%{public}d", usage);
2833 return deviceDescs;
2834 }
2835
2836 deviceDescs = audioPolicyService_.GetAvailableDevices(usage);
2837
2838 if (!hasSystemPermission) {
2839 for (auto &desc : deviceDescs) {
2840 desc->networkId_ = "";
2841 desc->interruptGroupId_ = GROUP_ID_NONE;
2842 desc->volumeGroupId_ = GROUP_ID_NONE;
2843 }
2844 }
2845
2846 std::vector<std::shared_ptr<AudioDeviceDescriptor>> deviceDevices = {};
2847 for (auto &desc : deviceDescs) {
2848 deviceDevices.push_back(std::make_shared<AudioDeviceDescriptor>(*desc));
2849 }
2850
2851 bool hasBTPermission = VerifyBluetoothPermission();
2852 if (!hasBTPermission) {
2853 audioPolicyService_.UpdateDescWhenNoBTPermission(deviceDevices);
2854 deviceDescs.clear();
2855 for (auto &dec : deviceDevices) {
2856 deviceDescs.push_back(make_shared<AudioDeviceDescriptor>(*dec));
2857 }
2858 }
2859
2860 return deviceDescs;
2861 }
2862
SetAvailableDeviceChangeCallback(const int32_t,const AudioDeviceUsage usage,const sptr<IRemoteObject> & object)2863 int32_t AudioPolicyServer::SetAvailableDeviceChangeCallback(const int32_t /*clientId*/, const AudioDeviceUsage usage,
2864 const sptr<IRemoteObject> &object)
2865 {
2866 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
2867 "SetAvailableDeviceChangeCallback set listener object is nullptr");
2868 switch (usage) {
2869 case MEDIA_OUTPUT_DEVICES:
2870 case MEDIA_INPUT_DEVICES:
2871 case ALL_MEDIA_DEVICES:
2872 case CALL_OUTPUT_DEVICES:
2873 case CALL_INPUT_DEVICES:
2874 case ALL_CALL_DEVICES:
2875 case D_ALL_DEVICES:
2876 break;
2877 default:
2878 AUDIO_ERR_LOG("Invalid AudioDeviceUsage");
2879 return ERR_INVALID_PARAM;
2880 }
2881
2882 int32_t clientPid = IPCSkeleton::GetCallingPid();
2883 bool hasBTPermission = VerifyBluetoothPermission();
2884 return audioPolicyService_.SetAvailableDeviceChangeCallback(clientPid, usage, object, hasBTPermission);
2885 }
2886
UnsetAvailableDeviceChangeCallback(const int32_t,AudioDeviceUsage usage)2887 int32_t AudioPolicyServer::UnsetAvailableDeviceChangeCallback(const int32_t /*clientId*/, AudioDeviceUsage usage)
2888 {
2889 int32_t clientPid = IPCSkeleton::GetCallingPid();
2890 return audioPolicyService_.UnsetAvailableDeviceChangeCallback(clientPid, usage);
2891 }
2892
OffloadStopPlaying(const AudioInterrupt & audioInterrupt)2893 int32_t AudioPolicyServer::OffloadStopPlaying(const AudioInterrupt &audioInterrupt)
2894 {
2895 return audioPolicyService_.OffloadStopPlaying(std::vector<int32_t>(1, audioInterrupt.streamId));
2896 }
2897
ConfigDistributedRoutingRole(const std::shared_ptr<AudioDeviceDescriptor> descriptor,CastType type)2898 int32_t AudioPolicyServer::ConfigDistributedRoutingRole(
2899 const std::shared_ptr<AudioDeviceDescriptor> descriptor, CastType type)
2900 {
2901 if (!PermissionUtil::VerifySystemPermission()) {
2902 AUDIO_ERR_LOG("No system permission");
2903 return ERR_PERMISSION_DENIED;
2904 }
2905 std::lock_guard<std::mutex> lock(descLock_);
2906 audioPolicyService_.ConfigDistributedRoutingRole(descriptor, type);
2907 OnDistributedRoutingRoleChange(descriptor, type);
2908 return SUCCESS;
2909 }
2910
SetDistributedRoutingRoleCallback(const sptr<IRemoteObject> & object)2911 int32_t AudioPolicyServer::SetDistributedRoutingRoleCallback(const sptr<IRemoteObject> &object)
2912 {
2913 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
2914 "SetDistributedRoutingRoleCallback set listener object is nullptr");
2915 int32_t clientPid = IPCSkeleton::GetCallingPid();
2916 bool hasBTPermission = VerifyBluetoothPermission();
2917 AUDIO_INFO_LOG("Entered %{public}s", __func__);
2918 sptr<IStandardAudioRoutingManagerListener> listener = iface_cast<IStandardAudioRoutingManagerListener>(object);
2919 if (listener != nullptr && audioPolicyServerHandler_ != nullptr) {
2920 listener->hasBTPermission_ = hasBTPermission;
2921 audioPolicyServerHandler_->AddDistributedRoutingRoleChangeCbsMap(clientPid, listener);
2922 }
2923 return SUCCESS;
2924 }
2925
UnsetDistributedRoutingRoleCallback()2926 int32_t AudioPolicyServer::UnsetDistributedRoutingRoleCallback()
2927 {
2928 int32_t clientPid = IPCSkeleton::GetCallingPid();
2929 AUDIO_INFO_LOG("Entered %{public}s", __func__);
2930 if (audioPolicyServerHandler_ != nullptr) {
2931 return audioPolicyServerHandler_->RemoveDistributedRoutingRoleChangeCbsMap(clientPid);
2932 }
2933 return SUCCESS;
2934 }
2935
OnDistributedRoutingRoleChange(const std::shared_ptr<AudioDeviceDescriptor> descriptor,const CastType type)2936 void AudioPolicyServer::OnDistributedRoutingRoleChange(const std::shared_ptr<AudioDeviceDescriptor> descriptor,
2937 const CastType type)
2938 {
2939 CHECK_AND_RETURN_LOG(audioPolicyServerHandler_ != nullptr, "audioPolicyServerHandler_ is nullptr");
2940 audioPolicyServerHandler_->SendDistributedRoutingRoleChange(descriptor, type);
2941 }
2942
RegisterPowerStateListener()2943 void AudioPolicyServer::RegisterPowerStateListener()
2944 {
2945 if (powerStateListener_ == nullptr) {
2946 powerStateListener_ = new (std::nothrow) PowerStateListener(this);
2947 }
2948
2949 if (powerStateListener_ == nullptr) {
2950 AUDIO_ERR_LOG("create power state listener failed");
2951 return;
2952 }
2953
2954 auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
2955 WatchTimeout guard("powerMgrClient.RegisterSyncSleepCallback:RegisterPowerStateListener");
2956 bool ret = powerMgrClient.RegisterSyncSleepCallback(powerStateListener_, SleepPriority::HIGH);
2957 guard.CheckCurrTimeout();
2958 if (!ret) {
2959 AUDIO_ERR_LOG("register sync sleep callback failed");
2960 } else {
2961 AUDIO_INFO_LOG("register sync sleep callback success");
2962 }
2963 }
2964
UnRegisterPowerStateListener()2965 void AudioPolicyServer::UnRegisterPowerStateListener()
2966 {
2967 if (powerStateListener_ == nullptr) {
2968 AUDIO_ERR_LOG("power state listener is null");
2969 return;
2970 }
2971
2972 auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
2973 WatchTimeout guard("powerMgrClient.UnRegisterSyncSleepCallback:UnRegisterPowerStateListener");
2974 bool ret = powerMgrClient.UnRegisterSyncSleepCallback(powerStateListener_);
2975 guard.CheckCurrTimeout();
2976 if (!ret) {
2977 AUDIO_WARNING_LOG("unregister sync sleep callback failed");
2978 } else {
2979 powerStateListener_ = nullptr;
2980 AUDIO_INFO_LOG("unregister sync sleep callback success");
2981 }
2982 }
2983
RegisterAppStateListener()2984 void AudioPolicyServer::RegisterAppStateListener()
2985 {
2986 AUDIO_INFO_LOG("OnAddSystemAbility app manager service start");
2987 if (appStateListener_ == nullptr) {
2988 appStateListener_ = new(std::nothrow) AppStateListener();
2989 }
2990
2991 if (appStateListener_ == nullptr) {
2992 AUDIO_ERR_LOG("create app state listener failed");
2993 return;
2994 }
2995
2996 if (appManager_.RegisterAppStateCallback(appStateListener_) != AppExecFwk::AppMgrResultCode::RESULT_OK) {
2997 AUDIO_ERR_LOG("register app state callback failed");
2998 }
2999 }
3000
RegisterSyncHibernateListener()3001 void AudioPolicyServer::RegisterSyncHibernateListener()
3002 {
3003 if (syncHibernateListener_ == nullptr) {
3004 syncHibernateListener_ = new (std::nothrow) SyncHibernateListener(this);
3005 }
3006
3007 if (syncHibernateListener_ == nullptr) {
3008 AUDIO_ERR_LOG("create sync hibernate listener failed");
3009 return;
3010 }
3011
3012 auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
3013 WatchTimeout guard("powerMgrClient.RegisterSyncHibernateCallback:RegisterSyncHibernateListener");
3014 bool ret = powerMgrClient.RegisterSyncHibernateCallback(syncHibernateListener_);
3015 guard.CheckCurrTimeout();
3016 if (!ret) {
3017 AUDIO_ERR_LOG("register sync hibernate callback failed");
3018 } else {
3019 AUDIO_INFO_LOG("register sync hibernate callback success");
3020 }
3021 }
3022
UnRegisterSyncHibernateListener()3023 void AudioPolicyServer::UnRegisterSyncHibernateListener()
3024 {
3025 if (syncHibernateListener_ == nullptr) {
3026 AUDIO_ERR_LOG("sync hibernate listener is null");
3027 return;
3028 }
3029
3030 auto& powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
3031 WatchTimeout guard("powerMgrClient.UnRegisterSyncHibernateCallback:UnRegisterSyncHibernateListener");
3032 bool ret = powerMgrClient.UnRegisterSyncHibernateCallback(syncHibernateListener_);
3033 guard.CheckCurrTimeout();
3034 if (!ret) {
3035 AUDIO_WARNING_LOG("unregister sync hibernate callback failed");
3036 } else {
3037 syncHibernateListener_ = nullptr;
3038 AUDIO_INFO_LOG("unregister sync hibernate callback success");
3039 }
3040 }
3041
IsSpatializationEnabled()3042 bool AudioPolicyServer::IsSpatializationEnabled()
3043 {
3044 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3045 if (!hasSystemPermission) {
3046 return false;
3047 }
3048 return audioSpatializationService_.IsSpatializationEnabled();
3049 }
3050
IsSpatializationEnabled(const std::string address)3051 bool AudioPolicyServer::IsSpatializationEnabled(const std::string address)
3052 {
3053 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3054 if (!hasSystemPermission) {
3055 return false;
3056 }
3057 return audioSpatializationService_.IsSpatializationEnabled(address);
3058 }
3059
IsSpatializationEnabledForCurrentDevice()3060 bool AudioPolicyServer::IsSpatializationEnabledForCurrentDevice()
3061 {
3062 return audioSpatializationService_.IsSpatializationEnabledForCurrentDevice();
3063 }
3064
SetSpatializationEnabled(const bool enable)3065 int32_t AudioPolicyServer::SetSpatializationEnabled(const bool enable)
3066 {
3067 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3068 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3069 return ERR_PERMISSION_DENIED;
3070 }
3071 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3072 if (!hasSystemPermission) {
3073 return ERR_PERMISSION_DENIED;
3074 }
3075 return audioSpatializationService_.SetSpatializationEnabled(enable);
3076 }
3077
SetSpatializationEnabled(const std::shared_ptr<AudioDeviceDescriptor> & selectedAudioDevice,const bool enable)3078 int32_t AudioPolicyServer::SetSpatializationEnabled(const std::shared_ptr<AudioDeviceDescriptor> &selectedAudioDevice,
3079 const bool enable)
3080 {
3081 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3082 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3083 return ERR_PERMISSION_DENIED;
3084 }
3085 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3086 if (!hasSystemPermission) {
3087 return ERR_PERMISSION_DENIED;
3088 }
3089 return audioSpatializationService_.SetSpatializationEnabled(selectedAudioDevice, enable);
3090 }
3091
IsHeadTrackingEnabled()3092 bool AudioPolicyServer::IsHeadTrackingEnabled()
3093 {
3094 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3095 if (!hasSystemPermission) {
3096 return false;
3097 }
3098 return audioSpatializationService_.IsHeadTrackingEnabled();
3099 }
3100
IsHeadTrackingEnabled(const std::string address)3101 bool AudioPolicyServer::IsHeadTrackingEnabled(const std::string address)
3102 {
3103 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3104 if (!hasSystemPermission) {
3105 return false;
3106 }
3107 return audioSpatializationService_.IsHeadTrackingEnabled(address);
3108 }
3109
SetHeadTrackingEnabled(const bool enable)3110 int32_t AudioPolicyServer::SetHeadTrackingEnabled(const bool enable)
3111 {
3112 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3113 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3114 return ERR_PERMISSION_DENIED;
3115 }
3116 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3117 if (!hasSystemPermission) {
3118 return ERR_PERMISSION_DENIED;
3119 }
3120 return audioSpatializationService_.SetHeadTrackingEnabled(enable);
3121 }
3122
SetHeadTrackingEnabled(const std::shared_ptr<AudioDeviceDescriptor> & selectedAudioDevice,const bool enable)3123 int32_t AudioPolicyServer::SetHeadTrackingEnabled(const std::shared_ptr<AudioDeviceDescriptor> &selectedAudioDevice,
3124 const bool enable)
3125 {
3126 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3127 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3128 return ERR_PERMISSION_DENIED;
3129 }
3130 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3131 if (!hasSystemPermission) {
3132 return ERR_PERMISSION_DENIED;
3133 }
3134 return audioSpatializationService_.SetHeadTrackingEnabled(selectedAudioDevice, enable);
3135 }
3136
GetSpatializationState(const StreamUsage streamUsage)3137 AudioSpatializationState AudioPolicyServer::GetSpatializationState(const StreamUsage streamUsage)
3138 {
3139 return audioSpatializationService_.GetSpatializationState(streamUsage);
3140 }
3141
IsSpatializationSupported()3142 bool AudioPolicyServer::IsSpatializationSupported()
3143 {
3144 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3145 if (!hasSystemPermission) {
3146 return false;
3147 }
3148 return audioSpatializationService_.IsSpatializationSupported();
3149 }
3150
IsSpatializationSupportedForDevice(const std::string address)3151 bool AudioPolicyServer::IsSpatializationSupportedForDevice(const std::string address)
3152 {
3153 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3154 if (!hasSystemPermission) {
3155 return false;
3156 }
3157 return audioSpatializationService_.IsSpatializationSupportedForDevice(address);
3158 }
3159
IsHeadTrackingSupported()3160 bool AudioPolicyServer::IsHeadTrackingSupported()
3161 {
3162 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3163 if (!hasSystemPermission) {
3164 return false;
3165 }
3166 return audioSpatializationService_.IsHeadTrackingSupported();
3167 }
3168
IsHeadTrackingSupportedForDevice(const std::string address)3169 bool AudioPolicyServer::IsHeadTrackingSupportedForDevice(const std::string address)
3170 {
3171 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3172 if (!hasSystemPermission) {
3173 return false;
3174 }
3175 return audioSpatializationService_.IsHeadTrackingSupportedForDevice(address);
3176 }
3177
UpdateSpatialDeviceState(const AudioSpatialDeviceState audioSpatialDeviceState)3178 int32_t AudioPolicyServer::UpdateSpatialDeviceState(const AudioSpatialDeviceState audioSpatialDeviceState)
3179 {
3180 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3181 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3182 return ERR_PERMISSION_DENIED;
3183 }
3184 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3185 if (!hasSystemPermission) {
3186 return ERR_PERMISSION_DENIED;
3187 }
3188 return audioSpatializationService_.UpdateSpatialDeviceState(audioSpatialDeviceState);
3189 }
3190
RegisterSpatializationStateEventListener(const uint32_t sessionID,const StreamUsage streamUsage,const sptr<IRemoteObject> & object)3191 int32_t AudioPolicyServer::RegisterSpatializationStateEventListener(const uint32_t sessionID,
3192 const StreamUsage streamUsage, const sptr<IRemoteObject> &object)
3193 {
3194 return audioSpatializationService_.RegisterSpatializationStateEventListener(sessionID, streamUsage, object);
3195 }
3196
UnregisterSpatializationStateEventListener(const uint32_t sessionID)3197 int32_t AudioPolicyServer::UnregisterSpatializationStateEventListener(const uint32_t sessionID)
3198 {
3199 return audioSpatializationService_.UnregisterSpatializationStateEventListener(sessionID);
3200 }
3201
RegisterPolicyCallbackClient(const sptr<IRemoteObject> & object,const int32_t zoneID)3202 int32_t AudioPolicyServer::RegisterPolicyCallbackClient(const sptr<IRemoteObject> &object, const int32_t zoneID)
3203 {
3204 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
3205 "RegisterPolicyCallbackClient listener object is nullptr");
3206
3207 sptr<IAudioPolicyClient> callback = iface_cast<IAudioPolicyClient>(object);
3208 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM,
3209 "RegisterPolicyCallbackClient listener obj cast failed");
3210
3211 int32_t clientPid = IPCSkeleton::GetCallingPid();
3212 AUDIO_DEBUG_LOG("register clientPid: %{public}d", clientPid);
3213
3214 bool hasBTPermission = VerifyBluetoothPermission();
3215 bool hasSysPermission = PermissionUtil::VerifySystemPermission();
3216 callback->hasBTPermission_ = hasBTPermission;
3217 callback->hasSystemPermission_ = hasSysPermission;
3218 callback->apiVersion_ = GetApiTargerVersion();
3219 audioPolicyService_.AddAudioPolicyClientProxyMap(clientPid, callback);
3220
3221 RegisterClientDeathRecipient(object, LISTENER_CLIENT);
3222 return SUCCESS;
3223 }
3224
CreateAudioInterruptZone(const std::set<int32_t> & pids,const int32_t zoneID)3225 int32_t AudioPolicyServer::CreateAudioInterruptZone(const std::set<int32_t> &pids, const int32_t zoneID)
3226 {
3227 return ERR_UNKNOWN;
3228 }
3229
AddAudioInterruptZonePids(const std::set<int32_t> & pids,const int32_t zoneID)3230 int32_t AudioPolicyServer::AddAudioInterruptZonePids(const std::set<int32_t> &pids, const int32_t zoneID)
3231 {
3232 return ERR_UNKNOWN;
3233 }
3234
RemoveAudioInterruptZonePids(const std::set<int32_t> & pids,const int32_t zoneID)3235 int32_t AudioPolicyServer::RemoveAudioInterruptZonePids(const std::set<int32_t> &pids, const int32_t zoneID)
3236 {
3237 return ERR_UNKNOWN;
3238 }
3239
ReleaseAudioInterruptZone(const int32_t zoneID)3240 int32_t AudioPolicyServer::ReleaseAudioInterruptZone(const int32_t zoneID)
3241 {
3242 return ERR_UNKNOWN;
3243 }
3244
SetCallDeviceActive(InternalDeviceType deviceType,bool active,std::string address,const int32_t uid)3245 int32_t AudioPolicyServer::SetCallDeviceActive(InternalDeviceType deviceType, bool active, std::string address,
3246 const int32_t uid)
3247 {
3248 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3249 if (!hasSystemPermission) {
3250 AUDIO_ERR_LOG("No system permission");
3251 return ERR_SYSTEM_PERMISSION_DENIED;
3252 }
3253 switch (deviceType) {
3254 case DeviceType::DEVICE_TYPE_EARPIECE:
3255 case DeviceType::DEVICE_TYPE_SPEAKER:
3256 case DeviceType::DEVICE_TYPE_BLUETOOTH_SCO:
3257 break;
3258 default:
3259 AUDIO_ERR_LOG("device=%{public}d not supported", deviceType);
3260 return ERR_NOT_SUPPORTED;
3261 }
3262 return audioPolicyService_.SetCallDeviceActive(deviceType, active, address, uid);
3263 }
3264
GetActiveBluetoothDevice()3265 std::shared_ptr<AudioDeviceDescriptor> AudioPolicyServer::GetActiveBluetoothDevice()
3266 {
3267 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3268 if (!hasSystemPermission) {
3269 AUDIO_ERR_LOG("No system permission");
3270 return make_shared<AudioDeviceDescriptor>();
3271 }
3272
3273 auto btdevice = audioPolicyService_.GetActiveBluetoothDevice();
3274
3275 bool hasBTPermission = VerifyBluetoothPermission();
3276 if (!hasBTPermission) {
3277 btdevice->deviceName_ = "";
3278 btdevice->macAddress_ = "";
3279 }
3280
3281 return btdevice;
3282 }
3283
GetBundleName()3284 std::string AudioPolicyServer::GetBundleName()
3285 {
3286 AppExecFwk::BundleInfo bundleInfo = GetBundleInfoFromUid(IPCSkeleton::GetCallingUid());
3287 return bundleInfo.name;
3288 }
3289
GetConverterConfig()3290 ConverterConfig AudioPolicyServer::GetConverterConfig()
3291 {
3292 return audioPolicyService_.GetConverterConfig();
3293 }
3294
GetSpatializationSceneType()3295 AudioSpatializationSceneType AudioPolicyServer::GetSpatializationSceneType()
3296 {
3297 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3298 if (!hasSystemPermission) {
3299 return SPATIALIZATION_SCENE_TYPE_MUSIC;
3300 }
3301 return audioSpatializationService_.GetSpatializationSceneType();
3302 }
3303
SetSpatializationSceneType(const AudioSpatializationSceneType spatializationSceneType)3304 int32_t AudioPolicyServer::SetSpatializationSceneType(const AudioSpatializationSceneType spatializationSceneType)
3305 {
3306 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3307 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3308 return ERR_PERMISSION_DENIED;
3309 }
3310 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3311 if (!hasSystemPermission) {
3312 return ERR_PERMISSION_DENIED;
3313 }
3314 return audioSpatializationService_.SetSpatializationSceneType(spatializationSceneType);
3315 }
3316
DisableSafeMediaVolume()3317 int32_t AudioPolicyServer::DisableSafeMediaVolume()
3318 {
3319 if (!VerifyPermission(MODIFY_AUDIO_SETTINGS_PERMISSION)) {
3320 AUDIO_ERR_LOG("MODIFY_AUDIO_SETTINGS_PERMISSION permission check failed");
3321 return ERR_PERMISSION_DENIED;
3322 }
3323 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3324 if (!hasSystemPermission) {
3325 return ERR_SYSTEM_PERMISSION_DENIED;
3326 }
3327 return audioPolicyService_.DisableSafeMediaVolume();
3328 }
3329
GetBundleInfoFromUid(int32_t callingUid)3330 AppExecFwk::BundleInfo AudioPolicyServer::GetBundleInfoFromUid(int32_t callingUid)
3331 {
3332 AudioXCollie audioXCollie("AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName",
3333 GET_BUNDLE_TIME_OUT_SECONDS);
3334 std::string bundleName {""};
3335 AppExecFwk::BundleInfo bundleInfo;
3336 WatchTimeout guard("SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager():GetBundleInfoFromUid");
3337 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3338 CHECK_AND_RETURN_RET_LOG(systemAbilityManager != nullptr, bundleInfo, "systemAbilityManager is nullptr");
3339 guard.CheckCurrTimeout();
3340
3341 sptr<IRemoteObject> remoteObject = systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
3342 CHECK_AND_RETURN_RET_PRELOG(remoteObject != nullptr, bundleInfo, "remoteObject is nullptr");
3343
3344 sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
3345 CHECK_AND_RETURN_RET_LOG(bundleMgrProxy != nullptr, bundleInfo, "bundleMgrProxy is nullptr");
3346
3347 WatchTimeout reguard("bundleMgrProxy->GetNameForUid:GetBundleInfoFromUid");
3348 bundleMgrProxy->GetNameForUid(callingUid, bundleName);
3349
3350 bundleMgrProxy->GetBundleInfoV9(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT |
3351 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES |
3352 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION |
3353 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO |
3354 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_HASH_VALUE,
3355 bundleInfo,
3356 AppExecFwk::Constants::ALL_USERID);
3357 reguard.CheckCurrTimeout();
3358
3359 return bundleInfo;
3360 }
3361
GetApiTargerVersion()3362 int32_t AudioPolicyServer::GetApiTargerVersion()
3363 {
3364 AppExecFwk::BundleInfo bundleInfo = GetBundleInfoFromUid(IPCSkeleton::GetCallingUid());
3365
3366 // Taking remainder of large integers
3367 int32_t apiTargetversion = bundleInfo.applicationInfo.apiTargetVersion % API_VERSION_REMAINDER;
3368 return apiTargetversion;
3369 }
3370
IsHighResolutionExist()3371 bool AudioPolicyServer::IsHighResolutionExist()
3372 {
3373 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3374 if (!hasSystemPermission) {
3375 AUDIO_ERR_LOG("No system permission");
3376 return false;
3377 }
3378 return isHighResolutionExist_;
3379 }
3380
SetHighResolutionExist(bool highResExist)3381 int32_t AudioPolicyServer::SetHighResolutionExist(bool highResExist)
3382 {
3383 bool hasSystemPermission = PermissionUtil::VerifySystemPermission();
3384 if (!hasSystemPermission) {
3385 AUDIO_ERR_LOG("No system permission");
3386 return ERR_PERMISSION_DENIED;
3387 }
3388 isHighResolutionExist_ = highResExist;
3389 return SUCCESS;
3390 }
3391
GetMaxAmplitude(int32_t deviceId)3392 float AudioPolicyServer::GetMaxAmplitude(int32_t deviceId)
3393 {
3394 AudioInterrupt audioInterrupt;
3395 GetSessionInfoInFocus(audioInterrupt);
3396 return audioPolicyService_.GetMaxAmplitude(deviceId, audioInterrupt);
3397 }
3398
IsHeadTrackingDataRequested(const std::string & macAddress)3399 bool AudioPolicyServer::IsHeadTrackingDataRequested(const std::string &macAddress)
3400 {
3401 return audioSpatializationService_.IsHeadTrackingDataRequested(macAddress);
3402 }
3403
SetAudioDeviceRefinerCallback(const sptr<IRemoteObject> & object)3404 int32_t AudioPolicyServer::SetAudioDeviceRefinerCallback(const sptr<IRemoteObject> &object)
3405 {
3406 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "SetAudioDeviceRefinerCallback object is nullptr");
3407 auto callerUid = IPCSkeleton::GetCallingUid();
3408 if (callerUid != UID_AUDIO) {
3409 return ERROR;
3410 }
3411 return audioRouterCenter_.SetAudioDeviceRefinerCallback(object);
3412 }
3413
UnsetAudioDeviceRefinerCallback()3414 int32_t AudioPolicyServer::UnsetAudioDeviceRefinerCallback()
3415 {
3416 auto callerUid = IPCSkeleton::GetCallingUid();
3417 if (callerUid != UID_AUDIO) {
3418 return ERROR;
3419 }
3420 return audioRouterCenter_.UnsetAudioDeviceRefinerCallback();
3421 }
3422
TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)3423 int32_t AudioPolicyServer::TriggerFetchDevice(AudioStreamDeviceChangeReasonExt reason)
3424 {
3425 auto callerUid = IPCSkeleton::GetCallingUid();
3426 if (callerUid != UID_AUDIO) {
3427 return ERROR;
3428 }
3429 return audioPolicyService_.TriggerFetchDevice(reason);
3430 }
3431
SetPreferredDevice(const PreferredType preferredType,const std::shared_ptr<AudioDeviceDescriptor> & desc,const int32_t uid)3432 int32_t AudioPolicyServer::SetPreferredDevice(const PreferredType preferredType,
3433 const std::shared_ptr<AudioDeviceDescriptor> &desc, const int32_t uid)
3434 {
3435 auto callerUid = IPCSkeleton::GetCallingUid();
3436 if (callerUid != UID_AUDIO) {
3437 AUDIO_ERR_LOG("No permission");
3438 return ERROR;
3439 }
3440 return audioPolicyUtils_.SetPreferredDevice(preferredType, desc, uid, "SetPreferredDevice");
3441 }
3442
SaveRemoteInfo(const std::string & networkId,DeviceType deviceType)3443 void AudioPolicyServer::SaveRemoteInfo(const std::string &networkId, DeviceType deviceType)
3444 {
3445 auto callerUid = IPCSkeleton::GetCallingUid();
3446 if (callerUid != UID_AUDIO) {
3447 AUDIO_ERR_LOG("No permission");
3448 return;
3449 }
3450 std::shared_ptr<AudioDeviceDescriptor> newMediaDescriptor =
3451 audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_MEDIA, -1, ROUTER_TYPE_USER_SELECT).front();
3452 std::shared_ptr<AudioDeviceDescriptor> newCallDescriptor =
3453 audioRouterCenter_.FetchOutputDevices(STREAM_USAGE_VOICE_COMMUNICATION, -1,
3454 ROUTER_TYPE_USER_SELECT).front();
3455 if (networkId == newMediaDescriptor->networkId_ && deviceType == newMediaDescriptor->deviceType_) {
3456 audioPolicyUtils_.SetPreferredDevice(AUDIO_MEDIA_RENDER, std::make_shared<AudioDeviceDescriptor>());
3457 }
3458 if (networkId == newCallDescriptor->networkId_ && deviceType == newCallDescriptor->deviceType_) {
3459 audioPolicyUtils_.SetPreferredDevice(AUDIO_CALL_RENDER, std::make_shared<AudioDeviceDescriptor>(), SYSTEM_UID,
3460 "SaveRemoteInfo");
3461 }
3462 audioDeviceManager_.SaveRemoteInfo(networkId, deviceType);
3463 }
3464
SetAudioDeviceAnahsCallback(const sptr<IRemoteObject> & object)3465 int32_t AudioPolicyServer::SetAudioDeviceAnahsCallback(const sptr<IRemoteObject> &object)
3466 {
3467 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "SetAudioDeviceAnahsCallback object is nullptr");
3468 auto callerUid = IPCSkeleton::GetCallingUid();
3469 if (callerUid != UID_AUDIO) {
3470 return ERROR;
3471 }
3472 return audioPolicyService_.SetAudioDeviceAnahsCallback(object);
3473 }
3474
UnsetAudioDeviceAnahsCallback()3475 int32_t AudioPolicyServer::UnsetAudioDeviceAnahsCallback()
3476 {
3477 auto callerUid = IPCSkeleton::GetCallingUid();
3478 if (callerUid != UID_AUDIO) {
3479 return ERROR;
3480 }
3481 return audioPolicyService_.UnsetAudioDeviceAnahsCallback();
3482 }
3483
NotifyAccountsChanged(const int & id)3484 void AudioPolicyServer::NotifyAccountsChanged(const int &id)
3485 {
3486 CHECK_AND_RETURN_LOG(interruptService_ != nullptr, "interruptService_ is nullptr");
3487 interruptService_->ClearAudioFocusInfoListOnAccountsChanged(id);
3488 audioPolicyService_.NotifyAccountsChanged(id);
3489 }
3490
MoveToNewPipe(const uint32_t sessionId,const AudioPipeType pipeType)3491 int32_t AudioPolicyServer::MoveToNewPipe(const uint32_t sessionId, const AudioPipeType pipeType)
3492 {
3493 return audioPolicyService_.MoveToNewPipe(sessionId, pipeType);
3494 }
3495
SetAudioConcurrencyCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)3496 int32_t AudioPolicyServer::SetAudioConcurrencyCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object)
3497 {
3498 return audioPolicyService_.SetAudioConcurrencyCallback(sessionID, object);
3499 }
3500
UnsetAudioConcurrencyCallback(const uint32_t sessionID)3501 int32_t AudioPolicyServer::UnsetAudioConcurrencyCallback(const uint32_t sessionID)
3502 {
3503 return audioPolicyService_.UnsetAudioConcurrencyCallback(sessionID);
3504 }
3505
ActivateAudioConcurrency(const AudioPipeType & pipeType)3506 int32_t AudioPolicyServer::ActivateAudioConcurrency(const AudioPipeType &pipeType)
3507 {
3508 return audioPolicyService_.ActivateAudioConcurrency(pipeType);
3509 }
3510
CheckHibernateState(bool hibernate)3511 void AudioPolicyServer::CheckHibernateState(bool hibernate)
3512 {
3513 audioPolicyService_.CheckHibernateState(hibernate);
3514 }
3515
UpdateSafeVolumeByS4()3516 void AudioPolicyServer::UpdateSafeVolumeByS4()
3517 {
3518 audioPolicyService_.UpdateSafeVolumeByS4();
3519 }
3520
CheckConnectedDevice()3521 void AudioPolicyServer::CheckConnectedDevice()
3522 {
3523 audioPolicyService_.CheckConnectedDevice();
3524 }
3525
SetDeviceConnectedFlagFalseAfterDuration()3526 void AudioPolicyServer::SetDeviceConnectedFlagFalseAfterDuration()
3527 {
3528 audioPolicyService_.SetDeviceConnectedFlagFalseAfterDuration();
3529 }
3530
GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)3531 int32_t AudioPolicyServer::GetSupportedAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
3532 {
3533 bool ret = PermissionUtil::VerifySystemPermission();
3534 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3535 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3536 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3537 return ERR_PERMISSION_DENIED;
3538 }
3539 audioPolicyService_.GetSupportedAudioEffectProperty(propertyArray);
3540 return AUDIO_OK;
3541 }
3542
SetAudioEffectProperty(const AudioEffectPropertyArrayV3 & propertyArray)3543 int32_t AudioPolicyServer::SetAudioEffectProperty(const AudioEffectPropertyArrayV3 &propertyArray)
3544 {
3545 bool ret = PermissionUtil::VerifySystemPermission();
3546 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3547 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3548 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3549 return ERR_PERMISSION_DENIED;
3550 }
3551 return audioPolicyService_.SetAudioEffectProperty(propertyArray);
3552 }
3553
GetAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray)3554 int32_t AudioPolicyServer::GetAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray)
3555 {
3556 bool ret = PermissionUtil::VerifySystemPermission();
3557 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3558 if (!VerifyPermission(MANAGE_SYSTEM_AUDIO_EFFECTS)) {
3559 AUDIO_ERR_LOG("MANAGE_SYSTEM_AUDIO_EFFECTS permission check failed");
3560 return ERR_PERMISSION_DENIED;
3561 }
3562 return audioPolicyService_.GetAudioEffectProperty(propertyArray);
3563 }
3564
GetSupportedAudioEffectProperty(AudioEffectPropertyArray & propertyArray)3565 int32_t AudioPolicyServer::GetSupportedAudioEffectProperty(AudioEffectPropertyArray &propertyArray)
3566 {
3567 bool ret = PermissionUtil::VerifySystemPermission();
3568 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3569 return audioPolicyService_.GetSupportedAudioEffectProperty(propertyArray);
3570 }
3571
GetSupportedAudioEnhanceProperty(AudioEnhancePropertyArray & propertyArray)3572 int32_t AudioPolicyServer::GetSupportedAudioEnhanceProperty(AudioEnhancePropertyArray &propertyArray)
3573 {
3574 bool ret = PermissionUtil::VerifySystemPermission();
3575 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3576 return audioPolicyService_.GetSupportedAudioEnhanceProperty(propertyArray);
3577 }
3578
GetAudioEnhanceProperty(AudioEnhancePropertyArray & propertyArray)3579 int32_t AudioPolicyServer::GetAudioEnhanceProperty(AudioEnhancePropertyArray &propertyArray)
3580 {
3581 bool ret = PermissionUtil::VerifySystemPermission();
3582 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3583 return audioPolicyService_.GetAudioEnhanceProperty(propertyArray);
3584 }
3585
SetAudioEnhanceProperty(const AudioEnhancePropertyArray & propertyArray)3586 int32_t AudioPolicyServer::SetAudioEnhanceProperty(const AudioEnhancePropertyArray &propertyArray)
3587 {
3588 bool ret = PermissionUtil::VerifySystemPermission();
3589 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3590 return audioPolicyService_.SetAudioEnhanceProperty(propertyArray);
3591 }
3592
SetAudioEffectProperty(const AudioEffectPropertyArray & propertyArray)3593 int32_t AudioPolicyServer::SetAudioEffectProperty(const AudioEffectPropertyArray &propertyArray)
3594 {
3595 bool ret = PermissionUtil::VerifySystemPermission();
3596 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3597 return audioPolicyService_.SetAudioEffectProperty(propertyArray);
3598 }
3599
GetAudioEffectProperty(AudioEffectPropertyArray & propertyArray)3600 int32_t AudioPolicyServer::GetAudioEffectProperty(AudioEffectPropertyArray &propertyArray)
3601 {
3602 bool ret = PermissionUtil::VerifySystemPermission();
3603 CHECK_AND_RETURN_RET_LOG(ret, ERR_SYSTEM_PERMISSION_DENIED, "No system permission");
3604 return audioPolicyService_.GetAudioEffectProperty(propertyArray);
3605 }
3606
InjectInterruption(const std::string networkId,InterruptEvent & event)3607 int32_t AudioPolicyServer::InjectInterruption(const std::string networkId, InterruptEvent &event)
3608 {
3609 auto callerUid = IPCSkeleton::GetCallingUid();
3610 if (callerUid != UID_CAST_ENGINE_SA) {
3611 AUDIO_ERR_LOG("InjectInterruption callerUid is Error: not cast_engine");
3612 return ERROR;
3613 }
3614 CHECK_AND_RETURN_RET_LOG(audioPolicyServerHandler_ != nullptr, ERROR, "audioPolicyServerHandler_ is nullptr");
3615 std::set<int32_t> sessionIds =
3616 AudioStreamCollector::GetAudioStreamCollector().GetSessionIdsOnRemoteDeviceByDeviceType(
3617 DEVICE_TYPE_REMOTE_CAST);
3618 InterruptEventInternal interruptEvent { event.eventType, event.forceType, event.hintType, 0.2f};
3619 ProcessRemoteInterrupt(sessionIds, interruptEvent);
3620 return SUCCESS;
3621 }
3622
CheckAudioSessionStrategy(const AudioSessionStrategy & sessionStrategy)3623 bool AudioPolicyServer::CheckAudioSessionStrategy(const AudioSessionStrategy &sessionStrategy)
3624 {
3625 bool result = false;
3626 switch (sessionStrategy.concurrencyMode) {
3627 case AudioConcurrencyMode::DEFAULT:
3628 case AudioConcurrencyMode::MIX_WITH_OTHERS:
3629 case AudioConcurrencyMode::DUCK_OTHERS:
3630 case AudioConcurrencyMode::PAUSE_OTHERS:
3631 result = true;
3632 break;
3633 default:
3634 AUDIO_ERR_LOG("Invalid concurrency mode: %{public}d!",
3635 static_cast<int32_t>(sessionStrategy.concurrencyMode));
3636 result = false;
3637 break;
3638 }
3639 return result;
3640 }
3641
ActivateAudioSession(const AudioSessionStrategy & strategy)3642 int32_t AudioPolicyServer::ActivateAudioSession(const AudioSessionStrategy &strategy)
3643 {
3644 if (interruptService_ == nullptr) {
3645 AUDIO_ERR_LOG("interruptService_ is nullptr!");
3646 return ERR_UNKNOWN;
3647 }
3648 if (!CheckAudioSessionStrategy(strategy)) {
3649 AUDIO_ERR_LOG("The audio session strategy is invalid!");
3650 return ERR_INVALID_PARAM;
3651 }
3652 int32_t callerPid = IPCSkeleton::GetCallingPid();
3653 AUDIO_INFO_LOG("activate audio session with concurrencyMode %{public}d for pid %{public}d",
3654 static_cast<int32_t>(strategy.concurrencyMode), callerPid);
3655 return interruptService_->ActivateAudioSession(callerPid, strategy);
3656 }
3657
DeactivateAudioSession()3658 int32_t AudioPolicyServer::DeactivateAudioSession()
3659 {
3660 if (interruptService_ == nullptr) {
3661 AUDIO_ERR_LOG("interruptService_ is nullptr!");
3662 return ERR_UNKNOWN;
3663 }
3664 int32_t callerPid = IPCSkeleton::GetCallingPid();
3665 AUDIO_INFO_LOG("deactivate audio session for pid %{public}d", callerPid);
3666 return interruptService_->DeactivateAudioSession(callerPid);
3667 }
3668
IsAudioSessionActivated()3669 bool AudioPolicyServer::IsAudioSessionActivated()
3670 {
3671 if (interruptService_ == nullptr) {
3672 AUDIO_ERR_LOG("interruptService_ is nullptr!");
3673 return false;
3674 }
3675 int32_t callerPid = IPCSkeleton::GetCallingPid();
3676 bool isActive = interruptService_->IsAudioSessionActivated(callerPid);
3677 AUDIO_INFO_LOG("callerPid %{public}d, isSessionActive: %{public}d.", callerPid, isActive);
3678 return isActive;
3679 }
3680
LoadSplitModule(const std::string & splitArgs,const std::string & networkId)3681 int32_t AudioPolicyServer::LoadSplitModule(const std::string &splitArgs, const std::string &networkId)
3682 {
3683 auto callerUid = IPCSkeleton::GetCallingUid();
3684 if (callerUid != UID_CAR_DISTRIBUTED_ENGINE_SA) {
3685 AUDIO_ERR_LOG("callerUid %{public}d is not allow LoadSplitModule", callerUid);
3686 return ERR_PERMISSION_DENIED;
3687 }
3688 return audioPolicyService_.LoadSplitModule(splitArgs, networkId);
3689 }
3690
IsAllowedPlayback(const int32_t & uid,const int32_t & pid)3691 bool AudioPolicyServer::IsAllowedPlayback(const int32_t &uid, const int32_t &pid)
3692 {
3693 auto callerUid = IPCSkeleton::GetCallingUid();
3694 if (callerUid != MEDIA_SERVICE_UID) {
3695 auto callerPid = IPCSkeleton::GetCallingPid();
3696 return audioPolicyService_.IsAllowedPlayback(callerUid, callerPid);
3697 }
3698 return audioPolicyService_.IsAllowedPlayback(uid, pid);
3699 }
3700
SetVoiceRingtoneMute(bool isMute)3701 int32_t AudioPolicyServer::SetVoiceRingtoneMute(bool isMute)
3702 {
3703 constexpr int32_t foundationUid = 5523; // "uid" : "foundation"
3704 auto callerUid = IPCSkeleton::GetCallingUid();
3705 // This function can only be used by foundation
3706 CHECK_AND_RETURN_RET_LOG(callerUid == foundationUid, ERROR,
3707 "SetVoiceRingtoneMute callerUid is error: not foundation");
3708 AUDIO_INFO_LOG("Set VoiceRingtone is %{public}d", isMute);
3709 return audioPolicyService_.SetVoiceRingtoneMute(isMute);
3710 }
3711
SetVirtualCall(const bool isVirtual)3712 int32_t AudioPolicyServer::SetVirtualCall(const bool isVirtual)
3713 {
3714 constexpr int32_t meetServiceUid = 5523; // "uid" : "meetservice"
3715 auto callerUid = IPCSkeleton::GetCallingUid();
3716 // This function can only be used by meetservice
3717 CHECK_AND_RETURN_RET_LOG(callerUid == meetServiceUid, ERROR,
3718 "SetVirtualCall callerUid is error: not meetservice");
3719 AUDIO_INFO_LOG("Set VirtualCall is %{public}d", isVirtual);
3720 return audioPolicyService_.SetVirtualCall(isVirtual);
3721 }
3722
SetDeviceConnectionStatus(const std::shared_ptr<AudioDeviceDescriptor> & desc,const bool isConnected)3723 int32_t AudioPolicyServer::SetDeviceConnectionStatus(const std::shared_ptr<AudioDeviceDescriptor> &desc,
3724 const bool isConnected)
3725 {
3726 AUDIO_INFO_LOG("deviceType: %{public}d, deviceRole: %{public}d, isConnected: %{public}d",
3727 desc->deviceType_, desc->deviceRole_, isConnected);
3728 auto callerUid = IPCSkeleton::GetCallingUid();
3729 CHECK_AND_RETURN_RET_LOG(callerUid == UID_TV_PROCESS_SA, ERR_PERMISSION_DENIED, "uid permission denied");
3730 bool ret = VerifyPermission(MANAGE_AUDIO_CONFIG);
3731 CHECK_AND_RETURN_RET_LOG(ret, ERR_PERMISSION_DENIED, "MANAGE_AUDIO_CONFIG permission denied");
3732 audioPolicyService_.OnDeviceStatusUpdated(*desc, isConnected);
3733 return SUCCESS;
3734 }
3735
SetQueryAllowedPlaybackCallback(const sptr<IRemoteObject> & object)3736 int32_t AudioPolicyServer::SetQueryAllowedPlaybackCallback(const sptr<IRemoteObject> &object)
3737 {
3738 constexpr int32_t avSessionUid = 6700; // "uid" : "av_session"
3739 auto callerUid = IPCSkeleton::GetCallingUid();
3740 // This function can only be used by av_session
3741 CHECK_AND_RETURN_RET_LOG(callerUid == avSessionUid, ERROR,
3742 "UpdateStreamState callerUid is error: not av_session");
3743 return audioPolicyService_.SetQueryAllowedPlaybackCallback(object);
3744 }
3745
UpdateDefaultOutputDeviceWhenStarting(const uint32_t sessionID)3746 void AudioPolicyServer::UpdateDefaultOutputDeviceWhenStarting(const uint32_t sessionID)
3747 {
3748 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStarting(sessionID);
3749 audioPolicyService_.TriggerFetchDevice();
3750 }
3751
UpdateDefaultOutputDeviceWhenStopping(const uint32_t sessionID)3752 void AudioPolicyServer::UpdateDefaultOutputDeviceWhenStopping(const uint32_t sessionID)
3753 {
3754 audioDeviceManager_.UpdateDefaultOutputDeviceWhenStopping(sessionID);
3755 audioPolicyService_.TriggerFetchDevice();
3756 }
3757 } // namespace AudioStandard
3758 } // namespace OHOS
3759