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 "AudioAdapterManager"
17 #endif
18
19 #include "audio_adapter_manager.h"
20
21
22 #include "parameter.h"
23 #include "parameters.h"
24
25 #include "audio_policy_service.h"
26 #include "audio_volume_parser.h"
27 #include "audio_policy_server.h"
28 #include "audio_volume.h"
29
30 using namespace std;
31
32 namespace OHOS {
33 namespace AudioStandard {
34 static const std::vector<AudioStreamType> VOLUME_TYPE_LIST = {
35 // all volume types except STREAM_ALL
36 STREAM_RING,
37 STREAM_VOICE_CALL,
38 STREAM_VOICE_ASSISTANT,
39 STREAM_ALARM,
40 STREAM_ACCESSIBILITY,
41 STREAM_SYSTEM,
42 STREAM_ULTRASONIC,
43 STREAM_VOICE_CALL_ASSISTANT,
44 // adjust the type of music from the head of list to end, make sure music is updated last.
45 // avoid interference from ring updates on special platform.
46 // when the device is switched to headset,ring and alarm is dualtone type.
47 // dualtone type use fixed volume curve of speaker.
48 // the ring and alarm are classified into the music group.
49 // the music volume becomes abnormal when the db value of music is modified.
50 STREAM_MUSIC
51 };
52
53 static const std::vector<DeviceType> VOLUME_GROUP_TYPE_LIST = {
54 DEVICE_TYPE_EARPIECE,
55 DEVICE_TYPE_SPEAKER,
56 DEVICE_TYPE_BLUETOOTH_A2DP,
57 DEVICE_TYPE_WIRED_HEADSET,
58 DEVICE_TYPE_REMOTE_CAST
59 };
60
61 static const std::vector<std::string> SYSTEM_SOUND_KEY_LIST = {
62 // all keys for system sound uri
63 "ringtone_for_sim_card_0",
64 "ringtone_for_sim_card_1",
65 "system_tone_for_sim_card_0",
66 "system_tone_for_sim_card_1",
67 "system_tone_for_notification"
68 };
69
70 static const std::unordered_map<DeviceType, DeviceVolumeType> DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP = {
71 {DEVICE_TYPE_EARPIECE, EARPIECE_VOLUME_TYPE},
72 {DEVICE_TYPE_SPEAKER, SPEAKER_VOLUME_TYPE},
73 {DEVICE_TYPE_WIRED_HEADSET, HEADSET_VOLUME_TYPE}
74 };
75
76 // LCOV_EXCL_START
Init()77 bool AudioAdapterManager::Init()
78 {
79 char testMode[10] = {0}; // 10 for system parameter usage
80 auto ret = GetParameter("debug.audio_service.testmodeon", "0", testMode, sizeof(testMode));
81 if (ret == 1 && testMode[0] == '1') {
82 AUDIO_DEBUG_LOG("testMode on");
83 testModeOn_ = true;
84 }
85
86 std::unique_ptr<AudioVolumeParser> audiovolumeParser = make_unique<AudioVolumeParser>();
87 if (!audiovolumeParser->LoadConfig(streamVolumeInfos_)) {
88 AUDIO_INFO_LOG("Audio Volume Config Load Configuration successfully");
89 useNonlinearAlgo_ = 1;
90 UpdateVolumeMapIndex();
91 }
92
93 // init volume before kvstore start by local prop for bootanimation
94 InitBootAnimationVolume();
95 AudioVolume::GetInstance()->SetDefaultAppVolume(appConfigVolume_.defaultVolume);
96 std::string defaultSafeVolume = std::to_string(GetMaxVolumeLevel(STREAM_MUSIC));
97 AUDIO_INFO_LOG("defaultSafeVolume %{public}s", defaultSafeVolume.c_str());
98 char currentSafeVolumeValue[3] = {0};
99 ret = GetParameter("const.audio.safe_media_volume", defaultSafeVolume.c_str(),
100 currentSafeVolumeValue, sizeof(currentSafeVolumeValue));
101 if (ret > 0) {
102 safeVolume_ = atoi(currentSafeVolumeValue);
103 AUDIO_INFO_LOG("Get currentSafeVolumeValue success %{public}d", safeVolume_);
104 } else {
105 AUDIO_ERR_LOG("Get currentSafeVolumeValue failed %{public}d", ret);
106 }
107
108 char safeVolumeTimeout[6] = {0};
109 ret = GetParameter("persist.multimedia.audio.safevolume.timeout", "1140",
110 safeVolumeTimeout, sizeof(safeVolumeTimeout));
111 if (ret > 0) {
112 safeVolumeTimeout_ = atoi(safeVolumeTimeout);
113 AUDIO_INFO_LOG("Get safeVolumeTimeout success %{public}d", safeVolumeTimeout_);
114 } else {
115 AUDIO_ERR_LOG("Get safeVolumeTimeout failed %{public}d", ret);
116 }
117
118 isVolumeUnadjustable_ = system::GetBoolParameter("const.multimedia.audio.fixedvolume", false);
119 AUDIO_INFO_LOG("Get fixdvolume parameter success %{public}d", isVolumeUnadjustable_);
120
121 handler_ = std::make_shared<AudioAdapterManagerHandler>();
122 return true;
123 }
124
InitBootAnimationVolume()125 void AudioAdapterManager::InitBootAnimationVolume()
126 {
127 char currentVolumeValue[3] = {0};
128 AudioVolumeType typeForBootAnimation = VolumeUtils::IsPCVolumeEnable() ? STREAM_SYSTEM : STREAM_RING;
129 int32_t bootAnimationVolume = volumeDataMaintainer_.GetStreamVolume(typeForBootAnimation);
130 AUDIO_DEBUG_LOG("Init: Type[%{public}d],volume[%{public}d]", typeForBootAnimation, bootAnimationVolume);
131 std::string defaultVolume = std::to_string(bootAnimationVolume);
132 auto ret = GetParameter("persist.multimedia.audio.ringtonevolume", defaultVolume.c_str(),
133 currentVolumeValue, sizeof(currentVolumeValue));
134 if (ret > 0) {
135 volumeDataMaintainer_.SetStreamVolume(typeForBootAnimation, atoi(currentVolumeValue));
136 AUDIO_INFO_LOG("Init: Get Type[%{public}d] volume to map volume [%{public}d]",
137 typeForBootAnimation, volumeDataMaintainer_.GetStreamVolume(typeForBootAnimation));
138 } else {
139 AUDIO_ERR_LOG("Init: Get volume parameter failed %{public}d", ret);
140 }
141 }
142
ConnectServiceAdapter()143 bool AudioAdapterManager::ConnectServiceAdapter()
144 {
145 std::unique_ptr<PolicyCallbackImpl> policyCallbackImpl = std::make_unique<PolicyCallbackImpl>(this);
146 audioServiceAdapter_ = AudioServiceAdapter::CreateAudioAdapter(std::move(policyCallbackImpl));
147 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, false,
148 "[AudioAdapterManager] Error in audio adapter initialization");
149
150 bool result = audioServiceAdapter_->Connect();
151 CHECK_AND_RETURN_RET_LOG(result, false, "[AudioAdapterManager] Error in connecting audio adapter");
152
153 return true;
154 }
155
InitKVStore()156 void AudioAdapterManager::InitKVStore()
157 {
158 InitKVStoreInternal();
159 }
160
InitKVStoreInternal()161 void AudioAdapterManager::InitKVStoreInternal()
162 {
163 CHECK_AND_RETURN_LOG(!isLoaded_, "InitKVStore: the database value is loaded");
164
165 AUDIO_INFO_LOG("in");
166 bool isFirstBoot = false;
167 volumeDataMaintainer_.RegisterCloned();
168 InitAudioPolicyKvStore(isFirstBoot);
169
170 if (handler_ != nullptr) {
171 handler_->SendKvDataUpdate(isFirstBoot);
172 }
173 }
174
HandleKvData(bool isFirstBoot)175 void AudioAdapterManager::HandleKvData(bool isFirstBoot)
176 {
177 InitVolumeMap(isFirstBoot);
178 InitRingerMode(isFirstBoot);
179 InitMuteStatusMap(isFirstBoot);
180 InitSafeStatus(isFirstBoot);
181 InitSafeTime(isFirstBoot);
182
183 if (isNeedCopySystemUrlData_) {
184 CloneSystemSoundUrl();
185 }
186
187 if (!isNeedCopyVolumeData_ && !isNeedCopyMuteData_ && !isNeedCopyRingerModeData_ && !isNeedCopySystemUrlData_) {
188 isAllCopyDone_ = true;
189 if (audioPolicyServerHandler_ != nullptr) {
190 audioPolicyServerHandler_->SendRingerModeUpdatedCallback(ringerMode_);
191 SetVolumeCallbackAfterClone();
192 }
193 }
194
195 if (isAllCopyDone_ && audioPolicyKvStore_ != nullptr) {
196 // delete KvStore
197 InitSafeStatus(true);
198 InitSafeTime(true);
199 AUDIO_INFO_LOG("Copy audio_policy private database success to settings database, delete private database...");
200 DeleteAudioPolicyKvStore();
201 }
202
203 // Make sure that the volume value is applied.
204 auto iter = VOLUME_TYPE_LIST.begin();
205 while (iter != VOLUME_TYPE_LIST.end()) {
206 SetVolumeDb(*iter);
207 iter++;
208 }
209 }
210
ReInitKVStore()211 int32_t AudioAdapterManager::ReInitKVStore()
212 {
213 CHECK_AND_RETURN_RET_LOG(audioPolicyKvStore_ != nullptr, ERR_INVALID_OPERATION,
214 "audioPolicyKvStore_ is already nullptr");
215 audioPolicyKvStore_ = nullptr;
216 DistributedKvDataManager manager;
217 Options options;
218
219 AppId appId;
220 appId.appId = "audio_policy_manager";
221 options.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
222
223 StoreId storeId;
224 storeId.storeId = "audiopolicy";
225 Status status = Status::SUCCESS;
226
227 status = manager.CloseKvStore(appId, storeId);
228 AUDIO_ERR_LOG("CloseKvStore status: %{public}d", status);
229 CHECK_AND_RETURN_RET_LOG(status == Status::SUCCESS, ERR_ILLEGAL_STATE, "CloseKvStore failed!");
230
231 status = manager.DeleteKvStore(appId, storeId, options.baseDir);
232 CHECK_AND_RETURN_RET_LOG(status == Status::SUCCESS, ERR_ILLEGAL_STATE, "CloseKvStore failed!");
233
234 InitKVStoreInternal();
235 return SUCCESS;
236 }
237
Deinit(void)238 void AudioAdapterManager::Deinit(void)
239 {
240 CHECK_AND_RETURN_LOG(audioServiceAdapter_, "Deinit audio adapter null");
241
242 if (handler_ != nullptr) {
243 AUDIO_INFO_LOG("release handler");
244 handler_->ReleaseEventRunner();
245 handler_ = nullptr;
246 }
247
248 return audioServiceAdapter_->Disconnect();
249 }
250
SetAudioStreamRemovedCallback(AudioStreamRemovedCallback * callback)251 int32_t AudioAdapterManager::SetAudioStreamRemovedCallback(AudioStreamRemovedCallback *callback)
252 {
253 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM,
254 "SetAudioStreamRemovedCallback callback == nullptr");
255
256 sessionCallback_ = callback;
257 return SUCCESS;
258 }
259
260 // LCOV_EXCL_STOP
GetMaxVolumeLevel(AudioVolumeType volumeType)261 int32_t AudioAdapterManager::GetMaxVolumeLevel(AudioVolumeType volumeType)
262 {
263 CHECK_AND_RETURN_RET_LOG(volumeType >= STREAM_VOICE_CALL && volumeType <= STREAM_TYPE_MAX,
264 ERR_INVALID_PARAM, "Invalid stream type");
265 if (volumeType == STREAM_APP) {
266 return appConfigVolume_.maxVolume;
267 }
268 if (maxVolumeIndexMap_.end() != maxVolumeIndexMap_.find(volumeType)) {
269 return maxVolumeIndexMap_[volumeType];
270 } else if (maxVolumeIndexMap_.end() != maxVolumeIndexMap_.find(STREAM_MUSIC)) {
271 AUDIO_WARNING_LOG("can't find volumeType:%{public}d and use default STREAM_MUSIC", volumeType);
272 return maxVolumeIndexMap_[STREAM_MUSIC];
273 } else {
274 AUDIO_ERR_LOG("use default max volume level %{public}d", MAX_VOLUME_LEVEL);
275 return MAX_VOLUME_LEVEL;
276 }
277 }
278
GetMinVolumeLevel(AudioVolumeType volumeType)279 int32_t AudioAdapterManager::GetMinVolumeLevel(AudioVolumeType volumeType)
280 {
281 CHECK_AND_RETURN_RET_LOG(volumeType >= STREAM_VOICE_CALL && volumeType <= STREAM_TYPE_MAX,
282 ERR_INVALID_PARAM, "Invalid stream type");
283 if (volumeType == STREAM_APP) {
284 return appConfigVolume_.minVolume;
285 }
286 if (minVolumeIndexMap_.end() != minVolumeIndexMap_.find(volumeType)) {
287 return minVolumeIndexMap_[volumeType];
288 } else if (minVolumeIndexMap_.end() != minVolumeIndexMap_.find(STREAM_MUSIC)) {
289 AUDIO_WARNING_LOG("can't find volumeType:%{public}d and use default STREAM_MUSIC", volumeType);
290 return minVolumeIndexMap_[STREAM_MUSIC];
291 } else {
292 AUDIO_ERR_LOG("use default max volume level %{public}d", MIN_VOLUME_LEVEL);
293 return MIN_VOLUME_LEVEL;
294 }
295 }
296
SaveRingtoneVolumeToLocal(AudioVolumeType volumeType,int32_t volumeLevel)297 void AudioAdapterManager::SaveRingtoneVolumeToLocal(AudioVolumeType volumeType, int32_t volumeLevel)
298 {
299 AudioVolumeType audioVolumeMap = VolumeUtils::GetVolumeTypeFromStreamType(volumeType);
300 // PC Boot Animation Volume use STREAM_SYSTEM
301 if ((volumeType == STREAM_RING && !VolumeUtils::IsPCVolumeEnable()) || (audioVolumeMap == STREAM_SYSTEM &&
302 currentActiveDevice_ == DEVICE_TYPE_SPEAKER)) {
303 int32_t volumeLevel =
304 volumeDataMaintainer_.GetStreamVolume(audioVolumeMap) * (GetStreamMute(audioVolumeMap) ? 0 : 1);
305 int32_t ret = SetParameter("persist.multimedia.audio.ringtonevolume", std::to_string(volumeLevel).c_str());
306 if (ret == 0) {
307 AUDIO_INFO_LOG("Save ringtone volume for boot success %{public}d", volumeLevel);
308 } else {
309 AUDIO_ERR_LOG("Save ringtone volume for boot failed, result %{public}d", ret);
310 }
311 }
312 }
313
SetDataShareReady(std::atomic<bool> isDataShareReady)314 void AudioAdapterManager::SetDataShareReady(std::atomic<bool> isDataShareReady)
315 {
316 volumeDataMaintainer_.SetDataShareReady(std::atomic_load(&isDataShareReady));
317 }
318
UpdateSafeVolumeByS4()319 void AudioAdapterManager::UpdateSafeVolumeByS4()
320 {
321 AUDIO_INFO_LOG("Update Safevolume by S4 reboot,reset wired and bt once");
322 isWiredBoot_ = true;
323 isBtBoot_ = true;
324 UpdateSafeVolume();
325 }
326
SetAppVolumeLevel(int32_t appUid,int32_t volumeLevel)327 int32_t AudioAdapterManager::SetAppVolumeLevel(int32_t appUid, int32_t volumeLevel)
328 {
329 AUDIO_INFO_LOG("SetSystemVolumeLevel: appUid: %{public}d, deviceType: %{public}d, volumeLevel:%{public}d",
330 appUid, currentActiveDevice_, volumeLevel);
331 volumeDataMaintainer_.SetAppVolume(appUid, volumeLevel);
332 return SetAppVolumeDb(appUid);
333 }
334
SetAppVolumeMuted(int32_t appUid,bool muted)335 int32_t AudioAdapterManager::SetAppVolumeMuted(int32_t appUid, bool muted)
336 {
337 AUDIO_INFO_LOG("SetSystemVolumeLevel: appUid: %{public}d, deviceType: %{public}d, muted:%{public}d",
338 appUid, currentActiveDevice_, muted);
339 volumeDataMaintainer_.SetAppVolumeMuted(appUid, muted);
340 return SetAppVolumeMutedDB(appUid, muted);
341 }
342
IsAppVolumeMute(int32_t appUid,bool owned)343 bool AudioAdapterManager::IsAppVolumeMute(int32_t appUid, bool owned)
344 {
345 AUDIO_INFO_LOG("IsAppVolumeMute: appUid: %{public}d, deviceType: %{public}d, owned:%{public}d",
346 appUid, currentActiveDevice_, owned);
347 bool isMute = false;
348 if (owned) {
349 isMute = volumeDataMaintainer_.GetAppMuteOwned(appUid);
350 } else {
351 isMute = volumeDataMaintainer_.GetAppMute(appUid);
352 }
353 return isMute;
354 }
355
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel)356 int32_t AudioAdapterManager::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel)
357 {
358 AUDIO_INFO_LOG("SetSystemVolumeLevel: streamType: %{public}d, deviceType: %{public}d, volumeLevel:%{public}d",
359 streamType, currentActiveDevice_, volumeLevel);
360 if (GetSystemVolumeLevel(streamType) == volumeLevel && currentActiveDevice_ != DEVICE_TYPE_BLUETOOTH_SCO &&
361 currentActiveDevice_ != DEVICE_TYPE_BLUETOOTH_A2DP && !VolumeUtils::IsPCVolumeEnable()) {
362 AUDIO_INFO_LOG("The volume is the same as before.");
363 return SUCCESS;
364 }
365 AUDIO_INFO_LOG("SetSystemVolumeLevel: streamType: %{public}d, deviceType: %{public}d, volumeLevel:%{public}d",
366 streamType, currentActiveDevice_, volumeLevel);
367 if (volumeLevel == 0 && !VolumeUtils::IsPCVolumeEnable() &&
368 (streamType == STREAM_VOICE_ASSISTANT || streamType == STREAM_VOICE_CALL ||
369 streamType == STREAM_ALARM || streamType == STREAM_ACCESSIBILITY ||
370 streamType == STREAM_VOICE_COMMUNICATION)) {
371 // these types can not set to mute, but don't return error
372 AUDIO_ERR_LOG("SetSystemVolumeLevel this type can not set mute");
373 return SUCCESS;
374 }
375 int32_t mimRet = GetMinVolumeLevel(streamType);
376 int32_t maxRet = GetMaxVolumeLevel(streamType);
377 CHECK_AND_RETURN_RET_LOG(volumeLevel >= mimRet && volumeLevel <= maxRet, ERR_OPERATION_FAILED,
378 "volumeLevel not in scope,mimRet:%{public}d maxRet:%{public}d", mimRet, maxRet);
379
380 // Save the volume to volumeLevelMap_.
381 volumeDataMaintainer_.SetStreamVolume(streamType, volumeLevel);
382 // Save the volume to settingsdata.
383 if (handler_ != nullptr) {
384 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_ != DEVICE_TYPE_REMOTE_CAST) {
385 AUDIO_INFO_LOG("DualToneStreamType. Save volume for speaker.");
386 handler_->SendSaveVolume(DEVICE_TYPE_SPEAKER, streamType, volumeLevel);
387 } else {
388 handler_->SendSaveVolume(currentActiveDevice_, streamType, volumeLevel);
389 SetDeviceSafeVolume(streamType, volumeLevel);
390 }
391 }
392
393 return SetVolumeDb(streamType);
394 }
395
SetSystemVolumeLevelWithDevice(AudioStreamType streamType,int32_t volumeLevel,DeviceType deviceType)396 int32_t AudioAdapterManager::SetSystemVolumeLevelWithDevice(AudioStreamType streamType, int32_t volumeLevel,
397 DeviceType deviceType)
398 {
399 AUDIO_INFO_LOG("SetSystemVolumeLevelWithDevice: streamType: %{public}d, currentDeviceType: %{public}d, "
400 "volumeLevel:%{public}d, deviceType: %{public}d", streamType, currentActiveDevice_, volumeLevel, deviceType);
401 int32_t mimRet = GetMinVolumeLevel(streamType);
402 int32_t maxRet = GetMaxVolumeLevel(streamType);
403 CHECK_AND_RETURN_RET_LOG(volumeLevel >= mimRet && volumeLevel <= maxRet, ERR_OPERATION_FAILED,
404 "volumeLevel not in scope,mimRet:%{public}d maxRet:%{public}d", mimRet, maxRet);
405 if (currentActiveDevice_ != deviceType) {
406 handler_->SendSaveVolume(deviceType, streamType, volumeLevel);
407 } else {
408 volumeDataMaintainer_.SetStreamVolume(streamType, volumeLevel);
409 handler_->SendSaveVolume(currentActiveDevice_, streamType, volumeLevel);
410 }
411 SetDeviceSafeVolume(streamType, volumeLevel);
412 return SetVolumeDb(streamType);
413 }
414
SetDeviceSafeVolume(const AudioStreamType streamType,const int32_t volumeLevel)415 void AudioAdapterManager::SetDeviceSafeVolume(const AudioStreamType streamType, const int32_t volumeLevel)
416 {
417 if (handler_ == nullptr) {
418 AUDIO_ERR_LOG("handler is nullptr");
419 return;
420 }
421
422 if (safeVolumeCall_ == false) {
423 AUDIO_ERR_LOG("safeVolumeCall is false, not deal");
424 return;
425 }
426
427 int64_t activeSafeTimeBt = GetCurentDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP);
428 int64_t activeSafeTime = GetCurentDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET);
429 SafeStatus safeStatusBt = GetCurrentDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP);
430 SafeStatus safeStatus = GetCurrentDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET);
431 int32_t btVolume = volumeDataMaintainer_.GetDeviceVolume(DEVICE_TYPE_BLUETOOTH_A2DP, STREAM_MUSIC);
432 int32_t wiredVolume = volumeDataMaintainer_.GetDeviceVolume(DEVICE_TYPE_WIRED_HEADSET, STREAM_MUSIC);
433 const int32_t ONE_MINUTE = 60;
434 bool isTimeout = activeSafeTimeBt + activeSafeTime >= ONE_MINUTE * GetSafeVolumeTimeout() ? true : false;
435 switch (currentActiveDevice_) {
436 case DEVICE_TYPE_WIRED_HEADSET:
437 case DEVICE_TYPE_WIRED_HEADPHONES:
438 case DEVICE_TYPE_USB_HEADSET:
439 case DEVICE_TYPE_USB_ARM_HEADSET:
440 if (btVolume > safeVolume_ && isTimeout && safeStatusBt == SAFE_ACTIVE) {
441 AUDIO_INFO_LOG("wired device timeout, set bt device to safe volume");
442 handler_->SendSaveVolume(DEVICE_TYPE_BLUETOOTH_A2DP, streamType, volumeLevel);
443 }
444 break;
445 case DEVICE_TYPE_BLUETOOTH_SCO:
446 case DEVICE_TYPE_BLUETOOTH_A2DP:
447 if (wiredVolume > safeVolume_ && isTimeout && safeStatus == SAFE_ACTIVE) {
448 AUDIO_INFO_LOG("bt device timeout, set wired device to safe volume");
449 handler_->SendSaveVolume(DEVICE_TYPE_WIRED_HEADSET, streamType, volumeLevel);
450 }
451 break;
452 default:
453 AUDIO_ERR_LOG("current device not set safe volume");
454 break;
455 }
456 }
457
SetRestoreVolumeFlag(const bool safeVolumeCall)458 void AudioAdapterManager::SetRestoreVolumeFlag(const bool safeVolumeCall)
459 {
460 safeVolumeCall_ = safeVolumeCall;
461 }
462
HandleSaveVolume(DeviceType deviceType,AudioStreamType streamType,int32_t volumeLevel)463 void AudioAdapterManager::HandleSaveVolume(DeviceType deviceType, AudioStreamType streamType, int32_t volumeLevel)
464 {
465 volumeDataMaintainer_.SaveVolume(deviceType, streamType, volumeLevel);
466 }
467
HandleStreamMuteStatus(AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType)468 void AudioAdapterManager::HandleStreamMuteStatus(AudioStreamType streamType, bool mute, StreamUsage streamUsage,
469 const DeviceType &deviceType)
470 {
471 if (deviceType != DEVICE_TYPE_NONE) {
472 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, mute);
473 } else {
474 volumeDataMaintainer_.SaveMuteStatus(currentActiveDevice_, streamType, mute);
475 }
476 }
477
HandleRingerMode(AudioRingerMode ringerMode)478 void AudioAdapterManager::HandleRingerMode(AudioRingerMode ringerMode)
479 {
480 int32_t volumeLevel =
481 volumeDataMaintainer_.GetStreamVolume(STREAM_RING) * ((ringerMode != RINGER_MODE_NORMAL) ? 0 : 1);
482 // Save volume in local prop for bootanimation
483 SaveRingtoneVolumeToLocal(STREAM_RING, volumeLevel);
484
485 volumeDataMaintainer_.SaveRingerMode(ringerMode);
486 }
487
SetAudioServerProxy(sptr<IStandardAudioService> gsp)488 void AudioAdapterManager::SetAudioServerProxy(sptr<IStandardAudioService> gsp)
489 {
490 CHECK_AND_RETURN_LOG(gsp != nullptr, "audioServerProxy null");
491 audioServerProxy_ = gsp;
492 }
493
SetAppVolumeDb(int32_t appUid)494 int32_t AudioAdapterManager::SetAppVolumeDb(int32_t appUid)
495 {
496 int32_t volumeLevel =
497 volumeDataMaintainer_.GetAppVolume(appUid) * (GetAppMute(appUid) ? 0 : 1);
498 float volumeDb = 1.0f;
499 volumeDb = CalculateVolumeDbNonlinear(STREAM_APP, currentActiveDevice_, volumeLevel);
500 AUDIO_INFO_LOG("volumeDb:%{public}f volume:%{public}d devicetype:%{public}d",
501 volumeDb, volumeLevel, currentActiveDevice_);
502 SetAppAudioVolume(appUid, volumeDb);
503 return SUCCESS;
504 }
505
SetAppVolumeMutedDB(int32_t appUid,bool muted)506 int32_t AudioAdapterManager::SetAppVolumeMutedDB(int32_t appUid, bool muted)
507 {
508 std::lock_guard<std::mutex> lock(audioVolumeMutex_);
509 auto audioVolume = AudioVolume::GetInstance();
510 CHECK_AND_RETURN_RET_LOG(audioVolume != nullptr, ERR_INVALID_PARAM, "audioVolume handle null");
511 AUDIO_INFO_LOG("appUid:%{public}d muted:%{public}d devicetype:%{public}d",
512 appUid, muted, currentActiveDevice_);
513 audioVolume->SetAppVolumeMute(appUid, muted);
514 return SUCCESS;
515 }
516
SetVolumeDb(AudioStreamType streamType)517 int32_t AudioAdapterManager::SetVolumeDb(AudioStreamType streamType)
518 {
519 int32_t volumeLevel =
520 volumeDataMaintainer_.GetStreamVolume(streamType) * (GetStreamMute(streamType) ? 0 : 1);
521 // Save volume in local prop for bootanimation
522 SaveRingtoneVolumeToLocal(streamType, volumeLevel);
523
524 float volumeDb = 1.0f;
525 if (useNonlinearAlgo_) {
526 if (Util::IsDualToneStreamType(streamType) &&
527 currentActiveDevice_ != DEVICE_TYPE_REMOTE_CAST && !VolumeUtils::IsPCVolumeEnable()) {
528 volumeDb = CalculateVolumeDbNonlinear(streamType, DEVICE_TYPE_SPEAKER, volumeLevel);
529 } else {
530 volumeDb = CalculateVolumeDbNonlinear(streamType, currentActiveDevice_, volumeLevel);
531 }
532 } else {
533 volumeDb = CalculateVolumeDb(volumeLevel);
534 }
535 // Set voice call assistant stream to full volume
536 if (streamType == STREAM_VOICE_CALL_ASSISTANT) {
537 volumeDb = 1.0f;
538 }
539
540 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
541 "SetSystemVolumeLevel audio adapter null");
542
543 AUDIO_INFO_LOG("streamType:%{public}d volumeDb:%{public}f volume:%{public}d devicetype:%{public}d",
544 streamType, volumeDb, volumeLevel, currentActiveDevice_);
545
546 // audio volume
547 SetAudioVolume(streamType, volumeDb);
548
549 return SUCCESS;
550 }
551
SetAppAudioVolume(int32_t appUid,float volumeDb)552 void AudioAdapterManager::SetAppAudioVolume(int32_t appUid, float volumeDb)
553 {
554 std::lock_guard<std::mutex> lock(audioVolumeMutex_);
555 auto audioVolume = AudioVolume::GetInstance();
556 CHECK_AND_RETURN_LOG(audioVolume != nullptr, "audioVolume handle null");
557 bool isMuted = GetAppMute(appUid);
558 int32_t appVolumeLevel = volumeDataMaintainer_.GetAppVolume(appUid) * (isMuted ? 0 : 1);
559 AppVolume appVolume(appUid, volumeDb, appVolumeLevel, isMuted);
560 audioVolume->SetAppVolume(appVolume);
561 }
562
SetAudioVolume(AudioStreamType streamType,float volumeDb)563 void AudioAdapterManager::SetAudioVolume(AudioStreamType streamType, float volumeDb)
564 {
565 static std::unordered_map<DeviceType, std::vector<std::string>> deviceClassMap = {
566 {DEVICE_TYPE_SPEAKER, {PRIMARY_CLASS, MCH_CLASS, REMOTE_CLASS, OFFLOAD_CLASS}},
567 {DEVICE_TYPE_USB_HEADSET, {PRIMARY_CLASS, MCH_CLASS, OFFLOAD_CLASS}},
568 {DEVICE_TYPE_BLUETOOTH_A2DP, {A2DP_CLASS, PRIMARY_CLASS, MCH_CLASS, OFFLOAD_CLASS}},
569 {DEVICE_TYPE_BLUETOOTH_SCO, {PRIMARY_CLASS, MCH_CLASS}},
570 {DEVICE_TYPE_EARPIECE, {PRIMARY_CLASS, MCH_CLASS}},
571 {DEVICE_TYPE_WIRED_HEADSET, {PRIMARY_CLASS, MCH_CLASS}},
572 {DEVICE_TYPE_WIRED_HEADPHONES, {PRIMARY_CLASS, MCH_CLASS}},
573 {DEVICE_TYPE_USB_ARM_HEADSET, {USB_CLASS}},
574 {DEVICE_TYPE_REMOTE_CAST, {REMOTE_CAST_INNER_CAPTURER_SINK_NAME}},
575 {DEVICE_TYPE_DP, {DP_CLASS}},
576 {DEVICE_TYPE_FILE_SINK, {FILE_CLASS}},
577 {DEVICE_TYPE_FILE_SOURCE, {FILE_CLASS}},
578 {DEVICE_TYPE_HDMI, {PRIMARY_CLASS}},
579 };
580
581 std::lock_guard<std::mutex> lock(audioVolumeMutex_);
582 AudioStreamType volumeType = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
583 bool isMuted = GetStreamMute(volumeType);
584 int32_t volumeLevel = volumeDataMaintainer_.GetStreamVolume(volumeType) * (isMuted ? 0 : 1);
585 if (GetActiveDevice() == DEVICE_TYPE_BLUETOOTH_A2DP && IsAbsVolumeScene() && volumeType == STREAM_MUSIC) {
586 isMuted = IsAbsVolumeMute();
587 volumeLevel = volumeDataMaintainer_.GetStreamVolume(volumeType) * (isMuted ? 0 : 1);
588 volumeDb = isMuted ? 0.0f : 0.63957f; // 0.63957 = -4dB
589 }
590 auto audioVolume = AudioVolume::GetInstance();
591 CHECK_AND_RETURN_LOG(audioVolume != nullptr, "audioVolume handle null");
592 auto it = deviceClassMap.find(GetActiveDevice());
593 if (it == deviceClassMap.end()) {
594 AUDIO_ERR_LOG("unkown device type %{public}d", GetActiveDevice());
595 return;
596 }
597 for (auto &deviceClass : it->second) {
598 SystemVolume systemVolume(volumeType, deviceClass, volumeDb, volumeLevel, isMuted);
599 if (deviceClass != OFFLOAD_CLASS) {
600 audioVolume->SetSystemVolume(systemVolume);
601 } else if (deviceClass == OFFLOAD_CLASS && volumeType == STREAM_MUSIC) {
602 audioVolume->SetSystemVolume(systemVolume);
603 SetOffloadVolume(volumeType, volumeDb);
604 }
605 }
606 }
607
SetOffloadVolume(AudioStreamType streamType,float volumeDb)608 void AudioAdapterManager::SetOffloadVolume(AudioStreamType streamType, float volumeDb)
609 {
610 float volume = volumeDb; // maybe only system volume
611 if (!(streamType == STREAM_MUSIC || streamType == STREAM_SPEECH)) {
612 return;
613 }
614 DeviceType dev = GetActiveDevice();
615 if (!(dev == DEVICE_TYPE_SPEAKER || dev == DEVICE_TYPE_BLUETOOTH_A2DP || dev == DEVICE_TYPE_USB_HEADSET)) {
616 return;
617 }
618 CHECK_AND_RETURN_LOG(audioServerProxy_ != nullptr, "audioServerProxy_ null");
619 std::string identity = IPCSkeleton::ResetCallingIdentity();
620 if (offloadSessionID_.has_value()) { // need stream volume and system volume
621 volume = AudioVolume::GetInstance()->GetVolume(offloadSessionID_.value(), streamType, OFFLOAD_CLASS);
622 audioServerProxy_->OffloadSetVolume(volume);
623 }
624 IPCSkeleton::SetCallingIdentity(identity);
625 }
626
SetOffloadSessionId(uint32_t sessionId)627 void AudioAdapterManager::SetOffloadSessionId(uint32_t sessionId)
628 {
629 if (sessionId < MIN_STREAMID || sessionId > MAX_STREAMID) {
630 AUDIO_PRERELEASE_LOGE("set sessionId[%{public}d] error", sessionId);
631 } else {
632 AUDIO_PRERELEASE_LOGI("set sessionId[%{public}d]", sessionId);
633 }
634 offloadSessionID_ = sessionId;
635 }
636
ResetOffloadSessionId()637 void AudioAdapterManager::ResetOffloadSessionId()
638 {
639 AUDIO_PRERELEASE_LOGI("reset offload sessionId[%{public}d]", offloadSessionID_.value());
640 offloadSessionID_.reset();
641 }
642
SetDoubleRingVolumeDb(const AudioStreamType & streamType,const int32_t & volumeLevel)643 int32_t AudioAdapterManager::SetDoubleRingVolumeDb(const AudioStreamType &streamType, const int32_t &volumeLevel)
644 {
645 float volumeDb = 1.0f;
646 if (useNonlinearAlgo_) {
647 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_ != DEVICE_TYPE_REMOTE_CAST) {
648 volumeDb = CalculateVolumeDbNonlinear(streamType, DEVICE_TYPE_SPEAKER, volumeLevel);
649 } else {
650 volumeDb = CalculateVolumeDbNonlinear(streamType, currentActiveDevice_, volumeLevel);
651 }
652 } else {
653 volumeDb = CalculateVolumeDb(volumeLevel);
654 }
655 SetAudioVolume(streamType, volumeDb);
656
657 return SUCCESS;
658 }
659
GetSystemVolumeLevel(AudioStreamType streamType)660 int32_t AudioAdapterManager::GetSystemVolumeLevel(AudioStreamType streamType)
661 {
662 if (GetStreamMuteInternal(streamType)) {
663 return MIN_VOLUME_LEVEL;
664 }
665
666 return volumeDataMaintainer_.GetStreamVolume(streamType);
667 }
668
GetAppVolumeLevel(int32_t appUid)669 int32_t AudioAdapterManager::GetAppVolumeLevel(int32_t appUid)
670 {
671 if (volumeDataMaintainer_.IsSetAppVolume(appUid)) {
672 return volumeDataMaintainer_.GetAppVolume(appUid);
673 } else {
674 return appConfigVolume_.defaultVolume;
675 }
676 }
677
GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)678 int32_t AudioAdapterManager::GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)
679 {
680 return volumeDataMaintainer_.GetStreamVolume(streamType);
681 }
682
GetSystemVolumeDb(AudioStreamType streamType)683 float AudioAdapterManager::GetSystemVolumeDb(AudioStreamType streamType)
684 {
685 int32_t volumeLevel = volumeDataMaintainer_.GetStreamVolume(streamType);
686 return CalculateVolumeDb(volumeLevel);
687 }
688
SetStreamMute(AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType)689 int32_t AudioAdapterManager::SetStreamMute(AudioStreamType streamType, bool mute, StreamUsage streamUsage,
690 const DeviceType &deviceType)
691 {
692 return SetStreamMuteInternal(streamType, mute, streamUsage, deviceType);
693 }
694
SetStreamMuteInternal(AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType)695 int32_t AudioAdapterManager::SetStreamMuteInternal(AudioStreamType streamType, bool mute,
696 StreamUsage streamUsage, const DeviceType &deviceType)
697 {
698 AUDIO_INFO_LOG("stream type %{public}d, mute:%{public}d, streamUsage:%{public}d", streamType, mute, streamUsage);
699 if (mute && !VolumeUtils::IsPCVolumeEnable() &&
700 (streamType == STREAM_VOICE_ASSISTANT || streamType == STREAM_VOICE_CALL ||
701 streamType == STREAM_ALARM || streamType == STREAM_ACCESSIBILITY ||
702 streamType == STREAM_VOICE_COMMUNICATION)) {
703 // these types can not set to mute, but don't return error
704 AUDIO_ERR_LOG("SetStreamMute: this type can not set mute");
705 return SUCCESS;
706 }
707 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_ != DEVICE_TYPE_SPEAKER &&
708 GetRingerMode() != RINGER_MODE_NORMAL && mute && Util::IsRingerOrAlarmerStreamUsage(streamUsage)) {
709 AUDIO_INFO_LOG("Dual tone stream type %{public}d, current active device:[%{public}d] is no speaker, dont mute",
710 streamType, mute);
711 return SUCCESS;
712 }
713
714 // set stream mute status to mem.
715 volumeDataMaintainer_.SetStreamMuteStatus(streamType, mute);
716
717 if (handler_ != nullptr) {
718 handler_->SendStreamMuteStatusUpdate(streamType, mute, streamUsage, deviceType);
719 }
720
721 // Achieve the purpose of adjusting the mute status by adjusting the stream volume.
722 return SetVolumeDb(streamType);
723 }
724
SetPersistMicMuteState(const bool isMute)725 int32_t AudioAdapterManager::SetPersistMicMuteState(const bool isMute)
726 {
727 AUDIO_INFO_LOG("Save mute state: %{public}d in setting db", isMute);
728 bool res = volumeDataMaintainer_.SaveMicMuteState(isMute);
729
730 return res == true ? SUCCESS : ERROR;
731 }
732
GetPersistMicMuteState(bool & isMute) const733 int32_t AudioAdapterManager::GetPersistMicMuteState(bool &isMute) const
734 {
735 bool res = volumeDataMaintainer_.GetMicMuteState(isMute);
736 AUDIO_INFO_LOG("Get mute state from setting db is: %{public}d", isMute);
737
738 return res == true ? SUCCESS : ERROR;
739 }
740
SetSourceOutputStreamMute(int32_t uid,bool setMute)741 int32_t AudioAdapterManager::SetSourceOutputStreamMute(int32_t uid, bool setMute)
742 {
743 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
744 "SetSourceOutputStreamMute audio adapter null");
745 return audioServiceAdapter_->SetSourceOutputMute(uid, setMute);
746 }
747
GetStreamMute(AudioStreamType streamType)748 bool AudioAdapterManager::GetStreamMute(AudioStreamType streamType)
749 {
750 return GetStreamMuteInternal(streamType);
751 }
752
GetAppMute(int32_t appUid)753 bool AudioAdapterManager::GetAppMute(int32_t appUid)
754 {
755 return volumeDataMaintainer_.GetAppMute(appUid);
756 }
757
GetStreamVolume(AudioStreamType streamType)758 int32_t AudioAdapterManager::GetStreamVolume(AudioStreamType streamType)
759 {
760 return volumeDataMaintainer_.GetStreamVolume(streamType);
761 }
762
GetStreamMuteInternal(AudioStreamType streamType)763 bool AudioAdapterManager::GetStreamMuteInternal(AudioStreamType streamType)
764 {
765 return volumeDataMaintainer_.GetStreamMute(streamType);
766 }
767
768 // LCOV_EXCL_START
GetAllSinks()769 vector<SinkInfo> AudioAdapterManager::GetAllSinks()
770 {
771 if (!audioServiceAdapter_) {
772 AUDIO_ERR_LOG("GetAllSinks audio adapter null");
773 vector<SinkInfo> sinkInputList;
774 return sinkInputList;
775 }
776
777 return audioServiceAdapter_->GetAllSinks();
778 }
779
GetAllSinkInputs(std::vector<SinkInput> & sinkInputs)780 void AudioAdapterManager::GetAllSinkInputs(std::vector<SinkInput> &sinkInputs)
781 {
782 AudioPolicyService::GetAudioPolicyService().GetAllSinkInputs(sinkInputs);
783 }
784
GetAllSourceOutputs()785 vector<SourceOutput> AudioAdapterManager::GetAllSourceOutputs()
786 {
787 if (!audioServiceAdapter_) {
788 AUDIO_ERR_LOG("GetAllSourceOutputs audio adapter null");
789 vector<SourceOutput> sourceOutputList;
790 return sourceOutputList;
791 }
792
793 return audioServiceAdapter_->GetAllSourceOutputs();
794 }
795
SuspendAudioDevice(std::string & portName,bool isSuspend)796 int32_t AudioAdapterManager::SuspendAudioDevice(std::string &portName, bool isSuspend)
797 {
798 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
799 "SuspendAudioDevice audio adapter null");
800
801 return audioServiceAdapter_->SuspendAudioDevice(portName, isSuspend);
802 }
803
SetSinkMute(const std::string & sinkName,bool isMute,bool isSync)804 bool AudioAdapterManager::SetSinkMute(const std::string &sinkName, bool isMute, bool isSync)
805 {
806 static std::unordered_map<std::string, std::string> sinkNameMap = {
807 {PRIMARY_SPEAKER, PRIMARY_CLASS},
808 {OFFLOAD_PRIMARY_SPEAKER, OFFLOAD_CLASS},
809 {BLUETOOTH_SPEAKER, A2DP_CLASS},
810 {MCH_PRIMARY_SPEAKER, MCH_CLASS},
811 {USB_SPEAKER, USB_CLASS},
812 {DP_SINK, DP_CLASS},
813 {FILE_SINK, FILE_CLASS},
814 {REMOTE_CAST_INNER_CAPTURER_SINK_NAME, REMOTE_CAST_INNER_CAPTURER_SINK_NAME},
815 };
816 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, false, "SetSinkMute audio adapter null");
817 auto audioVolume = AudioVolume::GetInstance();
818 CHECK_AND_RETURN_RET_LOG(audioVolume, false, "SetSinkMute audioVolume handle null");
819 auto it = sinkNameMap.find(sinkName);
820 for (auto &volumeType : VOLUME_TYPE_LIST) {
821 if (it != sinkNameMap.end()) {
822 if ((it->second == OFFLOAD_CLASS && volumeType == STREAM_MUSIC) ||
823 it->second != OFFLOAD_CLASS) {
824 audioVolume->SetSystemVolumeMute(volumeType, it->second, isMute);
825 }
826 } else if (sinkName.find("_out") != std::string::npos &&
827 sinkName.find(LOCAL_NETWORK_ID) == std::string::npos) {
828 audioVolume->SetSystemVolumeMute(volumeType, REMOTE_CLASS, isMute);
829 } else {
830 AUDIO_ERR_LOG("unkown sink name %{public}s", sinkName.c_str());
831 }
832 }
833
834 return audioServiceAdapter_->SetSinkMute(sinkName, isMute, isSync);
835 }
836
SelectDevice(DeviceRole deviceRole,InternalDeviceType deviceType,std::string name)837 int32_t AudioAdapterManager::SelectDevice(DeviceRole deviceRole, InternalDeviceType deviceType, std::string name)
838 {
839 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
840 "SelectDevice audio adapter null");
841 switch (deviceRole) {
842 case DeviceRole::INPUT_DEVICE:
843 return audioServiceAdapter_->SetDefaultSource(name);
844 case DeviceRole::OUTPUT_DEVICE: {
845 AUDIO_INFO_LOG("SetDefaultSink %{public}d", deviceType);
846 return audioServiceAdapter_->SetDefaultSink(name);
847 }
848 default:
849 AUDIO_ERR_LOG("SelectDevice error deviceRole %{public}d", deviceRole);
850 return ERR_OPERATION_FAILED;
851 }
852 return SUCCESS;
853 }
854
SetDeviceActive(InternalDeviceType deviceType,std::string name,bool active,DeviceFlag flag)855 int32_t AudioAdapterManager::SetDeviceActive(InternalDeviceType deviceType,
856 std::string name, bool active, DeviceFlag flag)
857 {
858 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
859 "SetDeviceActive audio adapter null");
860
861 switch (deviceType) {
862 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET: {
863 if (name == USB_SPEAKER) {
864 return audioServiceAdapter_->SetDefaultSink(name);
865 } else {
866 return audioServiceAdapter_->SetDefaultSource(name);
867 }
868 }
869 default: {
870 int32_t ret = SUCCESS;
871 int32_t errs[2]{SUCCESS, SUCCESS};
872 if (IsInputDevice(deviceType) && (flag & INPUT_DEVICES_FLAG)) {
873 AUDIO_INFO_LOG("SetDefaultSource %{public}d", deviceType);
874 errs[0] = audioServiceAdapter_->SetDefaultSource(name);
875 if (errs[0] != SUCCESS) {
876 AUDIO_ERR_LOG("SetDefaultSource err: %{public}d", errs[0]);
877 ret = errs[0];
878 }
879 }
880 if (IsOutputDevice(deviceType) && (flag & OUTPUT_DEVICES_FLAG)) {
881 AUDIO_INFO_LOG("SetDefaultSink %{public}d", deviceType);
882 errs[1] = audioServiceAdapter_->SetDefaultSink(name);
883 if (errs[1] != SUCCESS) {
884 AUDIO_ERR_LOG("SetDefaultSink err: %{public}d", errs[1]);
885 ret = errs[1];
886 }
887 }
888 // Ensure compatibility across different platforms and versions
889 if (errs[0] == SUCCESS || errs[1] == SUCCESS) {
890 return SUCCESS;
891 }
892 return ret;
893 }
894 }
895 return SUCCESS;
896 }
897
MaximizeVoiceAssistantVolume(InternalDeviceType deviceType)898 void AudioAdapterManager::MaximizeVoiceAssistantVolume(InternalDeviceType deviceType)
899 {
900 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP && IsAbsVolumeScene() && !VolumeUtils::IsPCVolumeEnable()) {
901 volumeDataMaintainer_.SetStreamVolume(STREAM_VOICE_ASSISTANT, MAX_VOLUME_LEVEL);
902 SetVolumeDb(STREAM_VOICE_ASSISTANT);
903 AUDIO_INFO_LOG("MaximizeVoiceAssistantVolume ok");
904 }
905 }
906
SetVolumeForSwitchDevice(InternalDeviceType deviceType)907 void AudioAdapterManager::SetVolumeForSwitchDevice(InternalDeviceType deviceType)
908 {
909 std::lock_guard<std::mutex> lock(activeDeviceMutex_);
910 MaximizeVoiceAssistantVolume(deviceType);
911 // The same device does not set the volume
912 bool isSameVolumeGroup = GetVolumeGroupForDevice(currentActiveDevice_) == GetVolumeGroupForDevice(deviceType);
913 if (currentActiveDevice_ == deviceType) {
914 AUDIO_INFO_LOG("Old device: %{public}d. New device: %{public}d. No need to update volume",
915 currentActiveDevice_, deviceType);
916 return;
917 }
918
919 AUDIO_INFO_LOG("SetVolumeForSwitchDevice: Load volume and mute status for new device %{public}d,"
920 "same volume group %{public}d", deviceType, isSameVolumeGroup);
921 // Current device must be updated even if kvStore is nullptr.
922 currentActiveDevice_ = deviceType;
923
924 if (!isSameVolumeGroup) {
925 // If there's no os account available when trying to get one, audio_server would sleep for 1 sec
926 // and retry for 5 times, which could cause a sysfreeze. Check if any os account is ready. If not,
927 // skip interacting with datashare.
928 bool osAccountReady = volumeDataMaintainer_.CheckOsAccountReady();
929 if (osAccountReady) {
930 LoadVolumeMap();
931 LoadMuteStatusMap();
932 UpdateSafeVolume();
933 } else {
934 AUDIO_WARNING_LOG("Os account is not ready, skip visiting datashare.");
935 }
936 }
937
938 auto iter = VOLUME_TYPE_LIST.begin();
939 while (iter != VOLUME_TYPE_LIST.end()) {
940 // update volume level and mute status for each stream type
941 SetVolumeDb(*iter);
942 AUDIO_INFO_LOG("SetVolumeForSwitchDevice: volume: %{public}d, mute: %{public}d for stream type %{public}d",
943 volumeDataMaintainer_.GetStreamVolume(*iter), volumeDataMaintainer_.GetStreamMute(*iter), *iter);
944 iter++;
945 }
946 }
947
MoveSinkInputByIndexOrName(uint32_t sinkInputId,uint32_t sinkIndex,std::string sinkName)948 int32_t AudioAdapterManager::MoveSinkInputByIndexOrName(uint32_t sinkInputId, uint32_t sinkIndex, std::string sinkName)
949 {
950 return audioServiceAdapter_->MoveSinkInputByIndexOrName(sinkInputId, sinkIndex, sinkName);
951 }
952
MoveSourceOutputByIndexOrName(uint32_t sourceOutputId,uint32_t sourceIndex,std::string sourceName)953 int32_t AudioAdapterManager::MoveSourceOutputByIndexOrName(uint32_t sourceOutputId, uint32_t sourceIndex,
954 std::string sourceName)
955 {
956 return audioServiceAdapter_->MoveSourceOutputByIndexOrName(sourceOutputId, sourceIndex, sourceName);
957 }
958
959 // LCOV_EXCL_STOP
SetRingerMode(AudioRingerMode ringerMode)960 int32_t AudioAdapterManager::SetRingerMode(AudioRingerMode ringerMode)
961 {
962 return SetRingerModeInternal(ringerMode);
963 }
964
SetRingerModeInternal(AudioRingerMode ringerMode)965 int32_t AudioAdapterManager::SetRingerModeInternal(AudioRingerMode ringerMode)
966 {
967 AUDIO_INFO_LOG("SetRingerMode: %{public}d", ringerMode);
968 ringerMode_ = ringerMode;
969
970 if (handler_ != nullptr) {
971 handler_->SendRingerModeUpdate(ringerMode);
972 }
973 return SUCCESS;
974 }
975
GetRingerMode() const976 AudioRingerMode AudioAdapterManager::GetRingerMode() const
977 {
978 return ringerMode_;
979 }
980
981 // LCOV_EXCL_START
OpenAudioPort(const AudioModuleInfo & audioModuleInfo)982 AudioIOHandle AudioAdapterManager::OpenAudioPort(const AudioModuleInfo &audioModuleInfo)
983 {
984 std::string moduleArgs = GetModuleArgs(audioModuleInfo);
985
986 AUDIO_INFO_LOG("[Adapter load-module] %{public}s %{public}s",
987 audioModuleInfo.lib.c_str(), audioModuleInfo.className.c_str());
988
989 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
990 curActiveCount_++;
991 AudioIOHandle ioHandle = audioServiceAdapter_->OpenAudioPort(audioModuleInfo.lib, moduleArgs.c_str());
992 AUDIO_INFO_LOG("Open %{public}d port end.", static_cast<int32_t>(ioHandle));
993 return ioHandle;
994 }
995
CloseAudioPort(AudioIOHandle ioHandle,bool isSync)996 int32_t AudioAdapterManager::CloseAudioPort(AudioIOHandle ioHandle, bool isSync)
997 {
998 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
999 curActiveCount_--;
1000 int32_t ret = audioServiceAdapter_->CloseAudioPort(ioHandle, isSync);
1001 AUDIO_INFO_LOG("Close %{public}d port end.", static_cast<int32_t>(ioHandle));
1002 return ret;
1003 }
1004
GetCurActivateCount() const1005 int32_t AudioAdapterManager::GetCurActivateCount() const
1006 {
1007 return curActiveCount_ > 0 ? curActiveCount_ : 0;
1008 }
1009
UpdateSinkArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1010 void UpdateSinkArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1011 {
1012 if (!audioModuleInfo.name.empty()) {
1013 args.append(" sink_name=");
1014 args.append(audioModuleInfo.name);
1015 }
1016
1017 if (!audioModuleInfo.adapterName.empty()) {
1018 args.append(" adapter_name=");
1019 args.append(audioModuleInfo.adapterName);
1020 }
1021
1022 if (!audioModuleInfo.className.empty()) {
1023 args.append(" device_class=");
1024 args.append(audioModuleInfo.className);
1025 }
1026
1027 if (!audioModuleInfo.fileName.empty()) {
1028 args.append(" file_path=");
1029 args.append(audioModuleInfo.fileName);
1030 }
1031 if (!audioModuleInfo.sinkLatency.empty()) {
1032 args.append(" sink_latency=");
1033 args.append(audioModuleInfo.sinkLatency);
1034 }
1035
1036 if (!audioModuleInfo.networkId.empty()) {
1037 args.append(" network_id=");
1038 args.append(audioModuleInfo.networkId);
1039 } else {
1040 args.append(" network_id=LocalDevice");
1041 }
1042
1043 if (!audioModuleInfo.deviceType.empty()) {
1044 args.append(" device_type=");
1045 args.append(audioModuleInfo.deviceType);
1046 }
1047
1048 if (!audioModuleInfo.extra.empty()) {
1049 args.append(" split_mode=");
1050 args.append(audioModuleInfo.extra);
1051 }
1052 }
1053
UpdateEcAndMicRefArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1054 void UpdateEcAndMicRefArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1055 {
1056 if (!audioModuleInfo.ecType.empty()) {
1057 args.append(" ec_type=");
1058 args.append(audioModuleInfo.ecType);
1059 }
1060
1061 if (!audioModuleInfo.ecAdapter.empty()) {
1062 args.append(" ec_adapter=");
1063 args.append(audioModuleInfo.ecAdapter);
1064 }
1065
1066 if (!audioModuleInfo.ecSamplingRate.empty()) {
1067 args.append(" ec_sampling_rate=");
1068 args.append(audioModuleInfo.ecSamplingRate);
1069 }
1070
1071 if (!audioModuleInfo.ecFormat.empty()) {
1072 args.append(" ec_format=");
1073 args.append(audioModuleInfo.ecFormat);
1074 }
1075
1076 if (!audioModuleInfo.ecChannels.empty()) {
1077 args.append(" ec_channels=");
1078 args.append(audioModuleInfo.ecChannels);
1079 }
1080
1081 if (!audioModuleInfo.openMicRef.empty()) {
1082 args.append(" open_mic_ref=");
1083 args.append(audioModuleInfo.openMicRef);
1084 }
1085
1086 if (!audioModuleInfo.micRefRate.empty()) {
1087 args.append(" mic_ref_rate=");
1088 args.append(audioModuleInfo.micRefRate);
1089 }
1090
1091 if (!audioModuleInfo.micRefFormat.empty()) {
1092 args.append(" mic_ref_format=");
1093 args.append(audioModuleInfo.micRefFormat);
1094 }
1095
1096 if (!audioModuleInfo.micRefChannels.empty()) {
1097 args.append(" mic_ref_channels=");
1098 args.append(audioModuleInfo.micRefChannels);
1099 }
1100 }
1101
UpdateSourceArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1102 void UpdateSourceArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1103 {
1104 if (!audioModuleInfo.name.empty()) {
1105 args.append(" source_name=");
1106 args.append(audioModuleInfo.name);
1107 }
1108
1109 if (!audioModuleInfo.adapterName.empty()) {
1110 args.append(" adapter_name=");
1111 args.append(audioModuleInfo.adapterName);
1112 }
1113
1114 if (!audioModuleInfo.className.empty()) {
1115 args.append(" device_class=");
1116 args.append(audioModuleInfo.className);
1117 }
1118
1119 if (!audioModuleInfo.fileName.empty()) {
1120 args.append(" file_path=");
1121 args.append(audioModuleInfo.fileName);
1122 }
1123
1124 if (!audioModuleInfo.networkId.empty()) {
1125 args.append(" network_id=");
1126 args.append(audioModuleInfo.networkId);
1127 } else {
1128 args.append(" network_id=LocalDevice");
1129 }
1130
1131 if (!audioModuleInfo.deviceType.empty()) {
1132 args.append(" device_type=");
1133 args.append(audioModuleInfo.deviceType);
1134 }
1135
1136 if (!audioModuleInfo.sourceType.empty()) {
1137 args.append(" source_type=");
1138 args.append(audioModuleInfo.sourceType);
1139 }
1140 }
1141
UpdateCommonArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1142 void UpdateCommonArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1143 {
1144 if (!audioModuleInfo.rate.empty()) {
1145 args = "rate=";
1146 args.append(audioModuleInfo.rate);
1147 }
1148
1149 if (!audioModuleInfo.channels.empty()) {
1150 args.append(" channels=");
1151 args.append(audioModuleInfo.channels);
1152 }
1153
1154 if (!audioModuleInfo.bufferSize.empty()) {
1155 args.append(" buffer_size=");
1156 args.append(audioModuleInfo.bufferSize);
1157 }
1158
1159 if (!audioModuleInfo.format.empty()) {
1160 args.append(" format=");
1161 args.append(audioModuleInfo.format);
1162 }
1163
1164 if (!audioModuleInfo.fixedLatency.empty()) {
1165 args.append(" fixed_latency=");
1166 args.append(audioModuleInfo.fixedLatency);
1167 }
1168
1169 if (!audioModuleInfo.renderInIdleState.empty()) {
1170 args.append(" render_in_idle_state=");
1171 args.append(audioModuleInfo.renderInIdleState);
1172 }
1173
1174 if (!audioModuleInfo.OpenMicSpeaker.empty()) {
1175 args.append(" open_mic_speaker=");
1176 args.append(audioModuleInfo.OpenMicSpeaker);
1177 }
1178
1179 if (!audioModuleInfo.offloadEnable.empty()) {
1180 args.append(" offload_enable=");
1181 args.append(audioModuleInfo.offloadEnable);
1182 }
1183
1184 if (!audioModuleInfo.defaultAdapterEnable.empty()) {
1185 args.append(" default_adapter_enable=");
1186 args.append(audioModuleInfo.defaultAdapterEnable);
1187 }
1188 AUDIO_INFO_LOG("[Adapter load-module] [PolicyManager] common args:%{public}s", args.c_str());
1189 }
1190
1191 // Private Members
GetModuleArgs(const AudioModuleInfo & audioModuleInfo) const1192 std::string AudioAdapterManager::GetModuleArgs(const AudioModuleInfo &audioModuleInfo) const
1193 {
1194 std::string args;
1195
1196 if (audioModuleInfo.lib == HDI_SINK) {
1197 UpdateCommonArgs(audioModuleInfo, args);
1198 UpdateSinkArgs(audioModuleInfo, args);
1199 if (testModeOn_) {
1200 args.append(" test_mode_on=");
1201 args.append("1");
1202 }
1203 } else if (audioModuleInfo.lib == SPLIT_STREAM_SINK) {
1204 UpdateCommonArgs(audioModuleInfo, args);
1205 UpdateSinkArgs(audioModuleInfo, args);
1206 } else if (audioModuleInfo.lib == HDI_SOURCE) {
1207 UpdateCommonArgs(audioModuleInfo, args);
1208 UpdateSourceArgs(audioModuleInfo, args);
1209 UpdateEcAndMicRefArgs(audioModuleInfo, args);
1210 } else if (audioModuleInfo.lib == PIPE_SINK) {
1211 if (!audioModuleInfo.fileName.empty()) {
1212 args = "file=";
1213 args.append(audioModuleInfo.fileName);
1214 }
1215 } else if (audioModuleInfo.lib == PIPE_SOURCE) {
1216 if (!audioModuleInfo.fileName.empty()) {
1217 args = "file=";
1218 args.append(audioModuleInfo.fileName);
1219 }
1220 } else if (audioModuleInfo.lib == CLUSTER_SINK) {
1221 UpdateCommonArgs(audioModuleInfo, args);
1222 if (!audioModuleInfo.name.empty()) {
1223 args.append(" sink_name=");
1224 args.append(audioModuleInfo.name);
1225 }
1226 } else if (audioModuleInfo.lib == EFFECT_SINK) {
1227 UpdateCommonArgs(audioModuleInfo, args);
1228 if (!audioModuleInfo.name.empty()) {
1229 args.append(" sink_name=");
1230 args.append(audioModuleInfo.name);
1231 }
1232 if (!audioModuleInfo.sceneName.empty()) {
1233 args.append(" scene_name=");
1234 args.append(audioModuleInfo.sceneName);
1235 }
1236 } else if (audioModuleInfo.lib == INNER_CAPTURER_SINK || audioModuleInfo.lib == RECEIVER_SINK) {
1237 UpdateCommonArgs(audioModuleInfo, args);
1238 if (!audioModuleInfo.name.empty()) {
1239 args.append(" sink_name=");
1240 args.append(audioModuleInfo.name);
1241 }
1242 }
1243 return args;
1244 }
1245
GetVolumeKeyForKvStore(DeviceType deviceType,AudioStreamType streamType)1246 std::string AudioAdapterManager::GetVolumeKeyForKvStore(DeviceType deviceType, AudioStreamType streamType)
1247 {
1248 DeviceGroup type = GetVolumeGroupForDevice(deviceType);
1249 std::string typeStr = std::to_string(type);
1250 CHECK_AND_RETURN_RET_LOG(type != DEVICE_GROUP_INVALID, typeStr,
1251 "Device %{public}d is not supported for kvStore", deviceType);
1252
1253 switch (streamType) {
1254 case STREAM_MUSIC:
1255 return typeStr + "_music_volume";
1256 case STREAM_RING:
1257 case STREAM_VOICE_RING:
1258 return typeStr + "_ring_volume";
1259 case STREAM_SYSTEM:
1260 return typeStr + "_system_volume";
1261 case STREAM_NOTIFICATION:
1262 return typeStr + "_notification_volume";
1263 case STREAM_ALARM:
1264 return typeStr + "_alarm_volume";
1265 case STREAM_DTMF:
1266 return typeStr + "_dtmf_volume";
1267 case STREAM_VOICE_CALL:
1268 case STREAM_VOICE_COMMUNICATION:
1269 return typeStr + "_voice_call_volume";
1270 case STREAM_VOICE_ASSISTANT:
1271 return typeStr + "_voice_assistant_volume";
1272 case STREAM_ACCESSIBILITY:
1273 return typeStr + "_accessibility_volume";
1274 case STREAM_ULTRASONIC:
1275 return typeStr + "_ultrasonic_volume";
1276 case STREAM_WAKEUP:
1277 return typeStr + "wakeup";
1278 default:
1279 AUDIO_ERR_LOG("GetVolumeKeyForKvStore: streamType %{public}d is not supported for kvStore", streamType);
1280 return "";
1281 }
1282 }
1283
GetStreamIDByType(std::string streamType)1284 AudioStreamType AudioAdapterManager::GetStreamIDByType(std::string streamType)
1285 {
1286 AudioStreamType stream = STREAM_MUSIC;
1287
1288 if (!streamType.compare(std::string("music")))
1289 stream = STREAM_MUSIC;
1290 else if (!streamType.compare(std::string("ring")))
1291 stream = STREAM_RING;
1292 else if (!streamType.compare(std::string("voice_call")))
1293 stream = STREAM_VOICE_CALL;
1294 else if (!streamType.compare(std::string("system")))
1295 stream = STREAM_SYSTEM;
1296 else if (!streamType.compare(std::string("notification")))
1297 stream = STREAM_NOTIFICATION;
1298 else if (!streamType.compare(std::string("alarm")))
1299 stream = STREAM_ALARM;
1300 else if (!streamType.compare(std::string("voice_assistant")))
1301 stream = STREAM_VOICE_ASSISTANT;
1302 else if (!streamType.compare(std::string("accessibility")))
1303 stream = STREAM_ACCESSIBILITY;
1304 else if (!streamType.compare(std::string("ultrasonic")))
1305 stream = STREAM_ULTRASONIC;
1306 else if (!streamType.compare(std::string("camcorder")))
1307 stream = STREAM_CAMCORDER;
1308 return stream;
1309 }
1310
GetDeviceCategory(DeviceType deviceType)1311 DeviceVolumeType AudioAdapterManager::GetDeviceCategory(DeviceType deviceType)
1312 {
1313 switch (deviceType) {
1314 case DEVICE_TYPE_EARPIECE:
1315 return EARPIECE_VOLUME_TYPE;
1316 case DEVICE_TYPE_SPEAKER:
1317 case DEVICE_TYPE_FILE_SOURCE:
1318 case DEVICE_TYPE_DP:
1319 case DEVICE_TYPE_HDMI:
1320 return SPEAKER_VOLUME_TYPE;
1321 case DEVICE_TYPE_WIRED_HEADSET:
1322 case DEVICE_TYPE_WIRED_HEADPHONES:
1323 case DEVICE_TYPE_BLUETOOTH_SCO:
1324 case DEVICE_TYPE_BLUETOOTH_A2DP:
1325 case DEVICE_TYPE_USB_HEADSET:
1326 case DEVICE_TYPE_USB_ARM_HEADSET:
1327 return HEADSET_VOLUME_TYPE;
1328 default:
1329 return SPEAKER_VOLUME_TYPE;
1330 }
1331 }
1332
InitAudioPolicyKvStore(bool & isFirstBoot)1333 bool AudioAdapterManager::InitAudioPolicyKvStore(bool& isFirstBoot)
1334 {
1335 DistributedKvDataManager manager;
1336 Options options;
1337
1338 AppId appId;
1339 appId.appId = "audio_policy_manager";
1340
1341 options.securityLevel = S1;
1342 options.createIfMissing = false;
1343 options.encrypt = false;
1344 options.autoSync = false;
1345 options.kvStoreType = KvStoreType::SINGLE_VERSION;
1346 options.area = EL1;
1347 options.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
1348
1349 StoreId storeId;
1350 storeId.storeId = "audiopolicy";
1351 Status status = Status::SUCCESS;
1352
1353 // open and initialize kvstore instance.
1354 if (audioPolicyKvStore_ == nullptr) {
1355 uint32_t retries = 0;
1356
1357 do {
1358 status = manager.GetSingleKvStore(options, appId, storeId, audioPolicyKvStore_);
1359 AUDIO_ERR_LOG("GetSingleKvStore status: %{public}d", status);
1360 if ((status == Status::SUCCESS) || (status == Status::INVALID_ARGUMENT) ||
1361 (status == Status::DATA_CORRUPTED) || (status == Status::CRYPT_ERROR)) {
1362 break;
1363 } else {
1364 AUDIO_ERR_LOG("InitAudioPolicyKvStore: Kvstore Connect failed! Retrying.");
1365 retries++;
1366 usleep(KVSTORE_CONNECT_RETRY_DELAY_TIME);
1367 }
1368 } while (retries <= KVSTORE_CONNECT_RETRY_COUNT);
1369 }
1370
1371 if (audioPolicyKvStore_ != nullptr) {
1372 isNeedCopyVolumeData_ = true;
1373 isNeedCopyMuteData_ = true;
1374 isNeedCopyRingerModeData_ = true;
1375 isNeedCopySystemUrlData_ = true;
1376 SetFirstBoot(false);
1377 return true;
1378 }
1379 // first boot
1380 char firstboot[3] = {0};
1381 GetParameter("persist.multimedia.audio.firstboot", "0", firstboot, sizeof(firstboot));
1382 if (stoi(firstboot) == 1) {
1383 AUDIO_INFO_LOG("first boot, ready init data to database");
1384 isFirstBoot = true;
1385 SetFirstBoot(false);
1386 }
1387
1388 return true;
1389 }
1390
DeleteAudioPolicyKvStore()1391 void AudioAdapterManager::DeleteAudioPolicyKvStore()
1392 {
1393 DistributedKvDataManager manager;
1394 Options options;
1395
1396 AppId appId;
1397 appId.appId = "audio_policy_manager";
1398
1399 options.securityLevel = S1;
1400 options.createIfMissing = false;
1401 options.encrypt = false;
1402 options.autoSync = false;
1403 options.kvStoreType = KvStoreType::SINGLE_VERSION;
1404 options.area = EL1;
1405 options.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
1406
1407 StoreId storeId;
1408 storeId.storeId = "audiopolicy";
1409 Status status = Status::SUCCESS;
1410
1411 if (audioPolicyKvStore_ != nullptr) {
1412 status = manager.CloseKvStore(appId, storeId);
1413 if (status != Status::SUCCESS) {
1414 AUDIO_ERR_LOG("close KvStore failed");
1415 }
1416 status = manager.DeleteKvStore(appId, storeId, options.baseDir);
1417 if (status != Status::SUCCESS) {
1418 AUDIO_ERR_LOG("DeleteKvStore failed");
1419 }
1420 audioPolicyKvStore_ = nullptr;
1421 }
1422 }
1423
UpdateSafeVolume()1424 void AudioAdapterManager::UpdateSafeVolume()
1425 {
1426 auto currentActiveOutputDeviceDescriptor =
1427 AudioPolicyService::GetAudioPolicyService().GetActiveOutputDeviceDescriptor();
1428 switch (currentActiveDevice_) {
1429 case DEVICE_TYPE_WIRED_HEADSET:
1430 case DEVICE_TYPE_WIRED_HEADPHONES:
1431 case DEVICE_TYPE_USB_HEADSET:
1432 case DEVICE_TYPE_USB_ARM_HEADSET:
1433 if (volumeDataMaintainer_.GetStreamVolume(STREAM_MUSIC) <= safeVolume_) {
1434 AUDIO_INFO_LOG("1st connect bt device volume is safe");
1435 isWiredBoot_ = false;
1436 return;
1437 }
1438 if (isWiredBoot_) {
1439 AUDIO_INFO_LOG("1st connect wired device:%{public}d after boot, update current volume to safevolume",
1440 currentActiveDevice_);
1441 volumeDataMaintainer_.SetStreamVolume(STREAM_MUSIC, safeVolume_);
1442 volumeDataMaintainer_.SaveVolume(currentActiveDevice_, STREAM_MUSIC, safeVolume_);
1443 isWiredBoot_ = false;
1444 }
1445 break;
1446 case DEVICE_TYPE_BLUETOOTH_SCO:
1447 case DEVICE_TYPE_BLUETOOTH_A2DP:
1448 if (volumeDataMaintainer_.GetStreamVolume(STREAM_MUSIC) <= safeVolume_) {
1449 AUDIO_INFO_LOG("1st connect bt device volume is safe");
1450 isBtBoot_ = false;
1451 return;
1452 }
1453 if (currentActiveOutputDeviceDescriptor != nullptr) {
1454 AUDIO_INFO_LOG("bluetooth Category:%{public}d", currentActiveOutputDeviceDescriptor->deviceCategory_);
1455 if (currentActiveOutputDeviceDescriptor->deviceCategory_ == BT_CAR ||
1456 currentActiveOutputDeviceDescriptor->deviceCategory_ == BT_SOUNDBOX) {
1457 AUDIO_ERR_LOG("current device: %{public}d is not support", currentActiveDevice_);
1458 return;
1459 }
1460 }
1461 if (isBtBoot_) {
1462 AUDIO_INFO_LOG("1st connect bt device:%{public}d after boot, update current volume to safevolume",
1463 currentActiveDevice_);
1464 volumeDataMaintainer_.SetStreamVolume(STREAM_MUSIC, safeVolume_);
1465 volumeDataMaintainer_.SaveVolume(currentActiveDevice_, STREAM_MUSIC, safeVolume_);
1466 isBtBoot_ = false;
1467 }
1468 break;
1469 default:
1470 AUDIO_ERR_LOG("current device: %{public}d is not support", currentActiveDevice_);
1471 break;
1472 }
1473 }
1474
InitVolumeMap(bool isFirstBoot)1475 void AudioAdapterManager::InitVolumeMap(bool isFirstBoot)
1476 {
1477 if (!isFirstBoot) {
1478 LoadVolumeMap();
1479 UpdateSafeVolume();
1480 return;
1481 }
1482 bool resetFirstFlag = false;
1483 AUDIO_INFO_LOG("InitVolumeMap: Wrote default stream volumes to KvStore");
1484 std::unordered_map<AudioStreamType, int32_t> volumeLevelMapTemp = volumeDataMaintainer_.GetVolumeMap();
1485 for (auto &deviceType: VOLUME_GROUP_TYPE_LIST) {
1486 for (auto &streamType: VOLUME_TYPE_LIST) {
1487 // if GetVolume failed, wirte default value
1488 if (!volumeDataMaintainer_.GetVolume(deviceType, streamType)) {
1489 int32_t volumeLevel = GetDefaultVolumeLevel(volumeLevelMapTemp, streamType, deviceType);
1490 auto ret = volumeDataMaintainer_.SaveVolume(deviceType, streamType, volumeLevel);
1491 resetFirstFlag = ret ? resetFirstFlag : true;
1492 }
1493 }
1494 }
1495 if (resetFirstFlag) {
1496 AUDIO_INFO_LOG("reset first boot init settingsdata");
1497 SetFirstBoot(true);
1498 }
1499 // reLoad the current device volume
1500 LoadVolumeMap();
1501 UpdateSafeVolume();
1502 }
1503
1504 // If the device specified by the VolumeType has a default volume level configured,
1505 // use that default volume level. Otherwise, use the default volume level for the VolumeType.
GetDefaultVolumeLevel(std::unordered_map<AudioStreamType,int32_t> & volumeLevelMapTemp,AudioVolumeType volumeType,DeviceType deviceType) const1506 int32_t AudioAdapterManager::GetDefaultVolumeLevel(
1507 std::unordered_map<AudioStreamType, int32_t> &volumeLevelMapTemp,
1508 AudioVolumeType volumeType, DeviceType deviceType) const
1509 {
1510 AudioVolumeType internalVolumeType = VolumeUtils::GetVolumeTypeFromStreamType(volumeType);
1511
1512 // find the volume level corresponding the the volume type
1513 auto volumeIt = volumeLevelMapTemp.find(internalVolumeType);
1514 int32_t defaultVolumeLevel = DEFAULT_VOLUME_LEVEL;
1515 if (volumeIt != volumeLevelMapTemp.end()) {
1516 defaultVolumeLevel = volumeIt->second;
1517 } else {
1518 AUDIO_ERR_LOG("Failed to get the volume level corresponding to the volume type");
1519 }
1520
1521 // find the volume level corresponding to the device specified by the volume type
1522 int32_t defaultDeviceVolumeLevel = -1;
1523 auto deviceIt = DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.find(deviceType);
1524 auto streamVolumeInfoIt = streamVolumeInfos_.find(internalVolumeType);
1525 if (deviceIt != DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.end() &&
1526 streamVolumeInfoIt != streamVolumeInfos_.end()) {
1527 std::shared_ptr<StreamVolumeInfo> streamVolumeInfo = streamVolumeInfoIt->second;
1528 DeviceVolumeType deviceVolumeType = deviceIt->second;
1529 if (streamVolumeInfo != nullptr) {
1530 auto deviceVolumeInfoIt = streamVolumeInfo->deviceVolumeInfos.find(deviceVolumeType);
1531 if (deviceVolumeInfoIt != streamVolumeInfo->deviceVolumeInfos.end() &&
1532 deviceVolumeInfoIt->second != nullptr) {
1533 defaultDeviceVolumeLevel = deviceVolumeInfoIt->second->defaultLevel;
1534 } else {
1535 AUDIO_ERR_LOG("deviceVolumeInfo is nullptr");
1536 }
1537 } else {
1538 AUDIO_ERR_LOG("streamVolumeInfo is nullptr");
1539 }
1540 }
1541
1542 int32_t volumeLevel = (defaultDeviceVolumeLevel == -1) ? defaultVolumeLevel : defaultDeviceVolumeLevel;
1543 return volumeLevel;
1544 }
1545
ResetRemoteCastDeviceVolume()1546 void AudioAdapterManager::ResetRemoteCastDeviceVolume()
1547 {
1548 for (auto &streamType: VOLUME_TYPE_LIST) {
1549 AudioStreamType streamAlias = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
1550 int32_t volumeLevel = GetMaxVolumeLevel(streamAlias);
1551 volumeDataMaintainer_.SaveVolume(DEVICE_TYPE_REMOTE_CAST, streamType, volumeLevel);
1552 if (streamType != STREAM_RING) {
1553 volumeDataMaintainer_.SaveMuteStatus(DEVICE_TYPE_REMOTE_CAST, streamType, false);
1554 }
1555 }
1556 }
1557
InitRingerMode(bool isFirstBoot)1558 void AudioAdapterManager::InitRingerMode(bool isFirstBoot)
1559 {
1560 if (isFirstBoot) {
1561 ringerMode_ = RINGER_MODE_NORMAL;
1562 isLoaded_ = true;
1563 if (!volumeDataMaintainer_.GetRingerMode(ringerMode_)) {
1564 isLoaded_ = volumeDataMaintainer_.SaveRingerMode(RINGER_MODE_NORMAL);
1565 }
1566 AUDIO_INFO_LOG("InitRingerMode first boot ringermode:%{public}d", ringerMode_);
1567 } else {
1568 // read ringerMode from private kvStore
1569 if (isNeedCopyRingerModeData_ && audioPolicyKvStore_ != nullptr) {
1570 AUDIO_INFO_LOG("copy ringerMode from private database to share database");
1571 Key key = "ringermode";
1572 Value value;
1573 Status status = audioPolicyKvStore_->Get(key, value);
1574 if (status == Status::SUCCESS) {
1575 ringerMode_ = static_cast<AudioRingerMode>(TransferByteArrayToType<int>(value.Data()));
1576 volumeDataMaintainer_.SaveRingerMode(ringerMode_);
1577 }
1578 isNeedCopyRingerModeData_ = false;
1579 }
1580 // if read ringer mode success, data is loaded.
1581 isLoaded_ = volumeDataMaintainer_.GetRingerMode(ringerMode_);
1582 }
1583
1584 int32_t volumeLevel =
1585 volumeDataMaintainer_.GetStreamVolume(STREAM_RING) * ((ringerMode_ != RINGER_MODE_NORMAL) ? 0 : 1);
1586 // Save volume in local prop for bootanimation
1587 SaveRingtoneVolumeToLocal(STREAM_RING, volumeLevel);
1588 }
1589
CloneVolumeMap(void)1590 void AudioAdapterManager::CloneVolumeMap(void)
1591 {
1592 CHECK_AND_RETURN_LOG(audioPolicyKvStore_ != nullptr, "clone volumemap failed, audioPolicyKvStore_nullptr");
1593 // read volume from private Kvstore
1594 AUDIO_INFO_LOG("Copy Volume from private database to shareDatabase");
1595 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
1596 for (auto &streamType : VOLUME_TYPE_LIST) {
1597 std::string volumeKey = GetVolumeKeyForKvStore(deviceType, streamType);
1598 Key key = volumeKey;
1599 Value value;
1600 Status status = audioPolicyKvStore_->Get(volumeKey, value);
1601 if (status != SUCCESS) {
1602 AUDIO_WARNING_LOG("get volumeLevel failed, deviceType:%{public}d, streanType:%{public}d",
1603 deviceType, streamType);
1604 continue;
1605 }
1606 int32_t volumeLevel = TransferByteArrayToType<int>(value.Data());
1607 // clone data to VolumeToShareData
1608 volumeDataMaintainer_.SaveVolume(deviceType, streamType, volumeLevel);
1609 }
1610 }
1611
1612 isNeedCopyVolumeData_ = false;
1613 }
1614
LoadVolumeMap(void)1615 bool AudioAdapterManager::LoadVolumeMap(void)
1616 {
1617 if (isNeedCopyVolumeData_ && (audioPolicyKvStore_ != nullptr)) {
1618 CloneVolumeMap();
1619 }
1620
1621 bool result = false;
1622 for (auto &streamType: VOLUME_TYPE_LIST) {
1623 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_ != DEVICE_TYPE_REMOTE_CAST) {
1624 result = volumeDataMaintainer_.GetVolume(DEVICE_TYPE_SPEAKER, streamType);
1625 } else {
1626 result = volumeDataMaintainer_.GetVolume(currentActiveDevice_, streamType);
1627 }
1628 if (!result) {
1629 AUDIO_ERR_LOG("LoadVolumeMap: Could not load volume for streamType[%{public}d] from kvStore", streamType);
1630 }
1631 }
1632
1633 return true;
1634 }
1635
TransferMuteStatus(void)1636 void AudioAdapterManager::TransferMuteStatus(void)
1637 {
1638 // read mute_streams_affected and transfer
1639 int32_t mute_streams_affected = 0;
1640 bool isNeedTransferMute = true;
1641 bool ret = volumeDataMaintainer_.GetMuteAffected(mute_streams_affected) &&
1642 volumeDataMaintainer_.GetMuteTransferStatus(isNeedTransferMute);
1643 if (!ret && (mute_streams_affected > 0) && isNeedTransferMute) {
1644 AUDIO_INFO_LOG("start transfer mute value");
1645 volumeDataMaintainer_.SetMuteAffectedToMuteStatusDataBase(mute_streams_affected);
1646 volumeDataMaintainer_.SaveMuteTransferStatus(false);
1647 }
1648 }
1649
InitMuteStatusMap(bool isFirstBoot)1650 void AudioAdapterManager::InitMuteStatusMap(bool isFirstBoot)
1651 {
1652 if (isFirstBoot) {
1653 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
1654 for (auto &streamType : VOLUME_TYPE_LIST) {
1655 CheckAndDealMuteStatus(deviceType, streamType);
1656 }
1657 }
1658 TransferMuteStatus();
1659 } else {
1660 LoadMuteStatusMap();
1661 }
1662 }
1663
CheckAndDealMuteStatus(const DeviceType & deviceType,const AudioStreamType & streamType)1664 void AudioAdapterManager::CheckAndDealMuteStatus(const DeviceType &deviceType, const AudioStreamType &streamType)
1665 {
1666 if (streamType == STREAM_RING) {
1667 bool muteStateForStreamRing = (ringerMode_ == RINGER_MODE_NORMAL) ? false : true;
1668 AUDIO_INFO_LOG("fist boot ringer mode:%{public}d, stream ring mute state:%{public}d", ringerMode_,
1669 muteStateForStreamRing);
1670 // set stream mute status to mem.
1671 if (currentActiveDevice_ == deviceType) {
1672 volumeDataMaintainer_.SetStreamMuteStatus(streamType, muteStateForStreamRing);
1673 }
1674 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, muteStateForStreamRing);
1675 } else if (!volumeDataMaintainer_.GetMuteStatus(deviceType, streamType)) {
1676 if (currentActiveDevice_ == deviceType) {
1677 volumeDataMaintainer_.SetStreamMuteStatus(streamType, false);
1678 }
1679 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, false);
1680 }
1681 if (currentActiveDevice_ == deviceType) {
1682 SetVolumeDb(streamType);
1683 }
1684 }
1685
SetVolumeCallbackAfterClone()1686 void AudioAdapterManager::SetVolumeCallbackAfterClone()
1687 {
1688 for (auto &streamType : VOLUME_TYPE_LIST) {
1689 VolumeEvent volumeEvent;
1690 volumeEvent.volumeType = streamType;
1691 volumeEvent.volume = GetSystemVolumeLevel(streamType);
1692 volumeEvent.updateUi = false;
1693 volumeEvent.volumeGroupId = 0;
1694 volumeEvent.networkId = LOCAL_NETWORK_ID;
1695 if (audioPolicyServerHandler_ != nullptr) {
1696 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
1697 }
1698 }
1699 }
1700
CloneMuteStatusMap(void)1701 void AudioAdapterManager::CloneMuteStatusMap(void)
1702 {
1703 // read mute status from private Kvstore
1704 CHECK_AND_RETURN_LOG(audioPolicyKvStore_ != nullptr, "clone mute status failed, audioPolicyKvStore_ nullptr");
1705 AUDIO_INFO_LOG("Copy mute from private database to shareDatabase");
1706 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
1707 for (auto &streamType : VOLUME_TYPE_LIST) {
1708 std::string muteKey = GetMuteKeyForKvStore(deviceType, streamType);
1709 Key key = muteKey;
1710 Value value;
1711 Status status = audioPolicyKvStore_->Get(key, value);
1712 if (status != SUCCESS) {
1713 AUDIO_WARNING_LOG("get muteStatus:failed, deviceType:%{public}d, streanType:%{public}d",
1714 deviceType, streamType);
1715 continue;
1716 }
1717 bool muteStatus = TransferByteArrayToType<int>(value.Data());
1718 // clone data to VolumeToShareData
1719 if (currentActiveDevice_ == deviceType) {
1720 volumeDataMaintainer_.SetStreamMuteStatus(streamType, muteStatus);
1721 }
1722 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, muteStatus);
1723 }
1724 }
1725 isNeedCopyMuteData_ = false;
1726 }
1727
LoadMuteStatusMap(void)1728 bool AudioAdapterManager::LoadMuteStatusMap(void)
1729 {
1730 if (isNeedCopyMuteData_ && (audioPolicyKvStore_ != nullptr)) {
1731 CloneMuteStatusMap();
1732 }
1733
1734 TransferMuteStatus();
1735
1736 for (auto &streamType: VOLUME_TYPE_LIST) {
1737 bool result = volumeDataMaintainer_.GetMuteStatus(currentActiveDevice_, streamType);
1738 if (!result) {
1739 AUDIO_WARNING_LOG("Could not load mute status for stream type %{public}d from database.", streamType);
1740 }
1741 if (streamType == STREAM_RING && VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_RING) {
1742 bool muteStateForStreamRing = (ringerMode_ == RINGER_MODE_NORMAL) ? false : true;
1743 if (currentActiveDevice_ != DEVICE_TYPE_SPEAKER) {
1744 continue;
1745 }
1746 AUDIO_INFO_LOG("ringer mode:%{public}d, stream ring mute state:%{public}d", ringerMode_,
1747 muteStateForStreamRing);
1748 if (muteStateForStreamRing == GetStreamMute(streamType)) {
1749 continue;
1750 }
1751 volumeDataMaintainer_.SaveMuteStatus(currentActiveDevice_, streamType, muteStateForStreamRing);
1752 SetStreamMute(streamType, muteStateForStreamRing);
1753 }
1754 }
1755 return true;
1756 }
1757
InitSafeStatus(bool isFirstBoot)1758 void AudioAdapterManager::InitSafeStatus(bool isFirstBoot)
1759 {
1760 if (isFirstBoot) {
1761 AUDIO_INFO_LOG("Wrote default safe status to KvStore");
1762 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
1763 // Adapt to safe volume upgrade scenarios
1764 if (!volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_) &&
1765 (deviceType == DEVICE_TYPE_WIRED_HEADSET)) {
1766 volumeDataMaintainer_.SaveSafeStatus(DEVICE_TYPE_WIRED_HEADSET, SAFE_ACTIVE);
1767 }
1768 if (!volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_) &&
1769 (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP)) {
1770 volumeDataMaintainer_.SaveSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, SAFE_ACTIVE);
1771 }
1772 }
1773 } else {
1774 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
1775 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
1776 }
1777 }
1778
InitSafeTime(bool isFirstBoot)1779 void AudioAdapterManager::InitSafeTime(bool isFirstBoot)
1780 {
1781 if (isFirstBoot) {
1782 AUDIO_INFO_LOG("Wrote default safe status to KvStore");
1783 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
1784 if (!volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_) &&
1785 (deviceType == DEVICE_TYPE_WIRED_HEADSET)) {
1786 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, 0);
1787 }
1788 if (!volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_) &&
1789 (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP)) {
1790 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0);
1791 }
1792 ConvertSafeTime();
1793 isNeedConvertSafeTime_ = false;
1794 }
1795 } else {
1796 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_);
1797 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_);
1798 if (isNeedConvertSafeTime_) {
1799 ConvertSafeTime();
1800 isNeedConvertSafeTime_ = false;
1801 }
1802 }
1803 }
1804
ConvertSafeTime(void)1805 void AudioAdapterManager::ConvertSafeTime(void)
1806 {
1807 // Adapt to safe volume time when upgrade scenarios
1808 if (safeActiveTime_ > 0) {
1809 safeActiveTime_ = safeActiveTime_ / CONVERT_FROM_MS_TO_SECONDS;
1810 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_);
1811 }
1812 if (safeActiveBtTime_ > 0) {
1813 safeActiveBtTime_ = safeActiveBtTime_ / CONVERT_FROM_MS_TO_SECONDS;
1814 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_);
1815 }
1816 }
1817
GetCurrentDeviceSafeStatus(DeviceType deviceType)1818 SafeStatus AudioAdapterManager::GetCurrentDeviceSafeStatus(DeviceType deviceType)
1819 {
1820 switch (deviceType) {
1821 case DEVICE_TYPE_WIRED_HEADSET:
1822 case DEVICE_TYPE_WIRED_HEADPHONES:
1823 case DEVICE_TYPE_USB_HEADSET:
1824 case DEVICE_TYPE_USB_ARM_HEADSET:
1825 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
1826 return safeStatus_;
1827 case DEVICE_TYPE_BLUETOOTH_SCO:
1828 case DEVICE_TYPE_BLUETOOTH_A2DP:
1829 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
1830 return safeStatusBt_;
1831 default:
1832 AUDIO_ERR_LOG("current device : %{public}d is not support", deviceType);
1833 break;
1834 }
1835
1836 return SAFE_UNKNOWN;
1837 }
1838
GetCurentDeviceSafeTime(DeviceType deviceType)1839 int64_t AudioAdapterManager::GetCurentDeviceSafeTime(DeviceType deviceType)
1840 {
1841 switch (deviceType) {
1842 case DEVICE_TYPE_WIRED_HEADSET:
1843 case DEVICE_TYPE_WIRED_HEADPHONES:
1844 case DEVICE_TYPE_USB_HEADSET:
1845 case DEVICE_TYPE_USB_ARM_HEADSET:
1846 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_);
1847 return safeActiveTime_;
1848 case DEVICE_TYPE_BLUETOOTH_SCO:
1849 case DEVICE_TYPE_BLUETOOTH_A2DP:
1850 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_);
1851 return safeActiveBtTime_;
1852 default:
1853 AUDIO_ERR_LOG("current device : %{public}d is not support", deviceType);
1854 break;
1855 }
1856
1857 return -1;
1858 }
1859
GetRestoreVolumeLevel(DeviceType deviceType)1860 int32_t AudioAdapterManager::GetRestoreVolumeLevel(DeviceType deviceType)
1861 {
1862 switch (deviceType) {
1863 case DEVICE_TYPE_WIRED_HEADSET:
1864 case DEVICE_TYPE_WIRED_HEADPHONES:
1865 case DEVICE_TYPE_USB_HEADSET:
1866 case DEVICE_TYPE_USB_ARM_HEADSET:
1867 volumeDataMaintainer_.GetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET, safeActiveVolume_);
1868 return safeActiveVolume_;
1869 case DEVICE_TYPE_BLUETOOTH_SCO:
1870 case DEVICE_TYPE_BLUETOOTH_A2DP:
1871 volumeDataMaintainer_.GetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtVolume_);
1872 return safeActiveBtVolume_;
1873 default:
1874 AUDIO_ERR_LOG("current device : %{public}d is not support", deviceType);
1875 break;
1876 }
1877
1878 return SAFE_UNKNOWN;
1879 }
1880
SetDeviceSafeStatus(DeviceType deviceType,SafeStatus status)1881 int32_t AudioAdapterManager::SetDeviceSafeStatus(DeviceType deviceType, SafeStatus status)
1882 {
1883 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1884 safeStatusBt_ = status;
1885 } else if (deviceType == DEVICE_TYPE_WIRED_HEADSET) {
1886 safeStatus_ = status;
1887 }
1888 bool ret = volumeDataMaintainer_.SaveSafeStatus(deviceType, status);
1889 CHECK_AND_RETURN_RET(ret, ERROR, "SaveSafeStatus failed");
1890 return SUCCESS;
1891 }
1892
SetDeviceSafeTime(DeviceType deviceType,int64_t time)1893 int32_t AudioAdapterManager::SetDeviceSafeTime(DeviceType deviceType, int64_t time)
1894 {
1895 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1896 safeActiveBtTime_ = time;
1897 } else if (deviceType == DEVICE_TYPE_WIRED_HEADSET) {
1898 safeActiveTime_ = time;
1899 }
1900 bool ret = volumeDataMaintainer_.SaveSafeVolumeTime(deviceType, time);
1901 CHECK_AND_RETURN_RET(ret, ERROR, "SetDeviceSafeTime failed");
1902 return SUCCESS;
1903 }
1904
SetRestoreVolumeLevel(DeviceType deviceType,int32_t volume)1905 int32_t AudioAdapterManager::SetRestoreVolumeLevel(DeviceType deviceType, int32_t volume)
1906 {
1907 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
1908 safeActiveBtVolume_ = volume;
1909 } else if (deviceType == DEVICE_TYPE_WIRED_HEADSET) {
1910 safeActiveVolume_ = volume;
1911 }
1912 bool ret = volumeDataMaintainer_.SetRestoreVolumeLevel(deviceType, volume);
1913 CHECK_AND_RETURN_RET(ret, ERROR, "SetRestoreVolumeLevel failed");
1914 return SUCCESS;
1915 }
1916
GetMuteKeyForKvStore(DeviceType deviceType,AudioStreamType streamType)1917 std::string AudioAdapterManager::GetMuteKeyForKvStore(DeviceType deviceType, AudioStreamType streamType)
1918 {
1919 std::string type = "";
1920 switch (deviceType) {
1921 case DEVICE_TYPE_EARPIECE:
1922 case DEVICE_TYPE_SPEAKER:
1923 case DEVICE_TYPE_DP:
1924 case DEVICE_TYPE_HDMI:
1925 type = "build-in";
1926 break;
1927 case DEVICE_TYPE_BLUETOOTH_A2DP:
1928 case DEVICE_TYPE_BLUETOOTH_SCO:
1929 type = "wireless";
1930 break;
1931 case DEVICE_TYPE_WIRED_HEADSET:
1932 case DEVICE_TYPE_USB_HEADSET:
1933 case DEVICE_TYPE_USB_ARM_HEADSET:
1934 type = "wired";
1935 break;
1936 default:
1937 AUDIO_ERR_LOG("GetMuteKeyForKvStore: device %{public}d is not supported for kvStore", deviceType);
1938 return "";
1939 }
1940
1941 switch (streamType) {
1942 case STREAM_MUSIC:
1943 return type + "_music_mute_status";
1944 case STREAM_RING:
1945 case STREAM_VOICE_RING:
1946 return type + "_ring_mute_status";
1947 case STREAM_SYSTEM:
1948 return type + "_system_mute_status";
1949 case STREAM_NOTIFICATION:
1950 return type + "_notification_mute_status";
1951 case STREAM_ALARM:
1952 return type + "_alarm_mute_status";
1953 case STREAM_DTMF:
1954 return type + "_dtmf_mute_status";
1955 case STREAM_VOICE_CALL:
1956 case STREAM_VOICE_COMMUNICATION:
1957 return type + "_voice_call_mute_status";
1958 case STREAM_VOICE_ASSISTANT:
1959 return type + "_voice_assistant_mute_status";
1960 case STREAM_ACCESSIBILITY:
1961 return type + "_accessibility_mute_status";
1962 case STREAM_ULTRASONIC:
1963 return type + "_unltrasonic_mute_status";
1964 default:
1965 AUDIO_ERR_LOG("GetMuteKeyForKvStore: streamType %{public}d is not supported for kvStore", streamType);
1966 return "";
1967 }
1968 }
1969
CalculateVolumeDb(int32_t volumeLevel)1970 float AudioAdapterManager::CalculateVolumeDb(int32_t volumeLevel)
1971 {
1972 float value = static_cast<float>(volumeLevel) / MAX_VOLUME_LEVEL;
1973 float roundValue = static_cast<int>(value * CONST_FACTOR);
1974
1975 return static_cast<float>(roundValue) / CONST_FACTOR;
1976 }
1977
CloneSystemSoundUrl(void)1978 void AudioAdapterManager::CloneSystemSoundUrl(void)
1979 {
1980 CHECK_AND_RETURN_LOG(isNeedCopySystemUrlData_ && (audioPolicyKvStore_ != nullptr),
1981 "audioPolicyKvStore_ is nullptr,clone systemurl failed");
1982 for (auto &key: SYSTEM_SOUND_KEY_LIST) {
1983 Value value;
1984 Status status = audioPolicyKvStore_->Get(key, value);
1985 if (status == Status::SUCCESS) {
1986 std::string systemSoundUri = value.ToString();
1987 systemSoundUriMap_[key] = systemSoundUri;
1988 volumeDataMaintainer_.SaveSystemSoundUrl(key, systemSoundUri);
1989 }
1990 }
1991 isNeedCopySystemUrlData_ = false;
1992 }
1993
InitSystemSoundUriMap()1994 void AudioAdapterManager::InitSystemSoundUriMap()
1995 {
1996 for (auto &key: SYSTEM_SOUND_KEY_LIST) {
1997 std::string systemSoundUri = "";
1998 volumeDataMaintainer_.GetSystemSoundUrl(key, systemSoundUri);
1999 if (systemSoundUri == "") {
2000 AUDIO_WARNING_LOG("Could not load system sound uri for %{public}s from kvStore", key.c_str());
2001 }
2002 systemSoundUriMap_[key] = systemSoundUri;
2003 }
2004 }
2005
SetSystemSoundUri(const std::string & key,const std::string & uri)2006 int32_t AudioAdapterManager::SetSystemSoundUri(const std::string &key, const std::string &uri)
2007 {
2008 auto pos = std::find(SYSTEM_SOUND_KEY_LIST.begin(), SYSTEM_SOUND_KEY_LIST.end(), key);
2009 if (pos == SYSTEM_SOUND_KEY_LIST.end()) {
2010 AUDIO_ERR_LOG("Invalid key %{public}s for system sound uri", key.c_str());
2011 return ERR_INVALID_PARAM;
2012 }
2013 std::lock_guard<std::mutex> lock(systemSoundMutex_);
2014 if (systemSoundUriMap_.size() == 0) {
2015 InitSystemSoundUriMap();
2016 CHECK_AND_RETURN_RET_LOG(systemSoundUriMap_.size() != 0, ERR_OPERATION_FAILED,
2017 "Failed to init system sound uri map.");
2018 }
2019 systemSoundUriMap_[key] = uri;
2020 if (!volumeDataMaintainer_.SaveSystemSoundUrl(key, uri)) {
2021 AUDIO_ERR_LOG("SetSystemSoundUri failed");
2022 return ERROR;
2023 }
2024 return SUCCESS;
2025 }
2026
GetSystemSoundUri(const std::string & key)2027 std::string AudioAdapterManager::GetSystemSoundUri(const std::string &key)
2028 {
2029 auto pos = std::find(SYSTEM_SOUND_KEY_LIST.begin(), SYSTEM_SOUND_KEY_LIST.end(), key);
2030 if (pos == SYSTEM_SOUND_KEY_LIST.end()) {
2031 AUDIO_ERR_LOG("Invalid key %{public}s for system sound uri", key.c_str());
2032 return "";
2033 }
2034 std::lock_guard<std::mutex> lock(systemSoundMutex_);
2035 if (systemSoundUriMap_.size() == 0) {
2036 InitSystemSoundUriMap();
2037 CHECK_AND_RETURN_RET_LOG(systemSoundUriMap_.size() != 0, "",
2038 "Failed to init system sound uri map.");
2039 }
2040 return systemSoundUriMap_[key];
2041 }
2042
GetMinStreamVolume() const2043 float AudioAdapterManager::GetMinStreamVolume() const
2044 {
2045 return MIN_STREAM_VOLUME;
2046 }
2047
GetMaxStreamVolume() const2048 float AudioAdapterManager::GetMaxStreamVolume() const
2049 {
2050 return MAX_STREAM_VOLUME;
2051 }
2052
IsVolumeUnadjustable()2053 bool AudioAdapterManager::IsVolumeUnadjustable()
2054 {
2055 return isVolumeUnadjustable_;
2056 }
2057
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType)2058 float AudioAdapterManager::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, DeviceType deviceType)
2059 {
2060 AUDIO_DEBUG_LOG("GetSystemVolumeInDb for volumeType: %{public}d deviceType:%{public}d volumeLevel:%{public}d",
2061 volumeType, deviceType, volumeLevel);
2062 if (useNonlinearAlgo_) {
2063 getSystemVolumeInDb_ = CalculateVolumeDbNonlinear(volumeType, deviceType, volumeLevel);
2064 } else {
2065 getSystemVolumeInDb_ = CalculateVolumeDb(volumeLevel);
2066 }
2067
2068 AUDIO_DEBUG_LOG("Get system volume in db success %{public}f", getSystemVolumeInDb_.load());
2069
2070 return getSystemVolumeInDb_;
2071 }
2072
GetPositionInVolumePoints(std::vector<VolumePoint> & volumePoints,int32_t idx)2073 uint32_t AudioAdapterManager::GetPositionInVolumePoints(std::vector<VolumePoint> &volumePoints, int32_t idx)
2074 {
2075 int32_t leftPos = 0;
2076 int32_t rightPos = static_cast<int32_t>(volumePoints.size() - 1);
2077 while (leftPos <= rightPos) {
2078 int32_t midPos = leftPos + (rightPos - leftPos)/NUMBER_TWO;
2079 int32_t c = static_cast<int32_t>(volumePoints[midPos].index) - idx;
2080 if (c == 0) {
2081 leftPos = midPos;
2082 break;
2083 } else if (c < 0) {
2084 leftPos = midPos + 1;
2085 } else {
2086 rightPos = midPos - 1;
2087 }
2088 }
2089 return leftPos;
2090 }
2091
CalculateVolumeDbNonlinear(AudioStreamType streamType,DeviceType deviceType,int32_t volumeLevel)2092 float AudioAdapterManager::CalculateVolumeDbNonlinear(AudioStreamType streamType,
2093 DeviceType deviceType, int32_t volumeLevel)
2094 {
2095 AUDIO_DEBUG_LOG("CalculateVolumeDbNonlinear for stream: %{public}d devicetype:%{public}d volumeLevel:%{public}d",
2096 streamType, deviceType, volumeLevel);
2097 AudioStreamType streamAlias = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
2098 int32_t minVolIndex = GetMinVolumeLevel(streamAlias);
2099 int32_t maxVolIndex = GetMaxVolumeLevel(streamAlias);
2100 if (minVolIndex < 0 || maxVolIndex < 0 || minVolIndex >= maxVolIndex) {
2101 return 0.0f;
2102 }
2103 if (volumeLevel < minVolIndex) {
2104 volumeLevel = minVolIndex;
2105 }
2106 if (volumeLevel > maxVolIndex) {
2107 volumeLevel = maxVolIndex;
2108 }
2109
2110 DeviceVolumeType deviceCategory = GetDeviceCategory(deviceType);
2111 std::vector<VolumePoint> volumePoints;
2112 GetVolumePoints(streamAlias, deviceCategory, volumePoints);
2113 uint32_t pointSize = volumePoints.size();
2114
2115 CHECK_AND_RETURN_RET_LOG(pointSize != 0, 1.0f, "pointSize is 0");
2116 int32_t volSteps = static_cast<int32_t>(1 + volumePoints[pointSize - 1].index - volumePoints[0].index);
2117 int32_t idxRatio = (volSteps * (volumeLevel - minVolIndex)) / (maxVolIndex - minVolIndex);
2118 int32_t position = static_cast<int32_t>(GetPositionInVolumePoints(volumePoints, idxRatio));
2119 if (position == 0) {
2120 if (minVolIndex != 0) {
2121 AUDIO_INFO_LOG("Min volume index not zero, use min db: %{public}0.1f", volumePoints[0].dbValue / 100.0f);
2122 return exp((volumePoints[0].dbValue / 100.0f) * 0.115129f);
2123 }
2124 AUDIO_DEBUG_LOG("position = 0, return 0.0");
2125 return 0.0f;
2126 } else if (position >= static_cast<int32_t>(pointSize)) {
2127 AUDIO_DEBUG_LOG("position > pointSize, return %{public}f",
2128 exp(volumePoints[pointSize - 1].dbValue * 0.115129f));
2129 return exp((volumePoints[pointSize - 1].dbValue / 100.0f) * 0.115129f);
2130 }
2131 float indexFactor = (static_cast<float>(idxRatio - static_cast<int32_t>(volumePoints[position - 1].index))) /
2132 (static_cast<float>(volumePoints[position].index - volumePoints[position - 1].index));
2133
2134 float dbValue = (volumePoints[position - 1].dbValue / 100.0f) +
2135 indexFactor * ((volumePoints[position].dbValue / 100.0f) - (volumePoints[position - 1].dbValue / 100.0f));
2136
2137 AUDIO_DEBUG_LOG(" index=[%{public}d, %{public}d, %{public}d]"
2138 "db=[%{public}0.1f %{public}0.1f %{public}0.1f] factor=[%{public}f]",
2139 volumePoints[position - 1].index, idxRatio, volumePoints[position].index,
2140 (static_cast<float>(volumePoints[position - 1].dbValue) / 100.0f), dbValue,
2141 (static_cast<float>(volumePoints[position].dbValue) / 100.0f), exp(dbValue * 0.115129f));
2142
2143 return exp(dbValue * 0.115129f);
2144 }
2145
InitVolumeMapIndex()2146 void AudioAdapterManager::InitVolumeMapIndex()
2147 {
2148 useNonlinearAlgo_ = 0;
2149 for (auto streamType : VOLUME_TYPE_LIST) {
2150 minVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)] = MIN_VOLUME_LEVEL;
2151 maxVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)] = MAX_VOLUME_LEVEL;
2152 volumeDataMaintainer_.SetStreamVolume(streamType, DEFAULT_VOLUME_LEVEL);
2153 AUDIO_DEBUG_LOG("streamType %{public}d index = [%{public}d, %{public}d, %{public}d]",
2154 streamType, minVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)],
2155 maxVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)],
2156 volumeDataMaintainer_.GetStreamVolume(streamType));
2157 }
2158
2159 volumeDataMaintainer_.SetStreamVolume(STREAM_VOICE_CALL_ASSISTANT, MAX_VOLUME_LEVEL);
2160 volumeDataMaintainer_.SetStreamVolume(STREAM_ULTRASONIC, MAX_VOLUME_LEVEL);
2161 }
2162
UpdateVolumeMapIndex()2163 void AudioAdapterManager::UpdateVolumeMapIndex()
2164 {
2165 bool isAppConfigVolumeInit = false;
2166 for (auto streamVolInfoPair : streamVolumeInfos_) {
2167 auto streamVolInfo = streamVolInfoPair.second;
2168 if (streamVolInfo->streamType == STREAM_APP) {
2169 appConfigVolume_.defaultVolume = streamVolInfo->defaultLevel;
2170 appConfigVolume_.maxVolume = streamVolInfo->maxLevel;
2171 appConfigVolume_.minVolume = streamVolInfo->minLevel;
2172 isAppConfigVolumeInit = true;
2173 AUDIO_DEBUG_LOG("AppConfigVolume default = %{public}d, max = %{public}d, min = %{public}d",
2174 appConfigVolume_.defaultVolume, appConfigVolume_.maxVolume, appConfigVolume_.minVolume);
2175 continue;
2176 }
2177 AudioVolumeType CurStreamType = VolumeUtils::GetVolumeTypeFromStreamType(streamVolInfo->streamType);
2178 minVolumeIndexMap_[CurStreamType] = streamVolInfo->minLevel;
2179 maxVolumeIndexMap_[CurStreamType] = streamVolInfo->maxLevel;
2180 volumeDataMaintainer_.SetStreamVolume(streamVolInfo->streamType, streamVolInfo->defaultLevel);
2181 AUDIO_DEBUG_LOG("update streamType %{public}d index = [%{public}d, %{public}d, %{public}d]",
2182 streamVolInfo->streamType, minVolumeIndexMap_[CurStreamType], maxVolumeIndexMap_[CurStreamType],
2183 volumeDataMaintainer_.GetStreamVolume(CurStreamType));
2184 }
2185 if (isAppConfigVolumeInit) {
2186 return;
2187 }
2188 if (minVolumeIndexMap_.find(STREAM_MUSIC) != minVolumeIndexMap_.end() &&
2189 maxVolumeIndexMap_.find(STREAM_MUSIC) != maxVolumeIndexMap_.end()) {
2190 appConfigVolume_.defaultVolume = maxVolumeIndexMap_[STREAM_MUSIC];
2191 appConfigVolume_.maxVolume = maxVolumeIndexMap_[STREAM_MUSIC];
2192 appConfigVolume_.minVolume = minVolumeIndexMap_[STREAM_MUSIC];
2193 } else {
2194 appConfigVolume_.defaultVolume = MAX_VOLUME_LEVEL;
2195 appConfigVolume_.maxVolume = MAX_VOLUME_LEVEL;
2196 appConfigVolume_.minVolume = MIN_VOLUME_LEVEL;
2197 }
2198 isAppConfigVolumeInit = true;
2199 AUDIO_DEBUG_LOG("next AppConfigVolume default = %{public}d, max = %{public}d, min = %{public}d",
2200 appConfigVolume_.defaultVolume, appConfigVolume_.maxVolume, appConfigVolume_.minVolume);
2201 }
2202
GetVolumePoints(AudioVolumeType streamType,DeviceVolumeType deviceType,std::vector<VolumePoint> & volumePoints)2203 void AudioAdapterManager::GetVolumePoints(AudioVolumeType streamType, DeviceVolumeType deviceType,
2204 std::vector<VolumePoint> &volumePoints)
2205 {
2206 auto streamVolInfo = streamVolumeInfos_.find(streamType);
2207 if (streamVolInfo == streamVolumeInfos_.end()) {
2208 AUDIO_DEBUG_LOG("Cannot find stream type %{public}d and try to use STREAM_MUSIC", streamType);
2209 streamVolInfo = streamVolumeInfos_.find(STREAM_MUSIC);
2210 CHECK_AND_RETURN_LOG(streamVolInfo != streamVolumeInfos_.end(),
2211 "Cannot find stream type STREAM_MUSIC");
2212 }
2213 auto deviceVolInfo = streamVolInfo->second->deviceVolumeInfos.find(deviceType);
2214 if (deviceVolInfo == streamVolInfo->second->deviceVolumeInfos.end()) {
2215 AUDIO_ERR_LOG("Cannot find device type %{public}d", deviceType);
2216 return;
2217 }
2218 volumePoints = deviceVolInfo->second->volumePoints;
2219 }
2220
GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfos)2221 void AudioAdapterManager::GetStreamVolumeInfoMap(StreamVolumeInfoMap &streamVolumeInfos)
2222 {
2223 streamVolumeInfos = streamVolumeInfos_;
2224 }
2225
SetActiveDevice(DeviceType deviceType)2226 void AudioAdapterManager::SetActiveDevice(DeviceType deviceType)
2227 {
2228 AUDIO_PRERELEASE_LOGI("SetActiveDevice deviceType %{public}d", deviceType);
2229 SetVolumeForSwitchDevice(deviceType);
2230 }
2231
GetActiveDevice()2232 DeviceType AudioAdapterManager::GetActiveDevice()
2233 {
2234 return currentActiveDevice_;
2235 }
2236
SetAbsVolumeScene(bool isAbsVolumeScene)2237 void AudioAdapterManager::SetAbsVolumeScene(bool isAbsVolumeScene)
2238 {
2239 AUDIO_PRERELEASE_LOGI("SetAbsVolumeScene: %{public}d", isAbsVolumeScene);
2240 isAbsVolumeScene_ = isAbsVolumeScene;
2241 if (currentActiveDevice_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
2242 SetVolumeDb(STREAM_MUSIC);
2243 } else {
2244 AUDIO_INFO_LOG("The currentActiveDevice is not A2DP");
2245 }
2246 }
2247
IsAbsVolumeScene() const2248 bool AudioAdapterManager::IsAbsVolumeScene() const
2249 {
2250 return isAbsVolumeScene_;
2251 }
2252
SetAbsVolumeMute(bool mute)2253 void AudioAdapterManager::SetAbsVolumeMute(bool mute)
2254 {
2255 AUDIO_INFO_LOG("SetAbsVolumeMute: %{public}d", mute);
2256 isAbsVolumeMute_ = mute;
2257 if (currentActiveDevice_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
2258 SetVolumeDb(STREAM_MUSIC);
2259 } else {
2260 AUDIO_INFO_LOG("The currentActiveDevice is not A2DP");
2261 }
2262 }
2263
2264
IsAbsVolumeMute() const2265 bool AudioAdapterManager::IsAbsVolumeMute() const
2266 {
2267 return isAbsVolumeMute_;
2268 }
2269
NotifyAccountsChanged(const int & id)2270 void AudioAdapterManager::NotifyAccountsChanged(const int &id)
2271 {
2272 AUDIO_INFO_LOG("start reload the kv data, current id:%{public}d", id);
2273 LoadVolumeMap();
2274 LoadMuteStatusMap();
2275
2276 auto iter = VOLUME_TYPE_LIST.begin();
2277 while (iter != VOLUME_TYPE_LIST.end()) {
2278 SetVolumeDb(*iter);
2279 AUDIO_INFO_LOG("NotifyAccountsChanged: volume: %{public}d, mute: %{public}d for stream type %{public}d",
2280 volumeDataMaintainer_.GetStreamVolume(*iter), volumeDataMaintainer_.GetStreamMute(*iter), *iter);
2281 iter++;
2282 }
2283 }
2284
DoRestoreData()2285 int32_t AudioAdapterManager::DoRestoreData()
2286 {
2287 isLoaded_ = false;
2288 isNeedConvertSafeTime_ = true; // reset convert safe volume status
2289 volumeDataMaintainer_.SaveMuteTransferStatus(true); // reset mute convert status
2290 InitKVStore();
2291 return SUCCESS;
2292 }
2293
GetSafeVolumeLevel() const2294 int32_t AudioAdapterManager::GetSafeVolumeLevel() const
2295 {
2296 return safeVolume_;
2297 }
2298
GetSafeVolumeTimeout() const2299 int32_t AudioAdapterManager::GetSafeVolumeTimeout() const
2300 {
2301 if (safeVolumeTimeout_ <= 0) {
2302 AUDIO_INFO_LOG("safeVolumeTimeout is invalid, return default value:%{public}d", DEFAULT_SAFE_VOLUME_TIMEOUT);
2303 return DEFAULT_SAFE_VOLUME_TIMEOUT;
2304 }
2305 return safeVolumeTimeout_;
2306 }
2307
SetFirstBoot(bool isFirst)2308 void AudioAdapterManager::SetFirstBoot(bool isFirst)
2309 {
2310 int32_t ret = 0;
2311 if (isFirst) {
2312 ret = SetParameter("persist.multimedia.audio.firstboot", std::to_string(1).c_str());
2313 } else {
2314 ret = SetParameter("persist.multimedia.audio.firstboot", std::to_string(0).c_str());
2315 }
2316 if (ret == 0) {
2317 AUDIO_INFO_LOG("Set first boot %{public}d success", isFirst);
2318 } else {
2319 AUDIO_ERR_LOG("Set first boot %{public}d failed, result %{public}d", isFirst, ret);
2320 }
2321 }
2322
SafeVolumeDump(std::string & dumpString)2323 void AudioAdapterManager::SafeVolumeDump(std::string &dumpString)
2324 {
2325 dumpString += "SafeVolume info:\n";
2326 for (auto &streamType : VOLUME_TYPE_LIST) {
2327 AppendFormat(dumpString, " - samplingAudioStreamTypeate: %d", streamType);
2328 AppendFormat(dumpString, " volumeLevel: %d\n", volumeDataMaintainer_.GetStreamVolume(streamType));
2329 AppendFormat(dumpString, " - AudioStreamType: %d", streamType);
2330 AppendFormat(dumpString, " streamMuteStatus: %d\n", volumeDataMaintainer_.GetStreamMute(streamType));
2331 }
2332 if (isSafeBoot_) {
2333 safeStatusBt_ = GetCurrentDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP);
2334 safeStatus_ = GetCurrentDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET);
2335 safeActiveBtTime_ = GetCurentDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP);
2336 safeActiveTime_ = GetCurentDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET);
2337 isSafeBoot_ = false;
2338 }
2339 std::string statusBt = (safeStatusBt_ == SAFE_ACTIVE) ? "SAFE_ACTIVE" : "SAFE_INACTIVE";
2340 std::string status = (safeStatus_ == SAFE_ACTIVE) ? "SAFE_ACTIVE" : "SAFE_INACTIVE";
2341 AppendFormat(dumpString, " - ringerMode: %d\n", ringerMode_);
2342 AppendFormat(dumpString, " - SafeVolume: %d\n", safeVolume_);
2343 AppendFormat(dumpString, " - BtSafeStatus: %s\n", statusBt.c_str());
2344 AppendFormat(dumpString, " - SafeStatus: %s\n", status.c_str());
2345 AppendFormat(dumpString, " - ActiveBtSafeTime: %lld\n", safeActiveBtTime_);
2346 AppendFormat(dumpString, " - ActiveSafeTime: %lld\n", safeActiveTime_);
2347 }
2348
SetVgsVolumeSupported(bool isVgsSupported)2349 void AudioAdapterManager::SetVgsVolumeSupported(bool isVgsSupported)
2350 {
2351 AUDIO_INFO_LOG("Set Vgs Supported: %{public}d", isVgsSupported);
2352 isVgsVolumeSupported_ = isVgsSupported;
2353 AudioVolume::GetInstance()->SetVgsVolumeSupported(isVgsSupported);
2354 }
2355
IsVgsVolumeSupported() const2356 bool AudioAdapterManager::IsVgsVolumeSupported() const
2357 {
2358 if (currentActiveDevice_ != DEVICE_TYPE_BLUETOOTH_SCO) {
2359 AUDIO_INFO_LOG("Current Active Device isn't SCO, return false");
2360 return false;
2361 }
2362 return isVgsVolumeSupported_;
2363 }
2364 // LCOV_EXCL_STOP
2365 } // namespace AudioStandard
2366 } // namespace OHOS
2367