1 /*
2 * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef LOG_TAG
16 #define LOG_TAG "AudioVolumeManager"
17 #endif
18
19 #include "audio_volume_manager.h"
20 #include <ability_manager_client.h>
21 #include "iservice_registry.h"
22 #include "parameter.h"
23 #include "parameters.h"
24 #include "audio_policy_log.h"
25 #include "audio_manager_listener_stub.h"
26 #include "audio_inner_call.h"
27 #include "media_monitor_manager.h"
28 #include "i_policy_provider.h"
29 #include "audio_spatialization_service.h"
30 #include "audio_safe_volume_notification.h"
31
32 #include "audio_server_proxy.h"
33 #include "audio_policy_utils.h"
34
35 namespace OHOS {
36 namespace AudioStandard {
37
38 static const int64_t WAIT_RINGER_MODE_MUTE_RESET_TIME_MS = 500; // 500ms
39 const int32_t DUAL_TONE_RING_VOLUME = 0;
GetEncryptAddr(const std::string & addr)40 static std::string GetEncryptAddr(const std::string &addr)
41 {
42 const int32_t START_POS = 6;
43 const int32_t END_POS = 13;
44 const int32_t ADDRESS_STR_LEN = 17;
45 if (addr.empty() || addr.length() != ADDRESS_STR_LEN) {
46 return std::string("");
47 }
48 std::string tmp = "**:**:**:**:**:**";
49 std::string out = addr;
50 for (int i = START_POS; i <= END_POS; i++) {
51 out[i] = tmp[i];
52 }
53 return out;
54 }
55
56 const int32_t ONE_MINUTE = 60;
57 const uint32_t ABS_VOLUME_SUPPORT_RETRY_INTERVAL_IN_MICROSECONDS = 10000;
58
59 static const std::vector<AudioVolumeType> VOLUME_TYPE_LIST = {
60 STREAM_VOICE_CALL,
61 STREAM_RING,
62 STREAM_MUSIC,
63 STREAM_VOICE_ASSISTANT,
64 STREAM_ALARM,
65 STREAM_ACCESSIBILITY,
66 STREAM_ULTRASONIC,
67 STREAM_SYSTEM,
68 STREAM_VOICE_CALL_ASSISTANT,
69 STREAM_ALL
70 };
71
Init(std::shared_ptr<AudioPolicyServerHandler> audioPolicyServerHandler)72 bool AudioVolumeManager::Init(std::shared_ptr<AudioPolicyServerHandler> audioPolicyServerHandler)
73 {
74 audioPolicyServerHandler_ = audioPolicyServerHandler;
75 if (policyVolumeMap_ == nullptr) {
76 size_t mapSize = IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume) + sizeof(bool);
77 AUDIO_INFO_LOG("InitSharedVolume create shared volume map with size %{public}zu", mapSize);
78 policyVolumeMap_ = AudioSharedMemory::CreateFormLocal(mapSize, "PolicyVolumeMap");
79 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
80 false, "Get shared memory failed!");
81 volumeVector_ = reinterpret_cast<Volume *>(policyVolumeMap_->GetBase());
82 sharedAbsVolumeScene_ = reinterpret_cast<bool *>(policyVolumeMap_->GetBase()) +
83 IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume);
84 }
85 return true;
86 }
DeInit(void)87 void AudioVolumeManager::DeInit(void)
88 {
89 volumeVector_ = nullptr;
90 sharedAbsVolumeScene_ = nullptr;
91 policyVolumeMap_ = nullptr;
92 safeVolumeExit_ = true;
93 if (calculateLoopSafeTime_ != nullptr && calculateLoopSafeTime_->joinable()) {
94 calculateLoopSafeTime_->join();
95 calculateLoopSafeTime_.reset();
96 calculateLoopSafeTime_ = nullptr;
97 }
98 if (safeVolumeDialogThrd_ != nullptr && safeVolumeDialogThrd_->joinable()) {
99 safeVolumeDialogThrd_->join();
100 safeVolumeDialogThrd_.reset();
101 safeVolumeDialogThrd_ = nullptr;
102 }
103 audioPolicyServerHandler_ = nullptr;
104 }
105
GetMaxVolumeLevel(AudioVolumeType volumeType) const106 int32_t AudioVolumeManager::GetMaxVolumeLevel(AudioVolumeType volumeType) const
107 {
108 if (volumeType == STREAM_ALL) {
109 volumeType = STREAM_MUSIC;
110 }
111 return audioPolicyManager_.GetMaxVolumeLevel(volumeType);
112 }
113
GetMinVolumeLevel(AudioVolumeType volumeType) const114 int32_t AudioVolumeManager::GetMinVolumeLevel(AudioVolumeType volumeType) const
115 {
116 if (volumeType == STREAM_ALL) {
117 volumeType = STREAM_MUSIC;
118 }
119 return audioPolicyManager_.GetMinVolumeLevel(volumeType);
120 }
121
GetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume & vol)122 bool AudioVolumeManager::GetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume &vol)
123 {
124 CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Get shared memory failed!");
125 size_t index = 0;
126 if (!IPolicyProvider::GetVolumeIndex(streamType, GetVolumeGroupForDevice(deviceType), index) ||
127 index >= IPolicyProvider::GetVolumeVectorSize()) {
128 return false;
129 }
130 vol.isMute = volumeVector_[index].isMute;
131 vol.volumeFloat = volumeVector_[index].volumeFloat;
132 vol.volumeInt = volumeVector_[index].volumeInt;
133 return true;
134 }
135
SetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume vol)136 bool AudioVolumeManager::SetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume vol)
137 {
138 CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Set shared memory failed!");
139 size_t index = 0;
140 if (!IPolicyProvider::GetVolumeIndex(streamType, GetVolumeGroupForDevice(deviceType), index) ||
141 index >= IPolicyProvider::GetVolumeVectorSize()) {
142 AUDIO_INFO_LOG("Don't find and Set Shared Volume failed");
143 return false;
144 }
145 volumeVector_[index].isMute = vol.isMute;
146 volumeVector_[index].volumeFloat = vol.volumeFloat;
147 volumeVector_[index].volumeInt = vol.volumeInt;
148 AUDIO_INFO_LOG("Success Set Shared Volume with StreamType:%{public}d, DeviceType:%{public}d", streamType,
149 deviceType);
150
151 AudioServerProxy::GetInstance().NotifyStreamVolumeChangedProxy(streamType, vol.volumeFloat);
152 return true;
153 }
154
InitSharedVolume(std::shared_ptr<AudioSharedMemory> & buffer)155 int32_t AudioVolumeManager::InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer)
156 {
157 AUDIO_INFO_LOG("InitSharedVolume start");
158 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
159 ERR_OPERATION_FAILED, "Get shared memory failed!");
160
161 // init volume map
162 // todo device
163 for (size_t i = 0; i < IPolicyProvider::GetVolumeVectorSize(); i++) {
164 bool isMute = audioPolicyManager_.GetStreamMute(g_volumeIndexVector[i].first);
165 int32_t currentVolumeLevel = audioPolicyManager_.GetSystemVolumeLevelNoMuteState(g_volumeIndexVector[i].first);
166 float volFloat = audioPolicyManager_.GetSystemVolumeInDb(g_volumeIndexVector[i].first,
167 (isMute ? 0 : currentVolumeLevel), audioActiveDevice_.GetCurrentOutputDeviceType());
168 volumeVector_[i].isMute = isMute;
169 volumeVector_[i].volumeFloat = volFloat;
170 volumeVector_[i].volumeInt = static_cast<uint32_t>(currentVolumeLevel);
171 }
172 SetSharedAbsVolumeScene(false);
173 buffer = policyVolumeMap_;
174
175 return SUCCESS;
176 }
177
SetSharedAbsVolumeScene(const bool support)178 void AudioVolumeManager::SetSharedAbsVolumeScene(const bool support)
179 {
180 CHECK_AND_RETURN_LOG(sharedAbsVolumeScene_ != nullptr, "sharedAbsVolumeScene is nullptr");
181 *sharedAbsVolumeScene_ = support;
182 }
183
GetAppVolumeLevel(int32_t appUid)184 int32_t AudioVolumeManager::GetAppVolumeLevel(int32_t appUid)
185 {
186 return audioPolicyManager_.GetAppVolumeLevel(appUid);
187 }
188
GetSystemVolumeLevel(AudioStreamType streamType)189 int32_t AudioVolumeManager::GetSystemVolumeLevel(AudioStreamType streamType)
190 {
191 Trace trace("AudioVolumeManager::GetSystemVolumeLevel");
192 if (streamType == STREAM_RING && !IsRingerModeMute()) {
193 AUDIO_PRERELEASE_LOGW("return 0 when dual tone ring");
194 return DUAL_TONE_RING_VOLUME;
195 }
196 {
197 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
198 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
199 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && streamType != STREAM_VOICE_CALL &&
200 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
201 A2dpDeviceConfigInfo info;
202 bool ret = audioA2dpDevice_.GetA2dpDeviceInfo(btDevice, info);
203 if (ret && info.absVolumeSupport) {
204 return info.mute ? 0 : info.volumeLevel;
205 }
206 }
207 }
208 return audioPolicyManager_.GetSystemVolumeLevel(streamType);
209 }
210
GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)211 int32_t AudioVolumeManager::GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)
212 {
213 return audioPolicyManager_.GetSystemVolumeLevelNoMuteState(streamType);
214 }
215
SetVolumeForSwitchDevice(DeviceType deviceType,const std::string & newSinkName)216 void AudioVolumeManager::SetVolumeForSwitchDevice(DeviceType deviceType, const std::string &newSinkName)
217 {
218 Trace trace("AudioVolumeManager::SetVolumeForSwitchDevice:" + std::to_string(deviceType));
219 // Load volume from KvStore and set volume for each stream type
220 audioPolicyManager_.SetVolumeForSwitchDevice(deviceType);
221
222 // The volume of voice_call needs to be adjusted separately
223 if (audioSceneManager_.GetAudioScene(true) == AUDIO_SCENE_PHONE_CALL) {
224 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
225 }
226
227 UpdateVolumeForLowLatency();
228 }
229
SetVoiceRingtoneMute(bool isMute)230 int32_t AudioVolumeManager::SetVoiceRingtoneMute(bool isMute)
231 {
232 AUDIO_INFO_LOG("Set Voice Ringtone is %{public}d", isMute);
233 isVoiceRingtoneMute_ = isMute ? true : false;
234 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
235 return SUCCESS;
236 }
237
SetVoiceCallVolume(int32_t volumeLevel)238 void AudioVolumeManager::SetVoiceCallVolume(int32_t volumeLevel)
239 {
240 Trace trace("AudioVolumeManager::SetVoiceCallVolume" + std::to_string(volumeLevel));
241 // set voice volume by the interface from hdi.
242 CHECK_AND_RETURN_LOG(volumeLevel != 0, "SetVoiceVolume: volume of voice_call cannot be set to 0");
243 float volumeDb = static_cast<float>(volumeLevel) /
244 static_cast<float>(audioPolicyManager_.GetMaxVolumeLevel(STREAM_VOICE_CALL));
245 volumeDb = isVoiceRingtoneMute_ ? 0 : volumeDb;
246 AudioServerProxy::GetInstance().SetVoiceVolumeProxy(volumeDb);
247 AUDIO_INFO_LOG("SetVoiceVolume: %{public}f", volumeDb);
248 }
249
UpdateVolumeForLowLatency()250 void AudioVolumeManager::UpdateVolumeForLowLatency()
251 {
252 Trace trace("AudioVolumeManager::UpdateVolumeForLowLatency");
253 // update volumes for low latency streams when loading volumes from the database.
254 Volume vol = {false, 1.0f, 0};
255 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
256 for (auto iter = VOLUME_TYPE_LIST.begin(); iter != VOLUME_TYPE_LIST.end(); iter++) {
257 vol.isMute = GetStreamMute(*iter);
258 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevelNoMuteState(*iter));
259 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(*iter,
260 (vol.isMute ? 0 : vol.volumeInt), curOutputDeviceType);
261 SetSharedVolume(*iter, curOutputDeviceType, vol);
262 }
263 SetSharedAbsVolumeScene(audioPolicyManager_.IsAbsVolumeScene());
264 }
265
InitKVStore()266 void AudioVolumeManager::InitKVStore()
267 {
268 audioPolicyManager_.InitKVStore();
269 UpdateVolumeForLowLatency();
270 AudioSpatializationService::GetAudioSpatializationService().InitSpatializationState();
271 }
272
CheckToCloseNotification(AudioStreamType streamType,int32_t volumeLevel)273 void AudioVolumeManager::CheckToCloseNotification(AudioStreamType streamType, int32_t volumeLevel)
274 {
275 AUDIO_INFO_LOG("AudioPolicyService::CheckVolumeCloseNotification enter.");
276 int32_t sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
277 if (volumeLevel < sVolumeLevel && DeviceIsSupportSafeVolume() &&
278 VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC) {
279 AUDIO_INFO_LOG("user select lower volume should close notification.");
280 if (increaseNIsShowing_) {
281 CancelSafeVolumeNotification(INCREASE_VOLUME_NOTIFICATION_ID);
282 increaseNIsShowing_ = false;
283 }
284 if (restoreNIsShowing_) {
285 CancelSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
286 restoreNIsShowing_ = false;
287 }
288 }
289 }
290
DeviceIsSupportSafeVolume()291 bool AudioVolumeManager::DeviceIsSupportSafeVolume()
292 {
293 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
294 DeviceCategory curOutputDeviceCategory = audioActiveDevice_.GetCurrentOutputDeviceCategory();
295 switch (curOutputDeviceType) {
296 case DEVICE_TYPE_BLUETOOTH_A2DP:
297 case DEVICE_TYPE_BLUETOOTH_SCO:
298 if (curOutputDeviceCategory != BT_SOUNDBOX &&
299 curOutputDeviceCategory != BT_CAR) {
300 return true;
301 }
302 [[fallthrough]];
303 case DEVICE_TYPE_WIRED_HEADSET:
304 case DEVICE_TYPE_WIRED_HEADPHONES:
305 case DEVICE_TYPE_USB_HEADSET:
306 case DEVICE_TYPE_USB_ARM_HEADSET:
307 return true;
308 default:
309 AUDIO_INFO_LOG("current device unsupport safe volume:%{public}d", curOutputDeviceType);
310 return false;
311 }
312 }
313
SetAppVolumeLevel(int32_t appUid,int32_t volumeLevel)314 int32_t AudioVolumeManager::SetAppVolumeLevel(int32_t appUid, int32_t volumeLevel)
315 {
316 AUDIO_INFO_LOG("enter AudioVolumeManager::SetAppVolumeLevel");
317 // audioPolicyManager_ : AudioAdapterManager
318 int32_t result = audioPolicyManager_.SetAppVolumeLevel(appUid, volumeLevel);
319 return result;
320 }
321
SetAppVolumeMuted(int32_t appUid,bool muted)322 int32_t AudioVolumeManager::SetAppVolumeMuted(int32_t appUid, bool muted)
323 {
324 AUDIO_INFO_LOG("enter AudioVolumeManager::SetAppVolumeMuted");
325 int32_t result = audioPolicyManager_.SetAppVolumeMuted(appUid, muted);
326 return result;
327 }
328
IsAppVolumeMute(int32_t appUid,bool owned)329 bool AudioVolumeManager::IsAppVolumeMute(int32_t appUid, bool owned)
330 {
331 AUDIO_INFO_LOG("enter AudioVolumeManager::IsAppVolumeMute");
332 bool result = audioPolicyManager_.IsAppVolumeMute(appUid, owned);
333 return result;
334 }
335
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel)336 int32_t AudioVolumeManager::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel)
337 {
338 int32_t result;
339 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
340 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && streamType !=STREAM_VOICE_CALL &&
341 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
342 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
343 result = SetA2dpDeviceVolume(btDevice, volumeLevel, true);
344 Volume vol = {false, 1.0f, 0};
345 vol.isMute = volumeLevel == 0 ? true : false;
346 vol.volumeInt = static_cast<uint32_t>(volumeLevel);
347 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType);
348 SetSharedVolume(streamType, curOutputDeviceType, vol);
349 #ifdef BLUETOOTH_ENABLE
350 if (result == SUCCESS) {
351 // set to avrcp device
352 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice, volumeLevel);
353 } else if (result == ERR_UNKNOWN) {
354 AUDIO_INFO_LOG("UNKNOWN RESULT set abs safe volume");
355 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice,
356 audioPolicyManager_.GetSafeVolumeLevel());
357 } else {
358 AUDIO_ERR_LOG("AudioVolumeManager::SetSystemVolumeLevel set abs volume failed");
359 }
360 #else
361 (void)result;
362 #endif
363 }
364 int32_t sVolumeLevel = SelectDealSafeVolume(streamType, volumeLevel);
365 CheckToCloseNotification(streamType, volumeLevel);
366 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERR_SET_VOL_FAILED_BY_SAFE_VOL,
367 "safevolume did not deal");
368 result = audioPolicyManager_.SetSystemVolumeLevel(VolumeUtils::GetVolumeTypeFromStreamType(streamType),
369 volumeLevel);
370 if (result == SUCCESS && (streamType == STREAM_VOICE_CALL || streamType == STREAM_VOICE_COMMUNICATION)) {
371 SetVoiceCallVolume(volumeLevel);
372 }
373 // todo
374 Volume vol = {false, 1.0f, 0};
375 vol.isMute = volumeLevel == 0 ? true : false;
376 vol.volumeInt = static_cast<uint32_t>(volumeLevel);
377 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType);
378 SetSharedVolume(streamType, curOutputDeviceType, vol);
379 return result;
380 }
381
SetSystemVolumeLevelWithDevice(AudioStreamType streamType,int32_t volumeLevel,DeviceType deviceType)382 int32_t AudioVolumeManager::SetSystemVolumeLevelWithDevice(AudioStreamType streamType, int32_t volumeLevel,
383 DeviceType deviceType)
384 {
385 int32_t result;
386 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
387 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC && streamType !=STREAM_VOICE_CALL &&
388 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
389 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
390 result = SetA2dpDeviceVolume(btDevice, volumeLevel, true);
391 Volume vol = {false, 1.0f, 0};
392 vol.isMute = volumeLevel == 0 ? true : false;
393 vol.volumeInt = static_cast<uint32_t>(volumeLevel);
394 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType);
395 SetSharedVolume(streamType, curOutputDeviceType, vol);
396 #ifdef BLUETOOTH_ENABLE
397 if (result == SUCCESS) {
398 // set to avrcp device
399 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice, volumeLevel);
400 } else if (result == ERR_UNKNOWN) {
401 AUDIO_INFO_LOG("UNKNOWN RESULT set abs safe volume");
402 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice,
403 audioPolicyManager_.GetSafeVolumeLevel());
404 }
405 #else
406 (void)result;
407 #endif
408 }
409 int32_t sVolumeLevel = SelectDealSafeVolume(streamType, volumeLevel);
410 CheckToCloseNotification(streamType, volumeLevel);
411 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERR_SET_VOL_FAILED_BY_SAFE_VOL,
412 "safevolume did not deal");
413 result = audioPolicyManager_.SetSystemVolumeLevelWithDevice(VolumeUtils::GetVolumeTypeFromStreamType(streamType),
414 volumeLevel, deviceType);
415 if (result == SUCCESS && (streamType == STREAM_VOICE_CALL || streamType == STREAM_VOICE_COMMUNICATION)) {
416 SetVoiceCallVolume(volumeLevel);
417 }
418 Volume vol = {false, 1.0f, 0};
419 vol.isMute = volumeLevel == 0 ? true : false;
420 vol.volumeInt = static_cast<uint32_t>(volumeLevel);
421 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType);
422 SetSharedVolume(streamType, curOutputDeviceType, vol);
423 return result;
424 }
425
SelectDealSafeVolume(AudioStreamType streamType,int32_t volumeLevel)426 int32_t AudioVolumeManager::SelectDealSafeVolume(AudioStreamType streamType, int32_t volumeLevel)
427 {
428 int32_t sVolumeLevel = volumeLevel;
429 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
430 DeviceCategory curOutputDeviceCategory = audioActiveDevice_.GetCurrentOutputDeviceCategory();
431 if (sVolumeLevel > audioPolicyManager_.GetSafeVolumeLevel() &&
432 VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC) {
433 switch (curOutputDeviceType) {
434 case DEVICE_TYPE_BLUETOOTH_A2DP:
435 case DEVICE_TYPE_BLUETOOTH_SCO:
436 if (curOutputDeviceCategory == BT_SOUNDBOX || curOutputDeviceCategory == BT_CAR) {
437 return sVolumeLevel;
438 }
439 if (isBtFirstBoot_) {
440 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
441 AUDIO_INFO_LOG("Btfirstboot set volume use safe volume");
442 } else {
443 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
444 }
445 break;
446 case DEVICE_TYPE_WIRED_HEADSET:
447 case DEVICE_TYPE_WIRED_HEADPHONES:
448 case DEVICE_TYPE_USB_HEADSET:
449 case DEVICE_TYPE_USB_ARM_HEADSET:
450 sVolumeLevel = DealWithSafeVolume(volumeLevel, false);
451 break;
452 default:
453 AUDIO_INFO_LOG("unsupport safe volume:%{public}d", curOutputDeviceType);
454 break;
455 }
456 }
457 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP || curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
458 isBtFirstBoot_ = false;
459 }
460 return sVolumeLevel;
461 }
462
SetA2dpDeviceVolume(const std::string & macAddress,const int32_t volumeLevel,bool internalCall)463 int32_t AudioVolumeManager::SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volumeLevel,
464 bool internalCall)
465 {
466 if (audioA2dpDevice_.SetA2dpDeviceVolumeLevel(macAddress, volumeLevel) == false) {
467 return ERROR;
468 }
469 int32_t sVolumeLevel = volumeLevel;
470 if (volumeLevel > audioPolicyManager_.GetSafeVolumeLevel()) {
471 if (internalCall) {
472 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
473 } else {
474 sVolumeLevel = HandleAbsBluetoothVolume(macAddress, volumeLevel);
475 }
476 }
477 isBtFirstBoot_ = false;
478 if (audioA2dpDevice_.SetA2dpDeviceVolumeLevel(macAddress, sVolumeLevel) == false) {
479 return ERROR;
480 }
481 bool mute = sVolumeLevel == 0 ? true : false;
482
483 if (internalCall) {
484 CheckToCloseNotification(STREAM_MUSIC, volumeLevel);
485 }
486
487 audioA2dpDevice_.SetA2dpDeviceMute(macAddress, mute);
488 audioPolicyManager_.SetAbsVolumeMute(mute);
489 AUDIO_INFO_LOG("success for macaddress:[%{public}s], volume value:[%{public}d]",
490 GetEncryptAddr(macAddress).c_str(), sVolumeLevel);
491 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERR_UNKNOWN, "safevolume did not deal");
492 return SUCCESS;
493 }
494
HandleAbsBluetoothVolume(const std::string & macAddress,const int32_t volumeLevel)495 int32_t AudioVolumeManager::HandleAbsBluetoothVolume(const std::string &macAddress, const int32_t volumeLevel)
496 {
497 int32_t sVolumeLevel = 0;
498 if (isBtFirstBoot_) {
499 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
500 AUDIO_INFO_LOG("Btfirstboot set volume use safe volume");
501 isBtFirstBoot_ = false;
502 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel);
503 } else {
504 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
505 if (sVolumeLevel != volumeLevel) {
506 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel);
507 }
508 }
509 return sVolumeLevel;
510 }
511
PublishSafeVolumeNotification(int32_t notificationId)512 void AudioVolumeManager::PublishSafeVolumeNotification(int32_t notificationId)
513 {
514 void *libHandle = dlopen("libaudio_safe_volume_notification_impl.z.so", RTLD_LAZY);
515 if (libHandle == nullptr) {
516 AUDIO_ERR_LOG("dlopen failed %{public}s", __func__);
517 return;
518 }
519 CreateSafeVolumeNotification *createSafeVolumeNotificationImpl =
520 reinterpret_cast<CreateSafeVolumeNotification*>(dlsym(libHandle, "CreateSafeVolumeNotificationImpl"));
521 if (createSafeVolumeNotificationImpl == nullptr) {
522 AUDIO_ERR_LOG("createSafeVolumeNotificationImpl failed %{public}s", __func__);
523 #ifndef TEST_COVERAGE
524 dlclose(libHandle);
525 #endif
526 return;
527 }
528 AudioSafeVolumeNotification *audioSafeVolumeNotificationImpl = createSafeVolumeNotificationImpl();
529 if (audioSafeVolumeNotificationImpl == nullptr) {
530 AUDIO_ERR_LOG("audioSafeVolumeNotificationImpl is nullptr %{public}s", __func__);
531 #ifndef TEST_COVERAGE
532 dlclose(libHandle);
533 #endif
534 return;
535 }
536 audioSafeVolumeNotificationImpl->PublishSafeVolumeNotification(notificationId);
537 delete audioSafeVolumeNotificationImpl;
538 #ifndef TEST_COVERAGE
539 dlclose(libHandle);
540 #endif
541 }
542
CancelSafeVolumeNotification(int32_t notificationId)543 void AudioVolumeManager::CancelSafeVolumeNotification(int32_t notificationId)
544 {
545 void *libHandle = dlopen("libaudio_safe_volume_notification_impl.z.so", RTLD_LAZY);
546 if (libHandle == nullptr) {
547 AUDIO_ERR_LOG("dlopen failed %{public}s", __func__);
548 return;
549 }
550 CreateSafeVolumeNotification *createSafeVolumeNotificationImpl =
551 reinterpret_cast<CreateSafeVolumeNotification*>(dlsym(libHandle, "CreateSafeVolumeNotificationImpl"));
552 if (createSafeVolumeNotificationImpl == nullptr) {
553 AUDIO_ERR_LOG("createSafeVolumeNotificationImpl failed %{public}s", __func__);
554 #ifndef TEST_COVERAGE
555 dlclose(libHandle);
556 #endif
557 return;
558 }
559 AudioSafeVolumeNotification *audioSafeVolumeNotificationImpl = createSafeVolumeNotificationImpl();
560 if (audioSafeVolumeNotificationImpl == nullptr) {
561 AUDIO_ERR_LOG("audioSafeVolumeNotificationImpl is nullptr %{public}s", __func__);
562 #ifndef TEST_COVERAGE
563 dlclose(libHandle);
564 #endif
565 return;
566 }
567 audioSafeVolumeNotificationImpl->CancelSafeVolumeNotification(notificationId);
568 delete audioSafeVolumeNotificationImpl;
569 #ifndef TEST_COVERAGE
570 dlclose(libHandle);
571 #endif
572 }
573
DealWithSafeVolume(const int32_t volumeLevel,bool isA2dpDevice)574 int32_t AudioVolumeManager::DealWithSafeVolume(const int32_t volumeLevel, bool isA2dpDevice)
575 {
576 if (isA2dpDevice) {
577 DeviceCategory curOutputDeviceCategory = audioActiveDevice_.GetCurrentOutputDeviceCategory();
578 AUDIO_INFO_LOG("bluetooth Category:%{public}d", curOutputDeviceCategory);
579 if (curOutputDeviceCategory == BT_SOUNDBOX || curOutputDeviceCategory == BT_CAR) {
580 return volumeLevel;
581 }
582 }
583
584 int32_t sVolumeLevel = volumeLevel;
585 safeStatusBt_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP);
586 safeStatus_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET);
587 if ((safeStatusBt_ == SAFE_INACTIVE && isA2dpDevice) ||
588 (safeStatus_ == SAFE_INACTIVE && !isA2dpDevice)) {
589 CreateCheckMusicActiveThread();
590 return sVolumeLevel;
591 }
592
593 if ((isA2dpDevice && safeStatusBt_ == SAFE_ACTIVE) ||
594 (!isA2dpDevice && safeStatus_ == SAFE_ACTIVE)) {
595 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
596 if (restoreNIsShowing_) {
597 CancelSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
598 restoreNIsShowing_ = false;
599 }
600 PublishSafeVolumeNotification(INCREASE_VOLUME_NOTIFICATION_ID);
601 increaseNIsShowing_ = true;
602 return sVolumeLevel;
603 }
604 return sVolumeLevel;
605 }
606
CreateCheckMusicActiveThread()607 void AudioVolumeManager::CreateCheckMusicActiveThread()
608 {
609 std::lock_guard<std::mutex> lock(checkMusicActiveThreadMutex_);
610 if (calculateLoopSafeTime_ == nullptr) {
611 calculateLoopSafeTime_ = std::make_unique<std::thread>([this] { this->CheckActiveMusicTime(); });
612 pthread_setname_np(calculateLoopSafeTime_->native_handle(), "OS_AudioPolicySafe");
613 }
614 }
615
IsWiredHeadSet(const DeviceType & deviceType)616 bool AudioVolumeManager::IsWiredHeadSet(const DeviceType &deviceType)
617 {
618 switch (deviceType) {
619 case DEVICE_TYPE_WIRED_HEADSET:
620 case DEVICE_TYPE_WIRED_HEADPHONES:
621 case DEVICE_TYPE_USB_HEADSET:
622 case DEVICE_TYPE_USB_ARM_HEADSET:
623 return true;
624 default:
625 return false;
626 }
627 }
628
IsBlueTooth(const DeviceType & deviceType)629 bool AudioVolumeManager::IsBlueTooth(const DeviceType &deviceType)
630 {
631 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP || deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
632 if (audioActiveDevice_.GetCurrentOutputDeviceCategory() != BT_CAR &&
633 audioActiveDevice_.GetCurrentOutputDeviceCategory() != BT_SOUNDBOX) {
634 return true;
635 }
636 }
637 return false;
638 }
639
CheckActiveMusicTime()640 int32_t AudioVolumeManager::CheckActiveMusicTime()
641 {
642 AUDIO_INFO_LOG("enter");
643 int32_t safeVolume = audioPolicyManager_.GetSafeVolumeLevel();
644 while (!safeVolumeExit_) {
645 bool activeMusic = audioSceneManager_.IsStreamActive(STREAM_MUSIC);
646 bool isUpSafeVolume = GetSystemVolumeLevel(STREAM_MUSIC) > safeVolume ? true : false;
647 streamMusicVol_ = isUpSafeVolume ? GetSystemVolumeLevel(STREAM_MUSIC) : streamMusicVol_;
648 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
649 AUDIO_INFO_LOG("activeMusic:%{public}d, deviceType_:%{public}d, isUpSafeVolume:%{public}d",
650 activeMusic, curOutputDeviceType, isUpSafeVolume);
651 if (activeMusic && (safeStatusBt_ == SAFE_INACTIVE) && isUpSafeVolume &&
652 IsBlueTooth(curOutputDeviceType)) {
653 audioPolicyManager_.SetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP, streamMusicVol_);
654 CheckBlueToothActiveMusicTime(safeVolume);
655 } else if (activeMusic && (safeStatus_ == SAFE_INACTIVE) && isUpSafeVolume &&
656 IsWiredHeadSet(curOutputDeviceType)) {
657 audioPolicyManager_.SetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET, streamMusicVol_);
658 CheckWiredActiveMusicTime(safeVolume);
659 } else {
660 startSafeTime_ = 0;
661 startSafeTimeBt_ = 0;
662 }
663 sleep(ONE_MINUTE);
664 }
665 return 0;
666 }
667
CheckMixActiveMusicTime(int32_t safeVolume)668 bool AudioVolumeManager::CheckMixActiveMusicTime(int32_t safeVolume)
669 {
670 int64_t mixSafeTime = activeSafeTimeBt_ + activeSafeTime_;
671 AUDIO_INFO_LOG("mix device cumulative time: %{public}" PRId64, mixSafeTime);
672 if (mixSafeTime >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
673 AUDIO_INFO_LOG("mix device safe volume timeout");
674 ChangeDeviceSafeStatus(SAFE_ACTIVE);
675 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
676 startSafeTimeBt_ = 0;
677 startSafeTime_ = 0;
678 activeSafeTimeBt_ = 0;
679 activeSafeTime_ = 0;
680 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0);
681 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, 0);
682 return true;
683 }
684 return false;
685 }
686
CheckBlueToothActiveMusicTime(int32_t safeVolume)687 void AudioVolumeManager::CheckBlueToothActiveMusicTime(int32_t safeVolume)
688 {
689 if (startSafeTimeBt_ == 0) {
690 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
691 }
692 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
693 if (activeSafeTimeBt_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
694 AUDIO_INFO_LOG("bluetooth device safe volume timeout");
695 ChangeDeviceSafeStatus(SAFE_ACTIVE);
696 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
697 startSafeTimeBt_ = 0;
698 activeSafeTimeBt_ = 0;
699 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0);
700 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
701 restoreNIsShowing_ = true;
702 } else if (CheckMixActiveMusicTime(safeVolume)) {
703 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
704 restoreNIsShowing_ = true;
705 } else if (currentTime - startSafeTimeBt_ >= ONE_MINUTE) {
706 activeSafeTimeBt_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP);
707 activeSafeTimeBt_ += currentTime - startSafeTimeBt_;
708 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, activeSafeTimeBt_);
709 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
710 AUDIO_INFO_LOG("bluetooth safe volume 1 min timeout, cumulative time: %{public}" PRId64, activeSafeTimeBt_);
711 }
712 startSafeTime_ = 0;
713 }
714
CheckWiredActiveMusicTime(int32_t safeVolume)715 void AudioVolumeManager::CheckWiredActiveMusicTime(int32_t safeVolume)
716 {
717 if (startSafeTime_ == 0) {
718 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
719 }
720 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
721 if (activeSafeTime_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
722 AUDIO_INFO_LOG("wired device safe volume timeout");
723 ChangeDeviceSafeStatus(SAFE_ACTIVE);
724 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
725 startSafeTime_ = 0;
726 activeSafeTime_ = 0;
727 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, 0);
728 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
729 restoreNIsShowing_ = true;
730 } else if (CheckMixActiveMusicTime(safeVolume)) {
731 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
732 restoreNIsShowing_ = true;
733 } else if (currentTime - startSafeTime_ >= ONE_MINUTE) {
734 activeSafeTime_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET);
735 activeSafeTime_ += currentTime - startSafeTime_;
736 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, activeSafeTime_);
737 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
738 AUDIO_INFO_LOG("wired safe volume 1 min timeout, cumulative time: %{public}" PRId64, activeSafeTime_);
739 }
740 startSafeTimeBt_ = 0;
741 }
742
RestoreSafeVolume(AudioStreamType streamType,int32_t safeVolume)743 void AudioVolumeManager::RestoreSafeVolume(AudioStreamType streamType, int32_t safeVolume)
744 {
745 userSelect_ = false;
746 isDialogSelectDestroy_.store(false);
747
748 if (GetSystemVolumeLevel(streamType) <= safeVolume) {
749 AUDIO_INFO_LOG("current volume <= safe volume, don't update volume.");
750 return;
751 }
752
753 AUDIO_INFO_LOG("restore safe volume.");
754 audioPolicyManager_.SetRestoreVolumeFlag(true);
755 SetSystemVolumeLevel(streamType, safeVolume);
756 audioPolicyManager_.SetRestoreVolumeFlag(false);
757 SetSafeVolumeCallback(streamType);
758 }
759
SetSafeVolumeCallback(AudioStreamType streamType)760 void AudioVolumeManager::SetSafeVolumeCallback(AudioStreamType streamType)
761 {
762 CHECK_AND_RETURN_LOG(VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC,
763 "streamtype:%{public}d no need to set safe volume callback.", streamType);
764 VolumeEvent volumeEvent;
765 volumeEvent.volumeType = streamType;
766 volumeEvent.volume = GetSystemVolumeLevel(streamType);
767 volumeEvent.updateUi = true;
768 volumeEvent.volumeGroupId = 0;
769 volumeEvent.networkId = LOCAL_NETWORK_ID;
770 if (audioPolicyServerHandler_ != nullptr && IsRingerModeMute()) {
771 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
772 }
773 }
774
OnReceiveEvent(const EventFwk::CommonEventData & eventData)775 void AudioVolumeManager::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
776 {
777 AUDIO_INFO_LOG("AudioVolumeManager::OnReceiveEvent enter.");
778 const AAFwk::Want& want = eventData.GetWant();
779 std::string action = want.GetAction();
780 if (action == AUDIO_RESTORE_VOLUME_EVENT) {
781 AUDIO_INFO_LOG("AUDIO_RESTORE_VOLUME_EVENT has been received");
782 std::lock_guard<std::mutex> lock(notifyMutex_);
783 CancelSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
784 restoreNIsShowing_ = false;
785 ChangeDeviceSafeStatus(SAFE_INACTIVE);
786 DealWithEventVolume(RESTORE_VOLUME_NOTIFICATION_ID);
787 SetSafeVolumeCallback(STREAM_MUSIC);
788 } else if (action == AUDIO_INCREASE_VOLUME_EVENT) {
789 AUDIO_INFO_LOG("AUDIO_INCREASE_VOLUME_EVENT has been received");
790 std::lock_guard<std::mutex> lock(notifyMutex_);
791 CancelSafeVolumeNotification(INCREASE_VOLUME_NOTIFICATION_ID);
792 increaseNIsShowing_ = false;
793 ChangeDeviceSafeStatus(SAFE_INACTIVE);
794 DealWithEventVolume(INCREASE_VOLUME_NOTIFICATION_ID);
795 SetSafeVolumeCallback(STREAM_MUSIC);
796 }
797 }
798
SetDeviceSafeVolumeStatus()799 void AudioVolumeManager::SetDeviceSafeVolumeStatus()
800 {
801 if (!userSelect_) {
802 return;
803 }
804
805 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
806 switch (curOutputDeviceType) {
807 case DEVICE_TYPE_BLUETOOTH_A2DP:
808 case DEVICE_TYPE_BLUETOOTH_SCO:
809 safeStatusBt_ = SAFE_INACTIVE;
810 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
811 CreateCheckMusicActiveThread();
812 break;
813 case DEVICE_TYPE_WIRED_HEADSET:
814 case DEVICE_TYPE_WIRED_HEADPHONES:
815 case DEVICE_TYPE_USB_HEADSET:
816 case DEVICE_TYPE_USB_ARM_HEADSET:
817 safeStatus_ = SAFE_INACTIVE;
818 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
819 CreateCheckMusicActiveThread();
820 break;
821 default:
822 AUDIO_INFO_LOG("safeVolume unsupported device:%{public}d", curOutputDeviceType);
823 break;
824 }
825 }
826
ChangeDeviceSafeStatus(SafeStatus safeStatus)827 void AudioVolumeManager::ChangeDeviceSafeStatus(SafeStatus safeStatus)
828 {
829 AUDIO_INFO_LOG("change all support safe volume devices status.");
830
831 safeStatusBt_ = safeStatus;
832 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
833
834 safeStatus_ = safeStatus;
835 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
836
837 CreateCheckMusicActiveThread();
838 }
839
DisableSafeMediaVolume()840 int32_t AudioVolumeManager::DisableSafeMediaVolume()
841 {
842 AUDIO_INFO_LOG("Enter");
843 std::lock_guard<std::mutex> lock(dialogMutex_);
844 userSelect_ = true;
845 isDialogSelectDestroy_.store(true);
846 dialogSelectCondition_.notify_all();
847 SetDeviceSafeVolumeStatus();
848 return SUCCESS;
849 }
850
SetAbsVolumeSceneAsync(const std::string & macAddress,const bool support)851 void AudioVolumeManager::SetAbsVolumeSceneAsync(const std::string &macAddress, const bool support)
852 {
853 usleep(SET_BT_ABS_SCENE_DELAY_MS);
854 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
855 AUDIO_INFO_LOG("success for macAddress:[%{public}s], support: %{public}d, active bt:[%{public}s]",
856 GetEncryptAddr(macAddress).c_str(), support, GetEncryptAddr(btDevice).c_str());
857
858 if (btDevice == macAddress) {
859 audioPolicyManager_.SetAbsVolumeScene(support);
860 SetSharedAbsVolumeScene(support);
861 int32_t volumeLevel = audioPolicyManager_.GetSystemVolumeLevelNoMuteState(STREAM_MUSIC);
862 SetSystemVolumeLevel(STREAM_MUSIC, volumeLevel);
863 }
864 }
865
SetDeviceAbsVolumeSupported(const std::string & macAddress,const bool support)866 int32_t AudioVolumeManager::SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support)
867 {
868 // Maximum number of attempts, preventing situations where a2dp device has not yet finished coming online.
869 int maxRetries = 3;
870 int retryCount = 0;
871 while (retryCount < maxRetries) {
872 retryCount++;
873 if (audioA2dpDevice_.SetA2dpDeviceAbsVolumeSupport(macAddress, support)) {
874 break;
875 }
876 CHECK_AND_RETURN_RET_LOG(retryCount != maxRetries, ERROR,
877 "failed, can't find device for macAddress:[%{public}s]", GetEncryptAddr(macAddress).c_str());;
878 usleep(ABS_VOLUME_SUPPORT_RETRY_INTERVAL_IN_MICROSECONDS);
879 }
880
881 // The delay setting is due to move a2dp sink after this
882 std::thread setAbsSceneThrd(&AudioVolumeManager::SetAbsVolumeSceneAsync, this, macAddress, support);
883 setAbsSceneThrd.detach();
884
885 return SUCCESS;
886 }
887
SetStreamMute(AudioStreamType streamType,bool mute,const StreamUsage & streamUsage,const DeviceType & deviceType)888 int32_t AudioVolumeManager::SetStreamMute(AudioStreamType streamType, bool mute, const StreamUsage &streamUsage,
889 const DeviceType &deviceType)
890 {
891 int32_t result = SUCCESS;
892 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
893 if (deviceType != DEVICE_TYPE_NONE) {
894 AUDIO_INFO_LOG("set stream mute for specified device [%{public}d]", deviceType);
895 curOutputDeviceType = deviceType;
896 }
897 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
898 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
899 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
900 if (audioA2dpDevice_.SetA2dpDeviceMute(btDevice, mute)) {
901 audioPolicyManager_.SetAbsVolumeMute(mute);
902 Volume vol = {false, 1.0f, 0};
903 vol.isMute = mute;
904 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevelNoMuteState(streamType));
905 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType,
906 (mute ? 0 : vol.volumeInt), curOutputDeviceType);
907 SetSharedVolume(streamType, curOutputDeviceType, vol);
908 #ifdef BLUETOOTH_ENABLE
909 // set to avrcp device
910 int32_t volumeLevel;
911 audioA2dpDevice_.GetA2dpDeviceVolumeLevel(btDevice, volumeLevel);
912 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice,
913 volumeLevel);
914 #endif
915 }
916 }
917 result = audioPolicyManager_.SetStreamMute(streamType, mute, streamUsage, curOutputDeviceType);
918
919 Volume vol = {false, 1.0f, 0};
920 vol.isMute = mute;
921 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevelNoMuteState(streamType));
922 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType,
923 (mute ? 0 : vol.volumeInt), curOutputDeviceType);
924 SetSharedVolume(streamType, curOutputDeviceType, vol);
925
926 return result;
927 }
928
GetStreamMute(AudioStreamType streamType) const929 bool AudioVolumeManager::GetStreamMute(AudioStreamType streamType) const
930 {
931 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
932 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
933 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
934 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
935 A2dpDeviceConfigInfo info;
936 bool ret = audioA2dpDevice_.GetA2dpDeviceInfo(btDevice, info);
937 if (ret == false || !info.absVolumeSupport) {
938 AUDIO_WARNING_LOG("Get failed for macAddress:[%{public}s]", GetEncryptAddr(btDevice).c_str());
939 } else {
940 return info.mute;
941 }
942 }
943 return audioPolicyManager_.GetStreamMute(streamType);
944 }
945
UpdateGroupInfo(GroupType type,std::string groupName,int32_t & groupId,std::string networkId,bool connected,int32_t mappingId)946 void AudioVolumeManager::UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId,
947 std::string networkId, bool connected, int32_t mappingId)
948 {
949 ConnectType connectType = CONNECT_TYPE_LOCAL;
950 if (networkId != LOCAL_NETWORK_ID) {
951 connectType = CONNECT_TYPE_DISTRIBUTED;
952 }
953 if (type == GroupType::VOLUME_TYPE) {
954 auto isPresent = [&groupName, &networkId] (const sptr<VolumeGroupInfo> &volumeInfo) {
955 return ((groupName == volumeInfo->groupName_) || (networkId == volumeInfo->networkId_));
956 };
957
958 auto iter = std::find_if(volumeGroups_.begin(), volumeGroups_.end(), isPresent);
959 if (iter != volumeGroups_.end()) {
960 groupId = (*iter)->volumeGroupId_;
961 // if status is disconnected, remove the group that has none audio device
962 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devsInGroup =
963 audioConnectedDevice_.GetDevicesForGroup(type, groupId);
964 if (!connected && devsInGroup.size() == 0) {
965 volumeGroups_.erase(iter);
966 }
967 return;
968 }
969 if (groupName != GROUP_NAME_NONE && connected) {
970 groupId = AudioGroupHandle::GetInstance().GetNextId(type);
971 sptr<VolumeGroupInfo> volumeGroupInfo = new(std::nothrow) VolumeGroupInfo(groupId,
972 mappingId, groupName, networkId, connectType);
973 volumeGroups_.push_back(volumeGroupInfo);
974 }
975 } else {
976 auto isPresent = [&groupName, &networkId] (const sptr<InterruptGroupInfo> &info) {
977 return ((groupName == info->groupName_) || (networkId == info->networkId_));
978 };
979
980 auto iter = std::find_if(interruptGroups_.begin(), interruptGroups_.end(), isPresent);
981 if (iter != interruptGroups_.end()) {
982 groupId = (*iter)->interruptGroupId_;
983 // if status is disconnected, remove the group that has none audio device
984 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devsInGroup =
985 audioConnectedDevice_.GetDevicesForGroup(type, groupId);
986 if (!connected && devsInGroup.size() == 0) {
987 interruptGroups_.erase(iter);
988 }
989 return;
990 }
991 if (groupName != GROUP_NAME_NONE && connected) {
992 groupId = AudioGroupHandle::GetInstance().GetNextId(type);
993 sptr<InterruptGroupInfo> interruptGroupInfo = new(std::nothrow) InterruptGroupInfo(groupId, mappingId,
994 groupName, networkId, connectType);
995 interruptGroups_.push_back(interruptGroupInfo);
996 }
997 }
998 }
999
GetVolumeGroupInfo(std::vector<sptr<VolumeGroupInfo>> & volumeGroupInfos)1000 void AudioVolumeManager::GetVolumeGroupInfo(std::vector<sptr<VolumeGroupInfo>>& volumeGroupInfos)
1001 {
1002 for (auto& v : volumeGroups_) {
1003 sptr<VolumeGroupInfo> info = new(std::nothrow) VolumeGroupInfo(v->volumeGroupId_, v->mappingId_, v->groupName_,
1004 v->networkId_, v->connectType_);
1005 volumeGroupInfos.push_back(info);
1006 }
1007 }
1008
DealWithEventVolume(const int32_t notificationId)1009 int32_t AudioVolumeManager::DealWithEventVolume(const int32_t notificationId)
1010 {
1011 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1012 int32_t restoreVolume = 0;
1013 const int32_t ONE_VOLUME_LEVEL = 1;
1014 int32_t safeVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
1015 int32_t ret = 0;
1016 bool isRestoreFlag = false;
1017 if (IsBlueTooth(curOutputDeviceType)) {
1018 switch (notificationId) {
1019 case RESTORE_VOLUME_NOTIFICATION_ID:
1020 restoreVolume = audioPolicyManager_.GetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP);
1021 isRestoreFlag = restoreVolume > safeVolumeLevel ? true : false;
1022 ret = isRestoreFlag ? SetSystemVolumeLevel(STREAM_MUSIC, restoreVolume) : ERROR;
1023 break;
1024 case INCREASE_VOLUME_NOTIFICATION_ID:
1025 ret = SetSystemVolumeLevel(STREAM_MUSIC, safeVolumeLevel + ONE_VOLUME_LEVEL);
1026 break;
1027 default:
1028 AUDIO_ERR_LOG("current state unsupport safe volume");
1029 }
1030 } else if (IsWiredHeadSet(curOutputDeviceType)) {
1031 switch (notificationId) {
1032 case RESTORE_VOLUME_NOTIFICATION_ID:
1033 restoreVolume = audioPolicyManager_.GetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET);
1034 isRestoreFlag = restoreVolume > safeVolumeLevel ? true : false;
1035 ret = isRestoreFlag ? SetSystemVolumeLevel(STREAM_MUSIC, restoreVolume) : ERROR;
1036 break;
1037 case INCREASE_VOLUME_NOTIFICATION_ID:
1038 ret = SetSystemVolumeLevel(STREAM_MUSIC, safeVolumeLevel + ONE_VOLUME_LEVEL);
1039 break;
1040 default:
1041 AUDIO_ERR_LOG("current state unsupport safe volume");
1042 }
1043 } else {
1044 AUDIO_ERR_LOG("current output device unsupport safe volume");
1045 ret = ERROR;
1046 }
1047 return ret;
1048 }
1049
ResetRingerModeMute()1050 int32_t AudioVolumeManager::ResetRingerModeMute()
1051 {
1052 if (audioPolicyManager_.SetStreamMute(STREAM_RING, true) == SUCCESS) {
1053 SetRingerModeMute(true);
1054 }
1055 return SUCCESS;
1056 }
1057
IsRingerModeMute()1058 bool AudioVolumeManager::IsRingerModeMute()
1059 {
1060 return ringerModeMute_.load();
1061 }
1062
SetRingerModeMute(bool flag)1063 void AudioVolumeManager::SetRingerModeMute(bool flag)
1064 {
1065 AUDIO_INFO_LOG("Set RingerModeMute_: %{public}d", flag);
1066 ringerModeMute_.store(flag);
1067 }
1068
GetVolumeGroupInfosNotWait(std::vector<sptr<VolumeGroupInfo>> & infos)1069 bool AudioVolumeManager::GetVolumeGroupInfosNotWait(std::vector<sptr<VolumeGroupInfo>> &infos)
1070 {
1071 if (!isPrimaryMicModuleInfoLoaded_) {
1072 return false;
1073 }
1074
1075 GetVolumeGroupInfo(infos);
1076 return true;
1077 }
1078
SetDefaultDeviceLoadFlag(bool isLoad)1079 void AudioVolumeManager::SetDefaultDeviceLoadFlag(bool isLoad)
1080 {
1081 isPrimaryMicModuleInfoLoaded_.store(isLoad);
1082 }
1083
GetLoadFlag()1084 bool AudioVolumeManager::GetLoadFlag()
1085 {
1086 return isPrimaryMicModuleInfoLoaded_.load();
1087 }
1088
NotifyVolumeGroup()1089 void AudioVolumeManager::NotifyVolumeGroup()
1090 {
1091 std::lock_guard<std::mutex> lock(defaultDeviceLoadMutex_);
1092 SetDefaultDeviceLoadFlag(true);
1093 }
1094
UpdateSafeVolumeByS4()1095 void AudioVolumeManager::UpdateSafeVolumeByS4()
1096 {
1097 AUDIO_INFO_LOG("Reset isBtFirstBoot by S4 reboot");
1098 isBtFirstBoot_ = true;
1099 return audioPolicyManager_.UpdateSafeVolumeByS4();
1100 }
1101
1102 }
1103 }
1104