• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     std::lock_guard<std::mutex> lock(micStateChangeMutex_);
466     AUDIO_INFO_LOG("Entered %{public}s", __func__);
467     bool isMicrophoneMute = IsMicrophoneMute(api_v);
468     int32_t ret = mPolicyService.SetMicrophoneMute(isMute);
469     if (ret == SUCCESS && isMicrophoneMute != isMute) {
470         for (auto it = micStateChangeListenerCbsMap_.begin(); it != micStateChangeListenerCbsMap_.end(); ++it) {
471             std::shared_ptr<AudioManagerMicStateChangeCallback> MicStateChangeListenerCb = it->second;
472             if (MicStateChangeListenerCb == nullptr) {
473                 AUDIO_ERR_LOG("micStateChangeListenerCbsMap_: nullptr for client : %{public}d", it->first);
474                 continue;
475             }
476 
477             AUDIO_DEBUG_LOG("micStateChangeListenerCbsMap_ :client =  %{public}d", it->first);
478             MicStateChangeEvent micStateChangeEvent;
479             micStateChangeEvent.mute = isMute;
480             MicStateChangeListenerCb->OnMicStateUpdated(micStateChangeEvent);
481         }
482     }
483     return ret;
484 }
485 
SetMicrophoneMute(bool isMute)486 int32_t AudioPolicyServer::SetMicrophoneMute(bool isMute)
487 {
488     AUDIO_INFO_LOG("Entered %{public}s", __func__);
489     if (!VerifyClientPermission(MICROPHONE_PERMISSION)) {
490         AUDIO_ERR_LOG("SetMicrophoneMute: MICROPHONE permission denied");
491         return ERR_PERMISSION_DENIED;
492     }
493     return SetMicrophoneMuteCommon(isMute, API_7);
494 }
495 
SetMicrophoneMuteAudioConfig(bool isMute)496 int32_t AudioPolicyServer::SetMicrophoneMuteAudioConfig(bool isMute)
497 {
498     AUDIO_INFO_LOG("Entered %{public}s", __func__);
499     if (!VerifyClientPermission(MANAGE_AUDIO_CONFIG)) {
500         AUDIO_ERR_LOG("SetMicrophoneMuteAudioConfig: MANAGE_AUDIO_CONFIG permission denied");
501         return ERR_PERMISSION_DENIED;
502     }
503     return SetMicrophoneMuteCommon(isMute, API_9);
504 }
505 
IsMicrophoneMute(API_VERSION api_v)506 bool AudioPolicyServer::IsMicrophoneMute(API_VERSION api_v)
507 {
508     AUDIO_INFO_LOG("Entered %{public}s", __func__);
509     if (api_v == API_7 && !VerifyClientPermission(MICROPHONE_PERMISSION)) {
510         AUDIO_ERR_LOG("IsMicrophoneMute: MICROPHONE permission denied");
511         return ERR_PERMISSION_DENIED;
512     }
513 
514     return mPolicyService.IsMicrophoneMute();
515 }
516 
GetRingerMode()517 AudioRingerMode AudioPolicyServer::GetRingerMode()
518 {
519     return mPolicyService.GetRingerMode();
520 }
521 
SetAudioScene(AudioScene audioScene)522 int32_t AudioPolicyServer::SetAudioScene(AudioScene audioScene)
523 {
524     return mPolicyService.SetAudioScene(audioScene);
525 }
526 
GetAudioScene()527 AudioScene AudioPolicyServer::GetAudioScene()
528 {
529     return mPolicyService.GetAudioScene();
530 }
531 
SetRingerModeCallback(const int32_t clientId,const sptr<IRemoteObject> & object)532 int32_t AudioPolicyServer::SetRingerModeCallback(const int32_t clientId, const sptr<IRemoteObject> &object)
533 {
534     std::lock_guard<std::mutex> lock(ringerModeMutex_);
535 
536     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
537 
538     sptr<IStandardRingerModeUpdateListener> listener = iface_cast<IStandardRingerModeUpdateListener>(object);
539     CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
540 
541     std::shared_ptr<AudioRingerModeCallback> callback = std::make_shared<AudioRingerModeListenerCallback>(listener);
542     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to  create cb obj");
543 
544     ringerModeListenerCbsMap_[clientId] = callback;
545 
546     return SUCCESS;
547 }
548 
UnsetRingerModeCallback(const int32_t clientId)549 int32_t AudioPolicyServer::UnsetRingerModeCallback(const int32_t clientId)
550 {
551     std::lock_guard<std::mutex> lock(ringerModeMutex_);
552 
553     if (ringerModeListenerCbsMap_.find(clientId) != ringerModeListenerCbsMap_.end()) {
554         ringerModeListenerCbsMap_.erase(clientId);
555         AUDIO_ERR_LOG("AudioPolicyServer: UnsetRingerModeCallback for client %{public}d done", clientId);
556         return SUCCESS;
557     } else {
558         AUDIO_ERR_LOG("AudioPolicyServer: Cb does not exit for client %{public}d cannot unregister", clientId);
559         return ERR_INVALID_OPERATION;
560     }
561 }
562 
SetMicStateChangeCallback(const int32_t clientId,const sptr<IRemoteObject> & object)563 int32_t AudioPolicyServer::SetMicStateChangeCallback(const int32_t clientId, const sptr<IRemoteObject> &object)
564 {
565     std::lock_guard<std::mutex> lock(micStateChangeMutex_);
566     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
567 
568     sptr<IStandardAudioRoutingManagerListener> listener = iface_cast<IStandardAudioRoutingManagerListener>(object);
569     CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
570 
571     std::shared_ptr<AudioManagerMicStateChangeCallback> callback =
572         std::make_shared<AudioRoutingManagerListenerCallback>(listener);
573     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to  create cb obj");
574 
575     micStateChangeListenerCbsMap_[clientId] = callback;
576 
577     return SUCCESS;
578 }
579 
SetDeviceChangeCallback(const int32_t clientId,const DeviceFlag flag,const sptr<IRemoteObject> & object)580 int32_t AudioPolicyServer::SetDeviceChangeCallback(const int32_t clientId, const DeviceFlag flag,
581     const sptr<IRemoteObject> &object)
582 {
583     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
584 
585     return mPolicyService.SetDeviceChangeCallback(clientId, flag, object);
586 }
587 
UnsetDeviceChangeCallback(const int32_t clientId)588 int32_t AudioPolicyServer::UnsetDeviceChangeCallback(const int32_t clientId)
589 {
590     return mPolicyService.UnsetDeviceChangeCallback(clientId);
591 }
592 
SetAudioInterruptCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)593 int32_t AudioPolicyServer::SetAudioInterruptCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object)
594 {
595     std::lock_guard<std::mutex> lock(interruptMutex_);
596 
597     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
598 
599     sptr<IStandardAudioPolicyManagerListener> listener = iface_cast<IStandardAudioPolicyManagerListener>(object);
600     CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
601 
602     std::shared_ptr<AudioInterruptCallback> callback = std::make_shared<AudioPolicyManagerListenerCallback>(listener);
603     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to  create cb obj");
604 
605     policyListenerCbsMap_[sessionID] = callback;
606     AUDIO_DEBUG_LOG("AudioPolicyServer: SetAudioInterruptCallback for sessionID %{public}d done", sessionID);
607 
608     return SUCCESS;
609 }
610 
UnsetAudioInterruptCallback(const uint32_t sessionID)611 int32_t AudioPolicyServer::UnsetAudioInterruptCallback(const uint32_t sessionID)
612 {
613     std::lock_guard<std::mutex> lock(interruptMutex_);
614 
615     if (policyListenerCbsMap_.erase(sessionID)) {
616         AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetAudioInterruptCallback for sessionID %{public}d done", sessionID);
617     } else {
618         AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetAudioInterruptCallback sessionID %{public}d not present/unset already",
619                         sessionID);
620     }
621 
622     return SUCCESS;
623 }
624 
SetAudioManagerInterruptCallback(const uint32_t clientID,const sptr<IRemoteObject> & object)625 int32_t AudioPolicyServer::SetAudioManagerInterruptCallback(const uint32_t clientID,
626                                                             const sptr<IRemoteObject> &object)
627 {
628     std::lock_guard<std::mutex> lock(interruptMutex_);
629 
630     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
631 
632     sptr<IStandardAudioPolicyManagerListener> listener = iface_cast<IStandardAudioPolicyManagerListener>(object);
633     CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
634 
635     std::shared_ptr<AudioInterruptCallback> callback = std::make_shared<AudioPolicyManagerListenerCallback>(listener);
636     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to  create cb obj");
637 
638     audioManagerListenerCbsMap_[clientID] = callback;
639     AUDIO_INFO_LOG("AudioPolicyServer: SetAudioManagerInterruptCallback for client id %{public}d done", clientID);
640 
641     return SUCCESS;
642 }
643 
UnsetAudioManagerInterruptCallback(const uint32_t clientID)644 int32_t AudioPolicyServer::UnsetAudioManagerInterruptCallback(const uint32_t clientID)
645 {
646     if (audioManagerListenerCbsMap_.erase(clientID)) {
647         AUDIO_INFO_LOG("AudioPolicyServer:UnsetAudioManagerInterruptCallback for client %{public}d done", clientID);
648     } else {
649         AUDIO_DEBUG_LOG("AudioPolicyServer:UnsetAudioManagerInterruptCallback client %{public}d not present",
650                         clientID);
651     }
652 
653     return SUCCESS;
654 }
655 
RequestAudioFocus(const uint32_t clientID,const AudioInterrupt & audioInterrupt)656 int32_t AudioPolicyServer::RequestAudioFocus(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
657 {
658     AUDIO_DEBUG_LOG("AudioPolicyServer: RequestAudioFocus in");
659     if (clientOnFocus_ == clientID) {
660         AUDIO_DEBUG_LOG("AudioPolicyServer: client already has focus");
661         NotifyFocusGranted(clientID, audioInterrupt);
662         return SUCCESS;
663     }
664 
665     if (focussedAudioInterruptInfo_ != nullptr) {
666         AUDIO_DEBUG_LOG("AudioPolicyServer: Existing stream: %{public}d, incoming stream: %{public}d",
667                         focussedAudioInterruptInfo_->streamType, audioInterrupt.streamType);
668         NotifyFocusAbandoned(clientOnFocus_, *focussedAudioInterruptInfo_);
669         AbandonAudioFocus(clientOnFocus_, *focussedAudioInterruptInfo_);
670     }
671 
672     AUDIO_DEBUG_LOG("AudioPolicyServer: Grant audio focus");
673     NotifyFocusGranted(clientID, audioInterrupt);
674 
675     return SUCCESS;
676 }
677 
AbandonAudioFocus(const uint32_t clientID,const AudioInterrupt & audioInterrupt)678 int32_t AudioPolicyServer::AbandonAudioFocus(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
679 {
680     AUDIO_INFO_LOG("AudioPolicyServer: AbandonAudioFocus in");
681 
682     if (clientID == clientOnFocus_) {
683         AUDIO_DEBUG_LOG("AudioPolicyServer: remove app focus");
684         focussedAudioInterruptInfo_.reset();
685         focussedAudioInterruptInfo_ = nullptr;
686         clientOnFocus_ = 0;
687     }
688 
689     return SUCCESS;
690 }
691 
NotifyFocusGranted(const uint32_t clientID,const AudioInterrupt & audioInterrupt)692 void AudioPolicyServer::NotifyFocusGranted(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
693 {
694     AUDIO_INFO_LOG("AudioPolicyServer: Notify focus granted in: %{public}d", clientID);
695     std::shared_ptr<AudioInterruptCallback> interruptCb = nullptr;
696     interruptCb = audioManagerListenerCbsMap_[clientID];
697     if (interruptCb) {
698         InterruptEventInternal interruptEvent = {};
699         interruptEvent.eventType = INTERRUPT_TYPE_END;
700         interruptEvent.forceType = INTERRUPT_SHARE;
701         interruptEvent.hintType = INTERRUPT_HINT_NONE;
702         interruptEvent.duckVolume = 0;
703 
704         AUDIO_DEBUG_LOG("AudioPolicyServer: callback focus granted");
705         interruptCb->OnInterrupt(interruptEvent);
706 
707         unique_ptr<AudioInterrupt> tempAudioInterruptInfo = make_unique<AudioInterrupt>();
708         tempAudioInterruptInfo->streamUsage = audioInterrupt.streamUsage;
709         tempAudioInterruptInfo->contentType = audioInterrupt.contentType;
710         tempAudioInterruptInfo->streamType = audioInterrupt.streamType;
711         tempAudioInterruptInfo->pauseWhenDucked = audioInterrupt.pauseWhenDucked;
712         focussedAudioInterruptInfo_ = move(tempAudioInterruptInfo);
713         clientOnFocus_ = clientID;
714     }
715 }
716 
NotifyFocusAbandoned(const uint32_t clientID,const AudioInterrupt & audioInterrupt)717 int32_t AudioPolicyServer::NotifyFocusAbandoned(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
718 {
719     AUDIO_INFO_LOG("AudioPolicyServer: Notify focus abandoned in: %{public}d", clientID);
720     std::shared_ptr<AudioInterruptCallback> interruptCb = nullptr;
721     interruptCb = audioManagerListenerCbsMap_[clientID];
722     if (!interruptCb) {
723         AUDIO_INFO_LOG("AudioPolicyServer: Notify failed, callback not present");
724         return ERR_INVALID_PARAM;
725     }
726 
727     InterruptEventInternal interruptEvent = {};
728     interruptEvent.eventType = INTERRUPT_TYPE_BEGIN;
729     interruptEvent.forceType = INTERRUPT_SHARE;
730     interruptEvent.hintType = INTERRUPT_HINT_STOP;
731     interruptEvent.duckVolume = 0;
732     AUDIO_DEBUG_LOG("AudioPolicyServer: callback focus abandoned");
733     interruptCb->OnInterrupt(interruptEvent);
734 
735     return SUCCESS;
736 }
737 
PrintOwnersLists()738 void AudioPolicyServer::PrintOwnersLists()
739 {
740     AUDIO_DEBUG_LOG("AudioPolicyServer: Printing active list");
741     for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
742         AUDIO_DEBUG_LOG("AudioPolicyServer: curActiveOwnersList_: streamType: %{public}d", it->streamType);
743         AUDIO_DEBUG_LOG("AudioPolicyServer: curActiveOwnersList_: sessionID: %{public}u", it->sessionID);
744     }
745 
746     AUDIO_DEBUG_LOG("AudioPolicyServer: Printing pending list");
747     for (auto it = pendingOwnersList_.begin(); it != pendingOwnersList_.end(); ++it) {
748         AUDIO_DEBUG_LOG("AudioPolicyServer: pendingOwnersList_: streamType: %{public}d", it->streamType);
749         AUDIO_DEBUG_LOG("AudioPolicyServer: pendingOwnersList_: sessionID: %{public}u", it->sessionID);
750     }
751 }
752 
ProcessPendingInterrupt(std::list<AudioInterrupt>::iterator & iterPending,const AudioInterrupt & incoming)753 bool AudioPolicyServer::ProcessPendingInterrupt(std::list<AudioInterrupt>::iterator &iterPending,
754                                                 const AudioInterrupt &incoming)
755 {
756     bool iterPendingErased = false;
757     AudioStreamType pendingStreamType = iterPending->streamType;
758     AudioStreamType incomingStreamType = incoming.streamType;
759 
760     auto focusMap = mPolicyService.GetAudioFocusMap();
761     std::pair<AudioStreamType, AudioStreamType> streamTypePair = std::make_pair(pendingStreamType, incomingStreamType);
762 
763     if (focusMap.find(streamTypePair) == focusMap.end()) {
764         AUDIO_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
765         return iterPendingErased;
766     }
767 
768     AudioFocusEntry focusEntry = focusMap[streamTypePair];
769     float duckVol = 0.2f;
770     InterruptEventInternal interruptEvent {INTERRUPT_TYPE_BEGIN, focusEntry.forceType, focusEntry.hintType, duckVol};
771 
772     uint32_t pendingSessionID = iterPending->sessionID;
773     std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
774 
775     if (focusEntry.actionOn == CURRENT && focusEntry.forceType == INTERRUPT_FORCE) {
776         policyListenerCb = policyListenerCbsMap_[pendingSessionID];
777 
778         if (focusEntry.hintType == INTERRUPT_HINT_STOP) {
779             iterPending = pendingOwnersList_.erase(iterPending);
780             iterPendingErased = true;
781         }
782 
783         if (policyListenerCb == nullptr) {
784             AUDIO_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
785             return iterPendingErased;
786         }
787         policyListenerCb->OnInterrupt(interruptEvent);
788     }
789 
790     return iterPendingErased;
791 }
792 
ProcessCurActiveInterrupt(std::list<AudioInterrupt>::iterator & iterActive,const AudioInterrupt & incoming)793 bool AudioPolicyServer::ProcessCurActiveInterrupt(std::list<AudioInterrupt>::iterator &iterActive,
794                                                   const AudioInterrupt &incoming)
795 {
796     bool iterActiveErased = false;
797     AudioStreamType activeStreamType = iterActive->streamType;
798     AudioStreamType incomingStreamType = incoming.streamType;
799 
800     auto focusMap = mPolicyService.GetAudioFocusMap();
801     std::pair<AudioStreamType, AudioStreamType> streamTypePair = std::make_pair(activeStreamType, incomingStreamType);
802 
803     if (focusMap.find(streamTypePair) == focusMap.end()) {
804         AUDIO_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
805         return iterActiveErased;
806     }
807 
808     AudioFocusEntry focusEntry = focusMap[streamTypePair];
809     InterruptEventInternal interruptEvent {INTERRUPT_TYPE_BEGIN, focusEntry.forceType, focusEntry.hintType, 0.2f};
810 
811     uint32_t activeSessionID = iterActive->sessionID;
812     uint32_t incomingSessionID = incoming.sessionID;
813     std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
814     if (focusEntry.actionOn == CURRENT) {
815         policyListenerCb = policyListenerCbsMap_[activeSessionID];
816     } else {
817         policyListenerCb = policyListenerCbsMap_[incomingSessionID];
818     }
819 
820     // focusEntry.forceType == INTERRUPT_SHARE
821     if (focusEntry.forceType != INTERRUPT_FORCE) {
822         if (policyListenerCb == nullptr) {
823             AUDIO_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
824             return iterActiveErased;
825         }
826         policyListenerCb->OnInterrupt(interruptEvent);
827         return iterActiveErased;
828     }
829 
830     // focusEntry.forceType == INTERRUPT_FORCE
831     AUDIO_INFO_LOG("AudioPolicyServer: Action is taken on: %{public}d", focusEntry.actionOn);
832     float volume = 0.0f;
833     if (focusEntry.actionOn == CURRENT) {
834         switch (focusEntry.hintType) {
835             case INTERRUPT_HINT_STOP:
836                 iterActive = curActiveOwnersList_.erase(iterActive);
837                 iterActiveErased = true;
838                 break;
839             case INTERRUPT_HINT_PAUSE:
840                 pendingOwnersList_.emplace_front(*iterActive);
841                 iterActive = curActiveOwnersList_.erase(iterActive);
842                 iterActiveErased = true;
843                 break;
844             case INTERRUPT_HINT_DUCK:
845                 volume = GetStreamVolume(incomingStreamType);
846                 interruptEvent.duckVolume = DUCK_FACTOR * volume;
847                 break;
848             default:
849                 break;
850         }
851     } else { // INCOMING
852         if (focusEntry.hintType == INTERRUPT_HINT_DUCK) {
853             AUDIO_INFO_LOG("AudioPolicyServer: force duck get GetStreamVolume(activeStreamType)");
854             volume = GetStreamVolume(activeStreamType);
855             interruptEvent.duckVolume = DUCK_FACTOR * volume;
856         }
857     }
858 
859     if (policyListenerCb == nullptr) {
860         AUDIO_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
861         return iterActiveErased;
862     }
863     policyListenerCb->OnInterrupt(interruptEvent);
864 
865     return iterActiveErased;
866 }
867 
ProcessFocusEntry(const AudioInterrupt & incomingInterrupt)868 int32_t AudioPolicyServer::ProcessFocusEntry(const AudioInterrupt &incomingInterrupt)
869 {
870     // Function: First Process pendingList and remove session that loses focus indefinitely
871     for (auto iterPending = pendingOwnersList_.begin(); iterPending != pendingOwnersList_.end();) {
872         bool IsIterPendingErased = ProcessPendingInterrupt(iterPending, incomingInterrupt);
873         if (!IsIterPendingErased) {
874             AUDIO_INFO_LOG("AudioPolicyServer: iterPending not erased while processing ++increment it");
875             ++iterPending;
876         }
877     }
878 
879     auto focusMap = mPolicyService.GetAudioFocusMap();
880     // Function: Process Focus entry
881     for (auto iterActive = curActiveOwnersList_.begin(); iterActive != curActiveOwnersList_.end();) {
882         AudioStreamType activeStreamType = iterActive->streamType;
883         AudioStreamType incomingStreamType = incomingInterrupt.streamType;
884         std::pair<AudioStreamType, AudioStreamType> streamTypePair =
885             std::make_pair(activeStreamType, incomingStreamType);
886 
887         if (focusMap.find(streamTypePair) == focusMap.end()) {
888             AUDIO_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
889             return ERR_INVALID_PARAM;
890         }
891 
892         AudioFocusEntry focusEntry = focusMap[streamTypePair];
893         if (focusEntry.isReject) {
894             AUDIO_INFO_LOG("AudioPolicyServer: focusEntry.isReject : ActivateAudioInterrupt request rejected");
895             return ERR_FOCUS_DENIED;
896         }
897         bool IsIterActiveErased = ProcessCurActiveInterrupt(iterActive, incomingInterrupt);
898         if (!IsIterActiveErased) {
899             AUDIO_INFO_LOG("AudioPolicyServer: iterActive not erased while processing ++increment it");
900             ++iterActive;
901         }
902     }
903 
904     return SUCCESS;
905 }
906 
AddToCurActiveList(const AudioInterrupt & audioInterrupt)907 void AudioPolicyServer::AddToCurActiveList(const AudioInterrupt &audioInterrupt)
908 {
909     if (curActiveOwnersList_.empty()) {
910         curActiveOwnersList_.emplace_front(audioInterrupt);
911         return;
912     }
913 
914     auto itCurActive = curActiveOwnersList_.begin();
915 
916     for (; itCurActive != curActiveOwnersList_.end(); ++itCurActive) {
917         AudioStreamType existingPriorityStreamType = itCurActive->streamType;
918         if (interruptPriorityMap_[existingPriorityStreamType] > interruptPriorityMap_[audioInterrupt.streamType]) {
919             continue;
920         } else {
921             curActiveOwnersList_.emplace(itCurActive, audioInterrupt);
922             return;
923         }
924     }
925 
926     if (itCurActive == curActiveOwnersList_.end()) {
927         curActiveOwnersList_.emplace_back(audioInterrupt);
928     }
929 }
930 
ActivateAudioInterrupt(const AudioInterrupt & audioInterrupt)931 int32_t AudioPolicyServer::ActivateAudioInterrupt(const AudioInterrupt &audioInterrupt)
932 {
933     std::lock_guard<std::mutex> lock(interruptMutex_);
934 
935     AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt");
936     AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.streamType: %{public}d", audioInterrupt.streamType);
937     AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.sessionID: %{public}u", audioInterrupt.sessionID);
938 
939     if (!mPolicyService.IsAudioInterruptEnabled()) {
940         AUDIO_DEBUG_LOG("AudioPolicyServer: interrupt is not enabled. No need to ActivateAudioInterrupt");
941         AddToCurActiveList(audioInterrupt);
942         return SUCCESS;
943     }
944 
945     AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt start: print active and pending lists");
946     PrintOwnersLists();
947 
948     // Check if the session is present in pending list, remove and treat it as a new request
949     uint32_t incomingSessionID = audioInterrupt.sessionID;
950     if (!pendingOwnersList_.empty()) {
951         AUDIO_DEBUG_LOG("If it is present in pending list, remove and treat is as new request");
952         pendingOwnersList_.remove_if([&incomingSessionID](AudioInterrupt &interrupt) {
953             return interrupt.sessionID == incomingSessionID;
954         });
955     }
956 
957     // If active owners list is empty, directly activate interrupt
958     if (curActiveOwnersList_.empty()) {
959         curActiveOwnersList_.emplace_front(audioInterrupt);
960         AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
961         PrintOwnersLists();
962         return SUCCESS;
963     }
964 
965     // If the session is already in active list, return
966     for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
967         if (it->sessionID == audioInterrupt.sessionID) {
968             AUDIO_DEBUG_LOG("AudioPolicyServer: sessionID %{public}d is already active", audioInterrupt.sessionID);
969             AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
970             PrintOwnersLists();
971             return SUCCESS;
972         }
973     }
974 
975     // Process ProcessFocusEntryTable for current active and pending lists
976     int32_t ret = ProcessFocusEntry(audioInterrupt);
977     if (ret) {
978         AUDIO_ERR_LOG("AudioPolicyServer:  ActivateAudioInterrupt request rejected");
979         AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
980         PrintOwnersLists();
981         return ERR_FOCUS_DENIED;
982     }
983 
984     // Activate request processed and accepted. Add the entry to active list
985     AddToCurActiveList(audioInterrupt);
986 
987     AUDIO_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
988     PrintOwnersLists();
989     return SUCCESS;
990 }
991 
UnduckCurActiveList(const AudioInterrupt & exitInterrupt)992 void AudioPolicyServer::UnduckCurActiveList(const AudioInterrupt &exitInterrupt)
993 {
994     std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
995     AudioStreamType exitStreamType = exitInterrupt.streamType;
996     InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
997 
998     for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
999         AudioStreamType activeStreamType = it->streamType;
1000         uint32_t activeSessionID = it->sessionID;
1001         if (interruptPriorityMap_[activeStreamType] > interruptPriorityMap_[exitStreamType]) {
1002                 continue;
1003         }
1004         policyListenerCb = policyListenerCbsMap_[activeSessionID];
1005         if (policyListenerCb == nullptr) {
1006             AUDIO_WARNING_LOG("AudioPolicyServer: Cb sessionID: %{public}d null. ignoring to Unduck", activeSessionID);
1007             return;
1008         }
1009         policyListenerCb->OnInterrupt(forcedUnducking);
1010     }
1011 }
1012 
ResumeUnduckPendingList(const AudioInterrupt & exitInterrupt)1013 void AudioPolicyServer::ResumeUnduckPendingList(const AudioInterrupt &exitInterrupt)
1014 {
1015     std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
1016     AudioStreamType exitStreamType = exitInterrupt.streamType;
1017     InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
1018     InterruptEventInternal resumeForcePaused {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_RESUME, 0.2f};
1019 
1020     for (auto it = pendingOwnersList_.begin(); it != pendingOwnersList_.end();) {
1021         AudioStreamType pendingStreamType = it->streamType;
1022         uint32_t pendingSessionID = it->sessionID;
1023         if (interruptPriorityMap_[pendingStreamType] > interruptPriorityMap_[exitStreamType]) {
1024             ++it;
1025             continue;
1026         }
1027         it = pendingOwnersList_.erase(it);
1028         policyListenerCb = policyListenerCbsMap_[pendingSessionID];
1029         if (policyListenerCb == nullptr) {
1030             AUDIO_WARNING_LOG("AudioPolicyServer: Cb sessionID: %{public}d null. ignoring resume", pendingSessionID);
1031             return;
1032         }
1033         policyListenerCb->OnInterrupt(forcedUnducking);
1034         policyListenerCb->OnInterrupt(resumeForcePaused);
1035     }
1036 }
1037 
DeactivateAudioInterrupt(const AudioInterrupt & audioInterrupt)1038 int32_t AudioPolicyServer::DeactivateAudioInterrupt(const AudioInterrupt &audioInterrupt)
1039 {
1040     std::lock_guard<std::mutex> lock(interruptMutex_);
1041 
1042     if (!mPolicyService.IsAudioInterruptEnabled()) {
1043         AUDIO_DEBUG_LOG("AudioPolicyServer: interrupt is not enabled. No need to DeactivateAudioInterrupt");
1044         uint32_t exitSessionID = audioInterrupt.sessionID;
1045         curActiveOwnersList_.remove_if([&exitSessionID](AudioInterrupt &interrupt) {
1046             return interrupt.sessionID == exitSessionID;
1047         });
1048         return SUCCESS;
1049     }
1050 
1051     AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt");
1052     AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.streamType: %{public}d", audioInterrupt.streamType);
1053     AUDIO_DEBUG_LOG("AudioPolicyServer: audioInterrupt.sessionID: %{public}u", audioInterrupt.sessionID);
1054 
1055     AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
1056     PrintOwnersLists();
1057 
1058     // Check and remove, its entry from pending first
1059     uint32_t exitSessionID = audioInterrupt.sessionID;
1060     pendingOwnersList_.remove_if([&exitSessionID](AudioInterrupt &interrupt) {
1061         return interrupt.sessionID == exitSessionID;
1062     });
1063 
1064     bool isInterruptActive = false;
1065     InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
1066     std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
1067     for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end();) {
1068         if (it->sessionID == audioInterrupt.sessionID) {
1069             policyListenerCb = policyListenerCbsMap_[it->sessionID];
1070             if (policyListenerCb != nullptr) {
1071                 policyListenerCb->OnInterrupt(forcedUnducking); // Unducks self, if ducked before
1072             }
1073             it = curActiveOwnersList_.erase(it);
1074             isInterruptActive = true;
1075         } else {
1076             ++it;
1077         }
1078     }
1079 
1080     // If it was not present in both the lists or present only in pending list,
1081     // No need to take any action on other sessions, just return.
1082     if (!isInterruptActive) {
1083         AUDIO_DEBUG_LOG("AudioPolicyServer: Session : %{public}d is not currently active. return success",
1084                         audioInterrupt.sessionID);
1085         AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
1086         PrintOwnersLists();
1087         return SUCCESS;
1088     }
1089 
1090     if (curActiveOwnersList_.empty() && pendingOwnersList_.empty()) {
1091         AUDIO_DEBUG_LOG("AudioPolicyServer: No other session active or pending. Deactivate complete, return success");
1092         AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
1093         PrintOwnersLists();
1094         return SUCCESS;
1095     }
1096 
1097     // unduck if the session was forced ducked
1098     UnduckCurActiveList(audioInterrupt);
1099 
1100     // resume and unduck if the session was forced paused
1101     ResumeUnduckPendingList(audioInterrupt);
1102 
1103     AUDIO_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt end: print active and pending lists");
1104     PrintOwnersLists();
1105     return SUCCESS;
1106 }
1107 
OnSessionRemoved(const uint32_t sessionID)1108 void AudioPolicyServer::OnSessionRemoved(const uint32_t sessionID)
1109 {
1110     uint32_t removedSessionID = sessionID;
1111 
1112     auto isSessionPresent = [&removedSessionID] (const AudioInterrupt &interrupt) {
1113         return interrupt.sessionID == removedSessionID;
1114     };
1115 
1116     AUDIO_DEBUG_LOG("AudioPolicyServer::OnSessionRemoved");
1117     std::unique_lock<std::mutex> lock(interruptMutex_);
1118 
1119     auto iterActive = std::find_if(curActiveOwnersList_.begin(), curActiveOwnersList_.end(), isSessionPresent);
1120     if (iterActive != curActiveOwnersList_.end()) {
1121         AudioInterrupt removedInterrupt = *iterActive;
1122         lock.unlock();
1123         AUDIO_DEBUG_LOG("Removed SessionID: %{public}u is present in active list", removedSessionID);
1124 
1125         (void)DeactivateAudioInterrupt(removedInterrupt);
1126         (void)UnsetAudioInterruptCallback(removedSessionID);
1127         return;
1128     }
1129     AUDIO_DEBUG_LOG("Removed SessionID: %{public}u is not present in active list", removedSessionID);
1130 
1131     auto iterPending = std::find_if(pendingOwnersList_.begin(), pendingOwnersList_.end(), isSessionPresent);
1132     if (iterPending != pendingOwnersList_.end()) {
1133         AudioInterrupt removedInterrupt = *iterPending;
1134         lock.unlock();
1135         AUDIO_DEBUG_LOG("Removed SessionID: %{public}u is present in pending list", removedSessionID);
1136 
1137         (void)DeactivateAudioInterrupt(removedInterrupt);
1138         (void)UnsetAudioInterruptCallback(removedSessionID);
1139         return;
1140     }
1141     AUDIO_DEBUG_LOG("Removed SessionID: %{public}u not present in pending list either", removedSessionID);
1142 
1143     // Though it is not present in the owners list, check and clear its entry from callback map
1144     lock.unlock();
1145     (void)UnsetAudioInterruptCallback(removedSessionID);
1146 }
1147 
GetStreamInFocus()1148 AudioStreamType AudioPolicyServer::GetStreamInFocus()
1149 {
1150     AudioStreamType streamInFocus = STREAM_DEFAULT;
1151     if (GetAudioScene() == AUDIO_SCENE_PHONE_CALL) {
1152         // When a call stream is playing, the stream type in focus is still ring.
1153         // So we set streamInFocus to call manually.
1154         streamInFocus = STREAM_VOICE_CALL;
1155     } else if (!curActiveOwnersList_.empty()) {
1156         streamInFocus = curActiveOwnersList_.front().streamType;
1157     }
1158 
1159     return streamInFocus;
1160 }
1161 
GetSessionInfoInFocus(AudioInterrupt & audioInterrupt)1162 int32_t AudioPolicyServer::GetSessionInfoInFocus(AudioInterrupt &audioInterrupt)
1163 {
1164     uint32_t invalidSessionID = static_cast<uint32_t>(-1);
1165     audioInterrupt = {STREAM_USAGE_UNKNOWN, CONTENT_TYPE_UNKNOWN, STREAM_DEFAULT, invalidSessionID};
1166 
1167     if (!curActiveOwnersList_.empty()) {
1168         audioInterrupt = curActiveOwnersList_.front();
1169     }
1170 
1171     return SUCCESS;
1172 }
1173 
SetVolumeKeyEventCallback(const int32_t clientPid,const sptr<IRemoteObject> & object)1174 int32_t AudioPolicyServer::SetVolumeKeyEventCallback(const int32_t clientPid, const sptr<IRemoteObject> &object)
1175 {
1176     std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
1177     AUDIO_DEBUG_LOG("AudioPolicyServer::SetVolumeKeyEventCallback");
1178     CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
1179                              "AudioPolicyServer::SetVolumeKeyEventCallback listener object is nullptr");
1180 
1181     sptr<IAudioVolumeKeyEventCallback> listener = iface_cast<IAudioVolumeKeyEventCallback>(object);
1182     CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM,
1183                              "AudioPolicyServer::SetVolumeKeyEventCallback listener obj cast failed");
1184 
1185     std::shared_ptr<VolumeKeyEventCallback> callback = std::make_shared<VolumeKeyEventCallbackListner>(listener);
1186     CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM,
1187                              "AudioPolicyServer::SetVolumeKeyEventCallback failed to create cb obj");
1188 
1189     volumeChangeCbsMap_[clientPid] = callback;
1190     return SUCCESS;
1191 }
1192 
UnsetVolumeKeyEventCallback(const int32_t clientPid)1193 int32_t AudioPolicyServer::UnsetVolumeKeyEventCallback(const int32_t clientPid)
1194 {
1195     std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
1196 
1197     if (volumeChangeCbsMap_.find(clientPid) != volumeChangeCbsMap_.end()) {
1198         volumeChangeCbsMap_.erase(clientPid);
1199         AUDIO_ERR_LOG("AudioPolicyServer::UnsetVolumeKeyEventCallback for clientPid %{public}d done", clientPid);
1200     } else {
1201         AUDIO_DEBUG_LOG("AudioPolicyServer::UnsetVolumeKeyEventCallback clientPid %{public}d not present/unset already",
1202                         clientPid);
1203     }
1204 
1205     return SUCCESS;
1206 }
1207 
VerifyClientPermission(const std::string & permissionName,uint32_t appTokenId,int32_t appUid,bool privacyFlag,AudioPermissionState state)1208 bool AudioPolicyServer::VerifyClientPermission(const std::string &permissionName, uint32_t appTokenId, int32_t appUid,
1209     bool privacyFlag, AudioPermissionState state)
1210 {
1211     auto callerUid = IPCSkeleton::GetCallingUid();
1212     AUDIO_DEBUG_LOG("[%{public}s] [tid:%{public}d] [uid:%{public}d]", permissionName.c_str(), appTokenId, callerUid);
1213 
1214     // Root users should be whitelisted
1215     if ((callerUid == ROOT_UID) || ((callerUid == MEDIA_SERVICE_UID) && (appUid == ROOT_UID))) {
1216         AUDIO_DEBUG_LOG("Root user. Permission GRANTED!!!");
1217         return true;
1218     }
1219 
1220     Security::AccessToken::AccessTokenID clientTokenId = 0;
1221     // Special handling required for media service
1222     if (callerUid == MEDIA_SERVICE_UID) {
1223         if (appTokenId == 0) {
1224             AUDIO_ERR_LOG("Invalid token received. Permission rejected");
1225             return false;
1226         }
1227         clientTokenId = appTokenId;
1228     } else {
1229         clientTokenId = IPCSkeleton::GetCallingTokenID();
1230     }
1231 
1232     int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(clientTokenId, permissionName);
1233     if (res != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
1234         AUDIO_ERR_LOG("Permission denied [tid:%{public}d]", clientTokenId);
1235         return false;
1236     }
1237     if (privacyFlag) {
1238         if (!PrivacyKit::IsAllowedUsingPermission(clientTokenId, MICROPHONE_PERMISSION)) {
1239             AUDIO_ERR_LOG("app background, not allow using perm for client %{public}d", clientTokenId);
1240         }
1241     }
1242 
1243     return true;
1244 }
1245 
getUsingPemissionFromPrivacy(const std::string & permissionName,uint32_t appTokenId,AudioPermissionState state)1246 bool AudioPolicyServer::getUsingPemissionFromPrivacy(const std::string &permissionName, uint32_t appTokenId,
1247     AudioPermissionState state)
1248 {
1249     auto callerUid = IPCSkeleton::GetCallingUid();
1250     AUDIO_DEBUG_LOG("[%{public}s] [tid:%{public}d] [uid:%{public}d]", permissionName.c_str(), appTokenId, callerUid);
1251 
1252     Security::AccessToken::AccessTokenID clientTokenId = 0;
1253     if (callerUid == MEDIA_SERVICE_UID) {
1254         if (appTokenId == 0) {
1255             AUDIO_ERR_LOG("Invalid token received. Permission rejected");
1256             return false;
1257         }
1258         clientTokenId = appTokenId;
1259     } else {
1260         clientTokenId = IPCSkeleton::GetCallingTokenID();
1261     }
1262 
1263     if (state == AUDIO_PERMISSION_START) {
1264         int res = PrivacyKit::StartUsingPermission(clientTokenId, MICROPHONE_PERMISSION);
1265         if (res != 0) {
1266             AUDIO_ERR_LOG("start using perm error for client %{public}d", clientTokenId);
1267         }
1268     } else {
1269         int res = PrivacyKit::StopUsingPermission(clientTokenId, MICROPHONE_PERMISSION);
1270         if (res != 0) {
1271             AUDIO_ERR_LOG("stop using perm error for client %{public}d", clientTokenId);
1272         }
1273     }
1274 
1275     return true;
1276 }
1277 
ReconfigureAudioChannel(const uint32_t & count,DeviceType deviceType)1278 int32_t AudioPolicyServer::ReconfigureAudioChannel(const uint32_t &count, DeviceType deviceType)
1279 {
1280     // Only root users should have access to this api
1281     if (ROOT_UID != IPCSkeleton::GetCallingUid()) {
1282         AUDIO_INFO_LOG("Unautorized user. Cannot modify channel");
1283         return ERR_PERMISSION_DENIED;
1284     }
1285 
1286     return mPolicyService.ReconfigureAudioChannel(count, deviceType);
1287 }
1288 
MapVolumeToHDI(int32_t volume)1289 float AudioPolicyServer::MapVolumeToHDI(int32_t volume)
1290 {
1291     float value = (float)volume / MAX_VOLUME_LEVEL;
1292     float roundValue = (int)(value * CONST_FACTOR);
1293 
1294     return (float)roundValue / CONST_FACTOR;
1295 }
1296 
ConvertVolumeToInt(float volume)1297 int32_t AudioPolicyServer::ConvertVolumeToInt(float volume)
1298 {
1299     float value = (float)volume * MAX_VOLUME_LEVEL;
1300     return nearbyint(value);
1301 }
1302 
GetPolicyData(PolicyData & policyData)1303 void AudioPolicyServer::GetPolicyData(PolicyData &policyData)
1304 {
1305     policyData.ringerMode = GetRingerMode();
1306     policyData.callStatus = GetAudioScene();
1307 
1308     // Get stream volumes
1309     for (int stream = AudioStreamType::STREAM_VOICE_CALL; stream <= AudioStreamType::STREAM_TTS; stream++) {
1310         AudioStreamType streamType = (AudioStreamType)stream;
1311 
1312         if (AudioServiceDump::IsStreamSupported(streamType)) {
1313             int32_t volume = ConvertVolumeToInt(GetStreamVolume(streamType));
1314             policyData.streamVolumes.insert({ streamType, volume });
1315         }
1316     }
1317 
1318     // Get Audio Focus Information
1319     AudioInterrupt audioInterrupt;
1320     if (GetSessionInfoInFocus(audioInterrupt) == SUCCESS) {
1321         policyData.audioFocusInfo = audioInterrupt;
1322     }
1323 
1324     GetDeviceInfo(policyData);
1325     GetGroupInfo(policyData);
1326 }
1327 
GetDeviceInfo(PolicyData & policyData)1328 void AudioPolicyServer::GetDeviceInfo(PolicyData& policyData)
1329 {
1330     DeviceFlag deviceFlag = DeviceFlag::INPUT_DEVICES_FLAG;
1331     std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors = GetDevices(deviceFlag);
1332 
1333     for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1334         AudioDeviceDescriptor audioDeviceDescriptor = **it;
1335         DevicesInfo deviceInfo;
1336         deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1337         deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1338         deviceInfo.conneceType  = CONNECT_TYPE_LOCAL;
1339         policyData.inputDevices.push_back(deviceInfo);
1340     }
1341 
1342     deviceFlag = DeviceFlag::OUTPUT_DEVICES_FLAG;
1343     audioDeviceDescriptors = GetDevices(deviceFlag);
1344 
1345     for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1346         AudioDeviceDescriptor audioDeviceDescriptor = **it;
1347         DevicesInfo deviceInfo;
1348         deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1349         deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1350         deviceInfo.conneceType  = CONNECT_TYPE_LOCAL;
1351         policyData.outputDevices.push_back(deviceInfo);
1352     }
1353 
1354     deviceFlag = DeviceFlag::DISTRIBUTED_INPUT_DEVICES_FLAG;
1355     audioDeviceDescriptors = GetDevices(deviceFlag);
1356 
1357     for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1358         AudioDeviceDescriptor audioDeviceDescriptor = **it;
1359         DevicesInfo deviceInfo;
1360         deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1361         deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1362         deviceInfo.conneceType  = CONNECT_TYPE_DISTRIBUTED;
1363         policyData.inputDevices.push_back(deviceInfo);
1364     }
1365 
1366     deviceFlag = DeviceFlag::DISTRIBUTED_OUTPUT_DEVICES_FLAG;
1367     audioDeviceDescriptors = GetDevices(deviceFlag);
1368 
1369     for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1370         AudioDeviceDescriptor audioDeviceDescriptor = **it;
1371         DevicesInfo deviceInfo;
1372         deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1373         deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1374         deviceInfo.conneceType  = CONNECT_TYPE_DISTRIBUTED;
1375         policyData.outputDevices.push_back(deviceInfo);
1376     }
1377 }
1378 
GetGroupInfo(PolicyData & policyData)1379 void AudioPolicyServer::GetGroupInfo(PolicyData& policyData)
1380 {
1381    // Get group info
1382     std::vector<sptr<VolumeGroupInfo>> groupInfos = GetVolumeGroupInfos();
1383     for (auto volumeGroupInfo : groupInfos) {
1384         GroupInfo info;
1385         info.groupId = volumeGroupInfo->volumeGroupId_;
1386         info.groupName = volumeGroupInfo->groupName_;
1387         info.type = volumeGroupInfo->connectType_;
1388         policyData.groupInfos.push_back(info);
1389     }
1390 }
1391 
Dump(int32_t fd,const std::vector<std::u16string> & args)1392 int32_t AudioPolicyServer::Dump(int32_t fd, const std::vector<std::u16string> &args)
1393 {
1394     AUDIO_DEBUG_LOG("AudioPolicyServer: Dump Process Invoked");
1395     std::unordered_set<std::u16string> argSets;
1396     std::u16string arg1(u"debug_interrupt_resume");
1397     std::u16string arg2(u"debug_interrupt_pause");
1398     for (decltype(args.size()) index = 0; index < args.size(); ++index) {
1399         argSets.insert(args[index]);
1400     }
1401 
1402     if (argSets.count(arg1) != 0) {
1403         InterruptType type = INTERRUPT_TYPE_BEGIN;
1404         InterruptForceType forceType = INTERRUPT_SHARE;
1405         InterruptHint hint = INTERRUPT_HINT_RESUME;
1406         InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
1407         for (auto it : policyListenerCbsMap_) {
1408             if (it.second != nullptr) {
1409                 it.second->OnInterrupt(interruptEvent);
1410             }
1411         }
1412     }
1413     if (argSets.count(arg2) != 0) {
1414         InterruptType type = INTERRUPT_TYPE_BEGIN;
1415         InterruptForceType forceType = INTERRUPT_SHARE;
1416         InterruptHint hint = INTERRUPT_HINT_PAUSE;
1417         InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
1418         for (auto it : policyListenerCbsMap_) {
1419             if (it.second != nullptr) {
1420                 it.second->OnInterrupt(interruptEvent);
1421             }
1422         }
1423     }
1424     std::string dumpString;
1425     PolicyData policyData;
1426     AudioServiceDump dumpObj;
1427 
1428     if (dumpObj.Initialize() != AUDIO_DUMP_SUCCESS) {
1429         AUDIO_ERR_LOG("AudioPolicyServer:: Audio Service Dump Not initialised\n");
1430         return AUDIO_DUMP_INIT_ERR;
1431     }
1432 
1433     GetPolicyData(policyData);
1434     dumpObj.AudioDataDump(policyData, dumpString);
1435 
1436     return write(fd, dumpString.c_str(), dumpString.size());
1437 }
1438 
GetAudioLatencyFromXml()1439 int32_t AudioPolicyServer::GetAudioLatencyFromXml()
1440 {
1441     return mPolicyService.GetAudioLatencyFromXml();
1442 }
1443 
GetSinkLatencyFromXml()1444 uint32_t AudioPolicyServer::GetSinkLatencyFromXml()
1445 {
1446     return mPolicyService.GetSinkLatencyFromXml();
1447 }
1448 
RegisterAudioRendererEventListener(int32_t clientUID,const sptr<IRemoteObject> & object)1449 int32_t AudioPolicyServer::RegisterAudioRendererEventListener(int32_t clientUID, const sptr<IRemoteObject> &object)
1450 {
1451     RegisterClientDeathRecipient(object, LISTENER_CLIENT);
1452     uint32_t clientTokenId = IPCSkeleton::GetCallingTokenID();
1453     bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION, clientTokenId);
1454     return mPolicyService.RegisterAudioRendererEventListener(clientUID, object, hasBTPermission);
1455 }
1456 
UnregisterAudioRendererEventListener(int32_t clientUID)1457 int32_t AudioPolicyServer::UnregisterAudioRendererEventListener(int32_t clientUID)
1458 {
1459     return mPolicyService.UnregisterAudioRendererEventListener(clientUID);
1460 }
1461 
RegisterAudioCapturerEventListener(int32_t clientUID,const sptr<IRemoteObject> & object)1462 int32_t AudioPolicyServer::RegisterAudioCapturerEventListener(int32_t clientUID, const sptr<IRemoteObject> &object)
1463 {
1464     RegisterClientDeathRecipient(object, LISTENER_CLIENT);
1465     uint32_t clientTokenId = IPCSkeleton::GetCallingTokenID();
1466     bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION, clientTokenId);
1467     return mPolicyService.RegisterAudioCapturerEventListener(clientUID, object, hasBTPermission);
1468 }
1469 
UnregisterAudioCapturerEventListener(int32_t clientUID)1470 int32_t AudioPolicyServer::UnregisterAudioCapturerEventListener(int32_t clientUID)
1471 {
1472     return mPolicyService.UnregisterAudioCapturerEventListener(clientUID);
1473 }
1474 
RegisterTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo,const sptr<IRemoteObject> & object)1475 int32_t AudioPolicyServer::RegisterTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo,
1476     const sptr<IRemoteObject> &object)
1477 {
1478     // update the clientUID
1479     auto callerUid =  IPCSkeleton::GetCallingUid();
1480     AUDIO_INFO_LOG("  AudioPolicyServer::RegisterTracker : [caller uid:%{public}d]==", callerUid);
1481     if (callerUid != MEDIA_SERVICE_UID) {
1482         if (mode == AUDIO_MODE_PLAYBACK) {
1483             streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
1484             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1485                 streamChangeInfo.audioRendererChangeInfo.clientUID);
1486         } else {
1487             streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
1488             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1489                 streamChangeInfo.audioCapturerChangeInfo.clientUID);
1490         }
1491     }
1492     RegisterClientDeathRecipient(object, TRACKER_CLIENT);
1493     return mPolicyService.RegisterTracker(mode, streamChangeInfo, object);
1494 }
1495 
UpdateTracker(AudioMode & mode,AudioStreamChangeInfo & streamChangeInfo)1496 int32_t AudioPolicyServer::UpdateTracker(AudioMode &mode, AudioStreamChangeInfo &streamChangeInfo)
1497 {
1498     // update the clientUID
1499     auto callerUid =  IPCSkeleton::GetCallingUid();
1500     AUDIO_INFO_LOG("  AudioPolicyServer::UpdateTracker : [caller uid:%{public}d]==", callerUid);
1501     if (callerUid != MEDIA_SERVICE_UID) {
1502         if (mode == AUDIO_MODE_PLAYBACK) {
1503             streamChangeInfo.audioRendererChangeInfo.clientUID = callerUid;
1504             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1505                 streamChangeInfo.audioRendererChangeInfo.clientUID);
1506         } else {
1507             streamChangeInfo.audioCapturerChangeInfo.clientUID = callerUid;
1508             AUDIO_DEBUG_LOG("Non media service caller, use the uid retrieved. ClientUID:%{public}d]",
1509                 streamChangeInfo.audioCapturerChangeInfo.clientUID);
1510         }
1511     }
1512     return mPolicyService.UpdateTracker(mode, streamChangeInfo);
1513 }
1514 
GetCurrentRendererChangeInfos(vector<unique_ptr<AudioRendererChangeInfo>> & audioRendererChangeInfos)1515 int32_t AudioPolicyServer::GetCurrentRendererChangeInfos(
1516     vector<unique_ptr<AudioRendererChangeInfo>> &audioRendererChangeInfos)
1517 {
1518     bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION);
1519     AUDIO_DEBUG_LOG("GetCurrentRendererChangeInfos: BT use permission: %{public}d", hasBTPermission);
1520     return mPolicyService.GetCurrentRendererChangeInfos(audioRendererChangeInfos, hasBTPermission);
1521 }
1522 
GetCurrentCapturerChangeInfos(vector<unique_ptr<AudioCapturerChangeInfo>> & audioCapturerChangeInfos)1523 int32_t AudioPolicyServer::GetCurrentCapturerChangeInfos(
1524     vector<unique_ptr<AudioCapturerChangeInfo>> &audioCapturerChangeInfos)
1525 {
1526     bool hasBTPermission = VerifyClientPermission(USE_BLUETOOTH_PERMISSION);
1527     AUDIO_DEBUG_LOG("GetCurrentCapturerChangeInfos: BT use permission: %{public}d", hasBTPermission);
1528     return mPolicyService.GetCurrentCapturerChangeInfos(audioCapturerChangeInfos, hasBTPermission);
1529 }
1530 
RegisterClientDeathRecipient(const sptr<IRemoteObject> & object,DeathRecipientId id)1531 void AudioPolicyServer::RegisterClientDeathRecipient(const sptr<IRemoteObject> &object, DeathRecipientId id)
1532 {
1533     AUDIO_INFO_LOG("Register clients death recipient!!");
1534     CHECK_AND_RETURN_LOG(object != nullptr, "Client proxy obj NULL!!");
1535 
1536     pid_t uid = 0;
1537     if (id == TRACKER_CLIENT) {
1538         // Deliberately casting UID to pid_t
1539         uid = static_cast<pid_t>(IPCSkeleton::GetCallingUid());
1540     } else {
1541         uid = IPCSkeleton::GetCallingPid();
1542     }
1543     if (id == TRACKER_CLIENT && std::find(clientDiedListenerState_.begin(), clientDiedListenerState_.end(), uid)
1544         != clientDiedListenerState_.end()) {
1545         AUDIO_INFO_LOG("Tracker has been registered for %{public}d!", uid);
1546         return;
1547     }
1548     sptr<AudioServerDeathRecipient> deathRecipient_ = new(std::nothrow) AudioServerDeathRecipient(uid);
1549     if (deathRecipient_ != nullptr) {
1550         if (id == TRACKER_CLIENT) {
1551             deathRecipient_->SetNotifyCb(std::bind(&AudioPolicyServer::RegisteredTrackerClientDied,
1552                 this, std::placeholders::_1));
1553         } else {
1554             AUDIO_INFO_LOG("RegisteredStreamListenerClientDied register!!");
1555             deathRecipient_->SetNotifyCb(std::bind(&AudioPolicyServer::RegisteredStreamListenerClientDied,
1556                 this, std::placeholders::_1));
1557         }
1558         bool result = object->AddDeathRecipient(deathRecipient_);
1559         if (result && id == TRACKER_CLIENT) {
1560             clientDiedListenerState_.push_back(uid);
1561         }
1562         if (!result) {
1563             AUDIO_ERR_LOG("failed to add deathRecipient");
1564         }
1565     }
1566 }
1567 
RegisteredTrackerClientDied(pid_t pid)1568 void AudioPolicyServer::RegisteredTrackerClientDied(pid_t pid)
1569 {
1570     AUDIO_INFO_LOG("RegisteredTrackerClient died: remove entry, uid %{public}d", pid);
1571     mPolicyService.RegisteredTrackerClientDied(pid);
1572     auto filter = [&pid](int val) {
1573         return pid == val;
1574     };
1575     clientDiedListenerState_.erase(std::remove_if(clientDiedListenerState_.begin(), clientDiedListenerState_.end(),
1576         filter), clientDiedListenerState_.end());
1577 }
1578 
RegisteredStreamListenerClientDied(pid_t pid)1579 void AudioPolicyServer::RegisteredStreamListenerClientDied(pid_t pid)
1580 {
1581     AUDIO_INFO_LOG("RegisteredStreamListenerClient died: remove entry, uid %{public}d", pid);
1582     mPolicyService.RegisteredStreamListenerClientDied(pid);
1583 }
1584 
UpdateStreamState(const int32_t clientUid,StreamSetState streamSetState,AudioStreamType audioStreamType)1585 int32_t AudioPolicyServer::UpdateStreamState(const int32_t clientUid,
1586     StreamSetState streamSetState, AudioStreamType audioStreamType)
1587 {
1588     AUDIO_INFO_LOG("UpdateStreamState::uid:%{public}d state:%{public}d sType:%{public}d", clientUid,
1589         streamSetState, audioStreamType);
1590 
1591     auto callerUid = IPCSkeleton::GetCallingUid();
1592     if (callerUid == clientUid) {
1593         AUDIO_ERR_LOG("UpdateStreamState clientUid value is error");
1594         return ERROR;
1595     }
1596 
1597     StreamSetState setState = StreamSetState::STREAM_PAUSE;
1598     if (streamSetState == StreamSetState::STREAM_RESUME) {
1599         setState  = StreamSetState::STREAM_RESUME;
1600     } else if (streamSetState != StreamSetState::STREAM_PAUSE) {
1601         AUDIO_ERR_LOG("UpdateStreamState streamSetState value is error");
1602         return ERROR;
1603     }
1604     StreamSetStateEventInternal setStateEvent = {};
1605     setStateEvent.streamSetState = setState;
1606     setStateEvent.audioStreamType = audioStreamType;
1607 
1608     return mPolicyService.UpdateStreamState(clientUid, setStateEvent);
1609 }
1610 
GetVolumeGroupInfos()1611 std::vector<sptr<VolumeGroupInfo>> AudioPolicyServer::GetVolumeGroupInfos()
1612 {
1613     return  mPolicyService.GetVolumeGroupInfos();
1614 }
1615 
RemoteParameterCallback(sptr<AudioPolicyServer> server)1616 AudioPolicyServer::RemoteParameterCallback::RemoteParameterCallback(sptr<AudioPolicyServer> server)
1617 {
1618     server_ = server;
1619 }
1620 
OnAudioParameterChange(const std::string networkId,const AudioParamKey key,const std::string & condition,const std::string & value)1621 void AudioPolicyServer::RemoteParameterCallback::OnAudioParameterChange(const std::string networkId,
1622     const AudioParamKey key, const std::string& condition, const std::string& value)
1623 {
1624     AUDIO_INFO_LOG("AudioPolicyServer::OnAudioParameterChange key:%{public}d, condition:%{public}s, value:%{public}s",
1625         key, condition.c_str(), value.c_str());
1626     if (server_ == nullptr) {
1627         AUDIO_ERR_LOG("server_ is nullptr");
1628         return;
1629     }
1630     switch (key) {
1631         case VOLUME:
1632             VolumeOnChange(networkId, condition);
1633             break;
1634         case INTERRUPT:
1635             InterruptOnChange(networkId, condition);
1636             break;
1637         case RENDER_STATE:
1638             StateOnChange(networkId, condition, value);
1639             break;
1640         default:
1641             AUDIO_DEBUG_LOG("[AudioPolicyServer]: No processing");
1642             break;
1643     }
1644 }
1645 
VolumeOnChange(const std::string networkId,const std::string & condition)1646 void AudioPolicyServer::RemoteParameterCallback::VolumeOnChange(const std::string networkId,
1647     const std::string& condition)
1648 {
1649     VolumeEvent volumeEvent;
1650     volumeEvent.networkId = networkId;
1651     char eventDes[EVENT_DES_SIZE];
1652     if (sscanf_s(condition.c_str(), "%[^;];AUDIO_STREAM_TYPE=%d;VOLUME_LEVEL=%d;IS_UPDATEUI=%d;VOLUME_GROUP_ID=%d;",
1653         eventDes, EVENT_DES_SIZE, &(volumeEvent.volumeType), &(volumeEvent.volume), &(volumeEvent.updateUi),
1654         &(volumeEvent.volumeGroupId)) < PARAMS_VOLUME_NUM) {
1655         AUDIO_ERR_LOG("[AudioPolicyServer]: Failed parse condition");
1656         return;
1657     }
1658 
1659     volumeEvent.updateUi = false;
1660     for (auto it = server_->volumeChangeCbsMap_.begin(); it != server_->volumeChangeCbsMap_.end(); ++it) {
1661         std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
1662         if (volumeChangeCb == nullptr) {
1663             AUDIO_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
1664             continue;
1665         }
1666 
1667         AUDIO_DEBUG_LOG("AudioPolicyServer:: trigger volumeChangeCb clientPid : %{public}d", it->first);
1668         volumeChangeCb->OnVolumeKeyEvent(volumeEvent);
1669     }
1670 }
1671 
InterruptOnChange(const std::string networkId,const std::string & condition)1672 void AudioPolicyServer::RemoteParameterCallback::InterruptOnChange(const std::string networkId,
1673     const std::string& condition)
1674 {
1675     char eventDes[EVENT_DES_SIZE];
1676     InterruptType type = INTERRUPT_TYPE_BEGIN;
1677     InterruptForceType forceType = INTERRUPT_SHARE;
1678     InterruptHint hint = INTERRUPT_HINT_NONE;
1679 
1680     if (sscanf_s(condition.c_str(), "%[^;];EVENT_TYPE=%d;FORCE_TYPE=%d;HINT_TYPE=%d;", eventDes,
1681         EVENT_DES_SIZE, &type, &forceType, &hint) < PARAMS_INTERRUPT_NUM) {
1682         AUDIO_ERR_LOG("[AudioPolicyServer]: Failed parse condition");
1683         return;
1684     }
1685 
1686     InterruptEventInternal interruptEvent {type, forceType, hint, 0.2f};
1687     for (auto it : server_->policyListenerCbsMap_) {
1688         if (it.second != nullptr) {
1689             it.second->OnInterrupt(interruptEvent);
1690         }
1691     }
1692 }
1693 
StateOnChange(const std::string networkId,const std::string & condition,const std::string & value)1694 void AudioPolicyServer::RemoteParameterCallback::StateOnChange(const std::string networkId,
1695     const std::string& condition, const std::string& value)
1696 {
1697     char eventDes[EVENT_DES_SIZE];
1698     char contentDes[RENDER_STATE_CONTENT_DES_SIZE];
1699     if (sscanf_s(condition.c_str(), "%[^;];%s", eventDes, EVENT_DES_SIZE, contentDes,
1700         RENDER_STATE_CONTENT_DES_SIZE) < PARAMS_RENDER_STATE_NUM) {
1701         AUDIO_ERR_LOG("[AudioPolicyServer]: Failed parse condition");
1702         return;
1703     }
1704     if (!strcmp(eventDes, "ERR_EVENT")) {
1705         server_->mPolicyService.NotifyRemoteRenderState(networkId, condition, value);
1706     }
1707 }
1708 
PermStateChangeCallback(Security::AccessToken::PermStateChangeInfo & result)1709 void AudioPolicyServer::PerStateChangeCbCustomizeCallback::PermStateChangeCallback(
1710     Security::AccessToken::PermStateChangeInfo& result)
1711 {
1712     ready_ = true;
1713     Security::AccessToken::HapTokenInfo hapTokenInfo;
1714     int32_t res = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(result.tokenID, hapTokenInfo);
1715     if (res < 0) {
1716         AUDIO_ERR_LOG("Call GetHapTokenInfo fail.");
1717     }
1718     bool bSetMute;
1719     if (result.PermStateChangeType > 0) {
1720         bSetMute = false;
1721     } else {
1722         bSetMute = true;
1723     }
1724 
1725     int32_t appUid = getUidByBundleName(hapTokenInfo.bundleName, hapTokenInfo.userID);
1726     if (appUid < 0) {
1727         AUDIO_ERR_LOG("fail to get uid.");
1728     } else {
1729         server_->mPolicyService.SetSourceOutputStreamMute(appUid, bSetMute);
1730         AUDIO_DEBUG_LOG(" get uid value:%{public}d", appUid);
1731     }
1732 }
1733 
getUidByBundleName(std::string bundle_name,int user_id)1734 int32_t AudioPolicyServer::PerStateChangeCbCustomizeCallback::getUidByBundleName(std::string bundle_name, int user_id)
1735 {
1736     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1737     if (systemAbilityManager == nullptr) {
1738         return ERR_INVALID_PARAM;
1739     }
1740 
1741     sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1742     if (remoteObject == nullptr) {
1743         return ERR_INVALID_PARAM;
1744     }
1745 
1746     sptr<AppExecFwk::IBundleMgr> bundleMgrProxy = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1747     if (bundleMgrProxy == nullptr) {
1748         return ERR_INVALID_PARAM;
1749     }
1750     int32_t iUid = bundleMgrProxy->GetUidByBundleName(bundle_name, user_id);
1751 
1752     return iUid;
1753 }
1754 
RegisterParamCallback()1755 void AudioPolicyServer::RegisterParamCallback()
1756 {
1757     AUDIO_INFO_LOG("AudioPolicyServer::RegisterParamCallback");
1758     remoteParameterCallback_ = std::make_shared<RemoteParameterCallback>(this);
1759     mPolicyService.SetParameterCallback(remoteParameterCallback_);
1760 }
1761 
RegisterBluetoothListener()1762 void AudioPolicyServer::RegisterBluetoothListener()
1763 {
1764     AUDIO_INFO_LOG("AudioPolicyServer::RegisterBluetoothListener");
1765     mPolicyService.RegisterBluetoothListener();
1766 }
1767 
SubscribeAccessibilityConfigObserver()1768 void AudioPolicyServer::SubscribeAccessibilityConfigObserver()
1769 {
1770     AUDIO_INFO_LOG("AudioPolicyServer::SubscribeAccessibilityConfigObserver");
1771     mPolicyService.SubscribeAccessibilityConfigObserver();
1772 }
1773 
IsAudioRendererLowLatencySupported(const AudioStreamInfo & audioStreamInfo)1774 bool AudioPolicyServer::IsAudioRendererLowLatencySupported(const AudioStreamInfo &audioStreamInfo)
1775 {
1776     AUDIO_INFO_LOG("IsAudioRendererLowLatencySupported server call");
1777     return true;
1778 }
1779 } // namespace AudioStandard
1780 } // namespace OHOS
1781