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_inner_call.h"
26 #include "media_monitor_manager.h"
27 #include "i_policy_provider.h"
28 #include "audio_spatialization_service.h"
29 #include "audio_safe_volume_notification.h"
30
31 #include "audio_server_proxy.h"
32 #include "audio_policy_utils.h"
33 #include "sle_audio_device_manager.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 constexpr int32_t CANCEL_FORCE_CONTROL_VOLUME_TYPE = -1;
59
60 static const std::vector<AudioVolumeType> VOLUME_TYPE_LIST = {
61 STREAM_VOICE_CALL,
62 STREAM_RING,
63 STREAM_MUSIC,
64 STREAM_VOICE_ASSISTANT,
65 STREAM_ALARM,
66 STREAM_ACCESSIBILITY,
67 STREAM_ULTRASONIC,
68 STREAM_SYSTEM,
69 STREAM_VOICE_CALL_ASSISTANT,
70 STREAM_ALL
71 };
72
73 static const std::vector<AudioStreamType> AUDIO_STREAMTYPE_VOLUME_LIST = {
74 STREAM_MUSIC,
75 STREAM_RING,
76 STREAM_SYSTEM,
77 STREAM_NOTIFICATION,
78 STREAM_ALARM,
79 STREAM_DTMF,
80 STREAM_VOICE_CALL,
81 STREAM_VOICE_ASSISTANT,
82 STREAM_ACCESSIBILITY,
83 STREAM_ULTRASONIC,
84 STREAM_WAKEUP,
85 };
86
Init(std::shared_ptr<AudioPolicyServerHandler> audioPolicyServerHandler)87 bool AudioVolumeManager::Init(std::shared_ptr<AudioPolicyServerHandler> audioPolicyServerHandler)
88 {
89 audioPolicyServerHandler_ = audioPolicyServerHandler;
90 if (policyVolumeMap_ == nullptr) {
91 size_t mapSize = IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume) + sizeof(bool);
92 AUDIO_INFO_LOG("InitSharedVolume create shared volume map with size %{public}zu", mapSize);
93 policyVolumeMap_ = AudioSharedMemory::CreateFormLocal(mapSize, "PolicyVolumeMap");
94 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
95 false, "Get shared memory failed!");
96 volumeVector_ = reinterpret_cast<Volume *>(policyVolumeMap_->GetBase());
97 sharedAbsVolumeScene_ = reinterpret_cast<bool *>(policyVolumeMap_->GetBase()) +
98 IPolicyProvider::GetVolumeVectorSize() * sizeof(Volume);
99 }
100 if (forceControlVolumeTypeMonitor_ == nullptr) {
101 forceControlVolumeTypeMonitor_ = std::make_shared<ForceControlVolumeTypeMonitor>();
102 }
103 return true;
104 }
DeInit(void)105 void AudioVolumeManager::DeInit(void)
106 {
107 volumeVector_ = nullptr;
108 sharedAbsVolumeScene_ = nullptr;
109 policyVolumeMap_ = nullptr;
110 safeVolumeExit_ = true;
111 forceControlVolumeTypeMonitor_ = nullptr;
112 if (calculateLoopSafeTime_ != nullptr && calculateLoopSafeTime_->joinable()) {
113 calculateLoopSafeTime_->join();
114 calculateLoopSafeTime_.reset();
115 calculateLoopSafeTime_ = nullptr;
116 }
117 if (safeVolumeDialogThrd_ != nullptr && safeVolumeDialogThrd_->joinable()) {
118 safeVolumeDialogThrd_->join();
119 safeVolumeDialogThrd_.reset();
120 safeVolumeDialogThrd_ = nullptr;
121 }
122 audioPolicyServerHandler_ = nullptr;
123 }
124
GetMaxVolumeLevel(AudioVolumeType volumeType,DeviceType deviceType) const125 int32_t AudioVolumeManager::GetMaxVolumeLevel(AudioVolumeType volumeType, DeviceType deviceType) const
126 {
127 if (volumeType == STREAM_ALL) {
128 volumeType = STREAM_MUSIC;
129 }
130 return audioPolicyManager_.GetMaxVolumeLevel(volumeType, deviceType);
131 }
132
GetMinVolumeLevel(AudioVolumeType volumeType,DeviceType deviceType) const133 int32_t AudioVolumeManager::GetMinVolumeLevel(AudioVolumeType volumeType, DeviceType deviceType) const
134 {
135 if (volumeType == STREAM_ALL) {
136 volumeType = STREAM_MUSIC;
137 }
138 return audioPolicyManager_.GetMinVolumeLevel(volumeType, deviceType);
139 }
140
SetSharedVolume(AudioVolumeType streamType,DeviceType deviceType,Volume vol)141 bool AudioVolumeManager::SetSharedVolume(AudioVolumeType streamType, DeviceType deviceType, Volume vol)
142 {
143 CHECK_AND_RETURN_RET_LOG(volumeVector_ != nullptr, false, "Set shared memory failed!");
144 size_t index = 0;
145 if (!IPolicyProvider::GetVolumeIndex(streamType, GetVolumeGroupForDevice(deviceType), index) ||
146 index >= IPolicyProvider::GetVolumeVectorSize()) {
147 AUDIO_INFO_LOG("not find device %{public}d, stream %{public}d", deviceType, streamType);
148 return false;
149 }
150 if (deviceType == DEVICE_TYPE_NEARLINK && streamType == STREAM_VOICE_CALL) {
151 vol.volumeFloat = 1.0f;
152 }
153 volumeVector_[index].isMute = vol.isMute;
154 volumeVector_[index].volumeFloat = vol.volumeFloat;
155 volumeVector_[index].volumeInt = vol.volumeInt;
156 volumeVector_[index].volumeDegree = vol.volumeDegree;
157 AUDIO_INFO_LOG("Success Set Shared Volume with StreamType:%{public}d, DeviceType:%{public}d, \
158 volume:%{public}d, volumeDegree:%{public}d",
159 streamType, deviceType, vol.volumeInt, vol.volumeDegree);
160
161 AudioServerProxy::GetInstance().NotifyStreamVolumeChangedProxy(streamType, vol.volumeFloat);
162 return true;
163 }
164
InitSharedVolume(std::shared_ptr<AudioSharedMemory> & buffer)165 int32_t AudioVolumeManager::InitSharedVolume(std::shared_ptr<AudioSharedMemory> &buffer)
166 {
167 AUDIO_INFO_LOG("InitSharedVolume start");
168 CHECK_AND_RETURN_RET_LOG(policyVolumeMap_ != nullptr && policyVolumeMap_->GetBase() != nullptr,
169 ERR_OPERATION_FAILED, "Get shared memory failed!");
170
171 // init volume map
172 // todo device
173 for (size_t i = 0; i < IPolicyProvider::GetVolumeVectorSize(); i++) {
174 bool isMute = audioPolicyManager_.GetStreamMute(g_volumeIndexVector[i].first);
175 int32_t currentVolumeLevel = audioPolicyManager_.GetSystemVolumeLevelNoMuteState(g_volumeIndexVector[i].first);
176 float volFloat = audioPolicyManager_.GetSystemVolumeInDb(g_volumeIndexVector[i].first,
177 (isMute ? 0 : currentVolumeLevel), audioActiveDevice_.GetCurrentOutputDeviceType());
178 volumeVector_[i].isMute = isMute;
179 volumeVector_[i].volumeFloat = volFloat;
180 volumeVector_[i].volumeInt = static_cast<uint32_t>(currentVolumeLevel);
181 }
182 SetSharedAbsVolumeScene(false);
183 buffer = policyVolumeMap_;
184
185 return SUCCESS;
186 }
187
SetSharedAbsVolumeScene(const bool support)188 void AudioVolumeManager::SetSharedAbsVolumeScene(const bool support)
189 {
190 CHECK_AND_RETURN_LOG(sharedAbsVolumeScene_ != nullptr, "sharedAbsVolumeScene is nullptr");
191 *sharedAbsVolumeScene_ = support;
192 }
193
GetAppVolumeLevel(int32_t appUid,int32_t & volumeLevel)194 int32_t AudioVolumeManager::GetAppVolumeLevel(int32_t appUid, int32_t &volumeLevel)
195 {
196 return audioPolicyManager_.GetAppVolumeLevel(appUid, volumeLevel);
197 }
198
GetSystemVolumeLevel(AudioStreamType streamType,int32_t zoneId)199 int32_t AudioVolumeManager::GetSystemVolumeLevel(AudioStreamType streamType, int32_t zoneId)
200 {
201 if (zoneId > 0) {
202 return audioPolicyManager_.GetZoneVolumeLevel(zoneId, streamType);
203 }
204 if (streamType == STREAM_RING && !IsRingerModeMute()) {
205 AUDIO_PRERELEASE_LOGW("return 0 when dual tone ring");
206 return DUAL_TONE_RING_VOLUME;
207 }
208 auto volumeType = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
209 {
210 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
211 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
212 if (volumeType == STREAM_MUSIC &&
213 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
214 A2dpDeviceConfigInfo info;
215 bool ret = audioA2dpDevice_.GetA2dpDeviceInfo(btDevice, info);
216 if (ret && info.absVolumeSupport) {
217 return info.mute ? 0 : info.volumeLevel;
218 }
219 }
220 }
221 auto deviceDesc = audioActiveDevice_.GetCurrentOutputDevice();
222 if (deviceDesc.deviceType_ == DEVICE_TYPE_NEARLINK &&
223 (volumeType == STREAM_MUSIC || volumeType == STREAM_VOICE_CALL)) {
224 return SleAudioDeviceManager::GetInstance().GetVolumeLevelByVolumeType(volumeType, deviceDesc);
225 }
226 int32_t volume = audioPolicyManager_.GetSystemVolumeLevel(streamType);
227 Trace trace("AudioVolumeManager::GetSystemVolumeLevel device" + std::to_string(deviceDesc.deviceType_) + " stream "
228 + std::to_string(streamType) + " volume " + std::to_string(volume));
229 return volume;
230 }
231
GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)232 int32_t AudioVolumeManager::GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)
233 {
234 return audioPolicyManager_.GetSystemVolumeLevelNoMuteState(streamType);
235 }
236
SetVolumeForSwitchDevice(AudioDeviceDescriptor deviceDescriptor,const std::string & newSinkName,bool enableSetVoiceCallVolume)237 int32_t AudioVolumeManager::SetVolumeForSwitchDevice(AudioDeviceDescriptor deviceDescriptor,
238 const std::string &newSinkName, bool enableSetVoiceCallVolume)
239 {
240 Trace trace("AudioVolumeManager::SetVolumeForSwitchDevice:" + std::to_string(deviceDescriptor.deviceType_));
241 // Load volume from KvStore and set volume for each stream type
242 audioPolicyManager_.SetVolumeForSwitchDevice(deviceDescriptor);
243
244 // The volume of voice_call needs to be adjusted separately
245 if (enableSetVoiceCallVolume && audioSceneManager_.GetAudioScene(true) == AUDIO_SCENE_PHONE_CALL) {
246 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
247 }
248 return SUCCESS;
249 }
250
SetVoiceRingtoneMute(bool isMute)251 int32_t AudioVolumeManager::SetVoiceRingtoneMute(bool isMute)
252 {
253 isVoiceRingtoneMute_ = isMute ? true : false;
254 SetVoiceCallVolume(GetSystemVolumeLevel(STREAM_VOICE_CALL));
255 return SUCCESS;
256 }
257
SetVoiceCallVolume(int32_t volumeLevel)258 void AudioVolumeManager::SetVoiceCallVolume(int32_t volumeLevel)
259 {
260 Trace trace("AudioVolumeManager::SetVoiceCallVolume" + std::to_string(volumeLevel));
261 // set voice volume by the interface from hdi.
262 CHECK_AND_RETURN_LOG(volumeLevel != 0, "SetVoiceVolume: volume of voice_call cannot be set to 0");
263 float volumeDb = static_cast<float>(volumeLevel) /
264 static_cast<float>(audioPolicyManager_.GetMaxVolumeLevel(STREAM_VOICE_CALL));
265 volumeDb = isVoiceRingtoneMute_ ? 0 : volumeDb;
266 if (audioActiveDevice_.GetCurrentOutputDeviceType() == DEVICE_TYPE_NEARLINK) {
267 volumeDb = 1;
268 }
269 AudioServerProxy::GetInstance().SetVoiceVolumeProxy(volumeDb);
270 AUDIO_INFO_LOG("%{public}f", volumeDb);
271 }
272
InitKVStore()273 void AudioVolumeManager::InitKVStore()
274 {
275 audioPolicyManager_.InitKVStore();
276 AudioSpatializationService::GetAudioSpatializationService().InitSpatializationState();
277 }
278
CheckToCloseNotification(AudioStreamType streamType,int32_t volumeLevel)279 void AudioVolumeManager::CheckToCloseNotification(AudioStreamType streamType, int32_t volumeLevel)
280 {
281 AUDIO_INFO_LOG("enter.");
282 int32_t sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
283 if (volumeLevel < sVolumeLevel && DeviceIsSupportSafeVolume() &&
284 VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC) {
285 AUDIO_INFO_LOG("user select lower volume should close notification.");
286 if (increaseNIsShowing_) {
287 CancelSafeVolumeNotification(INCREASE_VOLUME_NOTIFICATION_ID);
288 increaseNIsShowing_ = false;
289 }
290 if (restoreNIsShowing_) {
291 CancelSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
292 restoreNIsShowing_ = false;
293 }
294 }
295 }
296
DeviceIsSupportSafeVolume()297 bool AudioVolumeManager::DeviceIsSupportSafeVolume()
298 {
299 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
300 DeviceCategory curOutputDeviceCategory = audioPolicyManager_.GetCurrentOutputDeviceCategory();
301 switch (curOutputDeviceType) {
302 case DEVICE_TYPE_BLUETOOTH_A2DP:
303 case DEVICE_TYPE_BLUETOOTH_SCO:
304 if (curOutputDeviceCategory != BT_SOUNDBOX &&
305 curOutputDeviceCategory != BT_CAR) {
306 return true;
307 }
308 [[fallthrough]];
309 case DEVICE_TYPE_WIRED_HEADSET:
310 case DEVICE_TYPE_WIRED_HEADPHONES:
311 case DEVICE_TYPE_USB_HEADSET:
312 case DEVICE_TYPE_USB_ARM_HEADSET:
313 return true;
314 default:
315 AUDIO_INFO_LOG("current device unsupport safe volume:%{public}d", curOutputDeviceType);
316 return false;
317 }
318 }
319
SetAppVolumeLevel(int32_t appUid,int32_t volumeLevel)320 int32_t AudioVolumeManager::SetAppVolumeLevel(int32_t appUid, int32_t volumeLevel)
321 {
322 AUDIO_INFO_LOG("enter AudioVolumeManager::SetAppVolumeLevel");
323 // audioPolicyManager_ : AudioAdapterManager
324 int32_t result = audioPolicyManager_.SetAppVolumeLevel(appUid, volumeLevel);
325 return result;
326 }
327
SetAppVolumeMuted(int32_t appUid,bool muted)328 int32_t AudioVolumeManager::SetAppVolumeMuted(int32_t appUid, bool muted)
329 {
330 AUDIO_INFO_LOG("enter AudioVolumeManager::SetAppVolumeMuted");
331 int32_t result = audioPolicyManager_.SetAppVolumeMuted(appUid, muted);
332 return result;
333 }
334
IsAppVolumeMute(int32_t appUid,bool owned,bool & isMute)335 int32_t AudioVolumeManager::IsAppVolumeMute(int32_t appUid, bool owned, bool &isMute)
336 {
337 AUDIO_INFO_LOG("enter AudioVolumeManager::IsAppVolumeMute");
338 int32_t result = audioPolicyManager_.IsAppVolumeMute(appUid, owned, isMute);
339 return result;
340 }
341
SetAppRingMuted(int32_t appUid,bool muted)342 int32_t AudioVolumeManager::SetAppRingMuted(int32_t appUid, bool muted)
343 {
344 AUDIO_INFO_LOG("enter AudioVolumeManager::SetAppRingMuted");
345 int32_t result = audioPolicyManager_.SetAppRingMuted(appUid, muted);
346 return result;
347 }
348
IsAppRingMuted(int32_t appUid)349 bool AudioVolumeManager::IsAppRingMuted(int32_t appUid)
350 {
351 AUDIO_INFO_LOG("enter AudioVolumeManager::IsAppRingMuted");
352 return audioPolicyManager_.IsAppRingMuted(appUid);
353 }
354
GetVolumeAdjustZoneId()355 int32_t AudioVolumeManager::GetVolumeAdjustZoneId()
356 {
357 return audioPolicyManager_.GetVolumeAdjustZoneId();
358 }
359
SetAdjustVolumeForZone(int32_t zoneId)360 int32_t AudioVolumeManager::SetAdjustVolumeForZone(int32_t zoneId)
361 {
362 if (zoneId == 0) {
363 AudioDeviceDescriptor currentActiveDevice = audioActiveDevice_.GetCurrentOutputDevice();
364 audioPolicyManager_.SetVolumeForSwitchDevice(currentActiveDevice);
365 }
366 return audioPolicyManager_.SetAdjustVolumeForZone(zoneId);
367 }
368
HandleA2dpAbsVolume(AudioStreamType streamType,int32_t volumeLevel,DeviceType curOutputDeviceType)369 int32_t AudioVolumeManager::HandleA2dpAbsVolume(AudioStreamType streamType, int32_t volumeLevel,
370 DeviceType curOutputDeviceType)
371 {
372 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
373 int32_t result = SetA2dpDeviceVolume(btDevice, volumeLevel, true);
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 #ifdef BLUETOOTH_ENABLE
380 if (result == SUCCESS) {
381 // set to avrcp device
382 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice, volumeLevel);
383 } else if (result == ERR_UNKNOWN) {
384 AUDIO_INFO_LOG("UNKNOWN RESULT set abs safe volume");
385 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice,
386 audioPolicyManager_.GetSafeVolumeLevel());
387 } else {
388 AUDIO_ERR_LOG("AudioVolumeManager::SetSystemVolumeLevel set abs volume failed");
389 }
390 return result;
391 #else
392 return SUCCESS;
393 #endif
394 }
395
HandleNearlinkDeviceAbsVolume(AudioStreamType streamType,int32_t volumeLevel,DeviceType curOutputDeviceType)396 int32_t AudioVolumeManager::HandleNearlinkDeviceAbsVolume(AudioStreamType streamType, int32_t volumeLevel,
397 DeviceType curOutputDeviceType)
398 {
399 std::string nearlinkDevice = audioActiveDevice_.GetCurrentOutputDeviceMacAddr();
400 if (nearlinkDevice.empty()) {
401 AUDIO_ERR_LOG("nearlink device is empty");
402 return ERR_UNKNOWN;
403 }
404
405 Volume vol = {false, 1.0f, 0};
406 vol.isMute = volumeLevel == 0 ? true : false;
407 vol.volumeInt = static_cast<uint32_t>(volumeLevel);
408 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType);
409 SetSharedVolume(streamType, curOutputDeviceType, vol);
410
411 int32_t result = SetNearlinkDeviceVolume(nearlinkDevice, streamType, volumeLevel, true);
412 if (result == SUCCESS) {
413 auto volumeValue = SleAudioDeviceManager::GetInstance().GetVolumeLevelByVolumeType(streamType,
414 audioActiveDevice_.GetCurrentOutputDevice());
415 return SleAudioDeviceManager::GetInstance().SetDeviceAbsVolume(nearlinkDevice, streamType, volumeValue);
416 } else if (result == ERR_UNKNOWN) {
417 AUDIO_INFO_LOG("UNKNOWN RESULT set abs safe volume");
418 return SleAudioDeviceManager::GetInstance().SetDeviceAbsVolume(nearlinkDevice, streamType,
419 audioPolicyManager_.GetSafeVolumeLevel());
420 }
421 return result;
422 }
423
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel,int32_t zoneId)424 int32_t AudioVolumeManager::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel,
425 int32_t zoneId)
426 {
427 if (zoneId > 0) {
428 return audioPolicyManager_.SetZoneVolumeLevel(zoneId,
429 VolumeUtils::GetVolumeTypeFromStreamType(streamType), volumeLevel);
430 }
431 int32_t result = ERROR;
432 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
433 curOutputDeviceType_ = curOutputDeviceType;
434 auto volumeType = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
435 if (volumeType == STREAM_MUSIC &&
436 streamType != STREAM_VOICE_CALL &&
437 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
438 result = HandleA2dpAbsVolume(streamType, volumeLevel, curOutputDeviceType);
439 }
440
441 if (curOutputDeviceType == DEVICE_TYPE_NEARLINK &&
442 (volumeType == STREAM_MUSIC || volumeType == STREAM_VOICE_CALL)) {
443 result = HandleNearlinkDeviceAbsVolume(streamType, volumeLevel, curOutputDeviceType);
444 }
445
446 if (result == SUCCESS) {
447 return result;
448 }
449
450 int32_t sVolumeLevel = SelectDealSafeVolume(streamType, volumeLevel);
451 CheckToCloseNotification(streamType, volumeLevel);
452 if (volumeLevel != sVolumeLevel) {
453 volumeLevel = sVolumeLevel;
454 AUDIO_INFO_LOG("safevolume did not deal");
455 }
456 result = audioPolicyManager_.SetSystemVolumeLevel(VolumeUtils::GetVolumeTypeFromStreamType(streamType),
457 volumeLevel);
458 if (result == SUCCESS && (streamType == STREAM_VOICE_CALL || streamType == STREAM_VOICE_COMMUNICATION)) {
459 SetVoiceCallVolume(volumeLevel);
460 }
461 // todo
462 Volume vol = {false, 1.0f, 0};
463 vol.isMute = volumeLevel == 0 ? true : false;
464 vol.volumeInt = static_cast<uint32_t>(volumeLevel);
465 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType, volumeLevel, curOutputDeviceType);
466 SetSharedVolume(streamType, curOutputDeviceType, vol);
467 return result;
468 }
469
SaveSpecifiedDeviceVolume(AudioStreamType streamType,int32_t volumeLevel,DeviceType deviceType)470 int32_t AudioVolumeManager::SaveSpecifiedDeviceVolume(AudioStreamType streamType, int32_t volumeLevel,
471 DeviceType deviceType)
472 {
473 int32_t sVolumeLevel = volumeLevel;
474 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP || deviceType == DEVICE_TYPE_BLUETOOTH_SCO ||
475 deviceType == DEVICE_TYPE_USB_HEADSET || deviceType == DEVICE_TYPE_USB_ARM_HEADSET ||
476 deviceType == DEVICE_TYPE_WIRED_HEADSET || deviceType == DEVICE_TYPE_WIRED_HEADPHONES ||
477 deviceType == DEVICE_TYPE_NEARLINK) {
478 sVolumeLevel = SelectDealSafeVolume(streamType, volumeLevel, deviceType);
479 }
480 int32_t result = audioPolicyManager_.SaveSpecifiedDeviceVolume(
481 VolumeUtils::GetVolumeTypeFromStreamType(streamType), sVolumeLevel, deviceType);
482 return result;
483 }
484
SelectDealSafeVolume(AudioStreamType streamType,int32_t volumeLevel,DeviceType deviceType)485 int32_t AudioVolumeManager::SelectDealSafeVolume(AudioStreamType streamType, int32_t volumeLevel,
486 DeviceType deviceType)
487 {
488 int32_t sVolumeLevel = volumeLevel;
489 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) != STREAM_MUSIC) {
490 // Safe Volume only applying to STREAM_MUSIC
491 return sVolumeLevel;
492 }
493 DeviceType curOutputDeviceType = (deviceType == DEVICE_TYPE_NONE) ?
494 audioActiveDevice_.GetCurrentOutputDeviceType() : deviceType;
495 DeviceCategory curOutputDeviceCategory = audioPolicyManager_.GetCurrentOutputDeviceCategory();
496 if (sVolumeLevel > audioPolicyManager_.GetSafeVolumeLevel()) {
497 switch (curOutputDeviceType) {
498 case DEVICE_TYPE_BLUETOOTH_A2DP:
499 case DEVICE_TYPE_BLUETOOTH_SCO:
500 case DEVICE_TYPE_NEARLINK:
501 if (curOutputDeviceCategory == BT_SOUNDBOX || curOutputDeviceCategory == BT_CAR) {
502 return sVolumeLevel;
503 }
504 if (isBtFirstBoot_) {
505 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
506 AUDIO_INFO_LOG("Btfirstboot set volume use safe volume");
507 } else {
508 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
509 }
510 break;
511 case DEVICE_TYPE_WIRED_HEADSET:
512 case DEVICE_TYPE_WIRED_HEADPHONES:
513 case DEVICE_TYPE_USB_HEADSET:
514 case DEVICE_TYPE_USB_ARM_HEADSET:
515 sVolumeLevel = DealWithSafeVolume(volumeLevel, false);
516 break;
517 default:
518 AUDIO_INFO_LOG("unsupport safe volume:%{public}d", curOutputDeviceType);
519 break;
520 }
521 }
522 if (curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP || curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_SCO ||
523 curOutputDeviceType == DEVICE_TYPE_NEARLINK) {
524 isBtFirstBoot_ = false;
525 }
526 return sVolumeLevel;
527 }
528
SetA2dpDeviceVolume(const std::string & macAddress,const int32_t volumeLevel,bool internalCall)529 int32_t AudioVolumeManager::SetA2dpDeviceVolume(const std::string &macAddress, const int32_t volumeLevel,
530 bool internalCall)
531 {
532 if (audioA2dpDevice_.SetA2dpDeviceVolumeLevel(macAddress, volumeLevel) == false) {
533 return ERROR;
534 }
535 int32_t sVolumeLevel = volumeLevel;
536 if (volumeLevel > audioPolicyManager_.GetSafeVolumeLevel()) {
537 if (internalCall) {
538 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
539 } else {
540 sVolumeLevel = HandleAbsBluetoothVolume(macAddress, volumeLevel);
541 }
542 }
543 isBtFirstBoot_ = false;
544 if (audioA2dpDevice_.SetA2dpDeviceVolumeLevel(macAddress, sVolumeLevel) == false) {
545 return ERROR;
546 }
547 bool mute = sVolumeLevel == 0 ? true : false;
548
549 if (internalCall) {
550 CheckToCloseNotification(STREAM_MUSIC, volumeLevel);
551 }
552
553 audioA2dpDevice_.SetA2dpDeviceMute(macAddress, mute);
554 audioPolicyManager_.SetAbsVolumeMute(mute);
555 AUDIO_INFO_LOG("success for macaddress:[%{public}s], volume value:[%{public}d]",
556 GetEncryptAddr(macAddress).c_str(), sVolumeLevel);
557 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERR_UNKNOWN, "safevolume did not deal");
558 return SUCCESS;
559 }
560
HandleAbsBluetoothVolume(const std::string & macAddress,const int32_t volumeLevel,bool isNearlinkDevice,AudioStreamType streamType)561 int32_t AudioVolumeManager::HandleAbsBluetoothVolume(const std::string &macAddress, const int32_t volumeLevel,
562 bool isNearlinkDevice, AudioStreamType streamType)
563 {
564 int32_t sVolumeLevel = 0;
565 if (isBtFirstBoot_) {
566 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
567 AUDIO_INFO_LOG("Btfirstboot set volume use safe volume");
568 isBtFirstBoot_ = false;
569 if (!isNearlinkDevice) {
570 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel);
571 } else {
572 SleAudioDeviceManager::GetInstance().SetDeviceAbsVolume(macAddress, streamType, sVolumeLevel);
573 }
574 } else {
575 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
576 if (sVolumeLevel != volumeLevel) {
577 if (!isNearlinkDevice) {
578 Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(macAddress, sVolumeLevel);
579 } else {
580 SleAudioDeviceManager::GetInstance().SetDeviceAbsVolume(macAddress, streamType, sVolumeLevel);
581 }
582 }
583 }
584 return sVolumeLevel;
585 }
586
SetNearlinkDeviceVolume(const std::string & macAddress,AudioStreamType streamType,int32_t volumeLevel,bool internalCall)587 int32_t AudioVolumeManager::SetNearlinkDeviceVolume(const std::string &macAddress, AudioStreamType streamType,
588 int32_t volumeLevel, bool internalCall)
589 {
590 int32_t ret = SleAudioDeviceManager::GetInstance().SetNearlinkDeviceVolumeLevel(macAddress, streamType,
591 volumeLevel);
592 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "SetNearlinkDeviceVolumeLevel failed");
593 int32_t sVolumeLevel = volumeLevel;
594 // Voice call does not support safe volume
595 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC) {
596 if (volumeLevel > audioPolicyManager_.GetSafeVolumeLevel()) {
597 if (internalCall) {
598 sVolumeLevel = DealWithSafeVolume(volumeLevel, true);
599 } else {
600 sVolumeLevel = HandleAbsBluetoothVolume(macAddress, volumeLevel, true, streamType);
601 }
602 }
603 isBtFirstBoot_ = false;
604 }
605 ret = SleAudioDeviceManager::GetInstance().SetNearlinkDeviceVolumeLevel(macAddress, streamType, sVolumeLevel);
606 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "SetDeviceAbsVolume failed");
607 ret = audioPolicyManager_.SetSystemVolumeLevel(VolumeUtils::GetVolumeTypeFromStreamType(streamType),
608 sVolumeLevel);
609 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERROR, "SetSystemVolumeLevel failed");
610
611 bool mute = sVolumeLevel == 0 && (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC);
612
613 if (internalCall) {
614 CheckToCloseNotification(streamType, volumeLevel);
615 }
616
617 SleAudioDeviceManager::GetInstance().SetNearlinkDeviceMute(macAddress, streamType, mute);
618 audioPolicyManager_.SetAbsVolumeMute(mute);
619 AUDIO_INFO_LOG("success for macaddress:[%{public}s], volume value:[%{public}d], streamType [%{public}d]",
620 GetEncryptAddr(macAddress).c_str(), sVolumeLevel, streamType);
621 CHECK_AND_RETURN_RET_LOG(sVolumeLevel == volumeLevel, ERR_UNKNOWN, "safevolume did not deal");
622 return SUCCESS;
623 }
624
PublishSafeVolumeNotification(int32_t notificationId)625 void AudioVolumeManager::PublishSafeVolumeNotification(int32_t notificationId)
626 {
627 void *libHandle = dlopen("libaudio_safe_volume_notification_impl.z.so", RTLD_LAZY);
628 if (libHandle == nullptr) {
629 AUDIO_ERR_LOG("dlopen failed %{public}s", __func__);
630 return;
631 }
632 CreateSafeVolumeNotification *createSafeVolumeNotificationImpl =
633 reinterpret_cast<CreateSafeVolumeNotification*>(dlsym(libHandle, "CreateSafeVolumeNotificationImpl"));
634 if (createSafeVolumeNotificationImpl == nullptr) {
635 AUDIO_ERR_LOG("createSafeVolumeNotificationImpl failed %{public}s", __func__);
636 #ifndef TEST_COVERAGE
637 dlclose(libHandle);
638 #endif
639 return;
640 }
641 AudioSafeVolumeNotification *audioSafeVolumeNotificationImpl = createSafeVolumeNotificationImpl();
642 if (audioSafeVolumeNotificationImpl == nullptr) {
643 AUDIO_ERR_LOG("audioSafeVolumeNotificationImpl is nullptr %{public}s", __func__);
644 #ifndef TEST_COVERAGE
645 dlclose(libHandle);
646 #endif
647 return;
648 }
649 audioSafeVolumeNotificationImpl->PublishSafeVolumeNotification(notificationId);
650 delete audioSafeVolumeNotificationImpl;
651 #ifndef TEST_COVERAGE
652 dlclose(libHandle);
653 #endif
654 }
655
CancelSafeVolumeNotification(int32_t notificationId)656 void AudioVolumeManager::CancelSafeVolumeNotification(int32_t notificationId)
657 {
658 void *libHandle = dlopen("libaudio_safe_volume_notification_impl.z.so", RTLD_LAZY);
659 if (libHandle == nullptr) {
660 AUDIO_ERR_LOG("dlopen failed %{public}s", __func__);
661 return;
662 }
663 CreateSafeVolumeNotification *createSafeVolumeNotificationImpl =
664 reinterpret_cast<CreateSafeVolumeNotification*>(dlsym(libHandle, "CreateSafeVolumeNotificationImpl"));
665 if (createSafeVolumeNotificationImpl == nullptr) {
666 AUDIO_ERR_LOG("createSafeVolumeNotificationImpl failed %{public}s", __func__);
667 #ifndef TEST_COVERAGE
668 dlclose(libHandle);
669 #endif
670 return;
671 }
672 AudioSafeVolumeNotification *audioSafeVolumeNotificationImpl = createSafeVolumeNotificationImpl();
673 if (audioSafeVolumeNotificationImpl == nullptr) {
674 AUDIO_ERR_LOG("audioSafeVolumeNotificationImpl is nullptr %{public}s", __func__);
675 #ifndef TEST_COVERAGE
676 dlclose(libHandle);
677 #endif
678 return;
679 }
680 audioSafeVolumeNotificationImpl->CancelSafeVolumeNotification(notificationId);
681 delete audioSafeVolumeNotificationImpl;
682 #ifndef TEST_COVERAGE
683 dlclose(libHandle);
684 #endif
685 }
686
DealWithSafeVolume(const int32_t volumeLevel,bool isBtDevice)687 int32_t AudioVolumeManager::DealWithSafeVolume(const int32_t volumeLevel, bool isBtDevice)
688 {
689 if (isBtDevice) {
690 DeviceCategory curOutputDeviceCategory = audioPolicyManager_.GetCurrentOutputDeviceCategory();
691 AUDIO_INFO_LOG("bluetooth Category:%{public}d", curOutputDeviceCategory);
692 if (curOutputDeviceCategory == BT_SOUNDBOX || curOutputDeviceCategory == BT_CAR) {
693 return volumeLevel;
694 }
695 }
696
697 int32_t sVolumeLevel = volumeLevel;
698 safeStatusBt_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP);
699 safeStatus_ = audioPolicyManager_.GetCurrentDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET);
700 if ((safeStatusBt_ == SAFE_INACTIVE && isBtDevice) ||
701 (safeStatus_ == SAFE_INACTIVE && !isBtDevice)) {
702 CreateCheckMusicActiveThread();
703 return sVolumeLevel;
704 }
705
706 if ((isBtDevice && safeStatusBt_ == SAFE_ACTIVE) ||
707 (!isBtDevice && safeStatus_ == SAFE_ACTIVE)) {
708 sVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
709 if (restoreNIsShowing_) {
710 CancelSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
711 restoreNIsShowing_ = false;
712 }
713 PublishSafeVolumeNotification(INCREASE_VOLUME_NOTIFICATION_ID);
714 increaseNIsShowing_ = true;
715 return sVolumeLevel;
716 }
717 return sVolumeLevel;
718 }
719
CreateCheckMusicActiveThread()720 void AudioVolumeManager::CreateCheckMusicActiveThread()
721 {
722 std::lock_guard<std::mutex> lock(checkMusicActiveThreadMutex_);
723 if (calculateLoopSafeTime_ == nullptr) {
724 calculateLoopSafeTime_ = std::make_unique<std::thread>([this] { this->CheckActiveMusicTime(); });
725 pthread_setname_np(calculateLoopSafeTime_->native_handle(), "OS_AudioPolicySafe");
726 }
727 }
728
IsWiredHeadSet(const DeviceType & deviceType)729 bool AudioVolumeManager::IsWiredHeadSet(const DeviceType &deviceType)
730 {
731 switch (deviceType) {
732 case DEVICE_TYPE_WIRED_HEADSET:
733 case DEVICE_TYPE_WIRED_HEADPHONES:
734 case DEVICE_TYPE_USB_HEADSET:
735 case DEVICE_TYPE_USB_ARM_HEADSET:
736 return true;
737 default:
738 return false;
739 }
740 }
741
IsBlueTooth(const DeviceType & deviceType)742 bool AudioVolumeManager::IsBlueTooth(const DeviceType &deviceType)
743 {
744 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP || deviceType == DEVICE_TYPE_BLUETOOTH_SCO) {
745 if (audioPolicyManager_.GetCurrentOutputDeviceCategory() != BT_CAR &&
746 audioPolicyManager_.GetCurrentOutputDeviceCategory() != BT_SOUNDBOX) {
747 return true;
748 }
749 }
750 return false;
751 }
752
SetRestoreVolumeLevel(DeviceType deviceType,int32_t curDeviceVolume)753 void AudioVolumeManager::SetRestoreVolumeLevel(DeviceType deviceType, int32_t curDeviceVolume)
754 {
755 int32_t btDeviceVol = audioPolicyManager_.GetDeviceVolume(DEVICE_TYPE_BLUETOOTH_A2DP, STREAM_MUSIC);
756 int32_t wiredDeviceVol = audioPolicyManager_.GetDeviceVolume(DEVICE_TYPE_WIRED_HEADSET, STREAM_MUSIC);
757 int32_t safeVolume = audioPolicyManager_.GetSafeVolumeLevel();
758
759 btRestoreVol_ = btDeviceVol > safeVolume ? btDeviceVol : btRestoreVol_;
760 audioPolicyManager_.SetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP, btRestoreVol_);
761 wiredRestoreVol_ = wiredDeviceVol > safeVolume ? wiredDeviceVol : wiredRestoreVol_;
762 audioPolicyManager_.SetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET, wiredRestoreVol_);
763
764 AUDIO_INFO_LOG("btDeviceVol : %{public}d, wiredDeviceVol : %{public}d, curDeviceVolume : %{public}d",
765 btDeviceVol, wiredDeviceVol, curDeviceVolume);
766
767 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
768 AUDIO_INFO_LOG("set bt restore volume to db");
769 btRestoreVol_ = curDeviceVolume > safeVolume ? curDeviceVolume : btRestoreVol_;
770 audioPolicyManager_.SetRestoreVolumeLevel(deviceType, btRestoreVol_);
771 } else if (deviceType == DEVICE_TYPE_WIRED_HEADSET) {
772 AUDIO_INFO_LOG("set wired restore volume to db");
773 wiredRestoreVol_ = curDeviceVolume > safeVolume ? curDeviceVolume : wiredRestoreVol_;
774 audioPolicyManager_.SetRestoreVolumeLevel(deviceType, wiredRestoreVol_);
775 }
776 }
777
CheckActiveMusicTime()778 int32_t AudioVolumeManager::CheckActiveMusicTime()
779 {
780 AUDIO_INFO_LOG("enter");
781 int32_t safeVolume = audioPolicyManager_.GetSafeVolumeLevel();
782 while (!safeVolumeExit_) {
783 bool activeMusic = audioSceneManager_.IsStreamActive(STREAM_MUSIC);
784 int32_t curDeviceVolume = GetSystemVolumeLevel(STREAM_MUSIC);
785 bool isUpSafeVolume = curDeviceVolume > safeVolume ? true : false;
786 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
787 AUDIO_INFO_LOG("activeMusic:%{public}d, deviceType_:%{public}d, isUpSafeVolume:%{public}d",
788 activeMusic, curOutputDeviceType, isUpSafeVolume);
789 if (activeMusic && (safeStatusBt_ == SAFE_INACTIVE) && isUpSafeVolume &&
790 IsBlueTooth(curOutputDeviceType)) {
791 SetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP, curDeviceVolume);
792 CheckBlueToothActiveMusicTime(safeVolume);
793 } else if (activeMusic && (safeStatus_ == SAFE_INACTIVE) && isUpSafeVolume &&
794 IsWiredHeadSet(curOutputDeviceType)) {
795 SetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET, curDeviceVolume);
796 CheckWiredActiveMusicTime(safeVolume);
797 } else {
798 startSafeTime_ = 0;
799 startSafeTimeBt_ = 0;
800 }
801 sleep(ONE_MINUTE);
802 }
803 return 0;
804 }
805
CheckMixActiveMusicTime(int32_t safeVolume)806 bool AudioVolumeManager::CheckMixActiveMusicTime(int32_t safeVolume)
807 {
808 int64_t mixSafeTime = activeSafeTimeBt_ + activeSafeTime_;
809 AUDIO_INFO_LOG("mix device cumulative time: %{public}" PRId64, mixSafeTime);
810 if (mixSafeTime >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
811 AUDIO_INFO_LOG("mix device safe volume timeout");
812 ChangeDeviceSafeStatus(SAFE_ACTIVE);
813 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
814 startSafeTimeBt_ = 0;
815 startSafeTime_ = 0;
816 activeSafeTimeBt_ = 0;
817 activeSafeTime_ = 0;
818 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0);
819 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, 0);
820 return true;
821 }
822 return false;
823 }
824
CheckBlueToothActiveMusicTime(int32_t safeVolume)825 void AudioVolumeManager::CheckBlueToothActiveMusicTime(int32_t safeVolume)
826 {
827 if (startSafeTimeBt_ == 0) {
828 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
829 }
830 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
831 if (activeSafeTimeBt_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
832 AUDIO_INFO_LOG("bluetooth device safe volume timeout");
833 ChangeDeviceSafeStatus(SAFE_ACTIVE);
834 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
835 startSafeTimeBt_ = 0;
836 activeSafeTimeBt_ = 0;
837 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0);
838 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
839 restoreNIsShowing_ = true;
840 } else if (CheckMixActiveMusicTime(safeVolume)) {
841 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
842 restoreNIsShowing_ = true;
843 } else if (currentTime - startSafeTimeBt_ >= ONE_MINUTE) {
844 activeSafeTimeBt_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP);
845 activeSafeTimeBt_ += currentTime - startSafeTimeBt_;
846 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP, activeSafeTimeBt_);
847 startSafeTimeBt_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
848 AUDIO_INFO_LOG("bluetooth safe volume 1 min timeout, cumulative time: %{public}" PRId64, activeSafeTimeBt_);
849 }
850 startSafeTime_ = 0;
851 }
852
CheckWiredActiveMusicTime(int32_t safeVolume)853 void AudioVolumeManager::CheckWiredActiveMusicTime(int32_t safeVolume)
854 {
855 if (startSafeTime_ == 0) {
856 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
857 }
858 int32_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
859 if (activeSafeTime_ >= ONE_MINUTE * audioPolicyManager_.GetSafeVolumeTimeout()) {
860 AUDIO_INFO_LOG("wired device safe volume timeout");
861 ChangeDeviceSafeStatus(SAFE_ACTIVE);
862 RestoreSafeVolume(STREAM_MUSIC, safeVolume);
863 startSafeTime_ = 0;
864 activeSafeTime_ = 0;
865 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, 0);
866 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
867 restoreNIsShowing_ = true;
868 } else if (CheckMixActiveMusicTime(safeVolume)) {
869 PublishSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
870 restoreNIsShowing_ = true;
871 } else if (currentTime - startSafeTime_ >= ONE_MINUTE) {
872 activeSafeTime_ = audioPolicyManager_.GetCurentDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET);
873 activeSafeTime_ += currentTime - startSafeTime_;
874 audioPolicyManager_.SetDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET, activeSafeTime_);
875 startSafeTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
876 AUDIO_INFO_LOG("wired safe volume 1 min timeout, cumulative time: %{public}" PRId64, activeSafeTime_);
877 }
878 startSafeTimeBt_ = 0;
879 }
880
CheckLowerDeviceVolume(DeviceType deviceType)881 void AudioVolumeManager::CheckLowerDeviceVolume(DeviceType deviceType)
882 {
883 int32_t btVolume = audioPolicyManager_.GetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP);
884 int32_t wiredVolume = audioPolicyManager_.GetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET);
885
886 AUDIO_INFO_LOG("btVolume : %{public}d, wiredVolume : %{public}d", btVolume, wiredVolume);
887
888 int32_t safeVolume = audioPolicyManager_.GetSafeVolumeLevel();
889 switch (deviceType) {
890 case DEVICE_TYPE_WIRED_HEADSET:
891 case DEVICE_TYPE_WIRED_HEADPHONES:
892 case DEVICE_TYPE_USB_HEADSET:
893 case DEVICE_TYPE_USB_ARM_HEADSET:
894 if (btVolume > safeVolume) {
895 AUDIO_INFO_LOG("wired device timeout, set bt device to safe volume");
896 SaveSpecifiedDeviceVolume(STREAM_MUSIC, safeVolume, DEVICE_TYPE_BLUETOOTH_A2DP);
897 }
898 break;
899 case DEVICE_TYPE_BLUETOOTH_SCO:
900 case DEVICE_TYPE_BLUETOOTH_A2DP:
901 if (wiredVolume > safeVolume) {
902 AUDIO_INFO_LOG("bt device timeout, set wired device to safe volume");
903 SaveSpecifiedDeviceVolume(STREAM_MUSIC, safeVolume, DEVICE_TYPE_WIRED_HEADSET);
904 }
905 break;
906 default:
907 AUDIO_ERR_LOG("current device not set safe volume");
908 break;
909 }
910 }
911
RestoreSafeVolume(AudioStreamType streamType,int32_t safeVolume)912 void AudioVolumeManager::RestoreSafeVolume(AudioStreamType streamType, int32_t safeVolume)
913 {
914 userSelect_ = false;
915 isDialogSelectDestroy_.store(false);
916
917 if (GetSystemVolumeLevel(streamType) <= safeVolume) {
918 AUDIO_INFO_LOG("current volume <= safe volume, don't update volume.");
919 return;
920 }
921
922 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
923
924 AUDIO_INFO_LOG("restore safe volume.");
925 SetSystemVolumeLevel(streamType, safeVolume);
926 CheckLowerDeviceVolume(curOutputDeviceType);
927 SetSafeVolumeCallback(streamType);
928 }
929
SetSafeVolumeCallback(AudioStreamType streamType)930 void AudioVolumeManager::SetSafeVolumeCallback(AudioStreamType streamType)
931 {
932 CHECK_AND_RETURN_LOG(VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC,
933 "streamtype:%{public}d no need to set safe volume callback.", streamType);
934 VolumeEvent volumeEvent;
935 volumeEvent.volumeType = streamType;
936 volumeEvent.volume = GetSystemVolumeLevel(streamType);
937 volumeEvent.updateUi = true;
938 volumeEvent.volumeGroupId = 0;
939 volumeEvent.networkId = LOCAL_NETWORK_ID;
940 if (audioPolicyServerHandler_ != nullptr && IsRingerModeMute()) {
941 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
942 }
943 }
944
OnReceiveEvent(const EventFwk::CommonEventData & eventData)945 void AudioVolumeManager::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
946 {
947 AUDIO_INFO_LOG("enter.");
948 const AAFwk::Want& want = eventData.GetWant();
949 std::string action = want.GetAction();
950 if (action == AUDIO_RESTORE_VOLUME_EVENT) {
951 AUDIO_INFO_LOG("AUDIO_RESTORE_VOLUME_EVENT has been received");
952 std::lock_guard<std::mutex> lock(notifyMutex_);
953 CancelSafeVolumeNotification(RESTORE_VOLUME_NOTIFICATION_ID);
954 restoreNIsShowing_ = false;
955 ChangeDeviceSafeStatus(SAFE_INACTIVE);
956 DealWithEventVolume(RESTORE_VOLUME_NOTIFICATION_ID);
957 SetSafeVolumeCallback(STREAM_MUSIC);
958 } else if (action == AUDIO_INCREASE_VOLUME_EVENT) {
959 AUDIO_INFO_LOG("AUDIO_INCREASE_VOLUME_EVENT has been received");
960 std::lock_guard<std::mutex> lock(notifyMutex_);
961 CancelSafeVolumeNotification(INCREASE_VOLUME_NOTIFICATION_ID);
962 increaseNIsShowing_ = false;
963 ChangeDeviceSafeStatus(SAFE_INACTIVE);
964 DealWithEventVolume(INCREASE_VOLUME_NOTIFICATION_ID);
965 SetSafeVolumeCallback(STREAM_MUSIC);
966 }
967 }
968
SetDeviceSafeVolumeStatus()969 void AudioVolumeManager::SetDeviceSafeVolumeStatus()
970 {
971 if (!userSelect_) {
972 return;
973 }
974
975 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
976 switch (curOutputDeviceType) {
977 case DEVICE_TYPE_BLUETOOTH_A2DP:
978 case DEVICE_TYPE_BLUETOOTH_SCO:
979 case DEVICE_TYPE_NEARLINK:
980 safeStatusBt_ = SAFE_INACTIVE;
981 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
982 CreateCheckMusicActiveThread();
983 break;
984 case DEVICE_TYPE_WIRED_HEADSET:
985 case DEVICE_TYPE_WIRED_HEADPHONES:
986 case DEVICE_TYPE_USB_HEADSET:
987 case DEVICE_TYPE_USB_ARM_HEADSET:
988 safeStatus_ = SAFE_INACTIVE;
989 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
990 CreateCheckMusicActiveThread();
991 break;
992 default:
993 AUDIO_INFO_LOG("safeVolume unsupported device:%{public}d", curOutputDeviceType);
994 break;
995 }
996 }
997
ChangeDeviceSafeStatus(SafeStatus safeStatus)998 void AudioVolumeManager::ChangeDeviceSafeStatus(SafeStatus safeStatus)
999 {
1000 AUDIO_INFO_LOG("change all support safe volume devices status.");
1001
1002 safeStatusBt_ = safeStatus;
1003 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
1004
1005 safeStatus_ = safeStatus;
1006 audioPolicyManager_.SetDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
1007
1008 CreateCheckMusicActiveThread();
1009 }
1010
DisableSafeMediaVolume()1011 int32_t AudioVolumeManager::DisableSafeMediaVolume()
1012 {
1013 AUDIO_INFO_LOG("Enter");
1014 std::lock_guard<std::mutex> lock(dialogMutex_);
1015 userSelect_ = true;
1016 isDialogSelectDestroy_.store(true);
1017 dialogSelectCondition_.notify_all();
1018 SetDeviceSafeVolumeStatus();
1019 return SUCCESS;
1020 }
1021
SetAbsVolumeSceneAsync(const std::string & macAddress,const bool support)1022 void AudioVolumeManager::SetAbsVolumeSceneAsync(const std::string &macAddress, const bool support)
1023 {
1024 usleep(SET_BT_ABS_SCENE_DELAY_MS);
1025 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
1026 AUDIO_INFO_LOG("success for macAddress:[%{public}s], support: %{public}d, active bt:[%{public}s]",
1027 GetEncryptAddr(macAddress).c_str(), support, GetEncryptAddr(btDevice).c_str());
1028
1029 if (btDevice == macAddress) {
1030 audioPolicyManager_.SetAbsVolumeScene(support);
1031 SetSharedAbsVolumeScene(support);
1032 int32_t volumeLevel = audioPolicyManager_.GetSystemVolumeLevelNoMuteState(STREAM_MUSIC);
1033 audioPolicyManager_.SetSystemVolumeLevel(STREAM_MUSIC, volumeLevel);
1034 }
1035 }
1036
SetDeviceAbsVolumeSupported(const std::string & macAddress,const bool support)1037 int32_t AudioVolumeManager::SetDeviceAbsVolumeSupported(const std::string &macAddress, const bool support)
1038 {
1039 // Maximum number of attempts, preventing situations where a2dp device has not yet finished coming online.
1040 int maxRetries = 3;
1041 int retryCount = 0;
1042 while (retryCount < maxRetries) {
1043 retryCount++;
1044 int32_t currentVolume = audioPolicyManager_.GetSystemVolumeLevelNoMuteState(STREAM_MUSIC);
1045 bool currentMute = audioPolicyManager_.GetStreamMute(STREAM_MUSIC);
1046 if (audioA2dpDevice_.SetA2dpDeviceAbsVolumeSupport(macAddress, support, currentVolume, currentMute)) {
1047 break;
1048 }
1049 CHECK_AND_RETURN_RET_LOG(retryCount != maxRetries, ERROR,
1050 "failed, can't find device for macAddress:[%{public}s]", GetEncryptAddr(macAddress).c_str());;
1051 usleep(ABS_VOLUME_SUPPORT_RETRY_INTERVAL_IN_MICROSECONDS);
1052 }
1053
1054 // The delay setting is due to move a2dp sink after this
1055 std::thread setAbsSceneThrd(&AudioVolumeManager::SetAbsVolumeSceneAsync, this, macAddress, support);
1056 setAbsSceneThrd.detach();
1057
1058 return SUCCESS;
1059 }
1060
SetStreamMute(AudioStreamType streamType,bool mute,const StreamUsage & streamUsage,const DeviceType & deviceType,int32_t zoneId)1061 int32_t AudioVolumeManager::SetStreamMute(AudioStreamType streamType, bool mute, const StreamUsage &streamUsage,
1062 const DeviceType &deviceType, int32_t zoneId)
1063 {
1064 if (zoneId > 0) {
1065 return audioPolicyManager_.SetZoneMute(zoneId, streamType, mute, streamUsage, deviceType);
1066 }
1067 int32_t result = SUCCESS;
1068 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1069 if (deviceType != DEVICE_TYPE_NONE) {
1070 AUDIO_INFO_LOG("set stream mute for specified device [%{public}d]", deviceType);
1071 curOutputDeviceType = deviceType;
1072 }
1073 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
1074 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1075 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
1076 if (audioA2dpDevice_.SetA2dpDeviceMute(btDevice, mute)) {
1077 audioPolicyManager_.SetAbsVolumeMute(mute);
1078 Volume vol = {false, 1.0f, 0};
1079 vol.isMute = mute;
1080 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevelNoMuteState(streamType));
1081 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType,
1082 (mute ? 0 : vol.volumeInt), curOutputDeviceType);
1083 SetSharedVolume(streamType, curOutputDeviceType, vol);
1084 #ifdef BLUETOOTH_ENABLE
1085 // set to avrcp device
1086 int32_t volumeLevel;
1087 audioA2dpDevice_.GetA2dpDeviceVolumeLevel(btDevice, volumeLevel);
1088 return Bluetooth::AudioA2dpManager::SetDeviceAbsVolume(btDevice,
1089 volumeLevel);
1090 #endif
1091 }
1092 }
1093 result = audioPolicyManager_.SetStreamMute(streamType, mute, streamUsage, curOutputDeviceType,
1094 audioActiveDevice_.GetCurrentOutputDevice().networkId_);
1095
1096 Volume vol = {false, 1.0f, 0};
1097 vol.isMute = mute;
1098 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevelNoMuteState(streamType));
1099 vol.volumeFloat = audioPolicyManager_.GetSystemVolumeInDb(streamType,
1100 (mute ? 0 : vol.volumeInt), curOutputDeviceType);
1101 SetSharedVolume(streamType, curOutputDeviceType, vol);
1102
1103 return result;
1104 }
1105
GetStreamMute(AudioStreamType streamType,int32_t zoneId) const1106 bool AudioVolumeManager::GetStreamMute(AudioStreamType streamType, int32_t zoneId) const
1107 {
1108 if (zoneId > 0) {
1109 return audioPolicyManager_.GetZoneMute(zoneId, streamType);
1110 }
1111 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1112 if (VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_MUSIC &&
1113 curOutputDeviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1114 std::string btDevice = audioActiveDevice_.GetActiveBtDeviceMac();
1115 A2dpDeviceConfigInfo info;
1116 bool ret = audioA2dpDevice_.GetA2dpDeviceInfo(btDevice, info);
1117 if (ret == false || !info.absVolumeSupport) {
1118 AUDIO_WARNING_LOG("Get failed for macAddress:[%{public}s]", GetEncryptAddr(btDevice).c_str());
1119 } else {
1120 return info.mute;
1121 }
1122 }
1123 return audioPolicyManager_.GetStreamMute(streamType);
1124 }
1125
UpdateGroupInfo(GroupType type,std::string groupName,int32_t & groupId,std::string networkId,bool connected,int32_t mappingId)1126 void AudioVolumeManager::UpdateGroupInfo(GroupType type, std::string groupName, int32_t& groupId,
1127 std::string networkId, bool connected, int32_t mappingId)
1128 {
1129 std::lock_guard<std::mutex> lock(volumeGroupsMutex_);
1130 ConnectType connectType = CONNECT_TYPE_LOCAL;
1131 if (networkId != LOCAL_NETWORK_ID) {
1132 connectType = CONNECT_TYPE_DISTRIBUTED;
1133 }
1134 if (type == GroupType::VOLUME_TYPE) {
1135 auto isPresent = [&groupName, &networkId] (const sptr<VolumeGroupInfo> &volumeInfo) {
1136 return ((groupName == volumeInfo->groupName_) || (networkId == volumeInfo->networkId_));
1137 };
1138
1139 auto iter = std::find_if(volumeGroups_.begin(), volumeGroups_.end(), isPresent);
1140 if (iter != volumeGroups_.end()) {
1141 groupId = (*iter)->volumeGroupId_;
1142 // if status is disconnected, remove the group that has none audio device
1143 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devsInGroup =
1144 audioConnectedDevice_.GetDevicesForGroup(type, groupId);
1145 if (!connected && devsInGroup.size() == 0) {
1146 volumeGroups_.erase(iter);
1147 }
1148 return;
1149 }
1150 if (groupName != GROUP_NAME_NONE && connected) {
1151 groupId = AudioGroupHandle::GetInstance().GetNextId(type);
1152 sptr<VolumeGroupInfo> volumeGroupInfo = new(std::nothrow) VolumeGroupInfo(groupId,
1153 mappingId, groupName, networkId, connectType);
1154 volumeGroups_.push_back(volumeGroupInfo);
1155 }
1156 } else {
1157 auto isPresent = [&groupName, &networkId] (const sptr<InterruptGroupInfo> &info) {
1158 return ((groupName == info->groupName_) || (networkId == info->networkId_));
1159 };
1160
1161 auto iter = std::find_if(interruptGroups_.begin(), interruptGroups_.end(), isPresent);
1162 if (iter != interruptGroups_.end()) {
1163 groupId = (*iter)->interruptGroupId_;
1164 // if status is disconnected, remove the group that has none audio device
1165 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devsInGroup =
1166 audioConnectedDevice_.GetDevicesForGroup(type, groupId);
1167 if (!connected && devsInGroup.size() == 0) {
1168 interruptGroups_.erase(iter);
1169 }
1170 return;
1171 }
1172 if (groupName != GROUP_NAME_NONE && connected) {
1173 groupId = AudioGroupHandle::GetInstance().GetNextId(type);
1174 sptr<InterruptGroupInfo> interruptGroupInfo = new(std::nothrow) InterruptGroupInfo(groupId, mappingId,
1175 groupName, networkId, connectType);
1176 interruptGroups_.push_back(interruptGroupInfo);
1177 }
1178 }
1179 }
1180
GetVolumeGroupInfo(std::vector<sptr<VolumeGroupInfo>> & volumeGroupInfos)1181 void AudioVolumeManager::GetVolumeGroupInfo(std::vector<sptr<VolumeGroupInfo>>& volumeGroupInfos)
1182 {
1183 std::lock_guard<std::mutex> lock(volumeGroupsMutex_);
1184 for (auto& v : volumeGroups_) {
1185 sptr<VolumeGroupInfo> info = new(std::nothrow) VolumeGroupInfo(v->volumeGroupId_, v->mappingId_, v->groupName_,
1186 v->networkId_, v->connectType_);
1187 volumeGroupInfos.push_back(info);
1188 }
1189 }
1190
CheckRestoreDeviceVolume(DeviceType deviceType)1191 int32_t AudioVolumeManager::CheckRestoreDeviceVolume(DeviceType deviceType)
1192 {
1193 int32_t ret = 0;
1194 int32_t btRestoreVolume = audioPolicyManager_.GetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP);
1195 int32_t wiredRestoreVolume = audioPolicyManager_.GetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET);
1196
1197 AUDIO_INFO_LOG("btRestoreVolume: %{public}d, wiredRestoreVolume: %{public}d", btRestoreVolume, wiredRestoreVolume);
1198
1199 int32_t safeVolume = audioPolicyManager_.GetSafeVolumeLevel();
1200 switch (deviceType) {
1201 case DEVICE_TYPE_WIRED_HEADSET:
1202 case DEVICE_TYPE_WIRED_HEADPHONES:
1203 case DEVICE_TYPE_USB_HEADSET:
1204 case DEVICE_TYPE_USB_ARM_HEADSET:
1205 if (wiredRestoreVolume > safeVolume) {
1206 AUDIO_INFO_LOG("restore active wired device volume");
1207 ret = SetSystemVolumeLevel(STREAM_MUSIC, wiredRestoreVolume);
1208 }
1209 if (btRestoreVolume > safeVolume) {
1210 AUDIO_INFO_LOG("restore other bt device volume");
1211 SaveSpecifiedDeviceVolume(STREAM_MUSIC, btRestoreVolume, DEVICE_TYPE_BLUETOOTH_A2DP);
1212 }
1213 break;
1214 case DEVICE_TYPE_BLUETOOTH_SCO:
1215 case DEVICE_TYPE_BLUETOOTH_A2DP:
1216 if (btRestoreVolume > safeVolume) {
1217 AUDIO_INFO_LOG("restore active bt device volume");
1218 ret = SetSystemVolumeLevel(STREAM_MUSIC, btRestoreVolume);
1219 }
1220 if (wiredRestoreVolume > safeVolume) {
1221 AUDIO_INFO_LOG("restore other wired device volume");
1222 SaveSpecifiedDeviceVolume(STREAM_MUSIC, wiredRestoreVolume, DEVICE_TYPE_WIRED_HEADSET);
1223 }
1224 break;
1225 default:
1226 ret = ERROR;
1227 AUDIO_ERR_LOG("current device not set safe volume");
1228 break;
1229 }
1230
1231 return ret;
1232 }
1233
DealWithEventVolume(const int32_t notificationId)1234 int32_t AudioVolumeManager::DealWithEventVolume(const int32_t notificationId)
1235 {
1236 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1237 int32_t safeVolumeLevel = audioPolicyManager_.GetSafeVolumeLevel();
1238 const int32_t ONE_VOLUME_LEVEL = 1;
1239 int32_t ret = 0;
1240 if (IsBlueTooth(curOutputDeviceType)) {
1241 switch (notificationId) {
1242 case RESTORE_VOLUME_NOTIFICATION_ID:
1243 ret = CheckRestoreDeviceVolume(DEVICE_TYPE_BLUETOOTH_A2DP);
1244 break;
1245 case INCREASE_VOLUME_NOTIFICATION_ID:
1246 ret = SetSystemVolumeLevel(STREAM_MUSIC, safeVolumeLevel + ONE_VOLUME_LEVEL);
1247 break;
1248 default:
1249 AUDIO_ERR_LOG("current state unsupport safe volume");
1250 }
1251 } else if (IsWiredHeadSet(curOutputDeviceType)) {
1252 switch (notificationId) {
1253 case RESTORE_VOLUME_NOTIFICATION_ID:
1254 ret = CheckRestoreDeviceVolume(DEVICE_TYPE_WIRED_HEADSET);
1255 break;
1256 case INCREASE_VOLUME_NOTIFICATION_ID:
1257 ret = SetSystemVolumeLevel(STREAM_MUSIC, safeVolumeLevel + ONE_VOLUME_LEVEL);
1258 break;
1259 default:
1260 AUDIO_ERR_LOG("current state unsupport safe volume");
1261 }
1262 } else {
1263 AUDIO_ERR_LOG("current output device unsupport safe volume");
1264 ret = ERROR;
1265 }
1266 return ret;
1267 }
1268
ResetRingerModeMute()1269 int32_t AudioVolumeManager::ResetRingerModeMute()
1270 {
1271 if (audioPolicyManager_.SetStreamMute(STREAM_RING, true) == SUCCESS) {
1272 SetRingerModeMute(true);
1273 }
1274 return SUCCESS;
1275 }
1276
IsRingerModeMute()1277 bool AudioVolumeManager::IsRingerModeMute()
1278 {
1279 return ringerModeMute_.load();
1280 }
1281
SetRingerModeMute(bool flag)1282 void AudioVolumeManager::SetRingerModeMute(bool flag)
1283 {
1284 ringerModeMute_.store(flag);
1285 }
1286
GetVolumeGroupInfosNotWait(std::vector<sptr<VolumeGroupInfo>> & infos)1287 bool AudioVolumeManager::GetVolumeGroupInfosNotWait(std::vector<sptr<VolumeGroupInfo>> &infos)
1288 {
1289 if (!isPrimaryMicModuleInfoLoaded_) {
1290 return false;
1291 }
1292
1293 GetVolumeGroupInfo(infos);
1294 return true;
1295 }
1296
SetDefaultDeviceLoadFlag(bool isLoad)1297 void AudioVolumeManager::SetDefaultDeviceLoadFlag(bool isLoad)
1298 {
1299 isPrimaryMicModuleInfoLoaded_.store(isLoad);
1300 }
1301
GetLoadFlag()1302 bool AudioVolumeManager::GetLoadFlag()
1303 {
1304 return isPrimaryMicModuleInfoLoaded_.load();
1305 }
1306
NotifyVolumeGroup()1307 void AudioVolumeManager::NotifyVolumeGroup()
1308 {
1309 std::lock_guard<std::mutex> lock(defaultDeviceLoadMutex_);
1310 SetDefaultDeviceLoadFlag(true);
1311 }
1312
UpdateSafeVolumeByS4()1313 void AudioVolumeManager::UpdateSafeVolumeByS4()
1314 {
1315 AUDIO_INFO_LOG("Reset isBtFirstBoot by S4 reboot");
1316 isBtFirstBoot_ = true;
1317 return audioPolicyManager_.UpdateSafeVolumeByS4();
1318 }
1319
GetAllDeviceVolumeInfo()1320 std::vector<std::shared_ptr<AllDeviceVolumeInfo>> AudioVolumeManager::GetAllDeviceVolumeInfo()
1321 {
1322 std::vector<std::shared_ptr<AllDeviceVolumeInfo>> allDeviceVolumeInfo = {};
1323 std::shared_ptr<AllDeviceVolumeInfo> deviceVolumeInfo = std::make_shared<AllDeviceVolumeInfo>();
1324 auto deviceList = audioConnectedDevice_.GetDevicesInner(DeviceFlag::ALL_L_D_DEVICES_FLAG);
1325 for (auto &device : deviceList) {
1326 for (auto &streamType : AUDIO_STREAMTYPE_VOLUME_LIST) {
1327 if (streamType == STREAM_VOICE_CALL_ASSISTANT) {
1328 continue;
1329 }
1330 deviceVolumeInfo = audioPolicyManager_.GetAllDeviceVolumeInfo(device->deviceType_, streamType);
1331 if (deviceVolumeInfo != nullptr) {
1332 allDeviceVolumeInfo.push_back(deviceVolumeInfo);
1333 }
1334 }
1335 }
1336 return allDeviceVolumeInfo;
1337 }
1338
SaveSystemVolumeLevelInfo(AudioStreamType streamType,int32_t volumeLevel,int32_t appUid,std::string invocationTime)1339 void AudioVolumeManager::SaveSystemVolumeLevelInfo(AudioStreamType streamType, int32_t volumeLevel,
1340 int32_t appUid, std::string invocationTime)
1341 {
1342 AdjustVolumeInfo systemVolumeLevelInfo;
1343 systemVolumeLevelInfo.deviceType = curOutputDeviceType_;
1344 systemVolumeLevelInfo.streamType = streamType;
1345 systemVolumeLevelInfo.volumeLevel = volumeLevel;
1346 systemVolumeLevelInfo.appUid = appUid;
1347 systemVolumeLevelInfo.invocationTime = invocationTime;
1348 systemVolumeLevelInfo_->Add(systemVolumeLevelInfo);
1349 }
1350
SaveVolumeKeyRegistrationInfo(std::string keyType,std::string registrationTime,int32_t subscriptionId,bool registrationResult)1351 void AudioVolumeManager::SaveVolumeKeyRegistrationInfo(std::string keyType, std::string registrationTime,
1352 int32_t subscriptionId, bool registrationResult)
1353 {
1354 VolumeKeyEventRegistration volumeKeyEventRegistration;
1355 volumeKeyEventRegistration.keyType = keyType;
1356 volumeKeyEventRegistration.subscriptionId = subscriptionId;
1357 volumeKeyEventRegistration.registrationTime = registrationTime;
1358 volumeKeyEventRegistration.registrationResult = registrationResult;
1359 volumeKeyRegistrations_->Add(volumeKeyEventRegistration);
1360 }
1361
GetSystemVolumeLevelInfo(std::vector<AdjustVolumeInfo> & systemVolumeLevelInfo)1362 void AudioVolumeManager::GetSystemVolumeLevelInfo(std::vector<AdjustVolumeInfo> &systemVolumeLevelInfo)
1363 {
1364 systemVolumeLevelInfo = systemVolumeLevelInfo_->GetData();
1365 }
1366
GetVolumeKeyRegistrationInfo(std::vector<VolumeKeyEventRegistration> & keyRegistrationInfo)1367 void AudioVolumeManager::GetVolumeKeyRegistrationInfo(std::vector<VolumeKeyEventRegistration> &keyRegistrationInfo)
1368 {
1369 keyRegistrationInfo = volumeKeyRegistrations_->GetData();
1370 }
1371
ForceVolumeKeyControlType(AudioVolumeType volumeType,int32_t duration)1372 int32_t AudioVolumeManager::ForceVolumeKeyControlType(AudioVolumeType volumeType, int32_t duration)
1373 {
1374 CHECK_AND_RETURN_RET_LOG(duration >= CANCEL_FORCE_CONTROL_VOLUME_TYPE, ERR_INVALID_PARAM, "invalid duration");
1375 CHECK_AND_RETURN_RET_LOG(forceControlVolumeTypeMonitor_ != nullptr, ERR_UNKNOWN,
1376 "forceControlVolumeTypeMonitor_ is nullptr");
1377 std::lock_guard<std::mutex> lock(forceControlVolumeTypeMutex_);
1378 needForceControlVolumeType_ = (duration == CANCEL_FORCE_CONTROL_VOLUME_TYPE ? false : true);
1379 forceControlVolumeType_ = (duration == CANCEL_FORCE_CONTROL_VOLUME_TYPE ? STREAM_DEFAULT : volumeType);
1380 forceControlVolumeTypeMonitor_->SetTimer(duration, forceControlVolumeTypeMonitor_);
1381 return SUCCESS;
1382 }
1383
OnTimerExpired()1384 void AudioVolumeManager::OnTimerExpired()
1385 {
1386 std::lock_guard<std::mutex> lock(forceControlVolumeTypeMutex_);
1387 needForceControlVolumeType_ = false;
1388 forceControlVolumeType_ = STREAM_DEFAULT;
1389 }
1390
IsNeedForceControlVolumeType()1391 bool AudioVolumeManager::IsNeedForceControlVolumeType()
1392 {
1393 std::lock_guard<std::mutex> lock(forceControlVolumeTypeMutex_);
1394 return needForceControlVolumeType_;
1395 }
1396
GetForceControlVolumeType()1397 AudioVolumeType AudioVolumeManager::GetForceControlVolumeType()
1398 {
1399 std::lock_guard<std::mutex> lock(forceControlVolumeTypeMutex_);
1400 return forceControlVolumeType_;
1401 }
1402
~ForceControlVolumeTypeMonitor()1403 ForceControlVolumeTypeMonitor::~ForceControlVolumeTypeMonitor()
1404 {
1405 std::lock_guard<std::mutex> lock(monitorMtx_);
1406 StopMonitor();
1407 }
1408
OnTimeOut()1409 void ForceControlVolumeTypeMonitor::OnTimeOut()
1410 {
1411 {
1412 std::lock_guard<std::mutex> lock(monitorMtx_);
1413 StopMonitor();
1414 }
1415 audioVolumeManager_.OnTimerExpired();
1416 }
1417
StartMonitor(int32_t duration,std::shared_ptr<ForceControlVolumeTypeMonitor> cb)1418 void ForceControlVolumeTypeMonitor::StartMonitor(int32_t duration,
1419 std::shared_ptr<ForceControlVolumeTypeMonitor> cb)
1420 {
1421 int32_t cbId = DelayedSingleton<AudioPolicyStateMonitor>::GetInstance()->RegisterCallback(
1422 cb, duration, CallbackType::ONE_TIME);
1423 if (cbId == INVALID_CB_ID) {
1424 AUDIO_ERR_LOG("Register AudioPolicyStateMonitor failed");
1425 } else {
1426 cbId_ = cbId;
1427 }
1428 }
1429
StopMonitor()1430 void ForceControlVolumeTypeMonitor::StopMonitor()
1431 {
1432 if (cbId_ != INVALID_CB_ID) {
1433 DelayedSingleton<AudioPolicyStateMonitor>::GetInstance()->UnRegisterCallback(cbId_);
1434 cbId_ = INVALID_CB_ID;
1435 }
1436 }
1437
SetTimer(int32_t duration,std::shared_ptr<ForceControlVolumeTypeMonitor> cb)1438 void ForceControlVolumeTypeMonitor::SetTimer(int32_t duration,
1439 std::shared_ptr<ForceControlVolumeTypeMonitor> cb)
1440 {
1441 std::lock_guard<std::mutex> lock(monitorMtx_);
1442 StopMonitor();
1443 if (duration == CANCEL_FORCE_CONTROL_VOLUME_TYPE) {
1444 return;
1445 }
1446 duration_ = (duration > MAX_DURATION_TIME_S ? MAX_DURATION_TIME_S : duration);
1447 StartMonitor(duration_, cb);
1448 }
1449
SetSystemVolumeDegree(AudioStreamType streamType,int32_t volumeDegree,int32_t zoneId)1450 int32_t AudioVolumeManager::SetSystemVolumeDegree(AudioStreamType streamType, int32_t volumeDegree,
1451 int32_t zoneId)
1452 {
1453 int32_t volumeLevel = VolumeUtils::VolumeDegreeToLevel(volumeDegree);
1454 int32_t currentVolumeDegree = GetSystemVolumeDegree(streamType);
1455 int32_t currentVolumeLevel = VolumeUtils::VolumeDegreeToLevel(currentVolumeDegree);
1456 if (volumeLevel == currentVolumeLevel) {
1457 volumeDegree = currentVolumeDegree;
1458 AUDIO_WARNING_LOG("volume level dont change, keep volume degree=%{public}d", volumeDegree);
1459 }
1460
1461 Volume vol{};
1462 vol.isMute = volumeDegree == 0;
1463 vol.volumeInt = volumeLevel;
1464 vol.volumeDegree = static_cast<uint32_t>(volumeDegree);
1465 vol.volumeFloat = audioPolicyManager_.CalculateVolumeDb(volumeDegree, MAX_VOLUME_DEGREE);
1466 DeviceType curOutputDeviceType = audioActiveDevice_.GetCurrentOutputDeviceType();
1467 SetSharedVolume(streamType, curOutputDeviceType, vol);
1468
1469 return audioPolicyManager_.SetSystemVolumeDegree(VolumeUtils::GetVolumeTypeFromStreamType(streamType),
1470 volumeDegree);
1471 }
1472
GetSystemVolumeDegree(AudioStreamType streamType)1473 int32_t AudioVolumeManager::GetSystemVolumeDegree(AudioStreamType streamType)
1474 {
1475 return audioPolicyManager_.GetSystemVolumeDegree(streamType);
1476 }
1477
GetMinVolumeDegree(AudioVolumeType volumeType) const1478 int32_t AudioVolumeManager::GetMinVolumeDegree(AudioVolumeType volumeType) const
1479 {
1480 if (volumeType == STREAM_ALL) {
1481 volumeType = STREAM_MUSIC;
1482 }
1483 return audioPolicyManager_.GetMinVolumeDegree(volumeType);
1484 }
1485 }
1486 }
1487