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 <vector>
19
20 #include "audio_errors.h"
21 #include "audio_policy_manager_listener_proxy.h"
22 #include "audio_ringermode_update_listener_proxy.h"
23 #include "audio_server_death_recipient.h"
24 #include "audio_volume_key_event_callback_proxy.h"
25 #include "i_standard_audio_policy_manager_listener.h"
26
27 #include "input_manager.h"
28 #include "key_event.h"
29 #include "key_option.h"
30
31 #include "media_log.h"
32 #include "ipc_skeleton.h"
33 #include "iservice_registry.h"
34 #include "system_ability_definition.h"
35
36 #include "audio_service_dump.h"
37 #include "audio_policy_server.h"
38
39 using namespace std;
40
41 namespace OHOS {
42 namespace AudioStandard {
43 constexpr float DUCK_FACTOR = 0.2f; // 20%
REGISTER_SYSTEM_ABILITY_BY_ID(AudioPolicyServer,AUDIO_POLICY_SERVICE_ID,true)44 REGISTER_SYSTEM_ABILITY_BY_ID(AudioPolicyServer, AUDIO_POLICY_SERVICE_ID, true)
45
46 AudioPolicyServer::AudioPolicyServer(int32_t systemAbilityId, bool runOnCreate)
47 : SystemAbility(systemAbilityId, runOnCreate),
48 mPolicyService(AudioPolicyService::GetAudioPolicyService())
49 {
50 if (mPolicyService.SetAudioSessionCallback(this)) {
51 MEDIA_DEBUG_LOG("AudioPolicyServer: SetAudioSessionCallback failed");
52 }
53
54 interruptPriorityMap_[STREAM_VOICE_CALL] = THIRD_PRIORITY;
55 interruptPriorityMap_[STREAM_RING] = SECOND_PRIORITY;
56 interruptPriorityMap_[STREAM_MUSIC] = FIRST_PRIORITY;
57
58 clientOnFocus_ = 0;
59 focussedAudioInterruptInfo_ = nullptr;
60 }
61
OnDump()62 void AudioPolicyServer::OnDump()
63 {
64 return;
65 }
66
OnStart()67 void AudioPolicyServer::OnStart()
68 {
69 bool res = Publish(this);
70 if (res) {
71 MEDIA_DEBUG_LOG("AudioPolicyService OnStart res=%d", res);
72 }
73 AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
74 AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
75 AddSystemAbilityListener(AUDIO_DISTRIBUTED_SERVICE_ID);
76
77 mPolicyService.Init();
78 RegisterAudioServerDeathRecipient();
79 return;
80 }
81
OnStop()82 void AudioPolicyServer::OnStop()
83 {
84 mPolicyService.Deinit();
85 return;
86 }
87
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)88 void AudioPolicyServer::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
89 {
90 MEDIA_DEBUG_LOG("AudioPolicyServer::OnAddSystemAbility systemAbilityId:%{public}d", systemAbilityId);
91 switch (systemAbilityId) {
92 case MULTIMODAL_INPUT_SERVICE_ID:
93 MEDIA_DEBUG_LOG("AudioPolicyServer::OnAddSystemAbility SubscribeKeyEvents");
94 SubscribeKeyEvents();
95 break;
96 case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID:
97 MEDIA_DEBUG_LOG("AudioPolicyServer::OnAddSystemAbility InitKVStore");
98 InitKVStore();
99 break;
100 case AUDIO_DISTRIBUTED_SERVICE_ID:
101 MEDIA_DEBUG_LOG("AudioPolicyServer::OnAddSystemAbility ConnectServiceAdapter");
102 ConnectServiceAdapter();
103 break;
104 default:
105 MEDIA_DEBUG_LOG("AudioPolicyServer::OnAddSystemAbility unhandled sysabilityId:%{public}d", systemAbilityId);
106 break;
107 }
108 }
109
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)110 void AudioPolicyServer::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
111 {
112 MEDIA_DEBUG_LOG("AudioPolicyServer::OnRemoveSystemAbility systemAbilityId:%{public}d removed", systemAbilityId);
113 }
114
RegisterAudioServerDeathRecipient()115 void AudioPolicyServer::RegisterAudioServerDeathRecipient()
116 {
117 MEDIA_INFO_LOG("Register audio server death recipient");
118 pid_t pid = IPCSkeleton::GetCallingPid();
119 sptr<AudioServerDeathRecipient> deathRecipient_ = new(std::nothrow) AudioServerDeathRecipient(pid);
120 if (deathRecipient_ != nullptr) {
121 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
122 CHECK_AND_RETURN_LOG(samgr != nullptr, "Failed to obtain samgr");
123
124 sptr<IRemoteObject> object = samgr->GetSystemAbility(OHOS::AUDIO_DISTRIBUTED_SERVICE_ID);
125 CHECK_AND_RETURN_LOG(object != nullptr, "Audio service unavailable");
126
127 deathRecipient_->SetNotifyCb(std::bind(&AudioPolicyServer::AudioServerDied, this, std::placeholders::_1));
128 bool result = object->AddDeathRecipient(deathRecipient_);
129 if (!result) {
130 MEDIA_ERR_LOG("failed to add deathRecipient");
131 }
132 }
133 }
134
AudioServerDied(pid_t pid)135 void AudioPolicyServer::AudioServerDied(pid_t pid)
136 {
137 MEDIA_INFO_LOG("Audio server died: restart policy server pid %{public}d", pid);
138 kill(pid, SIGKILL);
139 }
140
SubscribeKeyEvents()141 void AudioPolicyServer::SubscribeKeyEvents()
142 {
143 MMI::InputManager *im = MMI::InputManager::GetInstance();
144 CHECK_AND_RETURN_LOG(im != nullptr, "Failed to obtain INPUT manager");
145
146 std::set<int32_t> preKeys;
147 std::shared_ptr<OHOS::MMI::KeyOption> keyOption_down = std::make_shared<OHOS::MMI::KeyOption>();
148 CHECK_AND_RETURN_LOG(keyOption_down != nullptr, "Invalid key option");
149 keyOption_down->SetPreKeys(preKeys);
150 keyOption_down->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_DOWN);
151 keyOption_down->SetFinalKeyDown(true);
152 keyOption_down->SetFinalKeyDownDuration(VOLUME_KEY_DURATION);
153 im->SubscribeKeyEvent(keyOption_down, [=](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
154 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
155 AudioStreamType streamInFocus = GetStreamInFocus();
156 if (streamInFocus == AudioStreamType::STREAM_DEFAULT) {
157 streamInFocus = AudioStreamType::STREAM_MUSIC;
158 }
159 float currentVolume = GetStreamVolume(streamInFocus);
160 int32_t volumeLevelInInt = ConvertVolumeToInt(currentVolume);
161 if (volumeLevelInInt <= MIN_VOLUME_LEVEL) {
162 for (auto it = volumeChangeCbsMap_.begin(); it != volumeChangeCbsMap_.end(); ++it) {
163 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
164 if (volumeChangeCb == nullptr) {
165 MEDIA_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
166 continue;
167 }
168
169 MEDIA_DEBUG_LOG("AudioPolicyServer:: trigger volumeChangeCb clientPid : %{public}d", it->first);
170 volumeChangeCb->OnVolumeKeyEvent(streamInFocus, MIN_VOLUME_LEVEL, true);
171 }
172 return;
173 }
174 SetStreamVolume(streamInFocus, MapVolumeToHDI(volumeLevelInInt - 1), true);
175 });
176 std::shared_ptr<OHOS::MMI::KeyOption> keyOption_up = std::make_shared<OHOS::MMI::KeyOption>();
177 keyOption_up->SetPreKeys(preKeys);
178 keyOption_up->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_VOLUME_UP);
179 keyOption_up->SetFinalKeyDown(true);
180 keyOption_up->SetFinalKeyDownDuration(0);
181 im->SubscribeKeyEvent(keyOption_up, [=](std::shared_ptr<MMI::KeyEvent> keyEventCallBack) {
182 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
183 AudioStreamType streamInFocus = GetStreamInFocus();
184 if (streamInFocus == AudioStreamType::STREAM_DEFAULT) {
185 streamInFocus = AudioStreamType::STREAM_MUSIC;
186 }
187 float currentVolume = GetStreamVolume(streamInFocus);
188 int32_t volumeLevelInInt = ConvertVolumeToInt(currentVolume);
189 if (volumeLevelInInt >= MAX_VOLUME_LEVEL) {
190 for (auto it = volumeChangeCbsMap_.begin(); it != volumeChangeCbsMap_.end(); ++it) {
191 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
192 if (volumeChangeCb == nullptr) {
193 MEDIA_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
194 continue;
195 }
196
197 MEDIA_DEBUG_LOG("AudioPolicyServer:: trigger volumeChangeCb clientPid : %{public}d", it->first);
198 volumeChangeCb->OnVolumeKeyEvent(streamInFocus, MAX_VOLUME_LEVEL, true);
199 }
200 return;
201 }
202 SetStreamVolume(streamInFocus, MapVolumeToHDI(volumeLevelInInt + 1), true);
203 });
204 }
205
InitKVStore()206 void AudioPolicyServer::InitKVStore()
207 {
208 mPolicyService.InitKVStore();
209 }
210
ConnectServiceAdapter()211 void AudioPolicyServer::ConnectServiceAdapter()
212 {
213 if (!mPolicyService.ConnectServiceAdapter()) {
214 MEDIA_ERR_LOG("AudioPolicyServer::ConnectServiceAdapter Error in connecting to audio service adapter");
215 return;
216 }
217 }
218
SetStreamVolume(AudioStreamType streamType,float volume)219 int32_t AudioPolicyServer::SetStreamVolume(AudioStreamType streamType, float volume)
220 {
221 return SetStreamVolume(streamType, volume, false);
222 }
223
GetStreamVolume(AudioStreamType streamType)224 float AudioPolicyServer::GetStreamVolume(AudioStreamType streamType)
225 {
226 return mPolicyService.GetStreamVolume(streamType);
227 }
228
SetStreamMute(AudioStreamType streamType,bool mute)229 int32_t AudioPolicyServer::SetStreamMute(AudioStreamType streamType, bool mute)
230 {
231 return mPolicyService.SetStreamMute(streamType, mute);
232 }
233
SetStreamVolume(AudioStreamType streamType,float volume,bool isUpdateUi)234 int32_t AudioPolicyServer::SetStreamVolume(AudioStreamType streamType, float volume, bool isUpdateUi)
235 {
236 int ret = mPolicyService.SetStreamVolume(streamType, volume);
237 for (auto it = volumeChangeCbsMap_.begin(); it != volumeChangeCbsMap_.end(); ++it) {
238 std::shared_ptr<VolumeKeyEventCallback> volumeChangeCb = it->second;
239 if (volumeChangeCb == nullptr) {
240 MEDIA_ERR_LOG("volumeChangeCb: nullptr for client : %{public}d", it->first);
241 continue;
242 }
243
244 MEDIA_DEBUG_LOG("AudioPolicyServer::SetStreamVolume trigger volumeChangeCb clientPid : %{public}d", it->first);
245 volumeChangeCb->OnVolumeKeyEvent(streamType, ConvertVolumeToInt(GetStreamVolume(streamType)), isUpdateUi);
246 }
247
248 return ret;
249 }
250
GetStreamMute(AudioStreamType streamType)251 bool AudioPolicyServer::GetStreamMute(AudioStreamType streamType)
252 {
253 return mPolicyService.GetStreamMute(streamType);
254 }
255
GetDevices(DeviceFlag deviceFlag)256 std::vector<sptr<AudioDeviceDescriptor>> AudioPolicyServer::GetDevices(DeviceFlag deviceFlag)
257 {
258 return mPolicyService.GetDevices(deviceFlag);
259 }
260
IsStreamActive(AudioStreamType streamType)261 bool AudioPolicyServer::IsStreamActive(AudioStreamType streamType)
262 {
263 return mPolicyService.IsStreamActive(streamType);
264 }
265
SetDeviceActive(InternalDeviceType deviceType,bool active)266 int32_t AudioPolicyServer::SetDeviceActive(InternalDeviceType deviceType, bool active)
267 {
268 return mPolicyService.SetDeviceActive(deviceType, active);
269 }
270
IsDeviceActive(InternalDeviceType deviceType)271 bool AudioPolicyServer::IsDeviceActive(InternalDeviceType deviceType)
272 {
273 return mPolicyService.IsDeviceActive(deviceType);
274 }
275
SetRingerMode(AudioRingerMode ringMode)276 int32_t AudioPolicyServer::SetRingerMode(AudioRingerMode ringMode)
277 {
278 int32_t ret = mPolicyService.SetRingerMode(ringMode);
279 if (ret == SUCCESS) {
280 for (auto it = ringerModeListenerCbsMap_.begin(); it != ringerModeListenerCbsMap_.end(); ++it) {
281 std::shared_ptr<AudioRingerModeCallback> ringerModeListenerCb = it->second;
282 if (ringerModeListenerCb == nullptr) {
283 MEDIA_ERR_LOG("ringerModeListenerCbsMap_: nullptr for client : %{public}d", it->first);
284 continue;
285 }
286
287 MEDIA_DEBUG_LOG("ringerModeListenerCbsMap_ :client = %{public}d", it->first);
288 ringerModeListenerCb->OnRingerModeUpdated(ringMode);
289 }
290 }
291
292 return ret;
293 }
294
GetRingerMode()295 AudioRingerMode AudioPolicyServer::GetRingerMode()
296 {
297 return mPolicyService.GetRingerMode();
298 }
299
SetAudioScene(AudioScene audioScene)300 int32_t AudioPolicyServer::SetAudioScene(AudioScene audioScene)
301 {
302 return mPolicyService.SetAudioScene(audioScene);
303 }
304
GetAudioScene()305 AudioScene AudioPolicyServer::GetAudioScene()
306 {
307 return mPolicyService.GetAudioScene();
308 }
309
SetRingerModeCallback(const int32_t clientId,const sptr<IRemoteObject> & object)310 int32_t AudioPolicyServer::SetRingerModeCallback(const int32_t clientId, const sptr<IRemoteObject> &object)
311 {
312 std::lock_guard<std::mutex> lock(ringerModeMutex_);
313
314 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
315
316 sptr<IStandardRingerModeUpdateListener> listener = iface_cast<IStandardRingerModeUpdateListener>(object);
317 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
318
319 std::shared_ptr<AudioRingerModeCallback> callback = std::make_shared<AudioRingerModeListenerCallback>(listener);
320 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
321
322 ringerModeListenerCbsMap_.insert({clientId, callback});
323
324 return SUCCESS;
325 }
326
UnsetRingerModeCallback(const int32_t clientId)327 int32_t AudioPolicyServer::UnsetRingerModeCallback(const int32_t clientId)
328 {
329 std::lock_guard<std::mutex> lock(ringerModeMutex_);
330
331 if (ringerModeListenerCbsMap_.find(clientId) != ringerModeListenerCbsMap_.end()) {
332 ringerModeListenerCbsMap_.erase(clientId);
333 MEDIA_ERR_LOG("AudioPolicyServer: UnsetRingerModeCallback for client %{public}d done", clientId);
334 return SUCCESS;
335 } else {
336 MEDIA_ERR_LOG("AudioPolicyServer: Cb does not exit for client %{public}d cannot unregister", clientId);
337 return ERR_INVALID_OPERATION;
338 }
339 }
340
SetDeviceChangeCallback(const int32_t clientId,const sptr<IRemoteObject> & object)341 int32_t AudioPolicyServer::SetDeviceChangeCallback(const int32_t clientId, const sptr<IRemoteObject> &object)
342 {
343 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
344
345 return mPolicyService.SetDeviceChangeCallback(clientId, object);
346 }
347
UnsetDeviceChangeCallback(const int32_t clientId)348 int32_t AudioPolicyServer::UnsetDeviceChangeCallback(const int32_t clientId)
349 {
350 return mPolicyService.UnsetDeviceChangeCallback(clientId);
351 }
352
SetAudioInterruptCallback(const uint32_t sessionID,const sptr<IRemoteObject> & object)353 int32_t AudioPolicyServer::SetAudioInterruptCallback(const uint32_t sessionID, const sptr<IRemoteObject> &object)
354 {
355 std::lock_guard<std::mutex> lock(interruptMutex_);
356
357 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
358
359 sptr<IStandardAudioPolicyManagerListener> listener = iface_cast<IStandardAudioPolicyManagerListener>(object);
360 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
361
362 std::shared_ptr<AudioInterruptCallback> callback = std::make_shared<AudioPolicyManagerListenerCallback>(listener);
363 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
364
365 policyListenerCbsMap_[sessionID] = callback;
366 MEDIA_DEBUG_LOG("AudioPolicyServer: SetAudioInterruptCallback for sessionID %{public}d done", sessionID);
367
368 return SUCCESS;
369 }
370
UnsetAudioInterruptCallback(const uint32_t sessionID)371 int32_t AudioPolicyServer::UnsetAudioInterruptCallback(const uint32_t sessionID)
372 {
373 std::lock_guard<std::mutex> lock(interruptMutex_);
374
375 if (policyListenerCbsMap_.erase(sessionID)) {
376 MEDIA_DEBUG_LOG("AudioPolicyServer:UnsetAudioInterruptCallback for sessionID %{public}d done", sessionID);
377 } else {
378 MEDIA_DEBUG_LOG("AudioPolicyServer:UnsetAudioInterruptCallback sessionID %{public}d not present/unset already",
379 sessionID);
380 }
381
382 return SUCCESS;
383 }
384
SetAudioManagerInterruptCallback(const uint32_t clientID,const sptr<IRemoteObject> & object)385 int32_t AudioPolicyServer::SetAudioManagerInterruptCallback(const uint32_t clientID,
386 const sptr<IRemoteObject> &object)
387 {
388 std::lock_guard<std::mutex> lock(interruptMutex_);
389
390 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer:set listener object is nullptr");
391
392 sptr<IStandardAudioPolicyManagerListener> listener = iface_cast<IStandardAudioPolicyManagerListener>(object);
393 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: listener obj cast failed");
394
395 std::shared_ptr<AudioInterruptCallback> callback = std::make_shared<AudioPolicyManagerListenerCallback>(listener);
396 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM, "AudioPolicyServer: failed to create cb obj");
397
398 audioManagerListenerCbsMap_[clientID] = callback;
399 MEDIA_INFO_LOG("AudioPolicyServer: SetAudioManagerInterruptCallback for client id %{public}d done", clientID);
400
401 return SUCCESS;
402 }
403
UnsetAudioManagerInterruptCallback(const uint32_t clientID)404 int32_t AudioPolicyServer::UnsetAudioManagerInterruptCallback(const uint32_t clientID)
405 {
406 if (audioManagerListenerCbsMap_.erase(clientID)) {
407 MEDIA_INFO_LOG("AudioPolicyServer:UnsetAudioManagerInterruptCallback for client %{public}d done", clientID);
408 } else {
409 MEDIA_DEBUG_LOG("AudioPolicyServer:UnsetAudioManagerInterruptCallback client %{public}d not present",
410 clientID);
411 }
412
413 return SUCCESS;
414 }
415
RequestAudioFocus(const uint32_t clientID,const AudioInterrupt & audioInterrupt)416 int32_t AudioPolicyServer::RequestAudioFocus(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
417 {
418 MEDIA_DEBUG_LOG("AudioPolicyServer: RequestAudioFocus in");
419 if (clientOnFocus_ == clientID) {
420 MEDIA_DEBUG_LOG("AudioPolicyServer: client already has focus..");
421 NotifyFocusGranted(clientID, audioInterrupt);
422 return SUCCESS;
423 }
424
425 if (focussedAudioInterruptInfo_ != nullptr) {
426 MEDIA_DEBUG_LOG("AudioPolicyServer: Existing stream: %{public}d, incoming stream: %{public}d",
427 focussedAudioInterruptInfo_->streamType, audioInterrupt.streamType);
428 NotifyFocusAbandoned(clientOnFocus_, *focussedAudioInterruptInfo_);
429 AbandonAudioFocus(clientOnFocus_, *focussedAudioInterruptInfo_);
430 }
431
432 MEDIA_DEBUG_LOG("AudioPolicyServer: Grant audio focus");
433 NotifyFocusGranted(clientID, audioInterrupt);
434
435 return SUCCESS;
436 }
437
AbandonAudioFocus(const uint32_t clientID,const AudioInterrupt & audioInterrupt)438 int32_t AudioPolicyServer::AbandonAudioFocus(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
439 {
440 MEDIA_INFO_LOG("AudioPolicyServer: AbandonAudioFocus in");
441
442 if (clientID == clientOnFocus_) {
443 MEDIA_DEBUG_LOG("AudioPolicyServer: remove app focus");
444 focussedAudioInterruptInfo_.reset();
445 focussedAudioInterruptInfo_ = nullptr;
446 clientOnFocus_ = 0;
447 }
448
449 return SUCCESS;
450 }
451
NotifyFocusGranted(const uint32_t clientID,const AudioInterrupt & audioInterrupt)452 void AudioPolicyServer::NotifyFocusGranted(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
453 {
454 MEDIA_INFO_LOG("AudioPolicyServer: Notify focus granted in: %{public}d", clientID);
455 std::shared_ptr<AudioInterruptCallback> interruptCb = nullptr;
456 interruptCb = audioManagerListenerCbsMap_[clientID];
457 if (interruptCb) {
458 InterruptEventInternal interruptEvent = {};
459 interruptEvent.eventType = INTERRUPT_TYPE_END;
460 interruptEvent.forceType = INTERRUPT_SHARE;
461 interruptEvent.hintType = INTERRUPT_HINT_NONE;
462 interruptEvent.duckVolume = 0;
463
464 MEDIA_DEBUG_LOG("AudioPolicyServer: callback focus granted");
465 interruptCb->OnInterrupt(interruptEvent);
466
467 unique_ptr<AudioInterrupt> tempAudioInterruptInfo = make_unique<AudioInterrupt>();
468 tempAudioInterruptInfo->streamUsage = audioInterrupt.streamUsage;
469 tempAudioInterruptInfo->contentType = audioInterrupt.contentType;
470 tempAudioInterruptInfo->streamType = audioInterrupt.streamType;
471 tempAudioInterruptInfo->pauseWhenDucked = audioInterrupt.pauseWhenDucked;
472 focussedAudioInterruptInfo_ = move(tempAudioInterruptInfo);
473 clientOnFocus_ = clientID;
474 }
475 }
476
NotifyFocusAbandoned(const uint32_t clientID,const AudioInterrupt & audioInterrupt)477 int32_t AudioPolicyServer::NotifyFocusAbandoned(const uint32_t clientID, const AudioInterrupt &audioInterrupt)
478 {
479 MEDIA_INFO_LOG("AudioPolicyServer: Notify focus abandoned in: %{public}d", clientID);
480 std::shared_ptr<AudioInterruptCallback> interruptCb = nullptr;
481 interruptCb = audioManagerListenerCbsMap_[clientID];
482 if (!interruptCb) {
483 MEDIA_INFO_LOG("AudioPolicyServer: Notify failed, callback not present");
484 return ERR_INVALID_PARAM;
485 }
486
487 InterruptEventInternal interruptEvent = {};
488 interruptEvent.eventType = INTERRUPT_TYPE_BEGIN;
489 interruptEvent.forceType = INTERRUPT_SHARE;
490 interruptEvent.hintType = INTERRUPT_HINT_STOP;
491 interruptEvent.duckVolume = 0;
492 MEDIA_DEBUG_LOG("AudioPolicyServer: callback focus abandoned");
493 interruptCb->OnInterrupt(interruptEvent);
494
495 return SUCCESS;
496 }
497
PrintOwnersLists()498 void AudioPolicyServer::PrintOwnersLists()
499 {
500 MEDIA_DEBUG_LOG("AudioPolicyServer: Printing active list");
501 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
502 MEDIA_DEBUG_LOG("AudioPolicyServer: curActiveOwnersList_: streamType: %{public}d", it->streamType);
503 MEDIA_DEBUG_LOG("AudioPolicyServer: curActiveOwnersList_: sessionID: %{public}u", it->sessionID);
504 }
505
506 MEDIA_DEBUG_LOG("AudioPolicyServer: Printing pending list");
507 for (auto it = pendingOwnersList_.begin(); it != pendingOwnersList_.end(); ++it) {
508 MEDIA_DEBUG_LOG("AudioPolicyServer: pendingOwnersList_: streamType: %{public}d", it->streamType);
509 MEDIA_DEBUG_LOG("AudioPolicyServer: pendingOwnersList_: sessionID: %{public}u", it->sessionID);
510 }
511 }
512
ProcessPendingInterrupt(std::list<AudioInterrupt>::iterator & iterPending,const AudioInterrupt & incoming)513 bool AudioPolicyServer::ProcessPendingInterrupt(std::list<AudioInterrupt>::iterator &iterPending,
514 const AudioInterrupt &incoming)
515 {
516 bool iterPendingErased = false;
517 AudioStreamType pendingStreamType = iterPending->streamType;
518 AudioStreamType incomingStreamType = incoming.streamType;
519
520 auto focusMap = mPolicyService.GetAudioFocusMap();
521 std::pair<AudioStreamType, AudioStreamType> streamTypePair = std::make_pair(pendingStreamType, incomingStreamType);
522
523 if (focusMap.find(streamTypePair) == focusMap.end()) {
524 MEDIA_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
525 return iterPendingErased;
526 }
527
528 AudioFocusEntry focusEntry = focusMap[streamTypePair];
529 float duckVol = 0.2f;
530 InterruptEventInternal interruptEvent {INTERRUPT_TYPE_BEGIN, focusEntry.forceType, focusEntry.hintType, duckVol};
531
532 uint32_t pendingSessionID = iterPending->sessionID;
533 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
534
535 if (focusEntry.actionOn == CURRENT && focusEntry.forceType == INTERRUPT_FORCE) {
536 policyListenerCb = policyListenerCbsMap_[pendingSessionID];
537
538 if (focusEntry.hintType == INTERRUPT_HINT_STOP) {
539 iterPending = pendingOwnersList_.erase(iterPending);
540 iterPendingErased = true;
541 }
542
543 if (policyListenerCb == nullptr) {
544 MEDIA_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
545 return iterPendingErased;
546 }
547 policyListenerCb->OnInterrupt(interruptEvent);
548 }
549
550 return iterPendingErased;
551 }
552
ProcessCurActiveInterrupt(std::list<AudioInterrupt>::iterator & iterActive,const AudioInterrupt & incoming)553 bool AudioPolicyServer::ProcessCurActiveInterrupt(std::list<AudioInterrupt>::iterator &iterActive,
554 const AudioInterrupt &incoming)
555 {
556 bool iterActiveErased = false;
557 AudioStreamType activeStreamType = iterActive->streamType;
558 AudioStreamType incomingStreamType = incoming.streamType;
559
560 auto focusMap = mPolicyService.GetAudioFocusMap();
561 std::pair<AudioStreamType, AudioStreamType> streamTypePair = std::make_pair(activeStreamType, incomingStreamType);
562
563 if (focusMap.find(streamTypePair) == focusMap.end()) {
564 MEDIA_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
565 return iterActiveErased;
566 }
567
568 AudioFocusEntry focusEntry = focusMap[streamTypePair];
569 InterruptEventInternal interruptEvent {INTERRUPT_TYPE_BEGIN, focusEntry.forceType, focusEntry.hintType, 0.2f};
570
571 uint32_t activeSessionID = iterActive->sessionID;
572 uint32_t incomingSessionID = incoming.sessionID;
573 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
574 if (focusEntry.actionOn == CURRENT) {
575 policyListenerCb = policyListenerCbsMap_[activeSessionID];
576 } else {
577 policyListenerCb = policyListenerCbsMap_[incomingSessionID];
578 }
579
580 // focusEntry.forceType == INTERRUPT_SHARE
581 if (focusEntry.forceType != INTERRUPT_FORCE) {
582 if (policyListenerCb == nullptr) {
583 MEDIA_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
584 return iterActiveErased;
585 }
586 policyListenerCb->OnInterrupt(interruptEvent);
587 return iterActiveErased;
588 }
589
590 // focusEntry.forceType == INTERRUPT_FORCE
591 MEDIA_INFO_LOG("AudioPolicyServer: Action is taken on: %{public}d", focusEntry.actionOn);
592 float volume = 0.0f;
593 if (focusEntry.actionOn == CURRENT) {
594 switch (focusEntry.hintType) {
595 case INTERRUPT_HINT_STOP:
596 iterActive = curActiveOwnersList_.erase(iterActive);
597 iterActiveErased = true;
598 break;
599 case INTERRUPT_HINT_PAUSE:
600 pendingOwnersList_.emplace_front(*iterActive);
601 iterActive = curActiveOwnersList_.erase(iterActive);
602 iterActiveErased = true;
603 break;
604 case INTERRUPT_HINT_DUCK:
605 volume = GetStreamVolume(incomingStreamType);
606 interruptEvent.duckVolume = DUCK_FACTOR * volume;
607 break;
608 default:
609 break;
610 }
611 } else { // INCOMING
612 if (focusEntry.hintType == INTERRUPT_HINT_DUCK) {
613 MEDIA_INFO_LOG("AudioPolicyServer: force duck get GetStreamVolume(activeStreamType)");
614 volume = GetStreamVolume(activeStreamType);
615 interruptEvent.duckVolume = DUCK_FACTOR * volume;
616 }
617 }
618
619 if (policyListenerCb == nullptr) {
620 MEDIA_WARNING_LOG("AudioPolicyServer: policyListenerCb is null so ignoring to apply focus policy");
621 return iterActiveErased;
622 }
623 policyListenerCb->OnInterrupt(interruptEvent);
624
625 return iterActiveErased;
626 }
627
ProcessFocusEntry(const AudioInterrupt & incomingInterrupt)628 int32_t AudioPolicyServer::ProcessFocusEntry(const AudioInterrupt &incomingInterrupt)
629 {
630 // Function: First Process pendingList and remove session that loses focus indefinitely
631 for (auto iterPending = pendingOwnersList_.begin(); iterPending != pendingOwnersList_.end();) {
632 bool IsIterPendingErased = ProcessPendingInterrupt(iterPending, incomingInterrupt);
633 if (!IsIterPendingErased) {
634 MEDIA_INFO_LOG("AudioPolicyServer: iterPending not erased while processing ++increment it");
635 ++iterPending;
636 }
637 }
638
639 auto focusMap = mPolicyService.GetAudioFocusMap();
640 // Function: Process Focus entry
641 for (auto iterActive = curActiveOwnersList_.begin(); iterActive != curActiveOwnersList_.end();) {
642 AudioStreamType activeStreamType = iterActive->streamType;
643 AudioStreamType incomingStreamType = incomingInterrupt.streamType;
644 std::pair<AudioStreamType, AudioStreamType> streamTypePair =
645 std::make_pair(activeStreamType, incomingStreamType);
646
647 if (focusMap.find(streamTypePair) == focusMap.end()) {
648 MEDIA_WARNING_LOG("AudioPolicyServer: Streame type is invalid");
649 return ERR_INVALID_PARAM;
650 }
651
652 AudioFocusEntry focusEntry = focusMap[streamTypePair];
653 if (focusEntry.isReject) {
654 MEDIA_INFO_LOG("AudioPolicyServer: focusEntry.isReject : ActivateAudioInterrupt request rejected");
655 return ERR_FOCUS_DENIED;
656 }
657 bool IsIterActiveErased = ProcessCurActiveInterrupt(iterActive, incomingInterrupt);
658 if (!IsIterActiveErased) {
659 MEDIA_INFO_LOG("AudioPolicyServer: iterActive not erased while processing ++increment it");
660 ++iterActive;
661 }
662 }
663
664 return SUCCESS;
665 }
666
AddToCurActiveList(const AudioInterrupt & audioInterrupt)667 void AudioPolicyServer::AddToCurActiveList(const AudioInterrupt &audioInterrupt)
668 {
669 if (curActiveOwnersList_.empty()) {
670 curActiveOwnersList_.emplace_front(audioInterrupt);
671 return;
672 }
673
674 auto itCurActive = curActiveOwnersList_.begin();
675
676 for (; itCurActive != curActiveOwnersList_.end(); ++itCurActive) {
677 AudioStreamType existingPriorityStreamType = itCurActive->streamType;
678 if (interruptPriorityMap_[existingPriorityStreamType] > interruptPriorityMap_[audioInterrupt.streamType]) {
679 continue;
680 } else {
681 curActiveOwnersList_.emplace(itCurActive, audioInterrupt);
682 return;
683 }
684 }
685
686 if (itCurActive == curActiveOwnersList_.end()) {
687 curActiveOwnersList_.emplace_back(audioInterrupt);
688 }
689 }
690
ActivateAudioInterrupt(const AudioInterrupt & audioInterrupt)691 int32_t AudioPolicyServer::ActivateAudioInterrupt(const AudioInterrupt &audioInterrupt)
692 {
693 std::lock_guard<std::mutex> lock(interruptMutex_);
694
695 MEDIA_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt");
696 MEDIA_DEBUG_LOG("AudioPolicyServer: audioInterrupt.streamType: %{public}d", audioInterrupt.streamType);
697 MEDIA_DEBUG_LOG("AudioPolicyServer: audioInterrupt.sessionID: %{public}u", audioInterrupt.sessionID);
698
699 if (!mPolicyService.IsAudioInterruptEnabled()) {
700 MEDIA_DEBUG_LOG("AudioPolicyServer: interrupt is not enabled. No need to ActivateAudioInterrupt");
701 AddToCurActiveList(audioInterrupt);
702 return SUCCESS;
703 }
704
705 MEDIA_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt start: print active and pending lists");
706 PrintOwnersLists();
707
708 // Check if the session is present in pending list, remove and treat it as a new request
709 uint32_t incomingSessionID = audioInterrupt.sessionID;
710 if (!pendingOwnersList_.empty()) {
711 MEDIA_DEBUG_LOG("If it is present in pending list, remove and treat is as new request");
712 pendingOwnersList_.remove_if([&incomingSessionID](AudioInterrupt &interrupt) {
713 return interrupt.sessionID == incomingSessionID;
714 });
715 }
716
717 // If active owners list is empty, directly activate interrupt
718 if (curActiveOwnersList_.empty()) {
719 curActiveOwnersList_.emplace_front(audioInterrupt);
720 MEDIA_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
721 PrintOwnersLists();
722 return SUCCESS;
723 }
724
725 // If the session is already in active list, return
726 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
727 if (it->sessionID == audioInterrupt.sessionID) {
728 MEDIA_DEBUG_LOG("AudioPolicyServer: sessionID %{public}d is already active", audioInterrupt.sessionID);
729 MEDIA_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
730 PrintOwnersLists();
731 return SUCCESS;
732 }
733 }
734
735 // Process ProcessFocusEntryTable for current active and pending lists
736 int32_t ret = ProcessFocusEntry(audioInterrupt);
737 if (ret) {
738 MEDIA_ERR_LOG("AudioPolicyServer: ActivateAudioInterrupt request rejected");
739 MEDIA_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
740 PrintOwnersLists();
741 return ERR_FOCUS_DENIED;
742 }
743
744 // Activate request processed and accepted. Add the entry to active list
745 AddToCurActiveList(audioInterrupt);
746
747 MEDIA_DEBUG_LOG("AudioPolicyServer: ActivateAudioInterrupt end: print active and pending lists");
748 PrintOwnersLists();
749 return SUCCESS;
750 }
751
UnduckCurActiveList(const AudioInterrupt & exitInterrupt)752 void AudioPolicyServer::UnduckCurActiveList(const AudioInterrupt &exitInterrupt)
753 {
754 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
755 AudioStreamType exitStreamType = exitInterrupt.streamType;
756 InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
757
758 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end(); ++it) {
759 AudioStreamType activeStreamType = it->streamType;
760 uint32_t activeSessionID = it->sessionID;
761 if (interruptPriorityMap_[activeStreamType] > interruptPriorityMap_[exitStreamType]) {
762 continue;
763 }
764 policyListenerCb = policyListenerCbsMap_[activeSessionID];
765 if (policyListenerCb == nullptr) {
766 MEDIA_WARNING_LOG("AudioPolicyServer: Cb sessionID: %{public}d null. ignoring to Unduck", activeSessionID);
767 return;
768 }
769 policyListenerCb->OnInterrupt(forcedUnducking);
770 }
771 }
772
ResumeUnduckPendingList(const AudioInterrupt & exitInterrupt)773 void AudioPolicyServer::ResumeUnduckPendingList(const AudioInterrupt &exitInterrupt)
774 {
775 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
776 AudioStreamType exitStreamType = exitInterrupt.streamType;
777 InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
778 InterruptEventInternal resumeForcePaused {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_RESUME, 0.2f};
779
780 for (auto it = pendingOwnersList_.begin(); it != pendingOwnersList_.end();) {
781 AudioStreamType pendingStreamType = it->streamType;
782 uint32_t pendingSessionID = it->sessionID;
783 if (interruptPriorityMap_[pendingStreamType] > interruptPriorityMap_[exitStreamType]) {
784 ++it;
785 continue;
786 }
787 it = pendingOwnersList_.erase(it);
788 policyListenerCb = policyListenerCbsMap_[pendingSessionID];
789 if (policyListenerCb == nullptr) {
790 MEDIA_WARNING_LOG("AudioPolicyServer: Cb sessionID: %{public}d null. ignoring resume", pendingSessionID);
791 return;
792 }
793 policyListenerCb->OnInterrupt(forcedUnducking);
794 policyListenerCb->OnInterrupt(resumeForcePaused);
795 }
796 }
797
DeactivateAudioInterrupt(const AudioInterrupt & audioInterrupt)798 int32_t AudioPolicyServer::DeactivateAudioInterrupt(const AudioInterrupt &audioInterrupt)
799 {
800 std::lock_guard<std::mutex> lock(interruptMutex_);
801
802 if (!mPolicyService.IsAudioInterruptEnabled()) {
803 MEDIA_DEBUG_LOG("AudioPolicyServer: interrupt is not enabled. No need to DeactivateAudioInterrupt");
804 uint32_t exitSessionID = audioInterrupt.sessionID;
805 curActiveOwnersList_.remove_if([&exitSessionID](AudioInterrupt &interrupt) {
806 return interrupt.sessionID == exitSessionID;
807 });
808 return SUCCESS;
809 }
810
811 MEDIA_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt");
812 MEDIA_DEBUG_LOG("AudioPolicyServer: audioInterrupt.streamType: %{public}d", audioInterrupt.streamType);
813 MEDIA_DEBUG_LOG("AudioPolicyServer: audioInterrupt.sessionID: %{public}u", audioInterrupt.sessionID);
814
815 MEDIA_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
816 PrintOwnersLists();
817
818 // Check and remove, its entry from pending first
819 uint32_t exitSessionID = audioInterrupt.sessionID;
820 pendingOwnersList_.remove_if([&exitSessionID](AudioInterrupt &interrupt) {
821 return interrupt.sessionID == exitSessionID;
822 });
823
824 bool isInterruptActive = false;
825 InterruptEventInternal forcedUnducking {INTERRUPT_TYPE_END, INTERRUPT_FORCE, INTERRUPT_HINT_UNDUCK, 0.2f};
826 std::shared_ptr<AudioInterruptCallback> policyListenerCb = nullptr;
827 for (auto it = curActiveOwnersList_.begin(); it != curActiveOwnersList_.end();) {
828 if (it->sessionID == audioInterrupt.sessionID) {
829 policyListenerCb = policyListenerCbsMap_[it->sessionID];
830 if (policyListenerCb != nullptr) {
831 policyListenerCb->OnInterrupt(forcedUnducking); // Unducks self, if ducked before
832 }
833 it = curActiveOwnersList_.erase(it);
834 isInterruptActive = true;
835 } else {
836 ++it;
837 }
838 }
839
840 // If it was not present in both the lists or present only in pending list,
841 // No need to take any action on other sessions, just return.
842 if (!isInterruptActive) {
843 MEDIA_DEBUG_LOG("AudioPolicyServer: Session : %{public}d is not currently active. return success",
844 audioInterrupt.sessionID);
845 MEDIA_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
846 PrintOwnersLists();
847 return SUCCESS;
848 }
849
850 if (curActiveOwnersList_.empty() && pendingOwnersList_.empty()) {
851 MEDIA_DEBUG_LOG("AudioPolicyServer: No ther session active or pending. Deactivate complete, return success");
852 MEDIA_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt start: print active and pending lists");
853 PrintOwnersLists();
854 return SUCCESS;
855 }
856
857 // unduck if the session was forced ducked
858 UnduckCurActiveList(audioInterrupt);
859
860 // resume and unduck if the session was forced paused
861 ResumeUnduckPendingList(audioInterrupt);
862
863 MEDIA_DEBUG_LOG("AudioPolicyServer: DeactivateAudioInterrupt end: print active and pending lists");
864 PrintOwnersLists();
865 return SUCCESS;
866 }
867
OnSessionRemoved(const uint32_t sessionID)868 void AudioPolicyServer::OnSessionRemoved(const uint32_t sessionID)
869 {
870 uint32_t removedSessionID = sessionID;
871
872 auto isSessionPresent = [&removedSessionID] (const AudioInterrupt &interrupt) {
873 return interrupt.sessionID == removedSessionID;
874 };
875
876 MEDIA_DEBUG_LOG("AudioPolicyServer::OnSessionRemoved");
877 std::unique_lock<std::mutex> lock(interruptMutex_);
878
879 auto iterActive = std::find_if(curActiveOwnersList_.begin(), curActiveOwnersList_.end(), isSessionPresent);
880 if (iterActive != curActiveOwnersList_.end()) {
881 AudioInterrupt removedInterrupt = *iterActive;
882 lock.unlock();
883 MEDIA_DEBUG_LOG("Removed SessionID: %{public}u is present in active list", removedSessionID);
884
885 (void)DeactivateAudioInterrupt(removedInterrupt);
886 (void)UnsetAudioInterruptCallback(removedSessionID);
887 return;
888 }
889 MEDIA_DEBUG_LOG("Removed SessionID: %{public}u is not present in active list", removedSessionID);
890
891 auto iterPending = std::find_if(pendingOwnersList_.begin(), pendingOwnersList_.end(), isSessionPresent);
892 if (iterPending != pendingOwnersList_.end()) {
893 AudioInterrupt removedInterrupt = *iterPending;
894 lock.unlock();
895 MEDIA_DEBUG_LOG("Removed SessionID: %{public}u is present in pending list", removedSessionID);
896
897 (void)DeactivateAudioInterrupt(removedInterrupt);
898 (void)UnsetAudioInterruptCallback(removedSessionID);
899 return;
900 }
901 MEDIA_DEBUG_LOG("Removed SessionID: %{public}u not present in pending list either", removedSessionID);
902
903 // Though it is not present in the owners list, check and clear its entry from callback map
904 lock.unlock();
905 (void)UnsetAudioInterruptCallback(removedSessionID);
906 }
907
GetStreamInFocus()908 AudioStreamType AudioPolicyServer::GetStreamInFocus()
909 {
910 AudioStreamType streamInFocus = STREAM_DEFAULT;
911 if (!curActiveOwnersList_.empty()) {
912 streamInFocus = curActiveOwnersList_.front().streamType;
913 }
914
915 return streamInFocus;
916 }
917
GetSessionInfoInFocus(AudioInterrupt & audioInterrupt)918 int32_t AudioPolicyServer::GetSessionInfoInFocus(AudioInterrupt &audioInterrupt)
919 {
920 uint32_t invalidSessionID = static_cast<uint32_t>(-1);
921 audioInterrupt = {STREAM_USAGE_UNKNOWN, CONTENT_TYPE_UNKNOWN, STREAM_DEFAULT, invalidSessionID};
922
923 if (!curActiveOwnersList_.empty()) {
924 audioInterrupt = curActiveOwnersList_.front();
925 }
926
927 return SUCCESS;
928 }
929
SetVolumeKeyEventCallback(const int32_t clientPid,const sptr<IRemoteObject> & object)930 int32_t AudioPolicyServer::SetVolumeKeyEventCallback(const int32_t clientPid, const sptr<IRemoteObject> &object)
931 {
932 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
933 MEDIA_DEBUG_LOG("AudioPolicyServer::SetVolumeKeyEventCallback");
934 CHECK_AND_RETURN_RET_LOG(object != nullptr, ERR_INVALID_PARAM,
935 "AudioPolicyServer::SetVolumeKeyEventCallback listener object is nullptr");
936
937 sptr<IAudioVolumeKeyEventCallback> listener = iface_cast<IAudioVolumeKeyEventCallback>(object);
938 CHECK_AND_RETURN_RET_LOG(listener != nullptr, ERR_INVALID_PARAM,
939 "AudioPolicyServer::SetVolumeKeyEventCallback listener obj cast failed");
940
941 std::shared_ptr<VolumeKeyEventCallback> callback = std::make_shared<VolumeKeyEventCallbackListner>(listener);
942 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM,
943 "AudioPolicyServer::SetVolumeKeyEventCallback failed to create cb obj");
944
945 volumeChangeCbsMap_.insert({ clientPid, callback });
946 return SUCCESS;
947 }
948
UnsetVolumeKeyEventCallback(const int32_t clientPid)949 int32_t AudioPolicyServer::UnsetVolumeKeyEventCallback(const int32_t clientPid)
950 {
951 std::lock_guard<std::mutex> lock(volumeKeyEventMutex_);
952
953 if (volumeChangeCbsMap_.find(clientPid) != volumeChangeCbsMap_.end()) {
954 volumeChangeCbsMap_.erase(clientPid);
955 MEDIA_ERR_LOG("AudioPolicyServer::UnsetVolumeKeyEventCallback for clientPid %{public}d done", clientPid);
956 } else {
957 MEDIA_DEBUG_LOG("AudioPolicyServer::UnsetVolumeKeyEventCallback clientPid %{public}d not present/unset already",
958 clientPid);
959 }
960
961 return SUCCESS;
962 }
963
MapVolumeToHDI(int32_t volume)964 float AudioPolicyServer::MapVolumeToHDI(int32_t volume)
965 {
966 float value = (float)volume / MAX_VOLUME_LEVEL;
967 float roundValue = (int)(value * CONST_FACTOR);
968
969 return (float)roundValue / CONST_FACTOR;
970 }
971
ConvertVolumeToInt(float volume)972 int32_t AudioPolicyServer::ConvertVolumeToInt(float volume)
973 {
974 float value = (float)volume * MAX_VOLUME_LEVEL;
975 return nearbyint(value);
976 }
977
GetPolicyData(PolicyData & policyData)978 void AudioPolicyServer::GetPolicyData(PolicyData &policyData)
979 {
980 policyData.ringerMode = GetRingerMode();
981 policyData.callStatus = GetAudioScene();
982
983 // Get stream volumes
984 for (int stream = AudioStreamType::STREAM_VOICE_CALL; stream <= AudioStreamType::STREAM_TTS; stream++) {
985 AudioStreamType streamType = (AudioStreamType)stream;
986
987 if (AudioServiceDump::IsStreamSupported(streamType)) {
988 int32_t volume = ConvertVolumeToInt(GetStreamVolume(streamType));
989 policyData.streamVolumes.insert({ streamType, volume });
990 }
991 }
992
993 // Get Audio Focus Information
994 AudioInterrupt audioInterrupt;
995 if (GetSessionInfoInFocus(audioInterrupt) == SUCCESS) {
996 policyData.audioFocusInfo = audioInterrupt;
997 }
998
999 // Get Input & Output Devices
1000
1001 DeviceFlag deviceFlag = DeviceFlag::INPUT_DEVICES_FLAG;
1002 std::vector<sptr<AudioDeviceDescriptor>> audioDeviceDescriptors = GetDevices(deviceFlag);
1003
1004 for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1005 AudioDeviceDescriptor audioDeviceDescriptor = **it;
1006 DevicesInfo deviceInfo;
1007 deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1008 deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1009 policyData.inputDevices.push_back(deviceInfo);
1010 }
1011
1012 deviceFlag = DeviceFlag::OUTPUT_DEVICES_FLAG;
1013 audioDeviceDescriptors = GetDevices(deviceFlag);
1014
1015 for (auto it = audioDeviceDescriptors.begin(); it != audioDeviceDescriptors.end(); it++) {
1016 AudioDeviceDescriptor audioDeviceDescriptor = **it;
1017 DevicesInfo deviceInfo;
1018 deviceInfo.deviceType = audioDeviceDescriptor.deviceType_;
1019 deviceInfo.deviceRole = audioDeviceDescriptor.deviceRole_;
1020 policyData.outputDevices.push_back(deviceInfo);
1021 }
1022 }
1023
Dump(int32_t fd,const std::vector<std::u16string> & args)1024 int32_t AudioPolicyServer::Dump(int32_t fd, const std::vector<std::u16string> &args)
1025 {
1026 MEDIA_DEBUG_LOG("AudioPolicyServer: Dump Process Invoked");
1027
1028 std::string dumpString;
1029 PolicyData policyData;
1030 AudioServiceDump dumpObj;
1031
1032 if (dumpObj.Initialize() != AUDIO_DUMP_SUCCESS) {
1033 MEDIA_ERR_LOG("AudioPolicyServer:: Audio Service Dump Not initialised\n");
1034 return AUDIO_DUMP_INIT_ERR;
1035 }
1036
1037 GetPolicyData(policyData);
1038 dumpObj.AudioDataDump(policyData, dumpString);
1039
1040 return write(fd, dumpString.c_str(), dumpString.size());
1041 }
1042 } // namespace AudioStandard
1043 } // namespace OHOS
1044