1 /*
2 * Copyright (c) 2021-2022 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
16 #include <csignal>
17 #include <memory>
18 #include <unordered_set>
19 #include <vector>
20
21 #include "audio_errors.h"
22 #include "audio_policy_manager_listener_proxy.h"
23 #include "audio_routing_manager_listener_proxy.h"
24 #include "audio_ringermode_update_listener_proxy.h"
25 #include "audio_volume_key_event_callback_proxy.h"
26 #include "i_standard_audio_policy_manager_listener.h"
27
28 #include "input_manager.h"
29 #include "key_event.h"
30 #include "key_option.h"
31
32 #include "privacy_kit.h"
33 #include "accesstoken_kit.h"
34 #include "audio_log.h"
35 #include "ipc_skeleton.h"
36 #include "iservice_registry.h"
37 #include "system_ability_definition.h"
38
39 #include "audio_service_dump.h"
40 #include "audio_policy_server.h"
41 #include "permission_state_change_info.h"
42 #include "token_setproc.h"
43
44 using OHOS::Security::AccessToken::PrivacyKit;
45 using namespace std;
46
47 namespace OHOS {
48 namespace AudioStandard {
49 constexpr float DUCK_FACTOR = 0.2f; // 20%
50 constexpr int32_t PARAMS_VOLUME_NUM = 5;
51 constexpr int32_t PARAMS_INTERRUPT_NUM = 4;
52 constexpr int32_t PARAMS_RENDER_STATE_NUM = 2;
53 constexpr int32_t EVENT_DES_SIZE = 60;
54 constexpr int32_t RENDER_STATE_CONTENT_DES_SIZE = 60;
REGISTER_SYSTEM_ABILITY_BY_ID(AudioPolicyServer,AUDIO_POLICY_SERVICE_ID,true)55 REGISTER_SYSTEM_ABILITY_BY_ID(AudioPolicyServer, AUDIO_POLICY_SERVICE_ID, true)
56
57 AudioPolicyServer::AudioPolicyServer(int32_t systemAbilityId, bool runOnCreate)
58 : SystemAbility(systemAbilityId, runOnCreate),
59 mPolicyService(AudioPolicyService::GetAudioPolicyService())
60 {
61 if (mPolicyService.SetAudioSessionCallback(this)) {
62 AUDIO_DEBUG_LOG("AudioPolicyServer: SetAudioSessionCallback failed");
63 }
64 interruptPriorityMap_[STREAM_VOICE_CALL] = THIRD_PRIORITY;
65 interruptPriorityMap_[STREAM_RING] = SECOND_PRIORITY;
66 interruptPriorityMap_[STREAM_MUSIC] = FIRST_PRIORITY;
67
68 clientOnFocus_ = 0;
69 focussedAudioInterruptInfo_ = nullptr;
70 }
71
OnDump()72 void AudioPolicyServer::OnDump()
73 {
74 return;
75 }
76
OnStart()77 void AudioPolicyServer::OnStart()
78 {
79 AUDIO_INFO_LOG("AudioPolicyService OnStart");
80 mPolicyService.Init();
81
82 AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
83 AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
84 AddSystemAbilityListener(AUDIO_DISTRIBUTED_SERVICE_ID);
85 AddSystemAbilityListener(BLUETOOTH_HOST_SYS_ABILITY_ID);
86 AddSystemAbilityListener(ACCESSIBILITY_MANAGER_SERVICE_ID);
87
88 bool res = Publish(this);
89 if (res) {
90 AUDIO_WARNING_LOG("AudioPolicyService OnStart res=%d", res);
91 }
92
93 Security::AccessToken::PermStateChangeScope scopeInfo;
94 scopeInfo.permList = {"ohos.permission.MICROPHONE"};
95 auto callbackPtr = std::make_shared<PerStateChangeCbCustomizeCallback>(scopeInfo, this);
96 callbackPtr->ready_ = false;
97 int32_t iRes = Security::AccessToken::AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr);
98 if (iRes < 0) {
99 AUDIO_ERR_LOG("fail to call RegisterPermStateChangeCallback.");
100 }
101 }
102
OnStop()103 void AudioPolicyServer::OnStop()
104 {
105 mPolicyService.Deinit();
106 return;
107 }
108
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)109 void AudioPolicyServer::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
110 {
111 AUDIO_DEBUG_LOG("OnAddSystemAbility systemAbilityId:%{public}d", systemAbilityId);
112 switch (systemAbilityId) {
113 case MULTIMODAL_INPUT_SERVICE_ID:
114 AUDIO_INFO_LOG("OnAddSystemAbility input service start");
115 SubscribeKeyEvents();
116 break;
117 case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID:
118 AUDIO_INFO_LOG("OnAddSystemAbility kv data service start");
119 InitKVStore();
120 break;
121 case AUDIO_DISTRIBUTED_SERVICE_ID:
122 AUDIO_INFO_LOG("OnAddSystemAbility audio service start");
123 ConnectServiceAdapter();
124 RegisterParamCallback();
125 break;
126 case BLUETOOTH_HOST_SYS_ABILITY_ID:
127 AUDIO_INFO_LOG("OnAddSystemAbility bluetooth service start");
128 RegisterBluetoothListener();
129 break;
130 case ACCESSIBILITY_MANAGER_SERVICE_ID:
131 AUDIO_INFO_LOG("OnAddSystemAbility accessibility service start");
132 SubscribeAccessibilityConfigObserver();
133 break;
134 default:
135 AUDIO_ERR_LOG("OnAddSystemAbility unhandled sysabilityId:%{public}d", systemAbilityId);
136 break;
137 }
138 }
139
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)140 void AudioPolicyServer::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
141 {
142 AUDIO_DEBUG_LOG("AudioPolicyServer::OnRemoveSystemAbility systemAbilityId:%{public}d removed", systemAbilityId);
143 }
144
SubscribeKeyEvents()145 void AudioPolicyServer::SubscribeKeyEvents()
146 {
147 MMI::InputManager *im = MMI::InputManager::GetInstance();
148 CHECK_AND_RETURN_LOG(im != nullptr, "Failed to obtain INPUT manager");
149
150 std::set<int32_t> preKeys;
151 std::shared_ptr<OHOS::MMI::KeyOption> keyOption_down = std::make_shared<OHOS::MMI::KeyOption>();
152 CHECK_AND_RETURN_LOG(keyOption_down != nullptr, "Invalid key option");
153 keyOption_down->SetPreKeys(preKeys);
154 keyOption_down->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN);
155 keyOption_down->SetFinalKeyDown(true);
156 keyOption_down->SetFinalKeyDownDuration(VOLUME_KEY_DURATION);
157 im->SubscribeKeyEvent(keyOption_down, [=](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
158 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
159 AudioStreamType streamInFocus = GetStreamInFocus();
160 if (streamInFocus == AudioStreamType::STREAM_DEFAULT) {
161 streamInFocus = AudioStreamType::STREAM_MUSIC;
162 }
163 float currentVolume = GetStreamVolume(streamInFocus);
164 int32_t volumeLevelInInt = ConvertVolumeToInt(currentVolume);
165 if (volumeLevelInInt <= MIN_VOLUME_LEVEL) {
166 for (auto it = volumeChangeCbsMap_.begin(); it != volumeChangeCbsMap_.end(); ++it) {
167 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
168 if (volumeChangeCb == nullptr) {
169 AUDIO_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
170 continue;
171 }
172
173 AUDIO_DEBUG_LOG("AudioPolicyServer:: trigger volumeChangeCb clientPid : %{public}d", it->first);
174 VolumeEvent volumeEvent;
175 volumeEvent.volumeType = streamInFocus;
176 volumeEvent.volume = MIN_VOLUME_LEVEL;
177 volumeEvent.updateUi = true;
178 volumeEvent.volumeGroupId = 0;
179 volumeEvent.networkId = LOCAL_NETWORK_ID;
180 volumeChangeCb->OnVolumeKeyEvent(volumeEvent);
181 }
182 return;
183 }
184 SetStreamVolume(streamInFocus, MapVolumeToHDI(volumeLevelInInt - 1), true);
185 });
186 std::shared_ptr<OHOS::MMI::KeyOption> keyOption_up = std::make_shared<OHOS::MMI::KeyOption>();
187 keyOption_up->SetPreKeys(preKeys);
188 keyOption_up->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP);
189 keyOption_up->SetFinalKeyDown(true);
190 keyOption_up->SetFinalKeyDownDuration(0);
191 im->SubscribeKeyEvent(keyOption_up, [=](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
192 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
193 AudioStreamType streamInFocus = GetStreamInFocus();
194 if (streamInFocus == AudioStreamType::STREAM_DEFAULT) {
195 streamInFocus = AudioStreamType::STREAM_MUSIC;
196 }
197 float currentVolume = GetStreamVolume(streamInFocus);
198 int32_t volumeLevelInInt = ConvertVolumeToInt(currentVolume);
199 if (volumeLevelInInt >= MAX_VOLUME_LEVEL) {
200 for (auto it = volumeChangeCbsMap_.begin(); it != volumeChangeCbsMap_.end(); ++it) {
201 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
202 if (volumeChangeCb == nullptr) {
203 AUDIO_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
204 continue;
205 }
206
207 AUDIO_DEBUG_LOG("AudioPolicyServer:: trigger volumeChangeCb clientPid : %{public}d", it->first);
208 VolumeEvent volumeEvent;
209 volumeEvent.volumeType = streamInFocus;
210 volumeEvent.volume = MAX_VOLUME_LEVEL;
211 volumeEvent.updateUi = true;
212 volumeEvent.volumeGroupId = 0;
213 volumeEvent.networkId = LOCAL_NETWORK_ID;
214 volumeChangeCb->OnVolumeKeyEvent(volumeEvent);
215 }
216 return;
217 }
218 SetStreamVolume(streamInFocus, MapVolumeToHDI(volumeLevelInInt + 1), true);
219 });
220 }
221
InitKVStore()222 void AudioPolicyServer::InitKVStore()
223 {
224 mPolicyService.InitKVStore();
225 }
226
ConnectServiceAdapter()227 void AudioPolicyServer::ConnectServiceAdapter()
228 {
229 if (!mPolicyService.ConnectServiceAdapter()) {
230 AUDIO_ERR_LOG("AudioPolicyServer::ConnectServiceAdapter Error in connecting to audio service adapter");
231 return;
232 }
233 }
234
SetStreamVolume(AudioStreamType streamType,float volume)235 int32_t AudioPolicyServer::SetStreamVolume(AudioStreamType streamType, float volume)
236 {
237 return SetStreamVolume(streamType, volume, false);
238 }
239
GetStreamVolume(AudioStreamType streamType)240 float AudioPolicyServer::GetStreamVolume(AudioStreamType streamType)
241 {
242 if (GetStreamMute(streamType)) {
243 return MIN_VOLUME_LEVEL;
244 }
245 return mPolicyService.GetStreamVolume(streamType);
246 }
247
SetLowPowerVolume(int32_t streamId,float volume)248 int32_t AudioPolicyServer::SetLowPowerVolume(int32_t streamId, float volume)
249 {
250 return mPolicyService.SetLowPowerVolume(streamId, volume);
251 }
252
GetLowPowerVolume(int32_t streamId)253 float AudioPolicyServer::GetLowPowerVolume(int32_t streamId)
254 {
255 return mPolicyService.GetLowPowerVolume(streamId);
256 }
257
GetSingleStreamVolume(int32_t streamId)258 float AudioPolicyServer::GetSingleStreamVolume(int32_t streamId)
259 {
260 return mPolicyService.GetSingleStreamVolume(streamId);
261 }
262
SetStreamMute(AudioStreamType streamType,bool mute)263 int32_t AudioPolicyServer::SetStreamMute(AudioStreamType streamType, bool mute)
264 {
265 if (streamType == AudioStreamType::STREAM_RING) {
266 if (!VerifyClientPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
267 AUDIO_ERR_LOG("SetStreamMute permission denied for stream type : %{public}d", streamType);
268 return ERR_PERMISSION_DENIED;
269 }
270 }
271
272 int result = mPolicyService.SetStreamMute(streamType, mute);
273 for (auto it = volumeChangeCbsMap_.begin(); it != volumeChangeCbsMap_.end(); ++it) {
274 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
275 if (volumeChangeCb == nullptr) {
276 AUDIO_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
277 continue;
278 }
279 AUDIO_DEBUG_LOG("AudioPolicyServer::SetStreamMute trigger volumeChangeCb clientPid : %{public}d", it->first);
280 VolumeEvent volumeEvent;
281 volumeEvent.volumeType = streamType;
282 volumeEvent.volume = ConvertVolumeToInt(GetStreamVolume(streamType));
283 volumeEvent.updateUi = false;
284 volumeEvent.volumeGroupId = 0;
285 volumeEvent.networkId = LOCAL_NETWORK_ID;
286 volumeChangeCb->OnVolumeKeyEvent(volumeEvent);
287 }
288
289 return result;
290 }
291
SetStreamVolume(AudioStreamType streamType,float volume,bool isUpdateUi)292 int32_t AudioPolicyServer::SetStreamVolume(AudioStreamType streamType, float volume, bool isUpdateUi)
293 {
294 if (streamType == AudioStreamType::STREAM_RING && !isUpdateUi) {
295 float currentRingVolume = GetStreamVolume(AudioStreamType::STREAM_RING);
296 if ((currentRingVolume > 0.0f && volume == 0.0f) || (currentRingVolume == 0.0f && volume > 0.0f)) {
297 if (!VerifyClientPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
298 AUDIO_ERR_LOG("Access policy permission denied for volume type : %{public}d", streamType);
299 return ERR_PERMISSION_DENIED;
300 }
301 }
302 }
303
304 int ret = mPolicyService.SetStreamVolume(streamType, volume);
305 for (auto it = volumeChangeCbsMap_.begin(); it != volumeChangeCbsMap_.end(); ++it) {
306 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
307 if (volumeChangeCb == nullptr) {
308 AUDIO_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
309 continue;
310 }
311
312 AUDIO_DEBUG_LOG("AudioPolicyServer::SetStreamVolume trigger volumeChangeCb clientPid : %{public}d", it->first);
313 VolumeEvent volumeEvent;
314 volumeEvent.volumeType = streamType;
315 volumeEvent.volume = ConvertVolumeToInt(GetStreamVolume(streamType));
316 volumeEvent.updateUi = isUpdateUi;
317 volumeEvent.volumeGroupId = 0;
318 volumeEvent.networkId = LOCAL_NETWORK_ID;
319 volumeChangeCb->OnVolumeKeyEvent(volumeEvent);
320 }
321
322 return ret;
323 }
324
GetStreamMute(AudioStreamType streamType)325 bool AudioPolicyServer::GetStreamMute(AudioStreamType streamType)
326 {
327 if (streamType == AudioStreamType::STREAM_RING) {
328 if (!VerifyClientPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
329 AUDIO_ERR_LOG("GetStreamMute permission denied for stream type : %{public}d", streamType);
330 return false;
331 }
332 }
333
334 return mPolicyService.GetStreamMute(streamType);
335 }
336
SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)337 int32_t AudioPolicyServer::SelectOutputDevice(sptr<AudioRendererFilter> audioRendererFilter,
338 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
339 {
340 int32_t ret = mPolicyService.SelectOutputDevice(audioRendererFilter, audioDeviceDescriptors);
341 return ret;
342 }
343
GetSelectedDeviceInfo(int32_t uid,int32_t pid,AudioStreamType streamType)344 std::string AudioPolicyServer::GetSelectedDeviceInfo(int32_t uid, int32_t pid, AudioStreamType streamType)
345 {
346 return mPolicyService.GetSelectedDeviceInfo(uid, pid, streamType);
347 }
348
SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)349 int32_t AudioPolicyServer::SelectInputDevice(sptr<AudioCapturerFilter> audioCapturerFilter,
350 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors)
351 {
352 int32_t ret = mPolicyService.SelectInputDevice(audioCapturerFilter, audioDeviceDescriptors);
353 return ret;
354 }
355
GetDevices(DeviceFlag deviceFlag)356 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyServer::GetDevices(DeviceFlag deviceFlag)
357 {
358 std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = mPolicyService.GetDevices(deviceFlag);
359 bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION);
360 if (!hasBTPermission) {
361 for (sptr<AudioDeviceDescriptor> desc : deviceDescs) {
362 if ((desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP)
363 || (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO)) {
364 desc->deviceName_ = "";
365 desc->macAddress_ = "";
366 }
367 }
368 }
369
370 return deviceDescs;
371 }
372
GetActiveOutputDeviceDescriptors()373 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyServer::GetActiveOutputDeviceDescriptors()
374 {
375 std::vector<sptr<AudioDeviceDescriptor>> deviceDescs = mPolicyService.GetActiveOutputDeviceDescriptors();
376 bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION);
377 if (!hasBTPermission) {
378 for (sptr<AudioDeviceDescriptor> desc : deviceDescs) {
379 if ((desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP)
380 || (desc->deviceType_ == DEVICE_TYPE_BLUETOOTH_SCO)) {
381 desc->deviceName_ = "";
382 desc->macAddress_ = "";
383 }
384 }
385 }
386
387 return deviceDescs;
388 }
389
IsStreamActive(AudioStreamType streamType)390 bool AudioPolicyServer::IsStreamActive(AudioStreamType streamType)
391 {
392 return mPolicyService.IsStreamActive(streamType);
393 }
394
SetDeviceActive(InternalDeviceType deviceType,bool active)395 int32_t AudioPolicyServer::SetDeviceActive(InternalDeviceType deviceType, bool active)
396 {
397 return mPolicyService.SetDeviceActive(deviceType, active);
398 }
399
IsDeviceActive(InternalDeviceType deviceType)400 bool AudioPolicyServer::IsDeviceActive(InternalDeviceType deviceType)
401 {
402 return mPolicyService.IsDeviceActive(deviceType);
403 }
404
GetActiveOutputDevice()405 InternalDeviceType AudioPolicyServer::GetActiveOutputDevice()
406 {
407 return mPolicyService.GetActiveOutputDevice();
408 }
409
GetActiveInputDevice()410 InternalDeviceType AudioPolicyServer::GetActiveInputDevice()
411 {
412 return mPolicyService.GetActiveInputDevice();
413 }
414
SetRingerMode(AudioRingerMode ringMode)415 int32_t AudioPolicyServer::SetRingerMode(AudioRingerMode ringMode)
416 {
417 bool isPermissionRequired = false;
418
419 if (ringMode == AudioRingerMode::RINGER_MODE_SILENT) {
420 isPermissionRequired = true;
421 } else {
422 AudioRingerMode currentRingerMode = GetRingerMode();
423 if (currentRingerMode == AudioRingerMode::RINGER_MODE_SILENT) {
424 isPermissionRequired = true;
425 }
426 }
427
428 if (isPermissionRequired) {
429 if (!VerifyClientPermission(ACCESS_NOTIFICATION_POLICY_PERMISSION)) {
430 AUDIO_ERR_LOG("Access policy permission denied for ringerMode : %{public}d", ringMode);
431 return ERR_PERMISSION_DENIED;
432 }
433 }
434
435 int32_t ret = mPolicyService.SetRingerMode(ringMode);
436 if (ret == SUCCESS) {
437 for (auto it = ringerModeListenerCbsMap_.begin(); it != ringerModeListenerCbsMap_.end(); ++it) {
438 std::shared_ptr<AudioRingerModeCallback> ringerModeListenerCb = it->second;
439 if (ringerModeListenerCb == nullptr) {
440 AUDIO_ERR_LOG("ringerModeListenerCbsMap_: nullptr for client : %{public}d", it->first);
441 continue;
442 }
443
444 AUDIO_DEBUG_LOG("ringerModeListenerCbsMap_ :client = %{public}d", it->first);
445 ringerModeListenerCb->OnRingerModeUpdated(ringMode);
446 }
447 }
448
449 return ret;
450 }
451
GetToneConfig(int32_t ltonetype)452 std::shared_ptr<ToneInfo> AudioPolicyServer::GetToneConfig(int32_t ltonetype)
453 {
454 return mPolicyService.GetToneConfig(ltonetype);
455 }
456
GetSupportedTones()457 std::vector<int32_t> AudioPolicyServer::GetSupportedTones()
458 {
459 return mPolicyService.GetSupportedTones();
460 }
461
462
SetMicrophoneMuteCommon(bool isMute,API_VERSION api_v)463 int32_t AudioPolicyServer::SetMicrophoneMuteCommon(bool isMute, API_VERSION api_v)
464 {
465 AUDIO_INFO_LOG("Entered %{public}s", __func__);
466 bool isMicrophoneMute = IsMicrophoneMute(api_v);
467 int32_t ret = mPolicyService.SetMicrophoneMute(isMute);
468 if (ret == SUCCESS && isMicrophoneMute != isMute) {
469 for (auto it = micStateChangeListenerCbsMap_.begin(); it != micStateChangeListenerCbsMap_.end(); ++it) {
470 std::shared_ptr<AudioManagerMicStateChangeCallback> MicStateChangeListenerCb = it->second;
471 if (MicStateChangeListenerCb == nullptr) {
472 AUDIO_ERR_LOG("micStateChangeListenerCbsMap_: nullptr for client : %{public}d", it->first);
473 continue;
474 }
475
476 AUDIO_DEBUG_LOG("micStateChangeListenerCbsMap_ :client = %{public}d", it->first);
477 MicStateChangeEvent micStateChangeEvent;
478 micStateChangeEvent.mute = isMute;
479 MicStateChangeListenerCb->OnMicStateUpdated(micStateChangeEvent);
480 }
481 }
482 return ret;
483 }
484
SetMicrophoneMute(bool isMute)485 int32_t AudioPolicyServer::SetMicrophoneMute(bool isMute)
486 {
487 AUDIO_INFO_LOG("Entered %{public}s", __func__);
488 if (!VerifyClientPermission(MICROPHONE_PERMISSION)) {
489 AUDIO_ERR_LOG("SetMicrophoneMute: MICROPHONE permission denied");
490 return ERR_PERMISSION_DENIED;
491 }
492 return SetMicrophoneMuteCommon(isMute, API_7);
493 }
494
SetMicrophoneMuteAudioConfig(bool isMute)495 int32_t AudioPolicyServer::SetMicrophoneMuteAudioConfig(bool isMute)
496 {
497 AUDIO_INFO_LOG("Entered %{public}s", __func__);
498 if (!VerifyClientPermission(MANAGE_AUDIO_CONFIG)) {
499 AUDIO_ERR_LOG("SetMicrophoneMuteAudioConfig: MANAGE_AUDIO_CONFIG permission denied");
500 return ERR_PERMISSION_DENIED;
501 }
502 return SetMicrophoneMuteCommon(isMute, API_9);
503 }
504
IsMicrophoneMute(API_VERSION api_v)505 bool AudioPolicyServer::IsMicrophoneMute(API_VERSION api_v)
506 {
507 AUDIO_INFO_LOG("Entered %{public}s", __func__);
508 if (api_v == API_7 && !VerifyClientPermission(MICROPHONE_PERMISSION)) {
509 AUDIO_ERR_LOG("IsMicrophoneMute: MICROPHONE permission denied");
510 return ERR_PERMISSION_DENIED;
511 }
512
513 return mPolicyService.IsMicrophoneMute();
514 }
515
GetRingerMode()516 AudioRingerMode AudioPolicyServer::GetRingerMode()
517 {
518 return mPolicyService.GetRingerMode();
519 }
520
SetAudioScene(AudioScene audioScene)521 int32_t AudioPolicyServer::SetAudioScene(AudioScene audioScene)
522 {
523 return mPolicyService.SetAudioScene(audioScene);
524 }
525
GetAudioScene()526 AudioScene AudioPolicyServer::GetAudioScene()
527 {
528 return mPolicyService.GetAudioScene();
529 }
530
SetRingerModeCallback(const int32_t clientId,const sptr<IRemoteObject> & object)531 int32_t AudioPolicyServer::SetRingerModeCallback(const int32_t clientId, const sptr<IRemoteObject> &object)
532 {
533 std::lock_guard<std::mutex> lock(ringerModeMutex_);
534
535 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
536
537 sptr<IStandardRingerModeUpdateListener> listener = iface_cast<IStandardRingerModeUpdateListener>(object);
538 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
539
540 std::shared_ptr<AudioRingerModeCallback> callback = std::make_shared<AudioRingerModeListenerCallback>(listener);
541 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
542
543 ringerModeListenerCbsMap_[clientId] = callback;
544
545 return SUCCESS;
546 }
547
UnsetRingerModeCallback(const int32_t clientId)548 int32_t AudioPolicyServer::UnsetRingerModeCallback(const int32_t clientId)
549 {
550 std::lock_guard<std::mutex> lock(ringerModeMutex_);
551
552 if (ringerModeListenerCbsMap_.find(clientId) != ringerModeListenerCbsMap_.end()) {
553 ringerModeListenerCbsMap_.erase(clientId);
554 AUDIO_ERR_LOG("AudioPolicyServer: UnsetRingerModeCallback for client %{public}d done", clientId);
555 return SUCCESS;
556 } else {
557 AUDIO_ERR_LOG("AudioPolicyServer: Cb does not exit for client %{public}d cannot unregister", clientId);
558 return ERR_INVALID_OPERATION;
559 }
560 }
561
SetMicStateChangeCallback(const int32_t clientId,const sptr<IRemoteObject> & object)562 int32_t AudioPolicyServer::SetMicStateChangeCallback(const int32_t clientId, const sptr<IRemoteObject> &object)
563 {
564 std::lock_guard<std::mutex> lock(micStateChangeMutex_);
565 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
566
567 sptr<IStandardAudioRoutingManagerListener> listener = iface_cast<IStandardAudioRoutingManagerListener>(object);
568 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
569
570 std::shared_ptr<AudioManagerMicStateChangeCallback> callback =
571 std::make_shared<AudioRoutingManagerListenerCallback>(listener);
572 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
573
574 micStateChangeListenerCbsMap_[clientId] = callback;
575
576 return SUCCESS;
577 }
578
SetDeviceChangeCallback(const int32_t clientId,const DeviceFlag flag,const sptr<IRemoteObject> & object)579 int32_t AudioPolicyServer::SetDeviceChangeCallback(const int32_t clientId, const DeviceFlag flag,
580 const sptr<IRemoteObject> &object)
581 {
582 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
583
584 return mPolicyService.SetDeviceChangeCallback(clientId, flag, object);
585 }
586
UnsetDeviceChangeCallback(const int32_t clientId)587 int32_t AudioPolicyServer::UnsetDeviceChangeCallback(const int32_t clientId)
588 {
589 return mPolicyService.UnsetDeviceChangeCallback(clientId);
590 }
591
SetAudioInterruptCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)592 int32_t AudioPolicyServer::SetAudioInterruptCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object)
593 {
594 std::lock_guard<std::mutex> lock(interruptMutex_);
595
596 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
597
598 sptr<IStandardAudioPolicyManagerListener> listener = iface_cast<IStandardAudioPolicyManagerListener>(object);
599 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
600
601 std::shared_ptr<AudioInterruptCallback> callback = std::make_shared<AudioPolicyManagerListenerCallback>(listener);
602 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
603
604 policyListenerCbsMap_[sessionID] = callback;
605 AUDIO_DEBUG_LOG("AudioPolicyServer: SetAudioInterruptCallback for sessionID %{public}d done", sessionID);
606
607 return SUCCESS;
608 }
609
UnsetAudioInterruptCallback(const uint32_t sessionID)610 int32_t AudioPolicyServer::UnsetAudioInterruptCallback(const uint32_t sessionID)
611 {
612 std::lock_guard<std::mutex> lock(interruptMutex_);
613
614 if (policyListenerCbsMap_.erase(sessionID)) {
615 AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetAudioInterruptCallback for sessionID %{public}d done", sessionID);
616 } else {
617 AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetAudioInterruptCallback sessionID %{public}d not present/unset already",
618 sessionID);
619 }
620
621 return SUCCESS;
622 }
623
SetAudioManagerInterruptCallback(const uint32_t clientID,const sptr<IRemoteObject> & object)624 int32_t AudioPolicyServer::SetAudioManagerInterruptCallback(const uint32_t clientID,
625 const sptr<IRemoteObject> &object)
626 {
627 std::lock_guard<std::mutex> lock(interruptMutex_);
628
629 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
630
631 sptr<IStandardAudioPolicyManagerListener> listener = iface_cast<IStandardAudioPolicyManagerListener>(object);
632 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
633
634 std::shared_ptr<AudioInterruptCallback> callback = std::make_shared<AudioPolicyManagerListenerCallback>(listener);
635 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
636
637 audioManagerListenerCbsMap_[clientID] = callback;
638 AUDIO_INFO_LOG("AudioPolicyServer: SetAudioManagerInterruptCallback for client id %{public}d done", clientID);
639
640 return SUCCESS;
641 }
642
UnsetAudioManagerInterruptCallback(const uint32_t clientID)643 int32_t AudioPolicyServer::UnsetAudioManagerInterruptCallback(const uint32_t clientID)
644 {
645 if (audioManagerListenerCbsMap_.erase(clientID)) {
646 AUDIO_INFO_LOG("AudioPolicyServer:UnsetAudioManagerInterruptCallback for client %{public}d done", clientID);
647 } else {
648 AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetAudioManagerInterruptCallback client %{public}d not present",
649 clientID);
650 }
651
652 return SUCCESS;
653 }
654
RequestAudioFocus(const uint32_t clientID,const AudioInterrupt & audioInterrupt)655 int32_t AudioPolicyServer::RequestAudioFocus(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
656 {
657 AUDIO_DEBUG_LOG("AudioPolicyServer: RequestAudioFocus in");
658 if (clientOnFocus_ == clientID) {
659 AUDIO_DEBUG_LOG("AudioPolicyServer: client already has focus");
660 NotifyFocusGranted(clientID, audioInterrupt);
661 return SUCCESS;
662 }
663
664 if (focussedAudioInterruptInfo_ != nullptr) {
665 AUDIO_DEBUG_LOG("AudioPolicyServer: Existing stream: %{public}d, incoming stream: %{public}d",
666 focussedAudioInterruptInfo_->streamType, audioInterrupt.streamType);
667 NotifyFocusAbandoned(clientOnFocus_, *focussedAudioInterruptInfo_);
668 AbandonAudioFocus(clientOnFocus_, *focussedAudioInterruptInfo_);
669 }
670
671 AUDIO_DEBUG_LOG("AudioPolicyServer: Grant audio focus");
672 NotifyFocusGranted(clientID, audioInterrupt);
673
674 return SUCCESS;
675 }
676
AbandonAudioFocus(const uint32_t clientID,const AudioInterrupt & audioInterrupt)677 int32_t AudioPolicyServer::AbandonAudioFocus(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
678 {
679 AUDIO_INFO_LOG("AudioPolicyServer: AbandonAudioFocus in");
680
681 if (clientID == clientOnFocus_) {
682 AUDIO_DEBUG_LOG("AudioPolicyServer: remove app focus");
683 focussedAudioInterruptInfo_.reset();
684 focussedAudioInterruptInfo_ = nullptr;
685 clientOnFocus_ = 0;
686 }
687
688 return SUCCESS;
689 }
690
NotifyFocusGranted(const uint32_t clientID,const AudioInterrupt & audioInterrupt)691 void AudioPolicyServer::NotifyFocusGranted(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
692 {
693 AUDIO_INFO_LOG("AudioPolicyServer: Notify focus granted in: %{public}d", clientID);
694 std::shared_ptr<AudioInterruptCallback> interruptCb = nullptr;
695 interruptCb = audioManagerListenerCbsMap_[clientID];
696 if (interruptCb) {
697 InterruptEventInternal interruptEvent = {};
698 interruptEvent.eventType = INTERRUPT_TYPE_END;
699 interruptEvent.forceType = INTERRUPT_SHARE;
700 interruptEvent.hintType = INTERRUPT_HINT_NONE;
701 interruptEvent.duckVolume = 0;
702
703 AUDIO_DEBUG_LOG("AudioPolicyServer: callback focus granted");
704 interruptCb->OnInterrupt(interruptEvent);
705
706 unique_ptr<AudioInterrupt> tempAudioInterruptInfo = make_unique<AudioInterrupt>();
707 tempAudioInterruptInfo->streamUsage = audioInterrupt.streamUsage;
708 tempAudioInterruptInfo->contentType = audioInterrupt.contentType;
709 tempAudioInterruptInfo->streamType = audioInterrupt.streamType;
710 tempAudioInterruptInfo->pauseWhenDucked = audioInterrupt.pauseWhenDucked;
711 focussedAudioInterruptInfo_ = move(tempAudioInterruptInfo);
712 clientOnFocus_ = clientID;
713 }
714 }
715
NotifyFocusAbandoned(const uint32_t clientID,const AudioInterrupt & audioInterrupt)716 int32_t AudioPolicyServer::NotifyFocusAbandoned(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
717 {
718 AUDIO_INFO_LOG("AudioPolicyServer: Notify focus abandoned in: %{public}d", clientID);
719 std::shared_ptr<AudioInterruptCallback> interruptCb = nullptr;
720 interruptCb = audioManagerListenerCbsMap_[clientID];
721 if (!interruptCb) {
722 AUDIO_INFO_LOG("AudioPolicyServer: Notify failed, callback not present");
723 return ERR_INVALID_PARAM;
724 }
725
726 InterruptEventInternal interruptEvent = {};
727 interruptEvent.eventType = INTERRUPT_TYPE_BEGIN;
728 interruptEvent.forceType = INTERRUPT_SHARE;
729 interruptEvent.hintType = INTERRUPT_HINT_STOP;
730 interruptEvent.duckVolume = 0;
731 AUDIO_DEBUG_LOG("AudioPolicyServer: callback focus abandoned");
732 interruptCb->OnInterrupt(interruptEvent);
733
734 return SUCCESS;
735 }
736
PrintOwnersLists()737 void AudioPolicyServer::PrintOwnersLists()
738 {
739 AUDIO_DEBUG_LOG("AudioPolicyServer: Printing active list");
740 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
741 AUDIO_DEBUG_LOG("AudioPolicyServer: curActiveOwnersList_: streamType: %{public}d", it->streamType);
742 AUDIO_DEBUG_LOG("AudioPolicyServer: curActiveOwnersList_: sessionID: %{public}u", it->sessionID);
743 }
744
745 AUDIO_DEBUG_LOG("AudioPolicyServer: Printing pending list");
746 for (auto it = pendingOwnersList_.begin(); it != pendingOwnersList_.end(); ++it) {
747 AUDIO_DEBUG_LOG("AudioPolicyServer: pendingOwnersList_: streamType: %{public}d", it->streamType);
748 AUDIO_DEBUG_LOG("AudioPolicyServer: pendingOwnersList_: sessionID: %{public}u", it->sessionID);
749 }
750 }
751
ProcessPendingInterrupt(std::list<AudioInterrupt>::iterator & iterPending,const AudioInterrupt & incoming)752 bool AudioPolicyServer::ProcessPendingInterrupt(std::list<AudioInterrupt>::iterator &iterPending,
753 const AudioInterrupt &incoming)
754 {
755 bool iterPendingErased = false;
756 AudioStreamType pendingStreamType = iterPending->streamType;
757 AudioStreamType incomingStreamType = incoming.streamType;
758
759 auto focusMap = mPolicyService.GetAudioFocusMap();
760 std::pair<AudioStreamType, AudioStreamType> streamTypePair = std::make_pair(pendingStreamType, incomingStreamType);
761
762 if (focusMap.find(streamTypePair) == focusMap.end()) {
763 AUDIO_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
764 return iterPendingErased;
765 }
766
767 AudioFocusEntry focusEntry = focusMap[streamTypePair];
768 float duckVol = 0.2f;
769 InterruptEventInternal interruptEvent {INTERRUPT_TYPE_BEGIN, focusEntry.forceType, focusEntry.hintType, duckVol};
770
771 uint32_t pendingSessionID = iterPending->sessionID;
772 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
773
774 if (focusEntry.actionOn == CURRENT && focusEntry.forceType == INTERRUPT_FORCE) {
775 policyListenerCb = policyListenerCbsMap_[pendingSessionID];
776
777 if (focusEntry.hintType == INTERRUPT_HINT_STOP) {
778 iterPending = pendingOwnersList_.erase(iterPending);
779 iterPendingErased = true;
780 }
781
782 if (policyListenerCb == nullptr) {
783 AUDIO_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
784 return iterPendingErased;
785 }
786 policyListenerCb->OnInterrupt(interruptEvent);
787 }
788
789 return iterPendingErased;
790 }
791
ProcessCurActiveInterrupt(std::list<AudioInterrupt>::iterator & iterActive,const AudioInterrupt & incoming)792 bool AudioPolicyServer::ProcessCurActiveInterrupt(std::list<AudioInterrupt>::iterator &iterActive,
793 const AudioInterrupt &incoming)
794 {
795 bool iterActiveErased = false;
796 AudioStreamType activeStreamType = iterActive->streamType;
797 AudioStreamType incomingStreamType = incoming.streamType;
798
799 auto focusMap = mPolicyService.GetAudioFocusMap();
800 std::pair<AudioStreamType, AudioStreamType> streamTypePair = std::make_pair(activeStreamType, incomingStreamType);
801
802 if (focusMap.find(streamTypePair) == focusMap.end()) {
803 AUDIO_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
804 return iterActiveErased;
805 }
806
807 AudioFocusEntry focusEntry = focusMap[streamTypePair];
808 InterruptEventInternal interruptEvent {INTERRUPT_TYPE_BEGIN, focusEntry.forceType, focusEntry.hintType, 0.2f};
809
810 uint32_t activeSessionID = iterActive->sessionID;
811 uint32_t incomingSessionID = incoming.sessionID;
812 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
813 if (focusEntry.actionOn == CURRENT) {
814 policyListenerCb = policyListenerCbsMap_[activeSessionID];
815 } else {
816 policyListenerCb = policyListenerCbsMap_[incomingSessionID];
817 }
818
819 // focusEntry.forceType == INTERRUPT_SHARE
820 if (focusEntry.forceType != INTERRUPT_FORCE) {
821 if (policyListenerCb == nullptr) {
822 AUDIO_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
823 return iterActiveErased;
824 }
825 policyListenerCb->OnInterrupt(interruptEvent);
826 return iterActiveErased;
827 }
828
829 // focusEntry.forceType == INTERRUPT_FORCE
830 AUDIO_INFO_LOG("AudioPolicyServer: Action is taken on: %{public}d", focusEntry.actionOn);
831 float volume = 0.0f;
832 if (focusEntry.actionOn == CURRENT) {
833 switch (focusEntry.hintType) {
834 case INTERRUPT_HINT_STOP:
835 iterActive = curActiveOwnersList_.erase(iterActive);
836 iterActiveErased = true;
837 break;
838 case INTERRUPT_HINT_PAUSE:
839 pendingOwnersList_.emplace_front(*iterActive);
840 iterActive = curActiveOwnersList_.erase(iterActive);
841 iterActiveErased = true;
842 break;
843 case INTERRUPT_HINT_DUCK:
844 volume = GetStreamVolume(incomingStreamType);
845 interruptEvent.duckVolume = DUCK_FACTOR * volume;
846 break;
847 default:
848 break;
849 }
850 } else { // INCOMING
851 if (focusEntry.hintType == INTERRUPT_HINT_DUCK) {
852 AUDIO_INFO_LOG("AudioPolicyServer: force duck get GetStreamVolume(activeStreamType)");
853 volume = GetStreamVolume(activeStreamType);
854 interruptEvent.duckVolume = DUCK_FACTOR * volume;
855 }
856 }
857
858 if (policyListenerCb == nullptr) {
859 AUDIO_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
860 return iterActiveErased;
861 }
862 policyListenerCb->OnInterrupt(interruptEvent);
863
864 return iterActiveErased;
865 }
866
ProcessFocusEntry(const AudioInterrupt & incomingInterrupt)867 int32_t AudioPolicyServer::ProcessFocusEntry(const AudioInterrupt &incomingInterrupt)
868 {
869 // Function: First Process pendingList and remove session that loses focus indefinitely
870 for (auto iterPending = pendingOwnersList_.begin(); iterPending != pendingOwnersList_.end();) {
871 bool IsIterPendingErased = ProcessPendingInterrupt(iterPending, incomingInterrupt);
872 if (!IsIterPendingErased) {
873 AUDIO_INFO_LOG("AudioPolicyServer: iterPending not erased while processing ++increment it");
874 ++iterPending;
875 }
876 }
877
878 auto focusMap = mPolicyService.GetAudioFocusMap();
879 // Function: Process Focus entry
880 for (auto iterActive = curActiveOwnersList_.begin(); iterActive != curActiveOwnersList_.end();) {
881 AudioStreamType activeStreamType = iterActive->streamType;
882 AudioStreamType incomingStreamType = incomingInterrupt.streamType;
883 std::pair<AudioStreamType, AudioStreamType> streamTypePair =
884 std::make_pair(activeStreamType, incomingStreamType);
885
886 if (focusMap.find(streamTypePair) == focusMap.end()) {
887 AUDIO_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
888 return ERR_INVALID_PARAM;
889 }
890
891 AudioFocusEntry focusEntry = focusMap[streamTypePair];
892 if (focusEntry.isReject) {
893 AUDIO_INFO_LOG("AudioPolicyServer: focusEntry.isReject : ActivateAudioInterrupt request rejected");
894 return ERR_FOCUS_DENIED;
895 }
896 bool IsIterActiveErased = ProcessCurActiveInterrupt(iterActive, incomingInterrupt);
897 if (!IsIterActiveErased) {
898 AUDIO_INFO_LOG("AudioPolicyServer: iterActive not erased while processing ++increment it");
899 ++iterActive;
900 }
901 }
902
903 return SUCCESS;
904 }
905
AddToCurActiveList(const AudioInterrupt & audioInterrupt)906 void AudioPolicyServer::AddToCurActiveList(const AudioInterrupt &audioInterrupt)
907 {
908 if (curActiveOwnersList_.empty()) {
909 curActiveOwnersList_.emplace_front(audioInterrupt);
910 return;
911 }
912
913 auto itCurActive = curActiveOwnersList_.begin();
914
915 for (; itCurActive != curActiveOwnersList_.end(); ++itCurActive) {
916 AudioStreamType existingPriorityStreamType = itCurActive->streamType;
917 if (interruptPriorityMap_[existingPriorityStreamType] > interruptPriorityMap_[audioInterrupt.streamType]) {
918 continue;
919 } else {
920 curActiveOwnersList_.emplace(itCurActive, audioInterrupt);
921 return;
922 }
923 }
924
925 if (itCurActive == curActiveOwnersList_.end()) {
926 curActiveOwnersList_.emplace_back(audioInterrupt);
927 }
928 }
929
ActivateAudioInterrupt(const AudioInterrupt & audioInterrupt)930 int32_t AudioPolicyServer::ActivateAudioInterrupt(const AudioInterrupt &audioInterrupt)
931 {
932 std::lock_guard<std::mutex> lock(interruptMutex_);
933
934 AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt");
935 AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.streamType: %{public}d", audioInterrupt.streamType);
936 AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.sessionID: %{public}u", audioInterrupt.sessionID);
937
938 if (!mPolicyService.IsAudioInterruptEnabled()) {
939 AUDIO_DEBUG_LOG("AudioPolicyServer: interrupt is not enabled. No need to ActivateAudioInterrupt");
940 AddToCurActiveList(audioInterrupt);
941 return SUCCESS;
942 }
943
944 AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt start: print active and pending lists");
945 PrintOwnersLists();
946
947 // Check if the session is present in pending list, remove and treat it as a new request
948 uint32_t incomingSessionID = audioInterrupt.sessionID;
949 if (!pendingOwnersList_.empty()) {
950 AUDIO_DEBUG_LOG("If it is present in pending list, remove and treat is as new request");
951 pendingOwnersList_.remove_if([&incomingSessionID](AudioInterrupt &interrupt) {
952 return interrupt.sessionID == incomingSessionID;
953 });
954 }
955
956 // If active owners list is empty, directly activate interrupt
957 if (curActiveOwnersList_.empty()) {
958 curActiveOwnersList_.emplace_front(audioInterrupt);
959 AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
960 PrintOwnersLists();
961 return SUCCESS;
962 }
963
964 // If the session is already in active list, return
965 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
966 if (it->sessionID == audioInterrupt.sessionID) {
967 AUDIO_DEBUG_LOG("AudioPolicyServer: sessionID %{public}d is already active", audioInterrupt.sessionID);
968 AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
969 PrintOwnersLists();
970 return SUCCESS;
971 }
972 }
973
974 // Process ProcessFocusEntryTable for current active and pending lists
975 int32_t ret = ProcessFocusEntry(audioInterrupt);
976 if (ret) {
977 AUDIO_ERR_LOG("AudioPolicyServer: ActivateAudioInterrupt request rejected");
978 AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
979 PrintOwnersLists();
980 return ERR_FOCUS_DENIED;
981 }
982
983 // Activate request processed and accepted. Add the entry to active list
984 AddToCurActiveList(audioInterrupt);
985
986 AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
987 PrintOwnersLists();
988 return SUCCESS;
989 }
990
UnduckCurActiveList(const AudioInterrupt & exitInterrupt)991 void AudioPolicyServer::UnduckCurActiveList(const AudioInterrupt &exitInterrupt)
992 {
993 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
994 AudioStreamType exitStreamType = exitInterrupt.streamType;
995 InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
996
997 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
998 AudioStreamType activeStreamType = it->streamType;
999 uint32_t activeSessionID = it->sessionID;
1000 if (interruptPriorityMap_[activeStreamType] > interruptPriorityMap_[exitStreamType]) {
1001 continue;
1002 }
1003 policyListenerCb = policyListenerCbsMap_[activeSessionID];
1004 if (policyListenerCb == nullptr) {
1005 AUDIO_WARNING_LOG("AudioPolicyServer: Cb sessionID: %{public}d null. ignoring to Unduck", activeSessionID);
1006 return;
1007 }
1008 policyListenerCb->OnInterrupt(forcedUnducking);
1009 }
1010 }
1011
ResumeUnduckPendingList(const AudioInterrupt & exitInterrupt)1012 void AudioPolicyServer::ResumeUnduckPendingList(const AudioInterrupt &exitInterrupt)
1013 {
1014 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
1015 AudioStreamType exitStreamType = exitInterrupt.streamType;
1016 InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
1017 InterruptEventInternal resumeForcePaused {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_RESUME, 0.2f};
1018
1019 for (auto it = pendingOwnersList_.begin(); it != pendingOwnersList_.end();) {
1020 AudioStreamType pendingStreamType = it->streamType;
1021 uint32_t pendingSessionID = it->sessionID;
1022 if (interruptPriorityMap_[pendingStreamType] > interruptPriorityMap_[exitStreamType]) {
1023 ++it;
1024 continue;
1025 }
1026 it = pendingOwnersList_.erase(it);
1027 policyListenerCb = policyListenerCbsMap_[pendingSessionID];
1028 if (policyListenerCb == nullptr) {
1029 AUDIO_WARNING_LOG("AudioPolicyServer: Cb sessionID: %{public}d null. ignoring resume", pendingSessionID);
1030 return;
1031 }
1032 policyListenerCb->OnInterrupt(forcedUnducking);
1033 policyListenerCb->OnInterrupt(resumeForcePaused);
1034 }
1035 }
1036
DeactivateAudioInterrupt(const AudioInterrupt & audioInterrupt)1037 int32_t AudioPolicyServer::DeactivateAudioInterrupt(const AudioInterrupt &audioInterrupt)
1038 {
1039 std::lock_guard<std::mutex> lock(interruptMutex_);
1040
1041 if (!mPolicyService.IsAudioInterruptEnabled()) {
1042 AUDIO_DEBUG_LOG("AudioPolicyServer: interrupt is not enabled. No need to DeactivateAudioInterrupt");
1043 uint32_t exitSessionID = audioInterrupt.sessionID;
1044 curActiveOwnersList_.remove_if([&exitSessionID](AudioInterrupt &interrupt) {
1045 return interrupt.sessionID == exitSessionID;
1046 });
1047 return SUCCESS;
1048 }
1049
1050 AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt");
1051 AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.streamType: %{public}d", audioInterrupt.streamType);
1052 AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.sessionID: %{public}u", audioInterrupt.sessionID);
1053
1054 AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
1055 PrintOwnersLists();
1056
1057 // Check and remove, its entry from pending first
1058 uint32_t exitSessionID = audioInterrupt.sessionID;
1059 pendingOwnersList_.remove_if([&exitSessionID](AudioInterrupt &interrupt) {
1060 return interrupt.sessionID == exitSessionID;
1061 });
1062
1063 bool isInterruptActive = false;
1064 InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
1065 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
1066 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end();) {
1067 if (it->sessionID == audioInterrupt.sessionID) {
1068 policyListenerCb = policyListenerCbsMap_[it->sessionID];
1069 if (policyListenerCb != nullptr) {
1070 policyListenerCb->OnInterrupt(forcedUnducking); // Unducks self, if ducked before
1071 }
1072 it = curActiveOwnersList_.erase(it);
1073 isInterruptActive = true;
1074 } else {
1075 ++it;
1076 }
1077 }
1078
1079 // If it was not present in both the lists or present only in pending list,
1080 // No need to take any action on other sessions, just return.
1081 if (!isInterruptActive) {
1082 AUDIO_DEBUG_LOG("AudioPolicyServer: Session : %{public}d is not currently active. return success",
1083 audioInterrupt.sessionID);
1084 AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
1085 PrintOwnersLists();
1086 return SUCCESS;
1087 }
1088
1089 if (curActiveOwnersList_.empty() && pendingOwnersList_.empty()) {
1090 AUDIO_DEBUG_LOG("AudioPolicyServer: No other session active or pending. Deactivate complete, return success");
1091 AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
1092 PrintOwnersLists();
1093 return SUCCESS;
1094 }
1095
1096 // unduck if the session was forced ducked
1097 UnduckCurActiveList(audioInterrupt);
1098
1099 // resume and unduck if the session was forced paused
1100 ResumeUnduckPendingList(audioInterrupt);
1101
1102 AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt end: print active and pending lists");
1103 PrintOwnersLists();
1104 return SUCCESS;
1105 }
1106
OnSessionRemoved(const uint32_t sessionID)1107 void AudioPolicyServer::OnSessionRemoved(const uint32_t sessionID)
1108 {
1109 uint32_t removedSessionID = sessionID;
1110
1111 auto isSessionPresent = [&removedSessionID] (const AudioInterrupt &interrupt) {
1112 return interrupt.sessionID == removedSessionID;
1113 };
1114
1115 AUDIO_DEBUG_LOG("AudioPolicyServer::OnSessionRemoved");
1116 std::unique_lock<std::mutex> lock(interruptMutex_);
1117
1118 auto iterActive = std::find_if(curActiveOwnersList_.begin(), curActiveOwnersList_.end(), isSessionPresent);
1119 if (iterActive != curActiveOwnersList_.end()) {
1120 AudioInterrupt removedInterrupt = *iterActive;
1121 lock.unlock();
1122 AUDIO_DEBUG_LOG("Removed SessionID: %{public}u is present in active list", removedSessionID);
1123
1124 (void)DeactivateAudioInterrupt(removedInterrupt);
1125 (void)UnsetAudioInterruptCallback(removedSessionID);
1126 return;
1127 }
1128 AUDIO_DEBUG_LOG("Removed SessionID: %{public}u is not present in active list", removedSessionID);
1129
1130 auto iterPending = std::find_if(pendingOwnersList_.begin(), pendingOwnersList_.end(), isSessionPresent);
1131 if (iterPending != pendingOwnersList_.end()) {
1132 AudioInterrupt removedInterrupt = *iterPending;
1133 lock.unlock();
1134 AUDIO_DEBUG_LOG("Removed SessionID: %{public}u is present in pending list", removedSessionID);
1135
1136 (void)DeactivateAudioInterrupt(removedInterrupt);
1137 (void)UnsetAudioInterruptCallback(removedSessionID);
1138 return;
1139 }
1140 AUDIO_DEBUG_LOG("Removed SessionID: %{public}u not present in pending list either", removedSessionID);
1141
1142 // Though it is not present in the owners list, check and clear its entry from callback map
1143 lock.unlock();
1144 (void)UnsetAudioInterruptCallback(removedSessionID);
1145 }
1146
GetStreamInFocus()1147 AudioStreamType AudioPolicyServer::GetStreamInFocus()
1148 {
1149 AudioStreamType streamInFocus = STREAM_DEFAULT;
1150 if (GetAudioScene() == AUDIO_SCENE_PHONE_CALL) {
1151 // When a call stream is playing, the stream type in focus is still ring.
1152 // So we set streamInFocus to call manually.
1153 streamInFocus = STREAM_VOICE_CALL;
1154 } else if (!curActiveOwnersList_.empty()) {
1155 streamInFocus = curActiveOwnersList_.front().streamType;
1156 }
1157
1158 return streamInFocus;
1159 }
1160
GetSessionInfoInFocus(AudioInterrupt & audioInterrupt)1161 int32_t AudioPolicyServer::GetSessionInfoInFocus(AudioInterrupt &audioInterrupt)
1162 {
1163 uint32_t invalidSessionID = static_cast<uint32_t>(-1);
1164 audioInterrupt = {STREAM_USAGE_UNKNOWN, CONTENT_TYPE_UNKNOWN, STREAM_DEFAULT, invalidSessionID};
1165
1166 if (!curActiveOwnersList_.empty()) {
1167 audioInterrupt = curActiveOwnersList_.front();
1168 }
1169
1170 return SUCCESS;
1171 }
1172
SetVolumeKeyEventCallback(const int32_t clientPid,const sptr<IRemoteObject> & object)1173 int32_t AudioPolicyServer::SetVolumeKeyEventCallback(const int32_t clientPid, const sptr<IRemoteObject> &object)
1174 {
1175 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
1176 AUDIO_DEBUG_LOG("AudioPolicyServer::SetVolumeKeyEventCallback");
1177 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
1178 "AudioPolicyServer::SetVolumeKeyEventCallback listener object is nullptr");
1179
1180 sptr<IAudioVolumeKeyEventCallback> listener = iface_cast<IAudioVolumeKeyEventCallback>(object);
1181 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM,
1182 "AudioPolicyServer::SetVolumeKeyEventCallback listener obj cast failed");
1183
1184 std::shared_ptr<VolumeKeyEventCallback> callback = std::make_shared<VolumeKeyEventCallbackListner>(listener);
1185 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM,
1186 "AudioPolicyServer::SetVolumeKeyEventCallback failed to create cb obj");
1187
1188 volumeChangeCbsMap_[clientPid] = callback;
1189 return SUCCESS;
1190 }
1191
UnsetVolumeKeyEventCallback(const int32_t clientPid)1192 int32_t AudioPolicyServer::UnsetVolumeKeyEventCallback(const int32_t clientPid)
1193 {
1194 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
1195
1196 if (volumeChangeCbsMap_.find(clientPid) != volumeChangeCbsMap_.end()) {
1197 volumeChangeCbsMap_.erase(clientPid);
1198 AUDIO_ERR_LOG("AudioPolicyServer::UnsetVolumeKeyEventCallback for clientPid %{public}d done", clientPid);
1199 } else {
1200 AUDIO_DEBUG_LOG("AudioPolicyServer::UnsetVolumeKeyEventCallback clientPid %{public}d not present/unset already",
1201 clientPid);
1202 }
1203
1204 return SUCCESS;
1205 }
1206
VerifyClientPermission(const std::string & permissionName,uint32_t appTokenId,int32_t appUid,bool privacyFlag,AudioPermissionState state)1207 bool AudioPolicyServer::VerifyClientPermission(const std::string &permissionName, uint32_t appTokenId, int32_t appUid,
1208 bool privacyFlag, AudioPermissionState state)
1209 {
1210 auto callerUid = IPCSkeleton::GetCallingUid();
1211 AUDIO_DEBUG_LOG("[%{public}s] [tid:%{public}d] [uid:%{public}d]", permissionName.c_str(), appTokenId, callerUid);
1212
1213 // Root users should be whitelisted
1214 if ((callerUid == ROOT_UID) || ((callerUid == MEDIA_SERVICE_UID) && (appUid == ROOT_UID))) {
1215 AUDIO_DEBUG_LOG("Root user. Permission GRANTED!!!");
1216 return true;
1217 }
1218
1219 Security::AccessToken::AccessTokenID clientTokenId = 0;
1220 // Special handling required for media service
1221 if (callerUid == MEDIA_SERVICE_UID) {
1222 if (appTokenId == 0) {
1223 AUDIO_ERR_LOG("Invalid token received. Permission rejected");
1224 return false;
1225 }
1226 clientTokenId = appTokenId;
1227 } else {
1228 clientTokenId = IPCSkeleton::GetCallingTokenID();
1229 }
1230
1231 int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(clientTokenId, permissionName);
1232 if (res != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
1233 AUDIO_ERR_LOG("Permission denied [tid:%{public}d]", clientTokenId);
1234 return false;
1235 }
1236 if (privacyFlag) {
1237 if (!PrivacyKit::IsAllowedUsingPermission(clientTokenId, MICROPHONE_PERMISSION)) {
1238 AUDIO_ERR_LOG("app background, not allow using perm for client %{public}d", clientTokenId);
1239 }
1240 }
1241
1242 return true;
1243 }
1244
getUsingPemissionFromPrivacy(const std::string & permissionName,uint32_t appTokenId,AudioPermissionState state)1245 bool AudioPolicyServer::getUsingPemissionFromPrivacy(const std::string &permissionName, uint32_t appTokenId,
1246 AudioPermissionState state)
1247 {
1248 auto callerUid = IPCSkeleton::GetCallingUid();
1249 AUDIO_DEBUG_LOG("[%{public}s] [tid:%{public}d] [uid:%{public}d]", permissionName.c_str(), appTokenId, callerUid);
1250
1251 Security::AccessToken::AccessTokenID clientTokenId = 0;
1252 if (callerUid == MEDIA_SERVICE_UID) {
1253 if (appTokenId == 0) {
1254 AUDIO_ERR_LOG("Invalid token received. Permission rejected");
1255 return false;
1256 }
1257 clientTokenId = appTokenId;
1258 } else {
1259 clientTokenId = IPCSkeleton::GetCallingTokenID();
1260 }
1261
1262 if (state == AUDIO_PERMISSION_START) {
1263 int res = PrivacyKit::StartUsingPermission(clientTokenId, MICROPHONE_PERMISSION);
1264 if (res != 0) {
1265 AUDIO_ERR_LOG("start using perm error for client %{public}d", clientTokenId);
1266 }
1267 } else {
1268 int res = PrivacyKit::StopUsingPermission(clientTokenId, MICROPHONE_PERMISSION);
1269 if (res != 0) {
1270 AUDIO_ERR_LOG("stop using perm error for client %{public}d", clientTokenId);
1271 }
1272 }
1273
1274 return true;
1275 }
1276
ReconfigureAudioChannel(const uint32_t & count,DeviceType deviceType)1277 int32_t AudioPolicyServer::ReconfigureAudioChannel(const uint32_t &count, DeviceType deviceType)
1278 {
1279 // Only root users should have access to this api
1280 if (ROOT_UID != IPCSkeleton::GetCallingUid()) {
1281 AUDIO_INFO_LOG("Unautorized user. Cannot modify channel");
1282 return ERR_PERMISSION_DENIED;
1283 }
1284
1285 return mPolicyService.ReconfigureAudioChannel(count, deviceType);
1286 }
1287
MapVolumeToHDI(int32_t volume)1288 float AudioPolicyServer::MapVolumeToHDI(int32_t volume)
1289 {
1290 float value = (float)volume / MAX_VOLUME_LEVEL;
1291 float roundValue = (int)(value * CONST_FACTOR);
1292
1293 return (float)roundValue / CONST_FACTOR;
1294 }
1295
ConvertVolumeToInt(float volume)1296 int32_t AudioPolicyServer::ConvertVolumeToInt(float volume)
1297 {
1298 float value = (float)volume * MAX_VOLUME_LEVEL;
1299 return nearbyint(value);
1300 }
1301
GetPolicyData(PolicyData & policyData)1302 void AudioPolicyServer::GetPolicyData(PolicyData &policyData)
1303 {
1304 policyData.ringerMode = GetRingerMode();
1305 policyData.callStatus = GetAudioScene();
1306
1307 // Get stream volumes
1308 for (int stream = AudioStreamType::STREAM_VOICE_CALL; stream <= AudioStreamType::STREAM_TTS; stream++) {
1309 AudioStreamType streamType = (AudioStreamType)stream;
1310
1311 if (AudioServiceDump::IsStreamSupported(streamType)) {
1312 int32_t volume = ConvertVolumeToInt(GetStreamVolume(streamType));
1313 policyData.streamVolumes.insert({ streamType, volume });
1314 }
1315 }
1316
1317 // Get Audio Focus Information
1318 AudioInterrupt audioInterrupt;
1319 if (GetSessionInfoInFocus(audioInterrupt) == SUCCESS) {
1320 policyData.audioFocusInfo = audioInterrupt;
1321 }
1322
1323 GetDeviceInfo(policyData);
1324 GetGroupInfo(policyData);
1325 }
1326
GetDeviceInfo(PolicyData & policyData)1327 void AudioPolicyServer::GetDeviceInfo(PolicyData& policyData)
1328 {
1329 DeviceFlag deviceFlag = DeviceFlag::INPUT_DEVICES_FLAG;
1330 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors = GetDevices(deviceFlag);
1331
1332 for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1333 AudioDeviceDescriptor audioDeviceDescriptor = **it;
1334 DevicesInfo deviceInfo;
1335 deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1336 deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1337 deviceInfo.conneceType = CONNECT_TYPE_LOCAL;
1338 policyData.inputDevices.push_back(deviceInfo);
1339 }
1340
1341 deviceFlag = DeviceFlag::OUTPUT_DEVICES_FLAG;
1342 audioDeviceDescriptors = GetDevices(deviceFlag);
1343
1344 for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1345 AudioDeviceDescriptor audioDeviceDescriptor = **it;
1346 DevicesInfo deviceInfo;
1347 deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1348 deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1349 deviceInfo.conneceType = CONNECT_TYPE_LOCAL;
1350 policyData.outputDevices.push_back(deviceInfo);
1351 }
1352
1353 deviceFlag = DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG;
1354 audioDeviceDescriptors = GetDevices(deviceFlag);
1355
1356 for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1357 AudioDeviceDescriptor audioDeviceDescriptor = **it;
1358 DevicesInfo deviceInfo;
1359 deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1360 deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1361 deviceInfo.conneceType = CONNECT_TYPE_DISTRIBUTED;
1362 policyData.inputDevices.push_back(deviceInfo);
1363 }
1364
1365 deviceFlag = DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG;
1366 audioDeviceDescriptors = GetDevices(deviceFlag);
1367
1368 for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1369 AudioDeviceDescriptor audioDeviceDescriptor = **it;
1370 DevicesInfo deviceInfo;
1371 deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1372 deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1373 deviceInfo.conneceType = CONNECT_TYPE_DISTRIBUTED;
1374 policyData.outputDevices.push_back(deviceInfo);
1375 }
1376 }
1377
GetGroupInfo(PolicyData & policyData)1378 void AudioPolicyServer::GetGroupInfo(PolicyData& policyData)
1379 {
1380 // Get group info
1381 std::vector<sptr<VolumeGroupInfo>> groupInfos = GetVolumeGroupInfos();
1382 for (auto volumeGroupInfo : groupInfos) {
1383 GroupInfo info;
1384 info.groupId = volumeGroupInfo->volumeGroupId_;
1385 info.groupName = volumeGroupInfo->groupName_;
1386 info.type = volumeGroupInfo->connectType_;
1387 policyData.groupInfos.push_back(info);
1388 }
1389 }
1390
Dump(int32_t fd,const std::vector<std::u16string> & args)1391 int32_t AudioPolicyServer::Dump(int32_t fd, const std::vector<std::u16string> &args)
1392 {
1393 AUDIO_DEBUG_LOG("AudioPolicyServer: Dump Process Invoked");
1394 std::unordered_set<std::u16string> argSets;
1395 std::u16string arg1(u"debug_interrupt_resume");
1396 std::u16string arg2(u"debug_interrupt_pause");
1397 for (decltype(args.size()) index = 0; index < args.size(); ++index) {
1398 argSets.insert(args[index]);
1399 }
1400
1401 if (argSets.count(arg1) != 0) {
1402 InterruptType type = INTERRUPT_TYPE_BEGIN;
1403 InterruptForceType forceType = INTERRUPT_SHARE;
1404 InterruptHint hint = INTERRUPT_HINT_RESUME;
1405 InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
1406 for (auto it : policyListenerCbsMap_) {
1407 if (it.second != nullptr) {
1408 it.second->OnInterrupt(interruptEvent);
1409 }
1410 }
1411 }
1412 if (argSets.count(arg2) != 0) {
1413 InterruptType type = INTERRUPT_TYPE_BEGIN;
1414 InterruptForceType forceType = INTERRUPT_SHARE;
1415 InterruptHint hint = INTERRUPT_HINT_PAUSE;
1416 InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
1417 for (auto it : policyListenerCbsMap_) {
1418 if (it.second != nullptr) {
1419 it.second->OnInterrupt(interruptEvent);
1420 }
1421 }
1422 }
1423 std::string dumpString;
1424 PolicyData policyData;
1425 AudioServiceDump dumpObj;
1426
1427 if (dumpObj.Initialize() != AUDIO_DUMP_SUCCESS) {
1428 AUDIO_ERR_LOG("AudioPolicyServer:: Audio Service Dump Not initialised\n");
1429 return AUDIO_DUMP_INIT_ERR;
1430 }
1431
1432 GetPolicyData(policyData);
1433 dumpObj.AudioDataDump(policyData, dumpString);
1434
1435 return write(fd, dumpString.c_str(), dumpString.size());
1436 }
1437
GetAudioLatencyFromXml()1438 int32_t AudioPolicyServer::GetAudioLatencyFromXml()
1439 {
1440 return mPolicyService.GetAudioLatencyFromXml();
1441 }
1442
GetSinkLatencyFromXml()1443 uint32_t AudioPolicyServer::GetSinkLatencyFromXml()
1444 {
1445 return mPolicyService.GetSinkLatencyFromXml();
1446 }
1447
RegisterAudioRendererEventListener(int32_t clientUID,const sptr<IRemoteObject> & object)1448 int32_t AudioPolicyServer::RegisterAudioRendererEventListener(int32_t clientUID, const sptr<IRemoteObject> &object)
1449 {
1450 RegisterClientDeathRecipient(object, LISTENER_CLIENT);
1451 uint32_t clientTokenId = IPCSkeleton::GetCallingTokenID();
1452 bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION, clientTokenId);
1453 return mPolicyService.RegisterAudioRendererEventListener(clientUID, object, hasBTPermission);
1454 }
1455
UnregisterAudioRendererEventListener(int32_t clientUID)1456 int32_t AudioPolicyServer::UnregisterAudioRendererEventListener(int32_t clientUID)
1457 {
1458 return mPolicyService.UnregisterAudioRendererEventListener(clientUID);
1459 }
1460
RegisterAudioCapturerEventListener(int32_t clientUID,const sptr<IRemoteObject> & object)1461 int32_t AudioPolicyServer::RegisterAudioCapturerEventListener(int32_t clientUID, const sptr<IRemoteObject> &object)
1462 {
1463 RegisterClientDeathRecipient(object, LISTENER_CLIENT);
1464 uint32_t clientTokenId = IPCSkeleton::GetCallingTokenID();
1465 bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION, clientTokenId);
1466 return mPolicyService.RegisterAudioCapturerEventListener(clientUID, object, hasBTPermission);
1467 }
1468
UnregisterAudioCapturerEventListener(int32_t clientUID)1469 int32_t AudioPolicyServer::UnregisterAudioCapturerEventListener(int32_t clientUID)
1470 {
1471 return mPolicyService.UnregisterAudioCapturerEventListener(clientUID);
1472 }
1473
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object)1474 int32_t AudioPolicyServer::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
1475 const sptr<IRemoteObject> &object)
1476 {
1477 // update the clientUID
1478 auto callerUid = IPCSkeleton::GetCallingUid();
1479 AUDIO_INFO_LOG(" AudioPolicyServer::RegisterTracker : [caller uid:%{public}d]==", callerUid);
1480 if (callerUid != MEDIA_SERVICE_UID) {
1481 if (mode == AUDIO_MODE_PLAYBACK) {
1482 streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
1483 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1484 streamChangeInfo.audioRendererChangeInfo.clientUID);
1485 } else {
1486 streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
1487 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1488 streamChangeInfo.audioCapturerChangeInfo.clientUID);
1489 }
1490 }
1491 RegisterClientDeathRecipient(object, TRACKER_CLIENT);
1492 return mPolicyService.RegisterTracker(mode, streamChangeInfo, object);
1493 }
1494
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)1495 int32_t AudioPolicyServer::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
1496 {
1497 // update the clientUID
1498 auto callerUid = IPCSkeleton::GetCallingUid();
1499 AUDIO_INFO_LOG(" AudioPolicyServer::UpdateTracker : [caller uid:%{public}d]==", callerUid);
1500 if (callerUid != MEDIA_SERVICE_UID) {
1501 if (mode == AUDIO_MODE_PLAYBACK) {
1502 streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
1503 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1504 streamChangeInfo.audioRendererChangeInfo.clientUID);
1505 } else {
1506 streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
1507 AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1508 streamChangeInfo.audioCapturerChangeInfo.clientUID);
1509 }
1510 }
1511 return mPolicyService.UpdateTracker(mode, streamChangeInfo);
1512 }
1513
GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos)1514 int32_t AudioPolicyServer::GetCurrentRendererChangeInfos(
1515 vector<unique_ptr<AudioRendererChangeInfo>> &audioRendererChangeInfos)
1516 {
1517 bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION);
1518 AUDIO_DEBUG_LOG("GetCurrentRendererChangeInfos: BT use permission: %{public}d", hasBTPermission);
1519 return mPolicyService.GetCurrentRendererChangeInfos(audioRendererChangeInfos, hasBTPermission);
1520 }
1521
GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos)1522 int32_t AudioPolicyServer::GetCurrentCapturerChangeInfos(
1523 vector<unique_ptr<AudioCapturerChangeInfo>> &audioCapturerChangeInfos)
1524 {
1525 bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION);
1526 AUDIO_DEBUG_LOG("GetCurrentCapturerChangeInfos: BT use permission: %{public}d", hasBTPermission);
1527 return mPolicyService.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos, hasBTPermission);
1528 }
1529
RegisterClientDeathRecipient(const sptr<IRemoteObject> & object,DeathRecipientId id)1530 void AudioPolicyServer::RegisterClientDeathRecipient(const sptr<IRemoteObject> &object, DeathRecipientId id)
1531 {
1532 AUDIO_INFO_LOG("Register clients death recipient!!");
1533 CHECK_AND_RETURN_LOG(object != nullptr, "Client proxy obj NULL!!");
1534
1535 pid_t uid = 0;
1536 if (id == TRACKER_CLIENT) {
1537 // Deliberately casting UID to pid_t
1538 uid = static_cast<pid_t>(IPCSkeleton::GetCallingUid());
1539 } else {
1540 uid = IPCSkeleton::GetCallingPid();
1541 }
1542 if (id == TRACKER_CLIENT && std::find(clientDiedListenerState_.begin(), clientDiedListenerState_.end(), uid)
1543 != clientDiedListenerState_.end()) {
1544 AUDIO_INFO_LOG("Tracker has been registered for %{public}d!", uid);
1545 return;
1546 }
1547 sptr<AudioServerDeathRecipient> deathRecipient_ = new(std::nothrow) AudioServerDeathRecipient(uid);
1548 if (deathRecipient_ != nullptr) {
1549 if (id == TRACKER_CLIENT) {
1550 deathRecipient_->SetNotifyCb(std::bind(&AudioPolicyServer::RegisteredTrackerClientDied,
1551 this, std::placeholders::_1));
1552 } else {
1553 AUDIO_INFO_LOG("RegisteredStreamListenerClientDied register!!");
1554 deathRecipient_->SetNotifyCb(std::bind(&AudioPolicyServer::RegisteredStreamListenerClientDied,
1555 this, std::placeholders::_1));
1556 }
1557 bool result = object->AddDeathRecipient(deathRecipient_);
1558 if (result && id == TRACKER_CLIENT) {
1559 clientDiedListenerState_.push_back(uid);
1560 }
1561 if (!result) {
1562 AUDIO_ERR_LOG("failed to add deathRecipient");
1563 }
1564 }
1565 }
1566
RegisteredTrackerClientDied(pid_t pid)1567 void AudioPolicyServer::RegisteredTrackerClientDied(pid_t pid)
1568 {
1569 AUDIO_INFO_LOG("RegisteredTrackerClient died: remove entry, uid %{public}d", pid);
1570 mPolicyService.RegisteredTrackerClientDied(pid);
1571 auto filter = [&pid](int val) {
1572 return pid == val;
1573 };
1574 clientDiedListenerState_.erase(std::remove_if(clientDiedListenerState_.begin(), clientDiedListenerState_.end(),
1575 filter), clientDiedListenerState_.end());
1576 }
1577
RegisteredStreamListenerClientDied(pid_t pid)1578 void AudioPolicyServer::RegisteredStreamListenerClientDied(pid_t pid)
1579 {
1580 AUDIO_INFO_LOG("RegisteredStreamListenerClient died: remove entry, uid %{public}d", pid);
1581 mPolicyService.RegisteredStreamListenerClientDied(pid);
1582 }
1583
UpdateStreamState(const int32_t clientUid,StreamSetState streamSetState,AudioStreamType audioStreamType)1584 int32_t AudioPolicyServer::UpdateStreamState(const int32_t clientUid,
1585 StreamSetState streamSetState, AudioStreamType audioStreamType)
1586 {
1587 AUDIO_INFO_LOG("UpdateStreamState::uid:%{public}d state:%{public}d sType:%{public}d", clientUid,
1588 streamSetState, audioStreamType);
1589
1590 auto callerUid = IPCSkeleton::GetCallingUid();
1591 if (callerUid == clientUid) {
1592 AUDIO_ERR_LOG("UpdateStreamState clientUid value is error");
1593 return ERROR;
1594 }
1595
1596 StreamSetState setState = StreamSetState::STREAM_PAUSE;
1597 if (streamSetState == StreamSetState::STREAM_RESUME) {
1598 setState = StreamSetState::STREAM_RESUME;
1599 } else if (streamSetState != StreamSetState::STREAM_PAUSE) {
1600 AUDIO_ERR_LOG("UpdateStreamState streamSetState value is error");
1601 return ERROR;
1602 }
1603 StreamSetStateEventInternal setStateEvent = {};
1604 setStateEvent.streamSetState = setState;
1605 setStateEvent.audioStreamType = audioStreamType;
1606
1607 return mPolicyService.UpdateStreamState(clientUid, setStateEvent);
1608 }
1609
GetVolumeGroupInfos()1610 std::vector<sptr<VolumeGroupInfo>> AudioPolicyServer::GetVolumeGroupInfos()
1611 {
1612 return mPolicyService.GetVolumeGroupInfos();
1613 }
1614
RemoteParameterCallback(sptr<AudioPolicyServer> server)1615 AudioPolicyServer::RemoteParameterCallback::RemoteParameterCallback(sptr<AudioPolicyServer> server)
1616 {
1617 server_ = server;
1618 }
1619
OnAudioParameterChange(const std::string networkId,const AudioParamKey key,const std::string & condition,const std::string & value)1620 void AudioPolicyServer::RemoteParameterCallback::OnAudioParameterChange(const std::string networkId,
1621 const AudioParamKey key, const std::string& condition, const std::string& value)
1622 {
1623 AUDIO_INFO_LOG("AudioPolicyServer::OnAudioParameterChange key:%{public}d, condition:%{public}s, value:%{public}s",
1624 key, condition.c_str(), value.c_str());
1625 if (server_ == nullptr) {
1626 AUDIO_ERR_LOG("server_ is nullptr");
1627 return;
1628 }
1629 switch (key) {
1630 case VOLUME:
1631 VolumeOnChange(networkId, condition);
1632 break;
1633 case INTERRUPT:
1634 InterruptOnChange(networkId, condition);
1635 break;
1636 case RENDER_STATE:
1637 StateOnChange(networkId, condition, value);
1638 break;
1639 default:
1640 AUDIO_DEBUG_LOG("[AudioPolicyServer]: No processing");
1641 break;
1642 }
1643 }
1644
VolumeOnChange(const std::string networkId,const std::string & condition)1645 void AudioPolicyServer::RemoteParameterCallback::VolumeOnChange(const std::string networkId,
1646 const std::string& condition)
1647 {
1648 VolumeEvent volumeEvent;
1649 volumeEvent.networkId = networkId;
1650 char eventDes[EVENT_DES_SIZE];
1651 if (sscanf_s(condition.c_str(), "%[^;];AUDIO_STREAM_TYPE=%d;VOLUME_LEVEL=%d;IS_UPDATEUI=%d;VOLUME_GROUP_ID=%d;",
1652 eventDes, EVENT_DES_SIZE, &(volumeEvent.volumeType), &(volumeEvent.volume), &(volumeEvent.updateUi),
1653 &(volumeEvent.volumeGroupId)) < PARAMS_VOLUME_NUM) {
1654 AUDIO_ERR_LOG("[AudioPolicyServer]: Failed parse condition");
1655 return;
1656 }
1657
1658 volumeEvent.updateUi = false;
1659 for (auto it = server_->volumeChangeCbsMap_.begin(); it != server_->volumeChangeCbsMap_.end(); ++it) {
1660 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
1661 if (volumeChangeCb == nullptr) {
1662 AUDIO_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
1663 continue;
1664 }
1665
1666 AUDIO_DEBUG_LOG("AudioPolicyServer:: trigger volumeChangeCb clientPid : %{public}d", it->first);
1667 volumeChangeCb->OnVolumeKeyEvent(volumeEvent);
1668 }
1669 }
1670
InterruptOnChange(const std::string networkId,const std::string & condition)1671 void AudioPolicyServer::RemoteParameterCallback::InterruptOnChange(const std::string networkId,
1672 const std::string& condition)
1673 {
1674 char eventDes[EVENT_DES_SIZE];
1675 InterruptType type = INTERRUPT_TYPE_BEGIN;
1676 InterruptForceType forceType = INTERRUPT_SHARE;
1677 InterruptHint hint = INTERRUPT_HINT_NONE;
1678
1679 if (sscanf_s(condition.c_str(), "%[^;];EVENT_TYPE=%d;FORCE_TYPE=%d;HINT_TYPE=%d;", eventDes,
1680 EVENT_DES_SIZE, &type, &forceType, &hint) < PARAMS_INTERRUPT_NUM) {
1681 AUDIO_ERR_LOG("[AudioPolicyServer]: Failed parse condition");
1682 return;
1683 }
1684
1685 InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
1686 for (auto it : server_->policyListenerCbsMap_) {
1687 if (it.second != nullptr) {
1688 it.second->OnInterrupt(interruptEvent);
1689 }
1690 }
1691 }
1692
StateOnChange(const std::string networkId,const std::string & condition,const std::string & value)1693 void AudioPolicyServer::RemoteParameterCallback::StateOnChange(const std::string networkId,
1694 const std::string& condition, const std::string& value)
1695 {
1696 char eventDes[EVENT_DES_SIZE];
1697 char contentDes[RENDER_STATE_CONTENT_DES_SIZE];
1698 if (sscanf_s(condition.c_str(), "%[^;];%s", eventDes, EVENT_DES_SIZE, contentDes,
1699 RENDER_STATE_CONTENT_DES_SIZE) < PARAMS_RENDER_STATE_NUM) {
1700 AUDIO_ERR_LOG("[AudioPolicyServer]: Failed parse condition");
1701 return;
1702 }
1703 if (!strcmp(eventDes, "ERR_EVENT")) {
1704 server_->mPolicyService.NotifyRemoteRenderState(networkId, condition, value);
1705 }
1706 }
1707
PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo & result)1708 void AudioPolicyServer::PerStateChangeCbCustomizeCallback::PermStateChangeCallback(
1709 Security::AccessToken::PermStateChangeInfo& result)
1710 {
1711 ready_ = true;
1712 Security::AccessToken::HapTokenInfo hapTokenInfo;
1713 int32_t res = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(result.tokenID, hapTokenInfo);
1714 if (res < 0) {
1715 AUDIO_ERR_LOG("Call GetHapTokenInfo fail.");
1716 }
1717 bool bSetMute;
1718 if (result.PermStateChangeType > 0) {
1719 bSetMute = false;
1720 } else {
1721 bSetMute = true;
1722 }
1723
1724 int32_t appUid = getUidByBundleName(hapTokenInfo.bundleName, hapTokenInfo.userID);
1725 if (appUid < 0) {
1726 AUDIO_ERR_LOG("fail to get uid.");
1727 } else {
1728 server_->mPolicyService.SetSourceOutputStreamMute(appUid, bSetMute);
1729 AUDIO_DEBUG_LOG(" get uid value:%{public}d", appUid);
1730 }
1731 }
1732
getUidByBundleName(std::string bundle_name,int user_id)1733 int32_t AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName(std::string bundle_name, int user_id)
1734 {
1735 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1736 if (systemAbilityManager == nullptr) {
1737 return ERR_INVALID_PARAM;
1738 }
1739
1740 sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1741 if (remoteObject == nullptr) {
1742 return ERR_INVALID_PARAM;
1743 }
1744
1745 sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1746 if (bundleMgrProxy == nullptr) {
1747 return ERR_INVALID_PARAM;
1748 }
1749 int32_t iUid = bundleMgrProxy->GetUidByBundleName(bundle_name, user_id);
1750
1751 return iUid;
1752 }
1753
RegisterParamCallback()1754 void AudioPolicyServer::RegisterParamCallback()
1755 {
1756 AUDIO_INFO_LOG("AudioPolicyServer::RegisterParamCallback");
1757 remoteParameterCallback_ = std::make_shared<RemoteParameterCallback>(this);
1758 mPolicyService.SetParameterCallback(remoteParameterCallback_);
1759 }
1760
RegisterBluetoothListener()1761 void AudioPolicyServer::RegisterBluetoothListener()
1762 {
1763 AUDIO_INFO_LOG("AudioPolicyServer::RegisterBluetoothListener");
1764 mPolicyService.RegisterBluetoothListener();
1765 }
1766
SubscribeAccessibilityConfigObserver()1767 void AudioPolicyServer::SubscribeAccessibilityConfigObserver()
1768 {
1769 AUDIO_INFO_LOG("AudioPolicyServer::SubscribeAccessibilityConfigObserver");
1770 mPolicyService.SubscribeAccessibilityConfigObserver();
1771 }
1772
IsAudioRendererLowLatencySupported(const AudioStreamInfo & audioStreamInfo)1773 bool AudioPolicyServer::IsAudioRendererLowLatencySupported(const AudioStreamInfo &audioStreamInfo)
1774 {
1775 AUDIO_INFO_LOG("IsAudioRendererLowLatencySupported server call");
1776 return true;
1777 }
1778 } // namespace AudioStandard
1779 } // namespace OHOS
1780