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 #include "audio_utils.h"
30 #include "audio_zone_service.h"
31
32 using namespace std;
33
34 namespace OHOS {
35 namespace AudioStandard {
36 static const char* DO_NOT_DISTURB_STATUS = "focus_mode_enable";
37 static const char* DO_NOT_DISTURB_STATUS_WHITE_LIST = "intelligent_scene_notification_white_list";
38 mutex g_deviceVolumeBehaviorListenerMutex;
39
40 static const std::vector<AudioStreamType> DISTRIBUTED_VOLUME_TYPE_LIST = {
41 // Distributed Volume Type.
42 STREAM_VOICE_CALL,
43 STREAM_VOICE_ASSISTANT,
44 STREAM_MUSIC
45 };
46
47 static const std::vector<AudioStreamType> VOLUME_TYPE_LIST = {
48 // all volume types except STREAM_ALL
49 STREAM_RING,
50 STREAM_VOICE_CALL,
51 STREAM_VOICE_ASSISTANT,
52 STREAM_ALARM,
53 STREAM_ACCESSIBILITY,
54 STREAM_ULTRASONIC,
55 STREAM_VOICE_CALL_ASSISTANT,
56 STREAM_MUSIC
57 };
58
59 static const std::vector<AudioStreamType> PC_VOLUME_TYPE_LIST = {
60 // all volume types except STREAM_ALL
61 STREAM_RING,
62 STREAM_VOICE_CALL,
63 STREAM_VOICE_ASSISTANT,
64 STREAM_ALARM,
65 STREAM_ACCESSIBILITY,
66 STREAM_SYSTEM,
67 STREAM_ULTRASONIC,
68 STREAM_VOICE_CALL_ASSISTANT,
69 // adjust the type of music from the head of list to end, make sure music is updated last.
70 // avoid interference from ring updates on special platform.
71 // when the device is switched to headset,ring and alarm is dualtone type.
72 // dualtone type use fixed volume curve of speaker.
73 // the ring and alarm are classified into the music group.
74 // the music volume becomes abnormal when the db value of music is modified.
75 STREAM_MUSIC
76 };
77
78 static const std::vector<DeviceType> VOLUME_GROUP_TYPE_LIST = {
79 DEVICE_TYPE_EARPIECE,
80 DEVICE_TYPE_SPEAKER,
81 DEVICE_TYPE_BLUETOOTH_A2DP,
82 DEVICE_TYPE_WIRED_HEADSET,
83 DEVICE_TYPE_REMOTE_CAST
84 };
85
86 static const std::vector<std::string> SYSTEM_SOUND_KEY_LIST = {
87 // all keys for system sound uri
88 "ringtone_for_sim_card_0",
89 "ringtone_for_sim_card_1",
90 "system_tone_for_sim_card_0",
91 "system_tone_for_sim_card_1",
92 "system_tone_for_notification"
93 };
94
95 static const std::unordered_map<DeviceType, DeviceVolumeType> DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP = {
96 {DEVICE_TYPE_EARPIECE, EARPIECE_VOLUME_TYPE},
97 {DEVICE_TYPE_SPEAKER, SPEAKER_VOLUME_TYPE},
98 {DEVICE_TYPE_WIRED_HEADSET, HEADSET_VOLUME_TYPE}
99 };
100
101 namespace {
102 const std::unordered_map<DeviceType, std::vector<std::string>> DEVICE_CLASS_MAP = {
103 {DEVICE_TYPE_SPEAKER, {PRIMARY_CLASS, MCH_CLASS, OFFLOAD_CLASS}},
104 {DEVICE_TYPE_USB_HEADSET, {PRIMARY_CLASS, MCH_CLASS, OFFLOAD_CLASS}},
105 {DEVICE_TYPE_BLUETOOTH_A2DP, {A2DP_CLASS, PRIMARY_CLASS, MCH_CLASS, OFFLOAD_CLASS}},
106 {DEVICE_TYPE_BLUETOOTH_SCO, {PRIMARY_CLASS, MCH_CLASS}},
107 {DEVICE_TYPE_NEARLINK, {PRIMARY_CLASS, MCH_CLASS, OFFLOAD_CLASS}},
108 {DEVICE_TYPE_EARPIECE, {PRIMARY_CLASS, MCH_CLASS}},
109 {DEVICE_TYPE_WIRED_HEADSET, {PRIMARY_CLASS, MCH_CLASS}},
110 {DEVICE_TYPE_WIRED_HEADPHONES, {PRIMARY_CLASS, MCH_CLASS}},
111 {DEVICE_TYPE_USB_ARM_HEADSET, {PRIMARY_CLASS, USB_CLASS}},
112 {DEVICE_TYPE_REMOTE_CAST, {REMOTE_CAST_INNER_CAPTURER_SINK_NAME}},
113 {DEVICE_TYPE_DP, {DP_CLASS}},
114 {DEVICE_TYPE_FILE_SINK, {FILE_CLASS}},
115 {DEVICE_TYPE_FILE_SOURCE, {FILE_CLASS}},
116 {DEVICE_TYPE_HDMI, {PRIMARY_CLASS}},
117 {DEVICE_TYPE_ACCESSORY, {ACCESSORY_CLASS}},
118 {DEVICE_TYPE_HEARING_AID, {HEARING_AID_CLASS}},
119 };
120 } // namespace
121
122 // LCOV_EXCL_START
Init()123 bool AudioAdapterManager::Init()
124 {
125 char testMode[10] = {0}; // 10 for system parameter usage
126 auto ret = GetParameter("debug.audio_service.testmodeon", "0", testMode, sizeof(testMode));
127 if (ret == 1 && testMode[0] == '1') {
128 AUDIO_DEBUG_LOG("testMode on");
129 testModeOn_ = true;
130 }
131
132 std::unique_ptr<AudioVolumeParser> audiovolumeParser = make_unique<AudioVolumeParser>();
133 CHECK_AND_RETURN_RET_LOG(audiovolumeParser, false, "audiovolumeParser is null");
134 auto lret = audiovolumeParser->LoadConfig(streamVolumeInfos_);
135 defaultVolumeTypeList_ = (VolumeUtils::IsPCVolumeEnable()) ? PC_VOLUME_TYPE_LIST : VOLUME_TYPE_LIST;
136 if (!lret) {
137 AUDIO_INFO_LOG("Audio Volume Config Load Configuration successfully");
138 useNonlinearAlgo_ = 1;
139 UpdateVolumeMapIndex();
140 }
141
142 // init volume before kvstore start by local prop for bootanimation
143 InitBootAnimationVolume();
144 AudioVolume::GetInstance()->SetDefaultAppVolume(appConfigVolume_.defaultVolume);
145 std::string defaultSafeVolume = std::to_string(GetMaxVolumeLevel(STREAM_MUSIC));
146 AUDIO_INFO_LOG("defaultSafeVolume %{public}s", defaultSafeVolume.c_str());
147 char currentSafeVolumeValue[4] = {0};
148 ret = GetParameter("const.audio.safe_media_volume", defaultSafeVolume.c_str(),
149 currentSafeVolumeValue, sizeof(currentSafeVolumeValue));
150 if (ret > 0) {
151 safeVolume_ = atoi(currentSafeVolumeValue);
152 AUDIO_INFO_LOG("Get currentSafeVolumeValue success %{public}d", safeVolume_);
153 } else {
154 safeVolume_ = GetMaxVolumeLevel(STREAM_MUSIC);
155 AUDIO_ERR_LOG("Get currentSafeVolumeValue failed %{public}d", ret);
156 }
157
158 char safeVolumeTimeout[6] = {0};
159 ret = GetParameter("persist.multimedia.audio.safevolume.timeout", "1140",
160 safeVolumeTimeout, sizeof(safeVolumeTimeout));
161 if (ret > 0) {
162 safeVolumeTimeout_ = atoi(safeVolumeTimeout);
163 AUDIO_INFO_LOG("Get safeVolumeTimeout success %{public}d", safeVolumeTimeout_);
164 } else {
165 AUDIO_ERR_LOG("Get safeVolumeTimeout failed %{public}d", ret);
166 }
167
168 isVolumeUnadjustable_ = system::GetBoolParameter("const.multimedia.audio.fixedvolume", false);
169 AUDIO_INFO_LOG("Get fixdvolume parameter success %{public}d", isVolumeUnadjustable_);
170
171 handler_ = std::make_shared<AudioAdapterManagerHandler>();
172 return true;
173 }
174
InitBootAnimationVolume()175 void AudioAdapterManager::InitBootAnimationVolume()
176 {
177 char currentVolumeValue[3] = {0};
178 AudioVolumeType typeForBootAnimation = VolumeUtils::IsPCVolumeEnable() ? STREAM_SYSTEM : STREAM_RING;
179 int32_t bootAnimationVolume = volumeDataMaintainer_.GetStreamVolume(typeForBootAnimation);
180 AUDIO_DEBUG_LOG("Init: Type[%{public}d],volume[%{public}d]", typeForBootAnimation, bootAnimationVolume);
181 std::string defaultVolume = std::to_string(bootAnimationVolume);
182 auto ret = GetParameter("persist.multimedia.audio.ringtonevolume", defaultVolume.c_str(),
183 currentVolumeValue, sizeof(currentVolumeValue));
184 if (ret > 0) {
185 volumeDataMaintainer_.SetStreamVolume(typeForBootAnimation, atoi(currentVolumeValue));
186 AUDIO_INFO_LOG("Init: Get Type[%{public}d] volume to map volume [%{public}d]",
187 typeForBootAnimation, volumeDataMaintainer_.GetStreamVolume(typeForBootAnimation));
188 } else {
189 AUDIO_ERR_LOG("Init: Get volume parameter failed %{public}d", ret);
190 }
191 }
192
ConnectServiceAdapter()193 bool AudioAdapterManager::ConnectServiceAdapter()
194 {
195 std::unique_ptr<PolicyCallbackImpl> policyCallbackImpl = std::make_unique<PolicyCallbackImpl>(this);
196 audioServiceAdapter_ = AudioServiceAdapter::CreateAudioAdapter(std::move(policyCallbackImpl));
197 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, false,
198 "[AudioAdapterManager] Error in audio adapter initialization");
199
200 bool result = audioServiceAdapter_->Connect();
201 CHECK_AND_RETURN_RET_LOG(result, false, "[AudioAdapterManager] Error in connecting audio adapter");
202
203 return true;
204 }
205
InitKVStore()206 void AudioAdapterManager::InitKVStore()
207 {
208 InitKVStoreInternal();
209 }
210
InitKVStoreInternal()211 void AudioAdapterManager::InitKVStoreInternal()
212 {
213 CHECK_AND_RETURN_LOG(!isLoaded_, "InitKVStore: the database value is loaded");
214
215 AUDIO_INFO_LOG("in");
216 bool isFirstBoot = false;
217 volumeDataMaintainer_.RegisterCloned();
218 InitAudioPolicyKvStore(isFirstBoot);
219
220 if (handler_ != nullptr) {
221 handler_->SendKvDataUpdate(isFirstBoot);
222 }
223 }
224
HandleKvData(bool isFirstBoot)225 void AudioAdapterManager::HandleKvData(bool isFirstBoot)
226 {
227 InitVolumeMap(isFirstBoot);
228 InitRingerMode(isFirstBoot);
229 InitMuteStatusMap(isFirstBoot);
230 InitSafeStatus(isFirstBoot);
231 InitSafeTime(isFirstBoot);
232
233 if (isNeedCopySystemUrlData_) {
234 CloneSystemSoundUrl();
235 }
236
237 if (!isNeedCopyVolumeData_ && !isNeedCopyMuteData_ && !isNeedCopyRingerModeData_ && !isNeedCopySystemUrlData_) {
238 isAllCopyDone_ = true;
239 if (audioPolicyServerHandler_ != nullptr) {
240 audioPolicyServerHandler_->SendRingerModeUpdatedCallback(ringerMode_);
241 SetVolumeCallbackAfterClone();
242 }
243 }
244
245 if (isAllCopyDone_ && audioPolicyKvStore_ != nullptr) {
246 // delete KvStore
247 InitSafeStatus(true);
248 InitSafeTime(true);
249 AUDIO_INFO_LOG("Copy audio_policy private database success to settings database, delete private database...");
250 DeleteAudioPolicyKvStore();
251 }
252
253 // Make sure that the volume value is applied.
254 auto iter = defaultVolumeTypeList_.begin();
255 while (iter != defaultVolumeTypeList_.end()) {
256 SetVolumeDb(*iter);
257 iter++;
258 }
259
260 UpdateVolumeForLowLatency();
261 }
262
ReInitKVStore()263 int32_t AudioAdapterManager::ReInitKVStore()
264 {
265 CHECK_AND_RETURN_RET_LOG(audioPolicyKvStore_ != nullptr, ERR_INVALID_OPERATION,
266 "audioPolicyKvStore_ is already nullptr");
267 audioPolicyKvStore_ = nullptr;
268 DistributedKvDataManager manager;
269 Options options;
270
271 AppId appId;
272 appId.appId = "audio_policy_manager";
273 options.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
274
275 StoreId storeId;
276 storeId.storeId = "audiopolicy";
277 Status status = Status::SUCCESS;
278
279 status = manager.CloseKvStore(appId, storeId);
280 AUDIO_ERR_LOG("CloseKvStore status: %{public}d", status);
281 CHECK_AND_RETURN_RET_LOG(status == Status::SUCCESS, ERR_ILLEGAL_STATE, "CloseKvStore failed!");
282
283 status = manager.DeleteKvStore(appId, storeId, options.baseDir);
284 CHECK_AND_RETURN_RET_LOG(status == Status::SUCCESS, ERR_ILLEGAL_STATE, "CloseKvStore failed!");
285
286 InitKVStoreInternal();
287 return SUCCESS;
288 }
289
Deinit(void)290 void AudioAdapterManager::Deinit(void)
291 {
292 CHECK_AND_RETURN_LOG(audioServiceAdapter_, "Deinit audio adapter null");
293
294 if (handler_ != nullptr) {
295 AUDIO_INFO_LOG("release handler");
296 handler_->ReleaseEventRunner();
297 handler_ = nullptr;
298 }
299
300 return audioServiceAdapter_->Disconnect();
301 }
302
SetAudioStreamRemovedCallback(AudioStreamRemovedCallback * callback)303 int32_t AudioAdapterManager::SetAudioStreamRemovedCallback(AudioStreamRemovedCallback *callback)
304 {
305 CHECK_AND_RETURN_RET_LOG(callback != nullptr, ERR_INVALID_PARAM,
306 "SetAudioStreamRemovedCallback callback == nullptr");
307
308 sessionCallback_ = callback;
309 return SUCCESS;
310 }
311
312 // LCOV_EXCL_STOP
GetMaxVolumeLevel(AudioVolumeType volumeType,DeviceType deviceType)313 int32_t AudioAdapterManager::GetMaxVolumeLevel(AudioVolumeType volumeType, DeviceType deviceType)
314 {
315 CHECK_AND_RETURN_RET_LOG(volumeType >= STREAM_VOICE_CALL && volumeType <= STREAM_TYPE_MAX,
316 ERR_INVALID_PARAM, "Invalid stream type");
317 if (volumeType == STREAM_APP) {
318 return appConfigVolume_.maxVolume;
319 }
320
321 if (streamVolumeInfos_.end() != streamVolumeInfos_.find(volumeType)) {
322 DeviceType type = currentActiveDevice_.deviceType_;
323 if (deviceType != DEVICE_TYPE_NONE) {
324 type = deviceType;
325 }
326 auto deviceIt = DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.find(type);
327 if (deviceIt != DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.end()) {
328 DeviceVolumeType deviceVolumeType = deviceIt->second;
329 if ((streamVolumeInfos_[volumeType] != nullptr) &&
330 (streamVolumeInfos_[volumeType]->deviceVolumeInfos.end() !=
331 streamVolumeInfos_[volumeType]->deviceVolumeInfos.find(deviceVolumeType)) &&
332 (streamVolumeInfos_[volumeType]->deviceVolumeInfos[deviceVolumeType] != nullptr) &&
333 (streamVolumeInfos_[volumeType]->deviceVolumeInfos[deviceVolumeType]->maxLevel != -1)) {
334 return streamVolumeInfos_[volumeType]->deviceVolumeInfos[deviceVolumeType]->maxLevel;
335 }
336 }
337 }
338
339 if (maxVolumeIndexMap_.end() != maxVolumeIndexMap_.find(volumeType)) {
340 return maxVolumeIndexMap_[volumeType];
341 } else if (maxVolumeIndexMap_.end() != maxVolumeIndexMap_.find(STREAM_MUSIC)) {
342 AUDIO_WARNING_LOG("can't find volumeType:%{public}d and use default STREAM_MUSIC", volumeType);
343 return maxVolumeIndexMap_[STREAM_MUSIC];
344 } else {
345 AUDIO_ERR_LOG("use default max volume level %{public}d", MAX_VOLUME_LEVEL);
346 return MAX_VOLUME_LEVEL;
347 }
348 }
349
GetMinVolumeLevel(AudioVolumeType volumeType,DeviceType deviceType)350 int32_t AudioAdapterManager::GetMinVolumeLevel(AudioVolumeType volumeType, DeviceType deviceType)
351 {
352 CHECK_AND_RETURN_RET_LOG(volumeType >= STREAM_VOICE_CALL && volumeType <= STREAM_TYPE_MAX,
353 ERR_INVALID_PARAM, "Invalid stream type");
354 if (volumeType == STREAM_APP) {
355 return appConfigVolume_.minVolume;
356 }
357
358 if (streamVolumeInfos_.end() != streamVolumeInfos_.find(volumeType)) {
359 DeviceType type = currentActiveDevice_.deviceType_;
360 if (deviceType != DEVICE_TYPE_NONE) {
361 type = deviceType;
362 }
363 auto deviceIt = DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.find(type);
364 if (deviceIt != DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.end()) {
365 DeviceVolumeType deviceVolumeType = deviceIt->second;
366 if ((streamVolumeInfos_[volumeType] != nullptr) &&
367 (streamVolumeInfos_[volumeType]->deviceVolumeInfos.end() !=
368 streamVolumeInfos_[volumeType]->deviceVolumeInfos.find(deviceVolumeType)) &&
369 (streamVolumeInfos_[volumeType]->deviceVolumeInfos[deviceVolumeType] != nullptr) &&
370 (streamVolumeInfos_[volumeType]->deviceVolumeInfos[deviceVolumeType]->minLevel != -1)) {
371 return streamVolumeInfos_[volumeType]->deviceVolumeInfos[deviceVolumeType]->minLevel;
372 }
373 }
374 }
375
376 if (minVolumeIndexMap_.end() != minVolumeIndexMap_.find(volumeType)) {
377 return minVolumeIndexMap_[volumeType];
378 } else if (minVolumeIndexMap_.end() != minVolumeIndexMap_.find(STREAM_MUSIC)) {
379 AUDIO_WARNING_LOG("can't find volumeType:%{public}d and use default STREAM_MUSIC", volumeType);
380 return minVolumeIndexMap_[STREAM_MUSIC];
381 } else {
382 AUDIO_ERR_LOG("use default max volume level %{public}d", MIN_VOLUME_LEVEL);
383 return MIN_VOLUME_LEVEL;
384 }
385 }
386
SaveRingtoneVolumeToLocal(AudioVolumeType volumeType,int32_t volumeLevel)387 void AudioAdapterManager::SaveRingtoneVolumeToLocal(AudioVolumeType volumeType, int32_t volumeLevel)
388 {
389 AudioVolumeType audioVolumeMap = VolumeUtils::GetVolumeTypeFromStreamType(volumeType);
390 // PC Boot Animation Volume use STREAM_SYSTEM
391 if ((volumeType == STREAM_RING && !VolumeUtils::IsPCVolumeEnable()) || (audioVolumeMap == STREAM_SYSTEM &&
392 currentActiveDevice_.deviceType_ == DEVICE_TYPE_SPEAKER)) {
393 int32_t volumeLevel =
394 volumeDataMaintainer_.GetStreamVolume(audioVolumeMap) * (GetStreamMute(audioVolumeMap) ? 0 : 1);
395 int32_t ret = SetParameter("persist.multimedia.audio.ringtonevolume", std::to_string(volumeLevel).c_str());
396 if (ret == 0) {
397 AUDIO_INFO_LOG("Save ringtone volume for boot success %{public}d", volumeLevel);
398 } else {
399 AUDIO_ERR_LOG("Save ringtone volume for boot failed, result %{public}d", ret);
400 }
401 }
402 }
403
SetDataShareReady(std::atomic<bool> isDataShareReady)404 void AudioAdapterManager::SetDataShareReady(std::atomic<bool> isDataShareReady)
405 {
406 volumeDataMaintainer_.SetDataShareReady(std::atomic_load(&isDataShareReady));
407 }
408
UpdateSafeVolumeByS4()409 void AudioAdapterManager::UpdateSafeVolumeByS4()
410 {
411 AUDIO_INFO_LOG("Update Safevolume by S4 reboot,reset wired and bt once");
412 isWiredBoot_ = true;
413 isBtBoot_ = true;
414 UpdateSafeVolume();
415 SetVolumeDb(STREAM_MUSIC);
416 }
417
SetAppVolumeLevel(int32_t appUid,int32_t volumeLevel)418 int32_t AudioAdapterManager::SetAppVolumeLevel(int32_t appUid, int32_t volumeLevel)
419 {
420 AUDIO_INFO_LOG("SetSystemVolumeLevel: appUid: %{public}d, deviceType: %{public}d, volumeLevel:%{public}d",
421 appUid, currentActiveDevice_.deviceType_, volumeLevel);
422 volumeDataMaintainer_.SetAppVolume(appUid, volumeLevel);
423 return SetAppVolumeDb(appUid);
424 }
425
SetAppVolumeMuted(int32_t appUid,bool muted)426 int32_t AudioAdapterManager::SetAppVolumeMuted(int32_t appUid, bool muted)
427 {
428 AUDIO_INFO_LOG("SetSystemVolumeLevel: appUid: %{public}d, deviceType: %{public}d, muted:%{public}d",
429 appUid, currentActiveDevice_.deviceType_, muted);
430 volumeDataMaintainer_.SetAppVolumeMuted(appUid, muted);
431 return SetAppVolumeMutedDB(appUid, muted);
432 }
433
SetAppRingMuted(int32_t appUid,bool muted)434 int32_t AudioAdapterManager::SetAppRingMuted(int32_t appUid, bool muted)
435 {
436 AUDIO_INFO_LOG("appUid: %{public}d, muted: %{public}d", appUid, muted);
437 auto audioVolume = AudioVolume::GetInstance();
438 CHECK_AND_RETURN_RET_LOG(audioVolume != nullptr, ERR_INVALID_PARAM, "audioVolume handle null");
439 bool isSetSuccess = audioVolume->SetAppRingMuted(appUid, muted);
440 CHECK_AND_RETURN_RET_LOG(isSetSuccess, ERROR, "set app ring muted: %{public}d fail", muted);
441 volumeDataMaintainer_.SetAppStreamMuted(appUid, STREAM_RING, muted);
442 return SUCCESS;
443 }
444
IsAppRingMuted(int32_t appUid)445 bool AudioAdapterManager::IsAppRingMuted(int32_t appUid)
446 {
447 AudioStreamType streamType = STREAM_RING;
448 return volumeDataMaintainer_.IsAppStreamMuted(appUid, streamType);
449 }
450
SetAdjustVolumeForZone(int32_t zoneId)451 int32_t AudioAdapterManager::SetAdjustVolumeForZone(int32_t zoneId)
452 {
453 std::lock_guard<std::mutex> lock(volumeDataMapMutex_);
454 volumeAdjustZoneId_ = zoneId;
455 if (zoneId == 0) {
456 return SUCCESS;
457 }
458 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devices =
459 AudioZoneService::GetInstance().FetchOutputDevices(zoneId, STREAM_USAGE_UNKNOWN, 0, ROUTER_TYPE_DEFAULT);
460 CHECK_AND_RETURN_RET_LOG(devices.size() >= 1 && devices[0] != nullptr, ERR_OPERATION_FAILED,
461 "zone device error");
462 if (volumeDataExtMaintainer_.find(devices[0]->GetKey()) == volumeDataExtMaintainer_.end()) {
463 volumeDataExtMaintainer_[devices[0]->GetKey()] = std::make_shared<VolumeDataMaintainer>();
464 if (devices[0]->IsDistributedSpeaker()) {
465 for (auto streamType : DISTRIBUTED_VOLUME_TYPE_LIST) {
466 int32_t maxVolumeLevel = GetMaxVolumeLevel(streamType);
467 volumeDataExtMaintainer_[devices[0]->GetKey()]->SetStreamVolume(streamType, maxVolumeLevel);
468 volumeDataExtMaintainer_[devices[0]->GetKey()]->SetStreamMuteStatus(streamType, false);
469 }
470 } else {
471 LoadMuteStatusMap(devices[0]);
472 LoadVolumeMap(devices[0]);
473 }
474 auto iter = defaultVolumeTypeList_.begin();
475 while (iter != defaultVolumeTypeList_.end()) {
476 SetVolumeDb(devices[0], *iter);
477 iter++;
478 }
479 }
480 return SUCCESS;
481 }
482
GetVolumeAdjustZoneId()483 int32_t AudioAdapterManager::GetVolumeAdjustZoneId()
484 {
485 return volumeAdjustZoneId_;
486 }
487
SetZoneMute(int32_t zoneId,AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType)488 int32_t AudioAdapterManager::SetZoneMute(int32_t zoneId, AudioStreamType streamType, bool mute,
489 StreamUsage streamUsage, const DeviceType &deviceType)
490 {
491 std::lock_guard<std::mutex> lock(volumeDataMapMutex_);
492 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devices =
493 AudioZoneService::GetInstance().FetchOutputDevices(zoneId, streamUsage, 0, ROUTER_TYPE_DEFAULT);
494 CHECK_AND_RETURN_RET_LOG(devices.size() >= 1 && devices[0] != nullptr, ERR_OPERATION_FAILED,
495 "zone device error");
496 return SetStreamMuteInternal(devices[0], streamType, mute, streamUsage);
497 }
498
GetZoneMute(int32_t zoneId,AudioStreamType streamType)499 bool AudioAdapterManager::GetZoneMute(int32_t zoneId, AudioStreamType streamType)
500 {
501 std::lock_guard<std::mutex> lock(volumeDataMapMutex_);
502 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devices =
503 AudioZoneService::GetInstance().FetchOutputDevices(zoneId, STREAM_USAGE_UNKNOWN, 0, ROUTER_TYPE_DEFAULT);
504 CHECK_AND_RETURN_RET_LOG(devices.size() >= 1 && devices[0] != nullptr, false,
505 "zone device error");
506 CHECK_AND_RETURN_RET_LOG(volumeDataExtMaintainer_.find(devices[0]->GetKey()) !=
507 volumeDataExtMaintainer_.end(), false, "volumeDataExtMaintainer_ error");
508 return GetStreamMuteInternal(devices[0], streamType);
509 }
510
GetZoneVolumeLevel(int32_t zoneId,AudioStreamType streamType)511 int32_t AudioAdapterManager::GetZoneVolumeLevel(int32_t zoneId, AudioStreamType streamType)
512 {
513 std::lock_guard<std::mutex> lock(volumeDataMapMutex_);
514 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devices =
515 AudioZoneService::GetInstance().FetchOutputDevices(zoneId, STREAM_USAGE_UNKNOWN, 0, ROUTER_TYPE_DEFAULT);
516 CHECK_AND_RETURN_RET_LOG(devices.size() >= 1 && devices[0] != nullptr, ERR_OPERATION_FAILED,
517 "zone device error");
518 CHECK_AND_RETURN_RET_LOG(volumeDataExtMaintainer_.find(devices[0]->GetKey()) !=
519 volumeDataExtMaintainer_.end(), ERR_OPERATION_FAILED, "volumeDataExtMaintainer_ error");
520 if (GetStreamMuteInternal(devices[0], streamType)) {
521 return MIN_VOLUME_LEVEL;
522 }
523 return volumeDataExtMaintainer_[devices[0]->GetKey()]->GetStreamVolume(streamType);
524 }
525
IsAppVolumeMute(int32_t appUid,bool owned,bool & isMute)526 int32_t AudioAdapterManager::IsAppVolumeMute(int32_t appUid, bool owned, bool &isMute)
527 {
528 AUDIO_INFO_LOG("IsAppVolumeMute: appUid: %{public}d, deviceType: %{public}d, owned:%{public}d",
529 appUid, currentActiveDevice_.deviceType_, owned);
530 if (owned) {
531 volumeDataMaintainer_.GetAppMuteOwned(appUid, isMute);
532 } else {
533 volumeDataMaintainer_.GetAppMute(appUid, isMute);
534 }
535 return SUCCESS;
536 }
537
SetZoneVolumeLevel(int32_t zoneId,AudioStreamType streamType,int32_t volumeLevel)538 int32_t AudioAdapterManager::SetZoneVolumeLevel(int32_t zoneId, AudioStreamType streamType, int32_t volumeLevel)
539 {
540 std::lock_guard<std::mutex> lock(volumeDataMapMutex_);
541 std::vector<std::shared_ptr<AudioDeviceDescriptor>> devices =
542 AudioZoneService::GetInstance().FetchOutputDevices(zoneId, STREAM_USAGE_UNKNOWN, 0, ROUTER_TYPE_DEFAULT);
543 CHECK_AND_RETURN_RET_LOG(devices.size() >= 1, ERR_OPERATION_FAILED, "zone device error");
544 int32_t mimRet = GetMinVolumeLevel(streamType);
545 int32_t maxRet = GetMaxVolumeLevel(streamType);
546 CHECK_AND_RETURN_RET_LOG(volumeLevel >= mimRet && volumeLevel <= maxRet, ERR_OPERATION_FAILED,
547 "volumeLevel not in scope,mimRet:%{public}d maxRet:%{public}d", mimRet, maxRet);
548
549 CHECK_AND_RETURN_RET_LOG(volumeDataExtMaintainer_.find(devices[0]->GetKey()) != volumeDataExtMaintainer_.end(),
550 ERR_OPERATION_FAILED, "volumeDataExtMaintainer_ error");
551 volumeDataExtMaintainer_[devices[0]->GetKey()]->SetStreamVolume(streamType, volumeLevel);
552 if (handler_ != nullptr && devices[0]->deviceType_ == DEVICE_TYPE_REMOTE_CAST) {
553 handler_->SendSaveVolume(devices[0]->deviceType_, streamType, volumeLevel, devices[0]->networkId_);
554 }
555 return SetVolumeDb(devices[0], streamType);
556 }
557
SetSystemVolumeLevel(AudioStreamType streamType,int32_t volumeLevel)558 int32_t AudioAdapterManager::SetSystemVolumeLevel(AudioStreamType streamType, int32_t volumeLevel)
559 {
560 Trace trace("KeyAction AudioAdapterManager::SetSystemVolumeLevel streamType:"
561 + std::to_string(streamType) + ", volumeLevel:" + std::to_string(volumeLevel));
562 AUDIO_INFO_LOG("streamType: %{public}d, deviceType: %{public}d, volumeLevel:%{public}d",
563 streamType, currentActiveDevice_.deviceType_, volumeLevel);
564 if (currentActiveDevice_.volumeBehavior_.isVolumeControlDisabled) {
565 AUDIO_WARNING_LOG("currentActiveDevice_.volumeBehavior_.isVolumeControlDisabled is true!");
566 return ERR_SET_VOL_FAILED_BY_VOLUME_CONTROL_DISABLED;
567 }
568 if (GetSystemVolumeLevel(streamType) == volumeLevel &&
569 currentActiveDevice_.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO &&
570 currentActiveDevice_.deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP && !VolumeUtils::IsPCVolumeEnable()) {
571 AUDIO_INFO_LOG("The volume is the same as before.");
572 return SUCCESS;
573 }
574 AUDIO_INFO_LOG("streamType: %{public}d, deviceType: %{public}d, volumeLevel:%{public}d",
575 streamType, currentActiveDevice_.deviceType_, volumeLevel);
576 if (volumeLevel == 0 && !VolumeUtils::IsPCVolumeEnable() &&
577 (streamType == STREAM_VOICE_CALL ||
578 streamType == STREAM_ALARM || streamType == STREAM_ACCESSIBILITY ||
579 streamType == STREAM_VOICE_COMMUNICATION)) {
580 // these types can not set to mute, but don't return error
581 AUDIO_ERR_LOG("this type can not set mute");
582 return SUCCESS;
583 }
584 int32_t mimRet = GetMinVolumeLevel(streamType);
585 int32_t maxRet = GetMaxVolumeLevel(streamType);
586 CHECK_AND_RETURN_RET_LOG(volumeLevel >= mimRet && volumeLevel <= maxRet, ERR_OPERATION_FAILED,
587 "volumeLevel not in scope,mimRet:%{public}d maxRet:%{public}d", mimRet, maxRet);
588
589 // Save the volume to volumeLevelMap_.
590 volumeDataMaintainer_.SetStreamVolume(streamType, volumeLevel);
591 // Save the volume to settingsdata.
592 if (currentActiveDevice_.volumeBehavior_.databaseVolumeName != "" && IsDistributedVolumeType(streamType)) {
593 volumeDataMaintainer_.SaveVolumeWithDatabaseVolumeName(
594 currentActiveDevice_.volumeBehavior_.databaseVolumeName, streamType, volumeLevel);
595 } else if (handler_ != nullptr) {
596 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_.deviceType_ != DEVICE_TYPE_REMOTE_CAST) {
597 AUDIO_INFO_LOG("DualToneStreamType. Save volume for speaker.");
598 handler_->SendSaveVolume(DEVICE_TYPE_SPEAKER, streamType, volumeLevel, "LocalDevice");
599 } else {
600 handler_->SendSaveVolume(currentActiveDevice_.deviceType_, streamType, volumeLevel,
601 currentActiveDevice_.networkId_);
602 }
603 }
604
605 return SetVolumeDb(streamType);
606 }
607
SaveSpecifiedDeviceVolume(AudioStreamType streamType,int32_t volumeLevel,DeviceType deviceType)608 int32_t AudioAdapterManager::SaveSpecifiedDeviceVolume(AudioStreamType streamType, int32_t volumeLevel,
609 DeviceType deviceType)
610 {
611 AUDIO_INFO_LOG("%{public}s: streamType: %{public}d, currentDeviceType: %{public}d, volumeLevel: %{public}d, "
612 "deviceType: %{public}d", __func__, streamType, currentActiveDevice_.deviceType_, volumeLevel,
613 deviceType);
614 int32_t mimRet = GetMinVolumeLevel(streamType);
615 int32_t maxRet = GetMaxVolumeLevel(streamType);
616 CHECK_AND_RETURN_RET_LOG(volumeLevel >= mimRet && volumeLevel <= maxRet, ERR_OPERATION_FAILED,
617 "volumeLevel not in scope,mimRet:%{public}d maxRet:%{public}d", mimRet, maxRet);
618 handler_->SendSaveVolume(deviceType, streamType, volumeLevel);
619 return SUCCESS;
620 }
621
GetDeviceVolume(DeviceType deviceType,AudioStreamType streamType)622 int32_t AudioAdapterManager::GetDeviceVolume(DeviceType deviceType, AudioStreamType streamType)
623 {
624 return volumeDataMaintainer_.GetDeviceVolume(deviceType, streamType);
625 }
626
HandleSaveVolume(DeviceType deviceType,AudioStreamType streamType,int32_t volumeLevel,std::string networkId)627 void AudioAdapterManager::HandleSaveVolume(DeviceType deviceType, AudioStreamType streamType, int32_t volumeLevel,
628 std::string networkId)
629 {
630 volumeDataMaintainer_.SaveVolume(deviceType, streamType, volumeLevel, networkId);
631 }
632
HandleSaveVolumeDegree(DeviceType deviceType,AudioStreamType streamType,int32_t volumeDegree,std::string networkId)633 void AudioAdapterManager::HandleSaveVolumeDegree(DeviceType deviceType, AudioStreamType streamType,
634 int32_t volumeDegree, std::string networkId)
635 {
636 volumeDataMaintainer_.SaveVolumeDegree(deviceType, streamType, volumeDegree, networkId);
637 }
638
HandleStreamMuteStatus(AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType,std::string networkId)639 void AudioAdapterManager::HandleStreamMuteStatus(AudioStreamType streamType, bool mute, StreamUsage streamUsage,
640 const DeviceType &deviceType, std::string networkId)
641 {
642 if (deviceType != DEVICE_TYPE_NONE) {
643 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, mute, networkId);
644 } else {
645 volumeDataMaintainer_.SaveMuteStatus(currentActiveDevice_.deviceType_, streamType, mute, networkId);
646 }
647 }
648
HandleRingerMode(AudioRingerMode ringerMode)649 void AudioAdapterManager::HandleRingerMode(AudioRingerMode ringerMode)
650 {
651 int32_t volumeLevel =
652 volumeDataMaintainer_.GetStreamVolume(STREAM_RING) * ((ringerMode != RINGER_MODE_NORMAL) ? 0 : 1);
653 // Save volume in local prop for bootanimation
654 SaveRingtoneVolumeToLocal(STREAM_RING, volumeLevel);
655
656 volumeDataMaintainer_.SaveRingerMode(ringerMode);
657 }
658
SetAudioServerProxy(sptr<IStandardAudioService> gsp)659 void AudioAdapterManager::SetAudioServerProxy(sptr<IStandardAudioService> gsp)
660 {
661 CHECK_AND_RETURN_LOG(gsp != nullptr, "audioServerProxy null");
662 audioServerProxy_ = gsp;
663 }
664
SetAppVolumeDb(int32_t appUid)665 int32_t AudioAdapterManager::SetAppVolumeDb(int32_t appUid)
666 {
667 int32_t volumeLevel = volumeDataMaintainer_.GetAppVolume(appUid);
668 float volumeDb = 1.0f;
669 volumeDb = CalculateVolumeDbNonlinear(STREAM_APP, currentActiveDevice_.deviceType_, volumeLevel);
670 AUDIO_INFO_LOG("volumeDb:%{public}f volume:%{public}d devicetype:%{public}d",
671 volumeDb, volumeLevel, currentActiveDevice_.deviceType_);
672 SetAppAudioVolume(appUid, volumeDb);
673 return SUCCESS;
674 }
675
SetAppVolumeMutedDB(int32_t appUid,bool muted)676 int32_t AudioAdapterManager::SetAppVolumeMutedDB(int32_t appUid, bool muted)
677 {
678 std::lock_guard<std::mutex> lock(audioVolumeMutex_);
679 auto audioVolume = AudioVolume::GetInstance();
680 CHECK_AND_RETURN_RET_LOG(audioVolume != nullptr, ERR_INVALID_PARAM, "audioVolume handle null");
681 AUDIO_INFO_LOG("appUid:%{public}d muted:%{public}d devicetype:%{public}d",
682 appUid, muted, currentActiveDevice_.deviceType_);
683 audioVolume->SetAppVolumeMute(appUid, muted);
684 return SUCCESS;
685 }
686
SetVolumeDb(std::shared_ptr<AudioDeviceDescriptor> & device,AudioStreamType streamType)687 int32_t AudioAdapterManager::SetVolumeDb(std::shared_ptr<AudioDeviceDescriptor> &device, AudioStreamType streamType)
688 {
689 int32_t volumeLevel =
690 volumeDataExtMaintainer_[device->GetKey()]->GetStreamVolume(streamType) *
691 (GetStreamMute(device, streamType) ? 0 : 1);
692
693 float volumeDb = 1.0f;
694 if (useNonlinearAlgo_) {
695 if (Util::IsDualToneStreamType(streamType) &&
696 device->deviceType_ != DEVICE_TYPE_REMOTE_CAST && !VolumeUtils::IsPCVolumeEnable()) {
697 volumeDb = CalculateVolumeDbNonlinear(streamType, DEVICE_TYPE_SPEAKER, volumeLevel);
698 } else {
699 volumeDb = CalculateVolumeDbNonlinear(streamType, device->deviceType_, volumeLevel);
700 }
701 } else {
702 volumeDb = CalculateVolumeDb(volumeLevel);
703 }
704 // Set voice call assistant stream to full volume
705 if (streamType == STREAM_VOICE_CALL_ASSISTANT) {
706 volumeDb = 1.0f;
707 }
708 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
709 "SetSystemVolumeLevel audio adapter null");
710 // audio volume
711 SetAudioVolume(device, streamType, volumeDb);
712 return SUCCESS;
713 }
714
SetVolumeDb(AudioStreamType streamType)715 int32_t AudioAdapterManager::SetVolumeDb(AudioStreamType streamType)
716 {
717 int32_t volumeLevel =
718 volumeDataMaintainer_.GetStreamVolume(streamType) * (GetStreamMute(streamType) ? 0 : 1);
719 // Save volume in local prop for bootanimation
720 SaveRingtoneVolumeToLocal(streamType, volumeLevel);
721
722 float volumeDb = 1.0f;
723 if (useNonlinearAlgo_) {
724 if (Util::IsDualToneStreamType(streamType) &&
725 currentActiveDevice_.deviceType_ != DEVICE_TYPE_REMOTE_CAST && !VolumeUtils::IsPCVolumeEnable()) {
726 volumeDb = CalculateVolumeDbNonlinear(streamType, DEVICE_TYPE_SPEAKER, volumeLevel);
727 } else {
728 volumeDb = CalculateVolumeDbNonlinear(streamType, currentActiveDevice_.deviceType_, volumeLevel);
729 }
730 } else {
731 volumeDb = CalculateVolumeDb(volumeLevel);
732 }
733 // Set voice call assistant stream to full volume
734 if (streamType == STREAM_VOICE_CALL_ASSISTANT) {
735 volumeDb = 1.0f;
736 }
737
738 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
739 "SetSystemVolumeLevel audio adapter null");
740
741 AUDIO_INFO_LOG("streamType:%{public}d volumeDb:%{public}f volume:%{public}d devicetype:%{public}d",
742 streamType, volumeDb, volumeLevel, currentActiveDevice_.deviceType_);
743
744 // audio volume
745 SetAudioVolume(streamType, volumeDb);
746
747 return SUCCESS;
748 }
749
SetAppAudioVolume(int32_t appUid,float volumeDb)750 void AudioAdapterManager::SetAppAudioVolume(int32_t appUid, float volumeDb)
751 {
752 std::lock_guard<std::mutex> lock(audioVolumeMutex_);
753 auto audioVolume = AudioVolume::GetInstance();
754 CHECK_AND_RETURN_LOG(audioVolume != nullptr, "audioVolume handle null");
755 bool isMuted = GetAppMute(appUid);
756 int32_t appVolumeLevel = volumeDataMaintainer_.GetAppVolume(appUid) * (isMuted ? 0 : 1);
757 AppVolume appVolume(appUid, volumeDb, appVolumeLevel, isMuted);
758 audioVolume->SetAppVolume(appVolume);
759 }
760
SetAudioVolume(AudioStreamType streamType,float volumeDb)761 void AudioAdapterManager::SetAudioVolume(AudioStreamType streamType, float volumeDb)
762 {
763 std::lock_guard<std::mutex> lock(audioVolumeMutex_);
764 AudioStreamType volumeType = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
765 bool isMuted = GetStreamMute(volumeType);
766 int32_t volumeLevel = volumeDataMaintainer_.GetStreamVolume(volumeType) * (isMuted ? 0 : 1);
767 if (GetActiveDevice() == DEVICE_TYPE_BLUETOOTH_A2DP && IsAbsVolumeScene() && volumeType == STREAM_MUSIC) {
768 isMuted = IsAbsVolumeMute();
769 volumeLevel = volumeDataMaintainer_.GetStreamVolume(volumeType) * (isMuted ? 0 : 1);
770 volumeDb = isMuted ? 0.0f : 0.63957f; // 0.63957 = -4dB
771 }
772 auto audioVolume = AudioVolume::GetInstance();
773 CHECK_AND_RETURN_LOG(audioVolume != nullptr, "audioVolume handle null");
774 if (currentActiveDevice_.IsDistributedSpeaker()) {
775 SystemVolume systemVolume(volumeType, REMOTE_CLASS, volumeDb, volumeLevel, isMuted);
776 audioVolume->SetSystemVolume(systemVolume);
777 SetOffloadVolume(volumeType, volumeDb, REMOTE_CLASS, currentActiveDevice_.networkId_);
778 return;
779 }
780 if (GetActiveDevice() == DEVICE_TYPE_NEARLINK) {
781 if (volumeType == STREAM_MUSIC && !isSleVoiceStatus_.load()) {
782 isMuted = IsAbsVolumeMute();
783 volumeDb = isMuted ? 0.0f : 0.63957f; // 0.63957 = -4dB
784 } else if (volumeType == STREAM_VOICE_CALL) {
785 volumeDb = 1.0f;
786 }
787 }
788 auto it = DEVICE_CLASS_MAP.find(GetActiveDevice());
789 if (it == DEVICE_CLASS_MAP.end()) {
790 AUDIO_ERR_LOG("unkown device type %{public}d", GetActiveDevice());
791 return;
792 }
793 for (auto &deviceClass : it->second) {
794 SystemVolume systemVolume(volumeType, deviceClass, volumeDb, volumeLevel, isMuted);
795 if (deviceClass != OFFLOAD_CLASS) {
796 audioVolume->SetSystemVolume(systemVolume);
797 } else if (deviceClass == OFFLOAD_CLASS && volumeType == STREAM_MUSIC) {
798 audioVolume->SetSystemVolume(systemVolume);
799 SetOffloadVolume(volumeType, volumeDb, OFFLOAD_CLASS);
800 }
801 }
802 }
803
SetAudioVolume(std::shared_ptr<AudioDeviceDescriptor> & device,AudioStreamType streamType,float volumeDb)804 void AudioAdapterManager::SetAudioVolume(std::shared_ptr<AudioDeviceDescriptor> &device,
805 AudioStreamType streamType, float volumeDb)
806 {
807 std::lock_guard<std::mutex> lock(audioVolumeMutex_);
808 AudioStreamType volumeType = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
809 bool isMuted = GetStreamMute(device, volumeType);
810 int32_t volumeLevel =
811 volumeDataExtMaintainer_[device->GetKey()]->GetStreamVolume(volumeType) *(isMuted ? 0 : 1);
812 auto audioVolume = AudioVolume::GetInstance();
813 CHECK_AND_RETURN_LOG(audioVolume != nullptr, "audioVolume handle null");
814 if (device->IsDistributedSpeaker()) {
815 SystemVolume systemVolume(volumeType, REMOTE_CLASS, volumeDb, volumeLevel, isMuted);
816 audioVolume->SetSystemVolume(systemVolume);
817 SetOffloadVolume(volumeType, volumeDb, REMOTE_CLASS, device->networkId_);
818 return;
819 }
820 auto it = DEVICE_CLASS_MAP.find(device->deviceType_);
821 if (it == DEVICE_CLASS_MAP.end()) {
822 AUDIO_ERR_LOG("unknown device type %{public}d", device->deviceType_);
823 return;
824 }
825 for (auto &deviceClass : it->second) {
826 SystemVolume systemVolume(volumeType, deviceClass, volumeDb, volumeLevel, isMuted);
827 if (deviceClass != OFFLOAD_CLASS) {
828 audioVolume->SetSystemVolume(systemVolume);
829 }
830 }
831 }
832
SetOffloadVolume(AudioStreamType streamType,float volumeDb,const std::string & deviceClass,const std::string & networkId)833 void AudioAdapterManager::SetOffloadVolume(AudioStreamType streamType, float volumeDb, const std::string &deviceClass,
834 const std::string &networkId)
835 {
836 float volume = volumeDb; // maybe only system volume
837 if (!(streamType == STREAM_MUSIC || streamType == STREAM_SPEECH)) {
838 return;
839 }
840 CHECK_AND_RETURN_LOG(audioServerProxy_ != nullptr, "audioServerProxy_ null");
841 std::string identity = IPCSkeleton::ResetCallingIdentity();
842 if (offloadSessionID_.has_value()) { // need stream volume and system volume
843 struct VolumeValues volumes = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
844 volume = AudioVolume::GetInstance()->GetVolume(offloadSessionID_.value(), streamType, deviceClass, &volumes);
845 std::string routeDeviceClass = deviceClass == REMOTE_CLASS ? "remote_offload" : "offload";
846 AUDIO_INFO_LOG("routeDeviceClass:%{public}s, networkId:%{public}s, volume:%{public}f", routeDeviceClass.c_str(),
847 networkId.c_str(), volume);
848 audioServerProxy_->OffloadSetVolume(volume, routeDeviceClass, networkId);
849 }
850 IPCSkeleton::SetCallingIdentity(identity);
851 }
852
SetOffloadSessionId(uint32_t sessionId)853 void AudioAdapterManager::SetOffloadSessionId(uint32_t sessionId)
854 {
855 if (sessionId < MIN_STREAMID || sessionId > MAX_STREAMID) {
856 AUDIO_PRERELEASE_LOGE("set sessionId[%{public}d] error", sessionId);
857 } else {
858 AUDIO_PRERELEASE_LOGI("set sessionId[%{public}d]", sessionId);
859 }
860 offloadSessionID_ = sessionId;
861 }
862
ResetOffloadSessionId()863 void AudioAdapterManager::ResetOffloadSessionId()
864 {
865 if (offloadSessionID_.has_value()) {
866 AUDIO_PRERELEASE_LOGI("reset offload sessionId[%{public}d]", offloadSessionID_.value());
867 offloadSessionID_.reset();
868 }
869 }
870
SetDoubleRingVolumeDb(const AudioStreamType & streamType,const int32_t & volumeLevel)871 int32_t AudioAdapterManager::SetDoubleRingVolumeDb(const AudioStreamType &streamType, const int32_t &volumeLevel)
872 {
873 float volumeDb = 1.0f;
874 if (useNonlinearAlgo_) {
875 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_.deviceType_ != DEVICE_TYPE_REMOTE_CAST) {
876 volumeDb = CalculateVolumeDbNonlinear(streamType, DEVICE_TYPE_SPEAKER, volumeLevel);
877 } else {
878 volumeDb = CalculateVolumeDbNonlinear(streamType, currentActiveDevice_.deviceType_, volumeLevel);
879 }
880 } else {
881 volumeDb = CalculateVolumeDb(volumeLevel);
882 }
883 SetAudioVolume(streamType, volumeDb);
884
885 return SUCCESS;
886 }
887
GetSystemVolumeLevel(AudioStreamType streamType)888 int32_t AudioAdapterManager::GetSystemVolumeLevel(AudioStreamType streamType)
889 {
890 if (GetStreamMuteInternal(streamType)) {
891 return MIN_VOLUME_LEVEL;
892 }
893
894 return volumeDataMaintainer_.GetStreamVolume(streamType);
895 }
896
GetAppVolumeLevel(int32_t appUid,int32_t & volumeLevel)897 int32_t AudioAdapterManager::GetAppVolumeLevel(int32_t appUid, int32_t &volumeLevel)
898 {
899 if (volumeDataMaintainer_.IsSetAppVolume(appUid)) {
900 volumeLevel = volumeDataMaintainer_.GetAppVolume(appUid);
901 } else {
902 volumeLevel = appConfigVolume_.defaultVolume;
903 }
904 return SUCCESS;
905 }
906
GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)907 int32_t AudioAdapterManager::GetSystemVolumeLevelNoMuteState(AudioStreamType streamType)
908 {
909 return volumeDataMaintainer_.GetStreamVolume(streamType);
910 }
911
GetSystemVolumeDb(AudioStreamType streamType)912 float AudioAdapterManager::GetSystemVolumeDb(AudioStreamType streamType)
913 {
914 int32_t volumeLevel = volumeDataMaintainer_.GetStreamVolume(streamType);
915 return CalculateVolumeDb(volumeLevel);
916 }
917
SetStreamMute(AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType,std::string networkId)918 int32_t AudioAdapterManager::SetStreamMute(AudioStreamType streamType, bool mute, StreamUsage streamUsage,
919 const DeviceType &deviceType, std::string networkId)
920 {
921 return SetStreamMuteInternal(streamType, mute, streamUsage, deviceType, networkId);
922 }
923
SetStreamMuteInternal(std::shared_ptr<AudioDeviceDescriptor> & device,AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType)924 int32_t AudioAdapterManager::SetStreamMuteInternal(std::shared_ptr<AudioDeviceDescriptor> &device,
925 AudioStreamType streamType, bool mute,
926 StreamUsage streamUsage, const DeviceType &deviceType)
927 {
928 if (Util::IsDualToneStreamType(streamType) && device->deviceType_ != DEVICE_TYPE_SPEAKER &&
929 GetRingerMode() != RINGER_MODE_NORMAL && mute && Util::IsRingerOrAlarmerStreamUsage(streamUsage)) {
930 AUDIO_INFO_LOG("Dual tone stream type %{public}d, current active device:[%{public}d] is no speaker, dont mute",
931 streamType, mute);
932 return SUCCESS;
933 }
934 volumeDataExtMaintainer_[device->GetKey()]->SetStreamMuteStatus(streamType, mute);
935
936 if (handler_ != nullptr) {
937 handler_->SendStreamMuteStatusUpdate(streamType, mute, streamUsage, deviceType, device->networkId_);
938 }
939 return SetVolumeDb(device, streamType);
940 }
941
SetInnerStreamMute(AudioStreamType streamType,bool mute,StreamUsage streamUsage)942 int32_t AudioAdapterManager::SetInnerStreamMute(AudioStreamType streamType, bool mute, StreamUsage streamUsage)
943 {
944 AUDIO_INFO_LOG("stream type %{public}d, mute:%{public}d, streamUsage:%{public}d", streamType, mute, streamUsage);
945 int32_t isSetStreamMute = IsHandleStreamMute(streamType, mute, streamUsage);
946 if (isSetStreamMute == SUCCESS) {
947 return SUCCESS;
948 }
949 // set stream mute status to mem.
950 volumeDataMaintainer_.SetStreamMuteStatus(streamType, mute);
951
952 if (currentActiveDevice_.deviceType_ == DEVICE_TYPE_NEARLINK) {
953 SetAbsVolumeMute(mute);
954 }
955
956 int32_t volume = GetSystemVolumeLevel(streamType);
957 VolumeEvent volumeEvent = VolumeEvent(streamType, volume, false);
958 if (audioPolicyServerHandler_ != nullptr) {
959 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
960 }
961
962 return SetVolumeDb(streamType);
963 }
964
IsHandleStreamMute(AudioStreamType streamType,bool mute,StreamUsage streamUsage)965 int32_t AudioAdapterManager::IsHandleStreamMute(AudioStreamType streamType, bool mute, StreamUsage streamUsage)
966 {
967 if (mute && !VolumeUtils::IsPCVolumeEnable() &&
968 (streamType == STREAM_VOICE_CALL ||
969 streamType == STREAM_ALARM || streamType == STREAM_ACCESSIBILITY ||
970 streamType == STREAM_VOICE_COMMUNICATION)) {
971 // these types can not set to mute, but don't return error
972 AUDIO_ERR_LOG("SetStreamMute: this type can not set mute");
973 return SUCCESS;
974 }
975 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_.deviceType_ != DEVICE_TYPE_SPEAKER &&
976 GetRingerMode() != RINGER_MODE_NORMAL && mute && Util::IsRingerOrAlarmerStreamUsage(streamUsage)) {
977 AUDIO_INFO_LOG("Dual tone stream type %{public}d, current active device:[%{public}d] is no speaker, dont mute",
978 streamType, mute);
979 return SUCCESS;
980 }
981 return ERROR;
982 }
983
SetStreamMuteInternal(AudioStreamType streamType,bool mute,StreamUsage streamUsage,const DeviceType & deviceType,std::string networkId)984 int32_t AudioAdapterManager::SetStreamMuteInternal(AudioStreamType streamType, bool mute,
985 StreamUsage streamUsage, const DeviceType &deviceType, std::string networkId)
986 {
987 AUDIO_INFO_LOG("stream type %{public}d, mute:%{public}d, streamUsage:%{public}d", streamType, mute, streamUsage);
988 if (currentActiveDevice_.volumeBehavior_.isVolumeControlDisabled) {
989 AUDIO_WARNING_LOG("currentActiveDevice_.volumeBehavior_.isVolumeControlDisabled is true!");
990 return ERR_SET_VOL_FAILED_BY_VOLUME_CONTROL_DISABLED;
991 }
992 int32_t isSetStreamMute = IsHandleStreamMute(streamType, mute, streamUsage);
993 if (isSetStreamMute == SUCCESS) {
994 return SUCCESS;
995 }
996
997 // set stream mute status to mem.
998 volumeDataMaintainer_.SetStreamMuteStatus(streamType, mute);
999
1000 if (currentActiveDevice_.volumeBehavior_.databaseVolumeName != "" && IsDistributedVolumeType(streamType)) {
1001 volumeDataMaintainer_.SaveMuteStatusWithDatabaseVolumeName(
1002 currentActiveDevice_.volumeBehavior_.databaseVolumeName, streamType, mute);
1003 } else if (handler_ != nullptr) {
1004 handler_->SendStreamMuteStatusUpdate(streamType, mute, streamUsage, deviceType, networkId);
1005 }
1006
1007 // Achieve the purpose of adjusting the mute status by adjusting the stream volume.
1008 return SetVolumeDb(streamType);
1009 }
1010
SetPersistMicMuteState(const bool isMute)1011 int32_t AudioAdapterManager::SetPersistMicMuteState(const bool isMute)
1012 {
1013 AUDIO_INFO_LOG("Save mute state: %{public}d in setting db", isMute);
1014 bool res = volumeDataMaintainer_.SaveMicMuteState(isMute);
1015
1016 return res == true ? SUCCESS : ERROR;
1017 }
1018
GetPersistMicMuteState(bool & isMute)1019 int32_t AudioAdapterManager::GetPersistMicMuteState(bool &isMute)
1020 {
1021 bool res = volumeDataMaintainer_.GetMicMuteState(isMute);
1022 AUDIO_INFO_LOG("Get mute state from setting db is: %{public}d", isMute);
1023
1024 return res == true ? SUCCESS : ERROR;
1025 }
1026
SetSourceOutputStreamMute(int32_t uid,bool setMute)1027 int32_t AudioAdapterManager::SetSourceOutputStreamMute(int32_t uid, bool setMute)
1028 {
1029 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
1030 "SetSourceOutputStreamMute audio adapter null");
1031 return audioServiceAdapter_->SetSourceOutputMute(uid, setMute);
1032 }
1033
GetStreamMute(AudioStreamType streamType)1034 bool AudioAdapterManager::GetStreamMute(AudioStreamType streamType)
1035 {
1036 return GetStreamMuteInternal(streamType);
1037 }
1038
GetStreamMute(std::shared_ptr<AudioDeviceDescriptor> & device,AudioStreamType streamType)1039 bool AudioAdapterManager::GetStreamMute(std::shared_ptr<AudioDeviceDescriptor> &device, AudioStreamType streamType)
1040 {
1041 return GetStreamMuteInternal(device, streamType);
1042 }
1043
GetAppMute(int32_t appUid)1044 bool AudioAdapterManager::GetAppMute(int32_t appUid)
1045 {
1046 bool isMute = false;
1047 volumeDataMaintainer_.GetAppMute(appUid, isMute);
1048 return isMute;
1049 }
1050
GetStreamVolume(AudioStreamType streamType)1051 int32_t AudioAdapterManager::GetStreamVolume(AudioStreamType streamType)
1052 {
1053 return volumeDataMaintainer_.GetStreamVolume(streamType);
1054 }
1055
GetStreamVolume(std::shared_ptr<AudioDeviceDescriptor> & device,AudioStreamType streamType)1056 int32_t AudioAdapterManager::GetStreamVolume(std::shared_ptr<AudioDeviceDescriptor> &device, AudioStreamType streamType)
1057 {
1058 return volumeDataExtMaintainer_[device->GetKey()]->GetStreamVolume(streamType);
1059 }
1060
GetStreamMuteInternal(AudioStreamType streamType)1061 bool AudioAdapterManager::GetStreamMuteInternal(AudioStreamType streamType)
1062 {
1063 return volumeDataMaintainer_.GetStreamMute(streamType);
1064 }
1065
GetStreamMuteInternal(std::shared_ptr<AudioDeviceDescriptor> & device,AudioStreamType streamType)1066 bool AudioAdapterManager::GetStreamMuteInternal(std::shared_ptr<AudioDeviceDescriptor> &device,
1067 AudioStreamType streamType)
1068 {
1069 return volumeDataExtMaintainer_[device->GetKey()]->GetStreamMute(streamType);
1070 }
1071
1072 // LCOV_EXCL_START
GetAllSinks()1073 vector<SinkInfo> AudioAdapterManager::GetAllSinks()
1074 {
1075 if (!audioServiceAdapter_) {
1076 AUDIO_ERR_LOG("GetAllSinks audio adapter null");
1077 vector<SinkInfo> sinkInputList;
1078 return sinkInputList;
1079 }
1080
1081 return audioServiceAdapter_->GetAllSinks();
1082 }
1083
GetAllSinkInputs(std::vector<SinkInput> & sinkInputs)1084 void AudioAdapterManager::GetAllSinkInputs(std::vector<SinkInput> &sinkInputs)
1085 {
1086 AudioPolicyService::GetAudioPolicyService().GetAllSinkInputs(sinkInputs);
1087 }
1088
GetAllSourceOutputs()1089 vector<SourceOutput> AudioAdapterManager::GetAllSourceOutputs()
1090 {
1091 if (!audioServiceAdapter_) {
1092 AUDIO_ERR_LOG("GetAllSourceOutputs audio adapter null");
1093 vector<SourceOutput> sourceOutputList;
1094 return sourceOutputList;
1095 }
1096
1097 return audioServiceAdapter_->GetAllSourceOutputs();
1098 }
1099
SuspendAudioDevice(std::string & portName,bool isSuspend)1100 int32_t AudioAdapterManager::SuspendAudioDevice(std::string &portName, bool isSuspend)
1101 {
1102 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
1103 "SuspendAudioDevice audio adapter null");
1104
1105 return audioServiceAdapter_->SuspendAudioDevice(portName, isSuspend);
1106 }
1107
SetSinkMute(const std::string & sinkName,bool isMute,bool isSync)1108 bool AudioAdapterManager::SetSinkMute(const std::string &sinkName, bool isMute, bool isSync)
1109 {
1110 static std::unordered_map<std::string, std::string> sinkNameMap = {
1111 {PRIMARY_SPEAKER, PRIMARY_CLASS},
1112 {OFFLOAD_PRIMARY_SPEAKER, OFFLOAD_CLASS},
1113 {BLUETOOTH_SPEAKER, A2DP_CLASS},
1114 {MCH_PRIMARY_SPEAKER, MCH_CLASS},
1115 {USB_SPEAKER, USB_CLASS},
1116 {DP_SINK, DP_CLASS},
1117 {FILE_SINK, FILE_CLASS},
1118 {REMOTE_CAST_INNER_CAPTURER_SINK_NAME, REMOTE_CAST_INNER_CAPTURER_SINK_NAME},
1119 };
1120 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, false, "SetSinkMute audio adapter null");
1121 auto audioVolume = AudioVolume::GetInstance();
1122 CHECK_AND_RETURN_RET_LOG(audioVolume, false, "SetSinkMute audioVolume handle null");
1123 auto it = sinkNameMap.find(sinkName);
1124 for (auto &volumeType : defaultVolumeTypeList_) {
1125 if (it != sinkNameMap.end()) {
1126 if ((it->second == OFFLOAD_CLASS && volumeType == STREAM_MUSIC) ||
1127 it->second != OFFLOAD_CLASS) {
1128 audioVolume->SetSystemVolumeMute(volumeType, it->second, isMute);
1129 }
1130 } else if (sinkName.find("_out") != std::string::npos &&
1131 sinkName.find(LOCAL_NETWORK_ID) == std::string::npos) {
1132 audioVolume->SetSystemVolumeMute(volumeType, REMOTE_CLASS, isMute);
1133 } else {
1134 AUDIO_ERR_LOG("unkown sink name %{public}s", sinkName.c_str());
1135 }
1136 }
1137
1138 return audioServiceAdapter_->SetSinkMute(sinkName, isMute, isSync);
1139 }
1140
SelectDevice(DeviceRole deviceRole,InternalDeviceType deviceType,std::string name)1141 int32_t AudioAdapterManager::SelectDevice(DeviceRole deviceRole, InternalDeviceType deviceType, std::string name)
1142 {
1143 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
1144 "SelectDevice audio adapter null");
1145 switch (deviceRole) {
1146 case DeviceRole::INPUT_DEVICE:
1147 return audioServiceAdapter_->SetDefaultSource(name);
1148 case DeviceRole::OUTPUT_DEVICE: {
1149 AUDIO_INFO_LOG("SetDefaultSink %{public}d", deviceType);
1150 return audioServiceAdapter_->SetDefaultSink(name);
1151 }
1152 default:
1153 AUDIO_ERR_LOG("SelectDevice error deviceRole %{public}d", deviceRole);
1154 return ERR_OPERATION_FAILED;
1155 }
1156 return SUCCESS;
1157 }
1158
SetDeviceActive(InternalDeviceType deviceType,std::string name,bool active,DeviceFlag flag)1159 int32_t AudioAdapterManager::SetDeviceActive(InternalDeviceType deviceType,
1160 std::string name, bool active, DeviceFlag flag)
1161 {
1162 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_, ERR_OPERATION_FAILED,
1163 "SetDeviceActive audio adapter null");
1164
1165 switch (deviceType) {
1166 case InternalDeviceType::DEVICE_TYPE_USB_ARM_HEADSET: {
1167 if (name == USB_SPEAKER) {
1168 return audioServiceAdapter_->SetDefaultSink(name);
1169 } else {
1170 return audioServiceAdapter_->SetDefaultSource(name);
1171 }
1172 }
1173 default: {
1174 int32_t ret = SUCCESS;
1175 int32_t errs[2]{SUCCESS, SUCCESS};
1176 if (IsInputDevice(deviceType) && (flag & INPUT_DEVICES_FLAG)) {
1177 AUDIO_INFO_LOG("SetDefaultSource %{public}d", deviceType);
1178 errs[0] = audioServiceAdapter_->SetDefaultSource(name);
1179 if (errs[0] != SUCCESS) {
1180 AUDIO_ERR_LOG("SetDefaultSource err: %{public}d", errs[0]);
1181 ret = errs[0];
1182 }
1183 }
1184 if (IsOutputDevice(deviceType) && (flag & OUTPUT_DEVICES_FLAG)) {
1185 AUDIO_INFO_LOG("SetDefaultSink %{public}d", deviceType);
1186 errs[1] = audioServiceAdapter_->SetDefaultSink(name);
1187 if (errs[1] != SUCCESS) {
1188 AUDIO_ERR_LOG("SetDefaultSink err: %{public}d", errs[1]);
1189 ret = errs[1];
1190 }
1191 }
1192 // Ensure compatibility across different platforms and versions
1193 if (errs[0] == SUCCESS || errs[1] == SUCCESS) {
1194 return SUCCESS;
1195 }
1196 return ret;
1197 }
1198 }
1199 return SUCCESS;
1200 }
1201
AdjustBluetoothVoiceAssistantVolume(InternalDeviceType deviceType,bool isA2dpSwitchToSco)1202 void AudioAdapterManager::AdjustBluetoothVoiceAssistantVolume(InternalDeviceType deviceType, bool isA2dpSwitchToSco)
1203 {
1204 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP && IsAbsVolumeScene() && !VolumeUtils::IsPCVolumeEnable()) {
1205 volumeDataMaintainer_.SetStreamVolume(STREAM_VOICE_ASSISTANT, MAX_VOLUME_LEVEL);
1206 AUDIO_INFO_LOG("a2dp ok");
1207 }
1208
1209 if (deviceType == DEVICE_TYPE_BLUETOOTH_SCO && isA2dpSwitchToSco) {
1210 if (!volumeDataMaintainer_.GetVolume(deviceType, STREAM_VOICE_ASSISTANT)) {
1211 AUDIO_ERR_LOG("sco voice assistant volume does not exist, use default.");
1212 volumeDataMaintainer_.SetStreamVolume(STREAM_VOICE_ASSISTANT, DEFAULT_VOLUME_LEVEL);
1213 } else {
1214 AUDIO_INFO_LOG("sco ok");
1215 }
1216 }
1217 }
1218
SetQueryDeviceVolumeBehaviorCallback(const sptr<IRemoteObject> & object)1219 int32_t AudioAdapterManager::SetQueryDeviceVolumeBehaviorCallback(const sptr<IRemoteObject> &object)
1220 {
1221 std::lock_guard<std::mutex> lock(g_deviceVolumeBehaviorListenerMutex);
1222 deviceVolumeBehaviorListener_ = iface_cast<IStandardAudioPolicyManagerListener>(object);
1223 return SUCCESS;
1224 }
1225
HandleDistributedDeviceVolume()1226 void AudioAdapterManager::HandleDistributedDeviceVolume()
1227 {
1228 if (!currentActiveDevice_.volumeBehavior_.isReady) {
1229 VolumeBehavior volumeBehavior = AudioDeviceManager::GetAudioDeviceManager().GetDeviceVolumeBehavior(
1230 currentActiveDevice_.networkId_, currentActiveDevice_.deviceType_);
1231 currentActiveDevice_.volumeBehavior_ = volumeBehavior;
1232 if (!currentActiveDevice_.volumeBehavior_.isReady) {
1233 std::lock_guard<std::mutex> lock(g_deviceVolumeBehaviorListenerMutex);
1234 CHECK_AND_RETURN_LOG(deviceVolumeBehaviorListener_ != nullptr, "deviceVolumeBehaviorListener_ is nullptr!");
1235 (void)deviceVolumeBehaviorListener_->OnQueryDeviceVolumeBehavior(volumeBehavior);
1236 currentActiveDevice_.volumeBehavior_.isVolumeControlDisabled = volumeBehavior.isVolumeControlDisabled;
1237 currentActiveDevice_.volumeBehavior_.databaseVolumeName = volumeBehavior.databaseVolumeName;
1238 currentActiveDevice_.volumeBehavior_.isReady = true;
1239 }
1240 }
1241
1242 for (auto streamType : DISTRIBUTED_VOLUME_TYPE_LIST) {
1243 int32_t maxVolumeLevel = GetMaxVolumeLevel(streamType);
1244 volumeDataMaintainer_.SetStreamVolume(streamType, maxVolumeLevel);
1245 volumeDataMaintainer_.SetStreamMuteStatus(streamType, false);
1246 }
1247
1248 if (currentActiveDevice_.volumeBehavior_.databaseVolumeName != "") {
1249 for (auto streamType : DISTRIBUTED_VOLUME_TYPE_LIST) {
1250 // if GetVolume failed, write the max volume as default value.
1251 if (!volumeDataMaintainer_.GetVolumeWithDatabaseVolumeName(
1252 currentActiveDevice_.volumeBehavior_.databaseVolumeName, streamType)) {
1253 int32_t maxVolumeLevel = GetMaxVolumeLevel(streamType);
1254 volumeDataMaintainer_.SaveVolumeWithDatabaseVolumeName(
1255 currentActiveDevice_.volumeBehavior_.databaseVolumeName, streamType, maxVolumeLevel);
1256 }
1257 if (!volumeDataMaintainer_.GetMuteStatusWithDatabaseVolumeName(
1258 currentActiveDevice_.volumeBehavior_.databaseVolumeName, streamType)) {
1259 volumeDataMaintainer_.SaveMuteStatusWithDatabaseVolumeName(
1260 currentActiveDevice_.volumeBehavior_.databaseVolumeName, streamType, false);
1261 }
1262 }
1263 }
1264
1265 for (auto streamType : DISTRIBUTED_VOLUME_TYPE_LIST) {
1266 SetVolumeDb(streamType);
1267 }
1268 }
1269
IsDistributedVolumeType(AudioStreamType streamType)1270 bool AudioAdapterManager::IsDistributedVolumeType(AudioStreamType streamType)
1271 {
1272 AudioVolumeType volumeType = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
1273 bool ret = std::count(DISTRIBUTED_VOLUME_TYPE_LIST.begin(), DISTRIBUTED_VOLUME_TYPE_LIST.end(), volumeType) != 0;
1274 return ret;
1275 }
1276
SetSleVoiceStatusFlag(bool isSleVoiceStatus)1277 void AudioAdapterManager::SetSleVoiceStatusFlag(bool isSleVoiceStatus)
1278 {
1279 isSleVoiceStatus_ = isSleVoiceStatus;
1280 AUDIO_INFO_LOG("SetSleVoiceStatusFlag: %{public}d", isSleVoiceStatus);
1281 }
1282
SetVolumeForSwitchDevice(AudioDeviceDescriptor deviceDescriptor)1283 void AudioAdapterManager::SetVolumeForSwitchDevice(AudioDeviceDescriptor deviceDescriptor)
1284 {
1285 std::lock_guard<std::mutex> lock(activeDeviceMutex_);
1286 if (!AudioZoneService::GetInstance().IsZoneDeviceVisible()) {
1287 std::shared_ptr<AudioDeviceDescriptor> desc = std::make_shared<AudioDeviceDescriptor>(deviceDescriptor);
1288 if (!audioDeviceManager_.IsDeviceConnected(desc)) {
1289 return;
1290 }
1291 }
1292 // The same device does not set the volume
1293 bool isSameVolumeGroup = ((GetVolumeGroupForDevice(currentActiveDevice_.deviceType_) ==
1294 GetVolumeGroupForDevice(deviceDescriptor.deviceType_)) &&
1295 (currentActiveDevice_.networkId_ == deviceDescriptor.networkId_));
1296 if ((currentActiveDevice_.deviceType_ == deviceDescriptor.deviceType_) &&
1297 (currentActiveDevice_.networkId_ == deviceDescriptor.networkId_)) {
1298 AUDIO_INFO_LOG("Old device: %{public}d. New device: %{public}d. No need to update volume",
1299 currentActiveDevice_.deviceType_, deviceDescriptor.deviceType_);
1300 return;
1301 }
1302
1303 AUDIO_INFO_LOG("Load volume and mute status for new device %{public}d,"
1304 "same volume group %{public}d", deviceDescriptor.deviceType_, isSameVolumeGroup);
1305 // Current device must be updated even if kvStore is nullptr.
1306 currentActiveDevice_ = deviceDescriptor;
1307 AudioVolume::GetInstance()->SetCurrentActiveDevice(currentActiveDevice_.deviceType_);
1308
1309 if (deviceDescriptor.deviceType_ == DEVICE_TYPE_SPEAKER && deviceDescriptor.networkId_ != LOCAL_NETWORK_ID) {
1310 HandleDistributedDeviceVolume();
1311 UpdateVolumeForLowLatency();
1312 return;
1313 }
1314
1315 if (!isSameVolumeGroup) {
1316 // If there's no os account available when trying to get one, audio_server would sleep for 1 sec
1317 // and retry for 5 times, which could cause a sysfreeze. Check if any os account is ready. If not,
1318 // skip interacting with datashare.
1319 bool osAccountReady = volumeDataMaintainer_.CheckOsAccountReady();
1320 if (osAccountReady) {
1321 LoadVolumeMap();
1322 LoadMuteStatusMap();
1323 UpdateSafeVolume();
1324 } else {
1325 AUDIO_WARNING_LOG("Os account is not ready, skip visiting datashare.");
1326 }
1327 }
1328
1329 AdjustBluetoothVoiceAssistantVolume(deviceDescriptor.deviceType_, isSameVolumeGroup);
1330
1331 auto iter = defaultVolumeTypeList_.begin();
1332 while (iter != defaultVolumeTypeList_.end()) {
1333 // update volume level and mute status for each stream type
1334 SetVolumeDb(*iter);
1335 AUDIO_INFO_LOG("volume: %{public}d, mute: %{public}d for stream type %{public}d",
1336 volumeDataMaintainer_.GetStreamVolume(*iter), volumeDataMaintainer_.GetStreamMute(*iter), *iter);
1337 iter++;
1338 }
1339
1340 UpdateVolumeForLowLatency();
1341 }
1342
MoveSinkInputByIndexOrName(uint32_t sinkInputId,uint32_t sinkIndex,std::string sinkName)1343 int32_t AudioAdapterManager::MoveSinkInputByIndexOrName(uint32_t sinkInputId, uint32_t sinkIndex, std::string sinkName)
1344 {
1345 return audioServiceAdapter_->MoveSinkInputByIndexOrName(sinkInputId, sinkIndex, sinkName);
1346 }
1347
MoveSourceOutputByIndexOrName(uint32_t sourceOutputId,uint32_t sourceIndex,std::string sourceName)1348 int32_t AudioAdapterManager::MoveSourceOutputByIndexOrName(uint32_t sourceOutputId, uint32_t sourceIndex,
1349 std::string sourceName)
1350 {
1351 return audioServiceAdapter_->MoveSourceOutputByIndexOrName(sourceOutputId, sourceIndex, sourceName);
1352 }
1353
1354 // LCOV_EXCL_STOP
SetRingerMode(AudioRingerMode ringerMode)1355 int32_t AudioAdapterManager::SetRingerMode(AudioRingerMode ringerMode)
1356 {
1357 return SetRingerModeInternal(ringerMode);
1358 }
1359
SetRingerModeInternal(AudioRingerMode ringerMode)1360 int32_t AudioAdapterManager::SetRingerModeInternal(AudioRingerMode ringerMode)
1361 {
1362 AUDIO_INFO_LOG("SetRingerMode: %{public}d", ringerMode);
1363 ringerMode_ = ringerMode;
1364
1365 if (handler_ != nullptr) {
1366 handler_->SendRingerModeUpdate(ringerMode);
1367 }
1368 return SUCCESS;
1369 }
1370
GetRingerMode() const1371 AudioRingerMode AudioAdapterManager::GetRingerMode() const
1372 {
1373 return ringerMode_;
1374 }
1375
IsPaRoute(uint32_t routeFlag)1376 bool AudioAdapterManager::IsPaRoute(uint32_t routeFlag)
1377 {
1378 if ((routeFlag & AUDIO_OUTPUT_FLAG_DIRECT) ||
1379 (routeFlag & AUDIO_OUTPUT_FLAG_FAST) ||
1380 (routeFlag & AUDIO_INPUT_FLAG_FAST)) {
1381 return false;
1382 }
1383 return true;
1384 }
1385
SaveRingerModeInfo(AudioRingerMode ringMode,std::string callerName,std::string invocationTime)1386 void AudioAdapterManager::SaveRingerModeInfo(AudioRingerMode ringMode, std::string callerName,
1387 std::string invocationTime)
1388 {
1389 RingerModeAdjustInfo ringerModeAdjustInfo;
1390 ringerModeAdjustInfo.ringMode = ringMode;
1391 ringerModeAdjustInfo.callerName = callerName;
1392 ringerModeAdjustInfo.invocationTime = invocationTime;
1393 saveRingerModeInfo_->Add(ringerModeAdjustInfo);
1394 }
1395
GetRingerModeInfo(std::vector<RingerModeAdjustInfo> & ringerModeInfo)1396 void AudioAdapterManager::GetRingerModeInfo(std::vector<RingerModeAdjustInfo> &ringerModeInfo)
1397 {
1398 ringerModeInfo = saveRingerModeInfo_->GetData();
1399 }
1400
GetAllDeviceVolumeInfo(DeviceType deviceType,AudioStreamType streamType)1401 std::shared_ptr<AllDeviceVolumeInfo> AudioAdapterManager::GetAllDeviceVolumeInfo(DeviceType deviceType,
1402 AudioStreamType streamType)
1403 {
1404 std::shared_ptr<AllDeviceVolumeInfo> deviceVolumeInfo = nullptr;
1405 if (volumeDataMaintainer_.GetVolume(deviceType, streamType)) {
1406 deviceVolumeInfo = std::make_shared<AllDeviceVolumeInfo>();
1407 deviceVolumeInfo->deviceType = deviceType;
1408 deviceVolumeInfo->streamType = streamType;
1409 deviceVolumeInfo->volumeValue = volumeDataMaintainer_.GetStreamVolume(streamType);
1410 }
1411 return deviceVolumeInfo;
1412 }
1413
1414 // LCOV_EXCL_START
OpenAudioPort(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & paIndex)1415 AudioIOHandle AudioAdapterManager::OpenAudioPort(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &paIndex)
1416 {
1417 std::string moduleArgs = GetModuleArgs(pipeInfo->moduleInfo_);
1418 AUDIO_INFO_LOG("[PipeExecInfo] pipe name %{public}s, moduleArgs %{public}s",
1419 pipeInfo->name_.c_str(), moduleArgs.c_str());
1420 curActiveCount_++;
1421 AudioIOHandle ioHandle = HDI_INVALID_ID;
1422 if (IsPaRoute(pipeInfo->routeFlag_)) {
1423 return OpenPaAudioPort(pipeInfo, paIndex, moduleArgs);
1424 }
1425 return OpenNotPaAudioPort(pipeInfo, paIndex);
1426 }
1427
OpenPaAudioPort(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & paIndex,std::string moduleArgs)1428 AudioIOHandle AudioAdapterManager::OpenPaAudioPort(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &paIndex,
1429 std::string moduleArgs)
1430 {
1431 AudioIOHandle ioHandle = HDI_INVALID_ID;
1432 CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ioHandle, "audioServerProxy_ null");
1433 std::string identity = IPCSkeleton::ResetCallingIdentity();
1434 if (pipeInfo->pipeRole_ == PIPE_ROLE_OUTPUT) {
1435 std::string idInfo = GetHdiSinkIdInfo(pipeInfo->moduleInfo_);
1436 IAudioSinkAttr attr = GetAudioSinkAttr(pipeInfo->moduleInfo_);
1437 audioServerProxy_->CreateHdiSinkPort(pipeInfo->moduleInfo_.className, idInfo, attr, ioHandle);
1438 } else if (pipeInfo->pipeRole_ == PIPE_ROLE_INPUT) {
1439 std::string idInfo = GetHdiSourceIdInfo(pipeInfo->moduleInfo_);
1440 IAudioSourceAttr attr = GetAudioSourceAttr(pipeInfo->moduleInfo_);
1441 audioServerProxy_->CreateHdiSourcePort(pipeInfo->moduleInfo_.className, idInfo, attr, ioHandle);
1442 } else {
1443 AUDIO_ERR_LOG("Invalid pipe role: %{public}u", pipeInfo->pipeRole_);
1444 }
1445 IPCSkeleton::SetCallingIdentity(identity);
1446 int32_t engineFlag = GetEngineFlag();
1447 if (engineFlag == 1) {
1448 int32_t ret = audioServiceAdapter_->OpenAudioPort(pipeInfo->moduleInfo_.lib, pipeInfo->moduleInfo_);
1449 paIndex = ret < 0 ? HDI_INVALID_ID : static_cast<uint32_t>(ret);
1450 } else {
1451 paIndex = audioServiceAdapter_->OpenAudioPort(pipeInfo->moduleInfo_.lib, moduleArgs.c_str());
1452 }
1453 AUDIO_INFO_LOG("[PipeExecInfo] Open %{public}u port, paIndex: %{public}u end.", ioHandle, paIndex);
1454 return ioHandle;
1455 }
1456
OpenNotPaAudioPort(std::shared_ptr<AudioPipeInfo> pipeInfo,uint32_t & paIndex)1457 AudioIOHandle AudioAdapterManager::OpenNotPaAudioPort(std::shared_ptr<AudioPipeInfo> pipeInfo, uint32_t &paIndex)
1458 {
1459 AudioIOHandle ioHandle = HDI_INVALID_ID;
1460 CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ioHandle, "audioServerProxy_ null");
1461 if (pipeInfo->pipeRole_ == PIPE_ROLE_OUTPUT) {
1462 std::string idInfo = HDI_ID_INFO_DEFAULT;
1463 HdiIdType idType = HDI_ID_TYPE_PRIMARY;
1464 GetSinkIdInfoAndIdType(pipeInfo, idInfo, idType);
1465 IAudioSinkAttr attr = GetAudioSinkAttr(pipeInfo->moduleInfo_);
1466 if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_FAST) {
1467 if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) {
1468 AUDIO_INFO_LOG("Use voip mmap");
1469 attr.audioStreamFlag = AUDIO_FLAG_VOIP_FAST;
1470 } else {
1471 attr.audioStreamFlag = AUDIO_FLAG_MMAP;
1472 }
1473 } else if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_DIRECT) {
1474 if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) {
1475 AUDIO_INFO_LOG("Use voip direct");
1476 attr.audioStreamFlag = AUDIO_FLAG_VOIP_DIRECT;
1477 } else {
1478 AUDIO_INFO_LOG("Use direct");
1479 attr.audioStreamFlag = AUDIO_FLAG_DIRECT;
1480 }
1481 }
1482 std::string identity = IPCSkeleton::ResetCallingIdentity();
1483 audioServerProxy_->CreateSinkPort(HDI_ID_BASE_RENDER, idType, idInfo, attr, ioHandle);
1484 IPCSkeleton::SetCallingIdentity(identity);
1485 } else if (pipeInfo->pipeRole_ == PIPE_ROLE_INPUT) {
1486 std::string idInfo = HDI_ID_INFO_DEFAULT;
1487 HdiIdType idType = HDI_ID_TYPE_PRIMARY;
1488 GetSourceIdInfoAndIdType(pipeInfo, idInfo, idType);
1489 IAudioSourceAttr attr = GetAudioSourceAttr(pipeInfo->moduleInfo_);
1490 if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_FAST) {
1491 if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_VOIP) {
1492 AUDIO_INFO_LOG("Use voip mmap");
1493 attr.audioStreamFlag = AUDIO_FLAG_VOIP_FAST;
1494 } else {
1495 attr.audioStreamFlag = AUDIO_FLAG_MMAP;
1496 }
1497 }
1498 std::string identity = IPCSkeleton::ResetCallingIdentity();
1499 audioServerProxy_->CreateSourcePort(HDI_ID_BASE_CAPTURE, idType, idInfo, attr, ioHandle);
1500 IPCSkeleton::SetCallingIdentity(identity);
1501 } else {
1502 AUDIO_ERR_LOG("Invalid pipe role: %{public}u", pipeInfo->pipeRole_);
1503 }
1504 AUDIO_INFO_LOG("[PipeExecInfo] Open %{public}u port, paIndex: %{public}u end.", ioHandle, paIndex);
1505 return ioHandle;
1506 }
1507
GetSinkIdInfoAndIdType(std::shared_ptr<AudioPipeInfo> pipeInfo,std::string & idInfo,HdiIdType & idType)1508 void AudioAdapterManager::GetSinkIdInfoAndIdType(
1509 std::shared_ptr<AudioPipeInfo> pipeInfo, std::string &idInfo, HdiIdType &idType)
1510 {
1511 if (pipeInfo->adapterName_ == "primary") {
1512 if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_FAST) {
1513 idType = HDI_ID_TYPE_FAST;
1514 if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) {
1515 idInfo = HDI_ID_INFO_VOIP;
1516 }
1517 } else if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_DIRECT) {
1518 idType = HDI_ID_TYPE_PRIMARY;
1519 if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_VOIP) {
1520 idInfo = HDI_ID_INFO_VOIP;
1521 }
1522 }
1523 } else if (pipeInfo->adapterName_ == "a2dp") {
1524 if (pipeInfo->routeFlag_ & AUDIO_OUTPUT_FLAG_FAST) {
1525 idType = HDI_ID_TYPE_BLUETOOTH;
1526 idInfo = HDI_ID_INFO_MMAP;
1527 }
1528 }
1529 }
1530
GetSourceIdInfoAndIdType(std::shared_ptr<AudioPipeInfo> pipeInfo,std::string & idInfo,HdiIdType & idType)1531 void AudioAdapterManager::GetSourceIdInfoAndIdType(
1532 std::shared_ptr<AudioPipeInfo> pipeInfo, std::string &idInfo, HdiIdType &idType)
1533 {
1534 if (pipeInfo->adapterName_ == "primary") {
1535 if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_FAST) {
1536 idType = HDI_ID_TYPE_FAST;
1537 if (pipeInfo->routeFlag_ & AUDIO_INPUT_FLAG_VOIP) {
1538 idInfo = HDI_ID_INFO_VOIP;
1539 }
1540 }
1541 }
1542 }
1543
ReloadAudioPort(const AudioModuleInfo & audioModuleInfo,uint32_t & paIndex)1544 AudioIOHandle AudioAdapterManager::ReloadAudioPort(const AudioModuleInfo &audioModuleInfo, uint32_t &paIndex)
1545 {
1546 std::string moduleArgs = GetModuleArgs(audioModuleInfo);
1547 AUDIO_INFO_LOG("[PipeExecInfo] PA moduleArgs %{public}s", moduleArgs.c_str());
1548
1549 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
1550 AudioIOHandle ioHandle = HDI_INVALID_ID;
1551 CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ioHandle, "audioServerProxy_ null");
1552 curActiveCount_++;
1553
1554 std::string identity = IPCSkeleton::ResetCallingIdentity();
1555 if (audioModuleInfo.lib == "libmodule-inner-capturer-sink.z.so") {
1556 std::string idInfo = audioModuleInfo.name;
1557 IAudioSinkAttr attr = GetAudioSinkAttr(audioModuleInfo);
1558 audioServerProxy_->CreateSinkPort(HDI_ID_BASE_RENDER, HDI_ID_TYPE_PRIMARY, idInfo, attr, ioHandle);
1559 } else {
1560 if (audioModuleInfo.role == HDI_AUDIO_PORT_SINK_ROLE) {
1561 std::string idInfo = GetHdiSinkIdInfo(audioModuleInfo);
1562 IAudioSinkAttr attr = GetAudioSinkAttr(audioModuleInfo);
1563 audioServerProxy_->CreateHdiSinkPort(audioModuleInfo.className, idInfo, attr, ioHandle);
1564 } else if (audioModuleInfo.role == HDI_AUDIO_PORT_SOURCE_ROLE) {
1565 std::string idInfo = GetHdiSourceIdInfo(audioModuleInfo);
1566 IAudioSourceAttr attr = GetAudioSourceAttr(audioModuleInfo);
1567 audioServerProxy_->CreateHdiSourcePort(audioModuleInfo.className, idInfo, attr, ioHandle);
1568 }
1569 }
1570 IPCSkeleton::SetCallingIdentity(identity);
1571
1572 int32_t ret = audioServiceAdapter_->ReloadAudioPort(audioModuleInfo.lib, audioModuleInfo);
1573 paIndex = ret < 0 ? HDI_INVALID_ID : static_cast<uint32_t>(ret);
1574
1575 AUDIO_INFO_LOG("[PipeExecInfo] Open %{public}u port, paIndex: %{public}u end", ioHandle, paIndex);
1576 return ioHandle;
1577 }
1578
OpenAudioPort(const AudioModuleInfo & audioModuleInfo,uint32_t & paIndex)1579 AudioIOHandle AudioAdapterManager::OpenAudioPort(const AudioModuleInfo &audioModuleInfo, uint32_t &paIndex)
1580 {
1581 std::string moduleArgs = GetModuleArgs(audioModuleInfo);
1582 AUDIO_INFO_LOG("[PipeExecInfo] PA moduleArgs %{public}s", moduleArgs.c_str());
1583
1584 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
1585 curActiveCount_++;
1586 AudioIOHandle ioHandle = HDI_INVALID_ID;
1587 CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ioHandle, "audioServerProxy_ null");
1588
1589 std::string identity = IPCSkeleton::ResetCallingIdentity();
1590 if (audioModuleInfo.lib == "libmodule-inner-capturer-sink.z.so") {
1591 std::string idInfo = audioModuleInfo.name;
1592 IAudioSinkAttr attr = GetAudioSinkAttr(audioModuleInfo);
1593 audioServerProxy_->CreateSinkPort(HDI_ID_BASE_RENDER, HDI_ID_TYPE_PRIMARY, idInfo, attr, ioHandle);
1594 } else {
1595 if (audioModuleInfo.role == HDI_AUDIO_PORT_SINK_ROLE) {
1596 std::string idInfo = GetHdiSinkIdInfo(audioModuleInfo);
1597 IAudioSinkAttr attr = GetAudioSinkAttr(audioModuleInfo);
1598 audioServerProxy_->CreateHdiSinkPort(audioModuleInfo.className, idInfo, attr, ioHandle);
1599 } else if (audioModuleInfo.role == HDI_AUDIO_PORT_SOURCE_ROLE) {
1600 std::string idInfo = GetHdiSourceIdInfo(audioModuleInfo);
1601 IAudioSourceAttr attr = GetAudioSourceAttr(audioModuleInfo);
1602 audioServerProxy_->CreateHdiSourcePort(audioModuleInfo.className, idInfo, attr, ioHandle);
1603 }
1604 }
1605 IPCSkeleton::SetCallingIdentity(identity);
1606
1607 int32_t engineFlag = GetEngineFlag();
1608 if (engineFlag == 1) {
1609 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ioHandle, "audioServiceAdapter_ null");
1610 int32_t ret = audioServiceAdapter_->OpenAudioPort(audioModuleInfo.lib, audioModuleInfo);
1611 paIndex = ret < 0 ? HDI_INVALID_ID : static_cast<uint32_t>(ret);
1612 } else {
1613 paIndex = audioServiceAdapter_->OpenAudioPort(audioModuleInfo.lib, moduleArgs.c_str());
1614 }
1615
1616 AUDIO_INFO_LOG("[PipeExecInfo] Open %{public}u port, paIndex: %{public}u end", ioHandle, paIndex);
1617 return ioHandle;
1618 }
1619
CloseAudioPort(AudioIOHandle ioHandle,uint32_t paIndex)1620 int32_t AudioAdapterManager::CloseAudioPort(AudioIOHandle ioHandle, uint32_t paIndex)
1621 {
1622 AUDIO_INFO_LOG("[PipeExecInfo] ioHandle: %{public}u, paIndex: %{public}u, curCount: %{public}d",
1623 ioHandle, paIndex, curActiveCount_);
1624 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
1625 CHECK_AND_RETURN_RET_LOG(audioServerProxy_ != nullptr, ERROR, "audioServerProxy_ null");
1626 curActiveCount_--;
1627 int32_t ret = audioServiceAdapter_->CloseAudioPort(paIndex);
1628 AudioIOHandle handleToClose = ioHandle;
1629 std::string identity = IPCSkeleton::ResetCallingIdentity();
1630 audioServerProxy_->DestroyHdiPort(ioHandle);
1631 IPCSkeleton::SetCallingIdentity(identity);
1632 AUDIO_INFO_LOG("[PipeExecInfo] Close %{public}u port, paIndex: %{public}u end", handleToClose, paIndex);
1633 return ret;
1634 }
1635
GetCurActivateCount() const1636 int32_t AudioAdapterManager::GetCurActivateCount() const
1637 {
1638 return curActiveCount_ > 0 ? curActiveCount_ : 0;
1639 }
1640
GetAudioEffectProperty(AudioEffectPropertyArrayV3 & propertyArray) const1641 int32_t AudioAdapterManager::GetAudioEffectProperty(AudioEffectPropertyArrayV3 &propertyArray) const
1642 {
1643 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
1644 int32_t ret = 0;
1645 AudioEffectPropertyArrayV3 effectPropertyArray = {};
1646 ret = audioServiceAdapter_->GetAudioEffectProperty(effectPropertyArray);
1647 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "GetAudioEffectProperty failed");
1648 propertyArray.property.insert(propertyArray.property.end(),
1649 effectPropertyArray.property.begin(), effectPropertyArray.property.end());
1650 AudioEffectPropertyArrayV3 enhancePropertyArray = {};
1651 ret = audioServiceAdapter_->GetAudioEnhanceProperty(enhancePropertyArray);
1652 CHECK_AND_RETURN_RET_LOG(ret == SUCCESS, ERR_OPERATION_FAILED, "GetAudioEnhanceProperty failed");
1653 propertyArray.property.insert(propertyArray.property.end(),
1654 enhancePropertyArray.property.begin(), enhancePropertyArray.property.end());
1655 return ret;
1656 }
1657
GetAudioEffectProperty(AudioEffectPropertyArray & propertyArray) const1658 int32_t AudioAdapterManager::GetAudioEffectProperty(AudioEffectPropertyArray &propertyArray) const
1659 {
1660 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
1661 return audioServiceAdapter_->GetAudioEffectProperty(propertyArray);
1662 }
1663
GetAudioEnhanceProperty(AudioEnhancePropertyArray & propertyArray,DeviceType deviceType) const1664 int32_t AudioAdapterManager::GetAudioEnhanceProperty(AudioEnhancePropertyArray &propertyArray,
1665 DeviceType deviceType) const
1666 {
1667 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
1668 return audioServiceAdapter_->GetAudioEnhanceProperty(propertyArray, deviceType);
1669 }
1670
UpdateCollaborativeState(bool isCollaborationEnabled)1671 int32_t AudioAdapterManager::UpdateCollaborativeState(bool isCollaborationEnabled)
1672 {
1673 CHECK_AND_RETURN_RET_LOG(audioServiceAdapter_ != nullptr, ERR_OPERATION_FAILED, "ServiceAdapter is null");
1674 AUDIO_INFO_LOG("AudioCollaborativeService UpdateCollaborativeState entered!");
1675 return audioServiceAdapter_->UpdateCollaborativeState(isCollaborationEnabled);
1676 }
1677
UpdateSinkArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1678 void AudioAdapterManager::UpdateSinkArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1679 {
1680 if (!audioModuleInfo.name.empty()) {
1681 args.append(" sink_name=");
1682 args.append(audioModuleInfo.name);
1683 }
1684
1685 if (!audioModuleInfo.adapterName.empty()) {
1686 args.append(" adapter_name=");
1687 args.append(audioModuleInfo.adapterName);
1688 }
1689
1690 if (!audioModuleInfo.className.empty()) {
1691 args.append(" device_class=");
1692 args.append(audioModuleInfo.className);
1693 }
1694
1695 if (!audioModuleInfo.fileName.empty()) {
1696 args.append(" file_path=");
1697 args.append(audioModuleInfo.fileName);
1698 }
1699 if (!audioModuleInfo.sinkLatency.empty()) {
1700 args.append(" sink_latency=");
1701 args.append(audioModuleInfo.sinkLatency);
1702 }
1703
1704 if (!audioModuleInfo.networkId.empty()) {
1705 args.append(" network_id=");
1706 args.append(audioModuleInfo.networkId);
1707 } else {
1708 args.append(" network_id=LocalDevice");
1709 }
1710
1711 if (!audioModuleInfo.deviceType.empty()) {
1712 args.append(" device_type=");
1713 args.append(audioModuleInfo.deviceType);
1714 }
1715
1716 if (!audioModuleInfo.extra.empty()) {
1717 args.append(" split_mode=");
1718 args.append(audioModuleInfo.extra);
1719 }
1720 if (audioModuleInfo.needEmptyChunk) {
1721 args.append(" need_empty_chunk=");
1722 args.append(std::to_string(*audioModuleInfo.needEmptyChunk));
1723 }
1724 }
1725
UpdateEcAndMicRefArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1726 void UpdateEcAndMicRefArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1727 {
1728 if (!audioModuleInfo.ecType.empty()) {
1729 args.append(" ec_type=");
1730 args.append(audioModuleInfo.ecType);
1731 }
1732
1733 if (!audioModuleInfo.ecAdapter.empty()) {
1734 args.append(" ec_adapter=");
1735 args.append(audioModuleInfo.ecAdapter);
1736 }
1737
1738 if (!audioModuleInfo.ecSamplingRate.empty()) {
1739 args.append(" ec_sampling_rate=");
1740 args.append(audioModuleInfo.ecSamplingRate);
1741 }
1742
1743 if (!audioModuleInfo.ecFormat.empty()) {
1744 args.append(" ec_format=");
1745 args.append(audioModuleInfo.ecFormat);
1746 }
1747
1748 if (!audioModuleInfo.ecChannels.empty()) {
1749 args.append(" ec_channels=");
1750 args.append(audioModuleInfo.ecChannels);
1751 }
1752
1753 if (!audioModuleInfo.openMicRef.empty()) {
1754 args.append(" open_mic_ref=");
1755 args.append(audioModuleInfo.openMicRef);
1756 }
1757
1758 if (!audioModuleInfo.micRefRate.empty()) {
1759 args.append(" mic_ref_rate=");
1760 args.append(audioModuleInfo.micRefRate);
1761 }
1762
1763 if (!audioModuleInfo.micRefFormat.empty()) {
1764 args.append(" mic_ref_format=");
1765 args.append(audioModuleInfo.micRefFormat);
1766 }
1767
1768 if (!audioModuleInfo.micRefChannels.empty()) {
1769 args.append(" mic_ref_channels=");
1770 args.append(audioModuleInfo.micRefChannels);
1771 }
1772 }
1773
UpdateSourceArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1774 void UpdateSourceArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1775 {
1776 if (!audioModuleInfo.name.empty()) {
1777 args.append(" source_name=");
1778 args.append(audioModuleInfo.name);
1779 }
1780
1781 if (!audioModuleInfo.adapterName.empty()) {
1782 args.append(" adapter_name=");
1783 args.append(audioModuleInfo.adapterName);
1784 }
1785
1786 if (!audioModuleInfo.className.empty()) {
1787 args.append(" device_class=");
1788 args.append(audioModuleInfo.className);
1789 }
1790
1791 if (!audioModuleInfo.fileName.empty()) {
1792 args.append(" file_path=");
1793 args.append(audioModuleInfo.fileName);
1794 }
1795
1796 if (!audioModuleInfo.networkId.empty()) {
1797 args.append(" network_id=");
1798 args.append(audioModuleInfo.networkId);
1799 } else {
1800 args.append(" network_id=LocalDevice");
1801 }
1802
1803 if (!audioModuleInfo.deviceType.empty()) {
1804 args.append(" device_type=");
1805 args.append(audioModuleInfo.deviceType);
1806 }
1807
1808 if (!audioModuleInfo.sourceType.empty()) {
1809 args.append(" source_type=");
1810 args.append(audioModuleInfo.sourceType);
1811 }
1812 }
1813
UpdateCommonArgs(const AudioModuleInfo & audioModuleInfo,std::string & args)1814 void UpdateCommonArgs(const AudioModuleInfo &audioModuleInfo, std::string &args)
1815 {
1816 if (!audioModuleInfo.rate.empty()) {
1817 args = "rate=";
1818 args.append(audioModuleInfo.rate);
1819 }
1820
1821 if (!audioModuleInfo.channels.empty()) {
1822 args.append(" channels=");
1823 args.append(audioModuleInfo.channels);
1824 }
1825
1826 if (!audioModuleInfo.bufferSize.empty()) {
1827 args.append(" buffer_size=");
1828 args.append(audioModuleInfo.bufferSize);
1829 }
1830
1831 if (!audioModuleInfo.format.empty()) {
1832 args.append(" format=");
1833 args.append(audioModuleInfo.format);
1834 }
1835
1836 if (!audioModuleInfo.fixedLatency.empty()) {
1837 args.append(" fixed_latency=");
1838 args.append(audioModuleInfo.fixedLatency);
1839 }
1840
1841 if (!audioModuleInfo.renderInIdleState.empty()) {
1842 args.append(" render_in_idle_state=");
1843 args.append(audioModuleInfo.renderInIdleState);
1844 }
1845
1846 if (!audioModuleInfo.OpenMicSpeaker.empty()) {
1847 args.append(" open_mic_speaker=");
1848 args.append(audioModuleInfo.OpenMicSpeaker);
1849 }
1850
1851 if (!audioModuleInfo.offloadEnable.empty()) {
1852 args.append(" offload_enable=");
1853 args.append(audioModuleInfo.offloadEnable);
1854 }
1855
1856 if (!audioModuleInfo.defaultAdapterEnable.empty()) {
1857 args.append(" default_adapter_enable=");
1858 args.append(audioModuleInfo.defaultAdapterEnable);
1859 }
1860 AUDIO_INFO_LOG("[Adapter load-module] [PolicyManager] common args:%{public}s", args.c_str());
1861 }
1862
1863 // Private Members
GetModuleArgs(const AudioModuleInfo & audioModuleInfo) const1864 std::string AudioAdapterManager::GetModuleArgs(const AudioModuleInfo &audioModuleInfo) const
1865 {
1866 std::string args;
1867
1868 if (audioModuleInfo.lib == HDI_SINK) {
1869 UpdateCommonArgs(audioModuleInfo, args);
1870 UpdateSinkArgs(audioModuleInfo, args);
1871 if (testModeOn_) {
1872 args.append(" test_mode_on=");
1873 args.append("1");
1874 }
1875 } else if (audioModuleInfo.lib == SPLIT_STREAM_SINK) {
1876 UpdateCommonArgs(audioModuleInfo, args);
1877 UpdateSinkArgs(audioModuleInfo, args);
1878 } else if (audioModuleInfo.lib == HDI_SOURCE) {
1879 UpdateCommonArgs(audioModuleInfo, args);
1880 UpdateSourceArgs(audioModuleInfo, args);
1881 UpdateEcAndMicRefArgs(audioModuleInfo, args);
1882 } else if (audioModuleInfo.lib == PIPE_SINK) {
1883 if (!audioModuleInfo.fileName.empty()) {
1884 args = "file=";
1885 args.append(audioModuleInfo.fileName);
1886 }
1887 } else if (audioModuleInfo.lib == PIPE_SOURCE) {
1888 if (!audioModuleInfo.fileName.empty()) {
1889 args = "file=";
1890 args.append(audioModuleInfo.fileName);
1891 }
1892 } else if (audioModuleInfo.lib == CLUSTER_SINK) {
1893 UpdateCommonArgs(audioModuleInfo, args);
1894 if (!audioModuleInfo.name.empty()) {
1895 args.append(" sink_name=");
1896 args.append(audioModuleInfo.name);
1897 }
1898 } else if (audioModuleInfo.lib == EFFECT_SINK) {
1899 UpdateCommonArgs(audioModuleInfo, args);
1900 if (!audioModuleInfo.name.empty()) {
1901 args.append(" sink_name=");
1902 args.append(audioModuleInfo.name);
1903 }
1904 if (!audioModuleInfo.sceneName.empty()) {
1905 args.append(" scene_name=");
1906 args.append(audioModuleInfo.sceneName);
1907 }
1908 } else if (audioModuleInfo.lib == INNER_CAPTURER_SINK || audioModuleInfo.lib == RECEIVER_SINK) {
1909 UpdateCommonArgs(audioModuleInfo, args);
1910 if (!audioModuleInfo.name.empty()) {
1911 args.append(" sink_name=");
1912 args.append(audioModuleInfo.name);
1913 }
1914 }
1915 return args;
1916 }
1917
GetHdiSinkIdInfo(const AudioModuleInfo & audioModuleInfo) const1918 std::string AudioAdapterManager::GetHdiSinkIdInfo(const AudioModuleInfo &audioModuleInfo) const
1919 {
1920 if (audioModuleInfo.className == "remote" || audioModuleInfo.className == "remote_offload") {
1921 return audioModuleInfo.networkId;
1922 }
1923 return HDI_ID_INFO_DEFAULT;
1924 }
1925
GetHdiSourceIdInfo(const AudioModuleInfo & audioModuleInfo) const1926 std::string AudioAdapterManager::GetHdiSourceIdInfo(const AudioModuleInfo &audioModuleInfo) const
1927 {
1928 if (audioModuleInfo.className == "primary" && audioModuleInfo.sourceType == "SOURCE_TYPE_WAKEUP") {
1929 return audioModuleInfo.name;
1930 }
1931 if (audioModuleInfo.className == "remote") {
1932 return audioModuleInfo.networkId;
1933 }
1934 return HDI_ID_INFO_DEFAULT;
1935 }
1936
ParseSinkAudioSampleFormat(const std::string & format)1937 static AudioSampleFormat ParseSinkAudioSampleFormat(const std::string &format)
1938 {
1939 if (format == "u8") {
1940 return SAMPLE_U8;
1941 } else if (format == "s16le") {
1942 return SAMPLE_S16LE;
1943 } else if (format == "s24le") {
1944 return SAMPLE_S24LE;
1945 } else if (format == "s32le") {
1946 return SAMPLE_S32LE;
1947 }
1948 return INVALID_WIDTH;
1949 }
1950
ParseSourceAudioSampleFormat(const std::string & format)1951 static AudioSampleFormat ParseSourceAudioSampleFormat(const std::string &format)
1952 {
1953 if (format == "u8") {
1954 return SAMPLE_U8;
1955 } else if (format == "s16le" || format == "s16be") {
1956 return SAMPLE_S16LE;
1957 } else if (format == "s24le" || format == "s24be") {
1958 return SAMPLE_S24LE;
1959 } else if (format == "s32le" || format == "s32be") {
1960 return SAMPLE_S32LE;
1961 }
1962 return SAMPLE_S16LE;
1963 }
1964
IsBigEndian(const std::string & format)1965 static bool IsBigEndian(const std::string &format)
1966 {
1967 if (format == "s16be" || format == "s24be" || format == "s32be" || format == "f32be") {
1968 return true;
1969 }
1970 return false;
1971 }
1972
GetAudioSinkAttr(const AudioModuleInfo & audioModuleInfo) const1973 IAudioSinkAttr AudioAdapterManager::GetAudioSinkAttr(const AudioModuleInfo &audioModuleInfo) const
1974 {
1975 IAudioSinkAttr attr;
1976 attr.adapterName = audioModuleInfo.adapterName.c_str();
1977 if (!audioModuleInfo.OpenMicSpeaker.empty()) {
1978 attr.openMicSpeaker = static_cast<uint32_t>(std::stoul(audioModuleInfo.OpenMicSpeaker));
1979 }
1980 attr.format = ParseSinkAudioSampleFormat(audioModuleInfo.format);
1981 if (!audioModuleInfo.rate.empty()) {
1982 attr.sampleRate = static_cast<uint32_t>(std::stoul(audioModuleInfo.rate));
1983 }
1984 if (!audioModuleInfo.channels.empty()) {
1985 attr.channel = static_cast<uint32_t>(std::stoul(audioModuleInfo.channels));
1986 }
1987 attr.volume = HDI_MAX_SINK_VOLUME_LEVEL;
1988 attr.filePath = audioModuleInfo.fileName.c_str();
1989 attr.deviceNetworkId = audioModuleInfo.networkId.c_str();
1990 attr.aux = audioModuleInfo.extra;
1991 if (!audioModuleInfo.deviceType.empty()) {
1992 attr.deviceType = std::stoi(audioModuleInfo.deviceType);
1993 }
1994 if (audioModuleInfo.className == "multichannel") {
1995 attr.channelLayout = HDI_DEFAULT_MULTICHANNEL_CHANNELLAYOUT;
1996 }
1997 return attr;
1998 }
1999
GetAudioSourceAttr(const AudioModuleInfo & audioModuleInfo) const2000 IAudioSourceAttr AudioAdapterManager::GetAudioSourceAttr(const AudioModuleInfo &audioModuleInfo) const
2001 {
2002 IAudioSourceAttr attr;
2003 attr.adapterName = audioModuleInfo.adapterName.c_str();
2004 if (!audioModuleInfo.OpenMicSpeaker.empty()) {
2005 attr.openMicSpeaker = static_cast<uint32_t>(std::stoul(audioModuleInfo.OpenMicSpeaker));
2006 }
2007 attr.format = ParseSourceAudioSampleFormat(audioModuleInfo.format);
2008 if (!audioModuleInfo.rate.empty()) {
2009 attr.sampleRate = static_cast<uint32_t>(std::stoul(audioModuleInfo.rate));
2010 }
2011 if (!audioModuleInfo.channels.empty()) {
2012 attr.channel = static_cast<uint32_t>(std::stoul(audioModuleInfo.channels));
2013 }
2014 if (!audioModuleInfo.bufferSize.empty()) {
2015 attr.bufferSize = static_cast<uint32_t>(std::stoul(audioModuleInfo.bufferSize));
2016 }
2017 if (!audioModuleInfo.channelLayout.empty()) {
2018 AUDIO_INFO_LOG("use custom channelLayout, %{public}s", audioModuleInfo.channelLayout.c_str());
2019 attr.channelLayout = static_cast<uint64_t>(std::stoul(audioModuleInfo.channelLayout));
2020 }
2021 attr.isBigEndian = IsBigEndian(audioModuleInfo.format);
2022 attr.filePath = audioModuleInfo.fileName.c_str();
2023 attr.deviceNetworkId = audioModuleInfo.networkId.c_str();
2024 if (!audioModuleInfo.deviceType.empty()) {
2025 attr.deviceType = std::stoi(audioModuleInfo.deviceType);
2026 }
2027 if (!audioModuleInfo.sourceType.empty()) {
2028 attr.sourceType = std::stoi(audioModuleInfo.sourceType);
2029 }
2030 if ((!audioModuleInfo.ecType.empty()) && static_cast<uint32_t>(std::stoul(audioModuleInfo.ecType)) ==
2031 HDI_EC_SAME_ADAPTER) {
2032 attr.hasEcConfig = true;
2033 attr.formatEc = ParseSourceAudioSampleFormat(audioModuleInfo.ecFormat);
2034 if (!audioModuleInfo.ecSamplingRate.empty()) {
2035 attr.sampleRateEc = static_cast<uint32_t>(std::stoul(audioModuleInfo.ecSamplingRate));
2036 }
2037 if (!audioModuleInfo.ecChannels.empty()) {
2038 attr.channelEc = static_cast<uint32_t>(std::stoul(audioModuleInfo.ecChannels));
2039 }
2040 }
2041 return attr;
2042 }
2043
GetVolumeKeyForKvStore(DeviceType deviceType,AudioStreamType streamType)2044 std::string AudioAdapterManager::GetVolumeKeyForKvStore(DeviceType deviceType, AudioStreamType streamType)
2045 {
2046 DeviceGroup type = GetVolumeGroupForDevice(deviceType);
2047 std::string typeStr = std::to_string(type);
2048 CHECK_AND_RETURN_RET_LOG(type != DEVICE_GROUP_INVALID, typeStr,
2049 "Device %{public}d is not supported for kvStore", deviceType);
2050
2051 switch (streamType) {
2052 case STREAM_MUSIC:
2053 return typeStr + "_music_volume";
2054 case STREAM_RING:
2055 case STREAM_VOICE_RING:
2056 return typeStr + "_ring_volume";
2057 case STREAM_SYSTEM:
2058 return typeStr + "_system_volume";
2059 case STREAM_NOTIFICATION:
2060 return typeStr + "_notification_volume";
2061 case STREAM_ALARM:
2062 return typeStr + "_alarm_volume";
2063 case STREAM_DTMF:
2064 return typeStr + "_dtmf_volume";
2065 case STREAM_VOICE_CALL:
2066 case STREAM_VOICE_COMMUNICATION:
2067 return typeStr + "_voice_call_volume";
2068 case STREAM_VOICE_ASSISTANT:
2069 return typeStr + "_voice_assistant_volume";
2070 case STREAM_ACCESSIBILITY:
2071 return typeStr + "_accessibility_volume";
2072 case STREAM_ULTRASONIC:
2073 return typeStr + "_ultrasonic_volume";
2074 case STREAM_WAKEUP:
2075 return typeStr + "wakeup";
2076 default:
2077 AUDIO_ERR_LOG("GetVolumeKeyForKvStore: streamType %{public}d is not supported for kvStore", streamType);
2078 return "";
2079 }
2080 }
2081
GetStreamIDByType(std::string streamType)2082 AudioStreamType AudioAdapterManager::GetStreamIDByType(std::string streamType)
2083 {
2084 AudioStreamType stream = STREAM_MUSIC;
2085
2086 if (!streamType.compare(std::string("music")))
2087 stream = STREAM_MUSIC;
2088 else if (!streamType.compare(std::string("ring")))
2089 stream = STREAM_RING;
2090 else if (!streamType.compare(std::string("voice_call")))
2091 stream = STREAM_VOICE_CALL;
2092 else if (!streamType.compare(std::string("system")))
2093 stream = STREAM_SYSTEM;
2094 else if (!streamType.compare(std::string("notification")))
2095 stream = STREAM_NOTIFICATION;
2096 else if (!streamType.compare(std::string("alarm")))
2097 stream = STREAM_ALARM;
2098 else if (!streamType.compare(std::string("voice_assistant")))
2099 stream = STREAM_VOICE_ASSISTANT;
2100 else if (!streamType.compare(std::string("accessibility")))
2101 stream = STREAM_ACCESSIBILITY;
2102 else if (!streamType.compare(std::string("ultrasonic")))
2103 stream = STREAM_ULTRASONIC;
2104 else if (!streamType.compare(std::string("camcorder")))
2105 stream = STREAM_CAMCORDER;
2106 return stream;
2107 }
2108
GetDeviceCategory(DeviceType deviceType)2109 DeviceVolumeType AudioAdapterManager::GetDeviceCategory(DeviceType deviceType)
2110 {
2111 switch (deviceType) {
2112 case DEVICE_TYPE_EARPIECE:
2113 return EARPIECE_VOLUME_TYPE;
2114 case DEVICE_TYPE_SPEAKER:
2115 case DEVICE_TYPE_FILE_SOURCE:
2116 case DEVICE_TYPE_DP:
2117 case DEVICE_TYPE_HDMI:
2118 case DEVICE_TYPE_ACCESSORY:
2119 return SPEAKER_VOLUME_TYPE;
2120 case DEVICE_TYPE_WIRED_HEADSET:
2121 case DEVICE_TYPE_WIRED_HEADPHONES:
2122 case DEVICE_TYPE_BLUETOOTH_SCO:
2123 case DEVICE_TYPE_BLUETOOTH_A2DP:
2124 case DEVICE_TYPE_USB_HEADSET:
2125 case DEVICE_TYPE_USB_ARM_HEADSET:
2126 return HEADSET_VOLUME_TYPE;
2127 default:
2128 return SPEAKER_VOLUME_TYPE;
2129 }
2130 }
2131
InitAudioPolicyKvStore(bool & isFirstBoot)2132 bool AudioAdapterManager::InitAudioPolicyKvStore(bool& isFirstBoot)
2133 {
2134 DistributedKvDataManager manager;
2135 Options options;
2136
2137 AppId appId;
2138 appId.appId = "audio_policy_manager";
2139
2140 options.securityLevel = S1;
2141 options.createIfMissing = false;
2142 options.encrypt = false;
2143 options.autoSync = false;
2144 options.kvStoreType = KvStoreType::SINGLE_VERSION;
2145 options.area = EL1;
2146 options.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
2147
2148 StoreId storeId;
2149 storeId.storeId = "audiopolicy";
2150 Status status = Status::SUCCESS;
2151 std::vector<StoreId> storeIds;
2152 status = manager.GetAllKvStoreId(appId, storeIds);
2153
2154 // open and initialize kvstore instance.
2155 if (audioPolicyKvStore_ == nullptr && storeIds.size() != static_cast<size_t>(0)) {
2156 uint32_t retries = 0;
2157
2158 do {
2159 status = manager.GetSingleKvStore(options, appId, storeId, audioPolicyKvStore_);
2160 AUDIO_ERR_LOG("GetSingleKvStore status: %{public}d", status);
2161 if ((status == Status::SUCCESS) || (status == Status::INVALID_ARGUMENT) ||
2162 (status == Status::DATA_CORRUPTED) || (status == Status::CRYPT_ERROR)) {
2163 break;
2164 } else {
2165 AUDIO_ERR_LOG("InitAudioPolicyKvStore: Kvstore Connect failed! Retrying.");
2166 retries++;
2167 usleep(KVSTORE_CONNECT_RETRY_DELAY_TIME);
2168 }
2169 } while (retries <= KVSTORE_CONNECT_RETRY_COUNT);
2170 }
2171
2172 if (audioPolicyKvStore_ != nullptr) {
2173 isNeedCopyVolumeData_ = true;
2174 isNeedCopyMuteData_ = true;
2175 isNeedCopyRingerModeData_ = true;
2176 isNeedCopySystemUrlData_ = true;
2177 SetFirstBoot(false);
2178 return true;
2179 }
2180 // first boot
2181 char firstboot[3] = {0};
2182 GetParameter("persist.multimedia.audio.firstboot", "0", firstboot, sizeof(firstboot));
2183 if (atoi(firstboot) == 1) {
2184 AUDIO_INFO_LOG("first boot, ready init data to database");
2185 isFirstBoot = true;
2186 SetFirstBoot(false);
2187 }
2188
2189 return true;
2190 }
2191
DeleteAudioPolicyKvStore()2192 void AudioAdapterManager::DeleteAudioPolicyKvStore()
2193 {
2194 DistributedKvDataManager manager;
2195 Options options;
2196
2197 AppId appId;
2198 appId.appId = "audio_policy_manager";
2199
2200 options.securityLevel = S1;
2201 options.createIfMissing = false;
2202 options.encrypt = false;
2203 options.autoSync = false;
2204 options.kvStoreType = KvStoreType::SINGLE_VERSION;
2205 options.area = EL1;
2206 options.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
2207
2208 StoreId storeId;
2209 storeId.storeId = "audiopolicy";
2210 Status status = Status::SUCCESS;
2211
2212 if (audioPolicyKvStore_ != nullptr) {
2213 status = manager.CloseKvStore(appId, storeId);
2214 if (status != Status::SUCCESS) {
2215 AUDIO_ERR_LOG("close KvStore failed");
2216 }
2217 status = manager.DeleteKvStore(appId, storeId, options.baseDir);
2218 if (status != Status::SUCCESS) {
2219 AUDIO_ERR_LOG("DeleteKvStore failed");
2220 }
2221 audioPolicyKvStore_ = nullptr;
2222 }
2223 }
2224
UpdateUsbSafeVolume()2225 void AudioAdapterManager::UpdateUsbSafeVolume()
2226 {
2227 if (volumeDataMaintainer_.GetStreamVolume(STREAM_MUSIC) <= safeVolume_) {
2228 AUDIO_INFO_LOG("1st connect bt device volume is safe");
2229 isWiredBoot_ = false;
2230 return;
2231 }
2232 if (isWiredBoot_ || safeStatus_) {
2233 AUDIO_INFO_LOG("1st connect wired device:%{public}d after boot, update current volume to safevolume",
2234 currentActiveDevice_.deviceType_);
2235 volumeDataMaintainer_.SetStreamVolume(STREAM_MUSIC, safeVolume_);
2236 volumeDataMaintainer_.SaveVolume(currentActiveDevice_.deviceType_, STREAM_MUSIC, safeVolume_,
2237 currentActiveDevice_.networkId_);
2238 isWiredBoot_ = false;
2239 }
2240 }
2241
UpdateSafeVolume()2242 void AudioAdapterManager::UpdateSafeVolume()
2243 {
2244 switch (currentActiveDevice_.deviceType_) {
2245 case DEVICE_TYPE_WIRED_HEADSET:
2246 case DEVICE_TYPE_WIRED_HEADPHONES:
2247 case DEVICE_TYPE_USB_HEADSET:
2248 case DEVICE_TYPE_USB_ARM_HEADSET:
2249 UpdateUsbSafeVolume();
2250 break;
2251 case DEVICE_TYPE_BLUETOOTH_SCO:
2252 case DEVICE_TYPE_BLUETOOTH_A2DP:
2253 case DEVICE_TYPE_NEARLINK:
2254 if (volumeDataMaintainer_.GetStreamVolume(STREAM_MUSIC) <= safeVolume_) {
2255 AUDIO_INFO_LOG("1st connect bt device volume is safe");
2256 isBtBoot_ = false;
2257 return;
2258 }
2259 if (currentActiveDevice_.deviceCategory_ == BT_CAR || currentActiveDevice_.deviceCategory_ == BT_SOUNDBOX) {
2260 AUDIO_ERR_LOG("current device: %{public}d is not support", currentActiveDevice_.deviceCategory_);
2261 return;
2262 }
2263 if (isBtBoot_ || safeStatusBt_) {
2264 AUDIO_INFO_LOG("1st connect bt device:%{public}d after boot, update current volume to safevolume",
2265 currentActiveDevice_.deviceType_);
2266 volumeDataMaintainer_.SetStreamVolume(STREAM_MUSIC, safeVolume_);
2267 volumeDataMaintainer_.SaveVolume(currentActiveDevice_.deviceType_, STREAM_MUSIC, safeVolume_,
2268 currentActiveDevice_.networkId_);
2269 isBtBoot_ = false;
2270 }
2271 break;
2272 default:
2273 AUDIO_ERR_LOG("current device: %{public}d is not support", currentActiveDevice_.deviceType_);
2274 break;
2275 }
2276 }
2277
InitVolumeMap(bool isFirstBoot)2278 void AudioAdapterManager::InitVolumeMap(bool isFirstBoot)
2279 {
2280 if (!isFirstBoot) {
2281 LoadVolumeMap();
2282 UpdateSafeVolume();
2283 return;
2284 }
2285 bool resetFirstFlag = false;
2286 AUDIO_INFO_LOG("InitVolumeMap: Wrote default stream volumes to KvStore");
2287 std::unordered_map<AudioStreamType, int32_t> volumeLevelMapTemp = volumeDataMaintainer_.GetVolumeMap();
2288 for (auto &deviceType: VOLUME_GROUP_TYPE_LIST) {
2289 for (auto &streamType: defaultVolumeTypeList_) {
2290 // if GetVolume failed, wirte default value
2291 if (!volumeDataMaintainer_.GetVolume(deviceType, streamType)) {
2292 int32_t volumeLevel = GetDefaultVolumeLevel(volumeLevelMapTemp, streamType, deviceType);
2293 auto ret = volumeDataMaintainer_.SaveVolume(deviceType, streamType, volumeLevel);
2294 resetFirstFlag = ret ? resetFirstFlag : true;
2295 }
2296
2297 if (!volumeDataMaintainer_.GetVolumeDegree(deviceType, streamType)) {
2298 int32_t defVolumeDegree = MIN_VOLUME_LEVEL;
2299 volumeDataMaintainer_.SaveVolumeDegree(deviceType, streamType, defVolumeDegree);
2300 }
2301 }
2302 }
2303 if (resetFirstFlag) {
2304 AUDIO_INFO_LOG("reset first boot init settingsdata");
2305 SetFirstBoot(true);
2306 }
2307 // reLoad the current device volume
2308 LoadVolumeMap();
2309 UpdateSafeVolume();
2310 }
2311
2312 // If the device specified by the VolumeType has a default volume level configured,
2313 // 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) const2314 int32_t AudioAdapterManager::GetDefaultVolumeLevel(
2315 std::unordered_map<AudioStreamType, int32_t> &volumeLevelMapTemp,
2316 AudioVolumeType volumeType, DeviceType deviceType) const
2317 {
2318 AudioVolumeType internalVolumeType = VolumeUtils::GetVolumeTypeFromStreamType(volumeType);
2319
2320 // find the volume level corresponding the the volume type
2321 auto volumeIt = volumeLevelMapTemp.find(internalVolumeType);
2322 int32_t defaultVolumeLevel = DEFAULT_VOLUME_LEVEL;
2323 if (volumeIt != volumeLevelMapTemp.end()) {
2324 defaultVolumeLevel = volumeIt->second;
2325 } else {
2326 AUDIO_ERR_LOG("Failed to get the volume level corresponding to the volume type");
2327 }
2328
2329 // find the volume level corresponding to the device specified by the volume type
2330 int32_t defaultDeviceVolumeLevel = -1;
2331 auto deviceIt = DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.find(deviceType);
2332 auto streamVolumeInfoIt = streamVolumeInfos_.find(internalVolumeType);
2333 if (deviceIt != DEVICE_TYPE_TO_DEVICE_VOLUME_TYPE_MAP.end() &&
2334 streamVolumeInfoIt != streamVolumeInfos_.end()) {
2335 std::shared_ptr<StreamVolumeInfo> streamVolumeInfo = streamVolumeInfoIt->second;
2336 DeviceVolumeType deviceVolumeType = deviceIt->second;
2337 if (streamVolumeInfo != nullptr) {
2338 auto deviceVolumeInfoIt = streamVolumeInfo->deviceVolumeInfos.find(deviceVolumeType);
2339 if (deviceVolumeInfoIt != streamVolumeInfo->deviceVolumeInfos.end() &&
2340 deviceVolumeInfoIt->second != nullptr) {
2341 defaultDeviceVolumeLevel = deviceVolumeInfoIt->second->defaultLevel;
2342 } else {
2343 AUDIO_ERR_LOG("deviceVolumeInfo is nullptr");
2344 }
2345 } else {
2346 AUDIO_ERR_LOG("streamVolumeInfo is nullptr");
2347 }
2348 }
2349
2350 int32_t volumeLevel = (defaultDeviceVolumeLevel == -1) ? defaultVolumeLevel : defaultDeviceVolumeLevel;
2351 return volumeLevel;
2352 }
2353
ResetRemoteCastDeviceVolume()2354 void AudioAdapterManager::ResetRemoteCastDeviceVolume()
2355 {
2356 for (auto &streamType: defaultVolumeTypeList_) {
2357 AudioStreamType streamAlias = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
2358 int32_t volumeLevel = GetMaxVolumeLevel(streamAlias);
2359 volumeDataMaintainer_.SaveVolume(DEVICE_TYPE_REMOTE_CAST, streamType, volumeLevel);
2360 if (streamType != STREAM_RING) {
2361 volumeDataMaintainer_.SaveMuteStatus(DEVICE_TYPE_REMOTE_CAST, streamType, false);
2362 }
2363 }
2364 }
2365
InitRingerMode(bool isFirstBoot)2366 void AudioAdapterManager::InitRingerMode(bool isFirstBoot)
2367 {
2368 if (isFirstBoot) {
2369 isLoaded_ = true;
2370 if (!volumeDataMaintainer_.GetRingerMode(ringerMode_)) {
2371 isLoaded_ = volumeDataMaintainer_.SaveRingerMode(ringerMode_);
2372 }
2373 AUDIO_INFO_LOG("InitRingerMode first boot ringermode:%{public}d", ringerMode_);
2374 } else {
2375 // read ringerMode from private kvStore
2376 if (isNeedCopyRingerModeData_ && audioPolicyKvStore_ != nullptr) {
2377 AUDIO_INFO_LOG("copy ringerMode from private database to share database");
2378 Key key = "ringermode";
2379 Value value;
2380 Status status = audioPolicyKvStore_->Get(key, value);
2381 if (status == Status::SUCCESS) {
2382 ringerMode_ = static_cast<AudioRingerMode>(TransferByteArrayToType<int>(value.Data()));
2383 volumeDataMaintainer_.SaveRingerMode(ringerMode_);
2384 }
2385 isNeedCopyRingerModeData_ = false;
2386 }
2387 // if read ringer mode success, data is loaded.
2388 isLoaded_ = volumeDataMaintainer_.GetRingerMode(ringerMode_);
2389 }
2390
2391 int32_t volumeLevel =
2392 volumeDataMaintainer_.GetStreamVolume(STREAM_RING) * ((ringerMode_ != RINGER_MODE_NORMAL) ? 0 : 1);
2393 // Save volume in local prop for bootanimation
2394 SaveRingtoneVolumeToLocal(STREAM_RING, volumeLevel);
2395 }
2396
CloneVolumeMap(void)2397 void AudioAdapterManager::CloneVolumeMap(void)
2398 {
2399 CHECK_AND_RETURN_LOG(audioPolicyKvStore_ != nullptr, "clone volumemap failed, audioPolicyKvStore_nullptr");
2400 // read volume from private Kvstore
2401 AUDIO_INFO_LOG("Copy Volume from private database to shareDatabase");
2402 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
2403 for (auto &streamType : defaultVolumeTypeList_) {
2404 std::string volumeKey = GetVolumeKeyForKvStore(deviceType, streamType);
2405 Key key = volumeKey;
2406 Value value;
2407 Status status = audioPolicyKvStore_->Get(volumeKey, value);
2408 if (status != SUCCESS) {
2409 AUDIO_WARNING_LOG("get volumeLevel failed, deviceType:%{public}d, streanType:%{public}d",
2410 deviceType, streamType);
2411 continue;
2412 }
2413 int32_t volumeLevel = TransferByteArrayToType<int>(value.Data());
2414 // clone data to VolumeToShareData
2415 volumeDataMaintainer_.SaveVolume(deviceType, streamType, volumeLevel);
2416 }
2417 }
2418
2419 isNeedCopyVolumeData_ = false;
2420 }
2421
HandleDistributedVolume(AudioStreamType streamType)2422 void AudioAdapterManager::HandleDistributedVolume(AudioStreamType streamType)
2423 {
2424 if (currentActiveDevice_.IsDistributedSpeaker()) {
2425 AUDIO_INFO_LOG("distributed device first connect, use default volume");
2426 if (streamType == STREAM_MUSIC || streamType == STREAM_VOICE_CALL ||
2427 streamType == STREAM_VOICE_ASSISTANT) {
2428 volumeDataMaintainer_.SetStreamVolume(streamType, MAX_VOLUME_LEVEL);
2429 SetSystemVolumeLevel(streamType, MAX_VOLUME_LEVEL);
2430 }
2431 }
2432
2433 if ((currentActiveDevice_.deviceType_ == DEVICE_TYPE_DP || currentActiveDevice_.deviceType_ == DEVICE_TYPE_HDMI)
2434 && streamType == STREAM_MUSIC) {
2435 AUDIO_INFO_LOG("first time switch dp or hdmi, use default volume");
2436 int32_t initialVolume = GetMaxVolumeLevel(streamType) > MAX_VOLUME_LEVEL ?
2437 DP_DEFAULT_VOLUME_LEVEL : GetMaxVolumeLevel(streamType);
2438 volumeDataMaintainer_.SetStreamVolume(STREAM_MUSIC, initialVolume);
2439 SetSystemVolumeLevel(STREAM_MUSIC, initialVolume);
2440 }
2441 }
2442
HandleDpConnection()2443 void AudioAdapterManager::HandleDpConnection()
2444 {
2445 AUDIO_INFO_LOG("dp device connect, set max volume of stream music");
2446 isDpReConnect_ = true;
2447 }
2448
RefreshVolumeWhenDpReConnect()2449 void AudioAdapterManager::RefreshVolumeWhenDpReConnect()
2450 {
2451 // dp reconnect need to set max volume
2452 AUDIO_INFO_LOG("DP reconnect, set max volume");
2453 SetSystemVolumeLevel(STREAM_MUSIC, GetMaxVolumeLevel(STREAM_MUSIC));
2454 SetSystemVolumeLevel(STREAM_VOICE_CALL, GetMaxVolumeLevel(STREAM_VOICE_CALL));
2455 SetSystemVolumeLevel(STREAM_VOICE_ASSISTANT, GetMaxVolumeLevel(STREAM_VOICE_ASSISTANT));
2456 isDpReConnect_ = false;
2457 }
2458
LoadVolumeMap(void)2459 bool AudioAdapterManager::LoadVolumeMap(void)
2460 {
2461 if (isNeedCopyVolumeData_ && (audioPolicyKvStore_ != nullptr)) {
2462 CloneVolumeMap();
2463 }
2464
2465 bool result = false;
2466 for (auto &streamType: defaultVolumeTypeList_) {
2467 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_.deviceType_ != DEVICE_TYPE_REMOTE_CAST) {
2468 result = volumeDataMaintainer_.GetVolume(DEVICE_TYPE_SPEAKER, streamType, currentActiveDevice_.networkId_);
2469 volumeDataMaintainer_.GetVolumeDegree(DEVICE_TYPE_SPEAKER, streamType, currentActiveDevice_.networkId_);
2470 } else {
2471 result = volumeDataMaintainer_.GetVolume(currentActiveDevice_.deviceType_, streamType,
2472 currentActiveDevice_.networkId_);
2473 volumeDataMaintainer_.GetVolumeDegree(currentActiveDevice_.deviceType_, streamType,
2474 currentActiveDevice_.networkId_);
2475 }
2476 if (!result) {
2477 AUDIO_ERR_LOG("LoadVolumeMap: Could not load volume for streamType[%{public}d] from kvStore", streamType);
2478 HandleDistributedVolume(streamType);
2479 HandleHearingAidVolume(streamType);
2480 }
2481 }
2482
2483 return true;
2484 }
2485
LoadVolumeMap(std::shared_ptr<AudioDeviceDescriptor> & device)2486 bool AudioAdapterManager::LoadVolumeMap(std::shared_ptr<AudioDeviceDescriptor> &device)
2487 {
2488 bool result = false;
2489 for (auto &streamType: defaultVolumeTypeList_) {
2490 result = volumeDataExtMaintainer_[device->GetKey()]->GetVolume(device->deviceType_, streamType);
2491 if (!result) {
2492 AUDIO_ERR_LOG("LoadVolumeMap: Could not load volume for streamType[%{public}d] from kvStore", streamType);
2493 }
2494 }
2495
2496 return true;
2497 }
2498
TransferMuteStatus(void)2499 void AudioAdapterManager::TransferMuteStatus(void)
2500 {
2501 // read mute_streams_affected and transfer
2502 int32_t mute_streams_affected = 0;
2503 bool isNeedTransferMute = true;
2504 bool ret = volumeDataMaintainer_.GetMuteAffected(mute_streams_affected) &&
2505 volumeDataMaintainer_.GetMuteTransferStatus(isNeedTransferMute);
2506 if (!ret && (mute_streams_affected > 0) && isNeedTransferMute) {
2507 AUDIO_INFO_LOG("start transfer mute value");
2508 volumeDataMaintainer_.SetMuteAffectedToMuteStatusDataBase(mute_streams_affected);
2509 volumeDataMaintainer_.SaveMuteTransferStatus(false);
2510 }
2511 }
2512
InitMuteStatusMap(bool isFirstBoot)2513 void AudioAdapterManager::InitMuteStatusMap(bool isFirstBoot)
2514 {
2515 if (isFirstBoot) {
2516 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
2517 for (auto &streamType : defaultVolumeTypeList_) {
2518 CheckAndDealMuteStatus(deviceType, streamType);
2519 }
2520 }
2521 TransferMuteStatus();
2522 } else {
2523 LoadMuteStatusMap();
2524 }
2525 }
2526
CheckAndDealMuteStatus(const DeviceType & deviceType,const AudioStreamType & streamType)2527 void AudioAdapterManager::CheckAndDealMuteStatus(const DeviceType &deviceType, const AudioStreamType &streamType)
2528 {
2529 if (streamType == STREAM_RING) {
2530 bool muteStateForStreamRing = (ringerMode_ == RINGER_MODE_NORMAL) ? false : true;
2531 AUDIO_INFO_LOG("fist boot ringer mode:%{public}d, stream ring mute state:%{public}d", ringerMode_,
2532 muteStateForStreamRing);
2533 // set stream mute status to mem.
2534 if (currentActiveDevice_.deviceType_ == deviceType) {
2535 volumeDataMaintainer_.SetStreamMuteStatus(streamType, muteStateForStreamRing);
2536 }
2537 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, muteStateForStreamRing,
2538 currentActiveDevice_.networkId_);
2539 } else if (!volumeDataMaintainer_.GetMuteStatus(deviceType, streamType)) {
2540 if (currentActiveDevice_.deviceType_ == deviceType) {
2541 volumeDataMaintainer_.SetStreamMuteStatus(streamType, false);
2542 }
2543 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, false, currentActiveDevice_.networkId_);
2544 }
2545 if (currentActiveDevice_.deviceType_ == deviceType) {
2546 SetVolumeDb(streamType);
2547 }
2548 }
2549
SetVolumeCallbackAfterClone()2550 void AudioAdapterManager::SetVolumeCallbackAfterClone()
2551 {
2552 for (auto &streamType : defaultVolumeTypeList_) {
2553 VolumeEvent volumeEvent;
2554 volumeEvent.volumeType = streamType;
2555 volumeEvent.volume = GetSystemVolumeLevel(streamType);
2556 volumeEvent.updateUi = false;
2557 volumeEvent.volumeGroupId = 0;
2558 volumeEvent.networkId = LOCAL_NETWORK_ID;
2559 if (audioPolicyServerHandler_ != nullptr) {
2560 audioPolicyServerHandler_->SendVolumeKeyEventCallback(volumeEvent);
2561 }
2562 }
2563 }
2564
CloneMuteStatusMap(void)2565 void AudioAdapterManager::CloneMuteStatusMap(void)
2566 {
2567 // read mute status from private Kvstore
2568 CHECK_AND_RETURN_LOG(audioPolicyKvStore_ != nullptr, "clone mute status failed, audioPolicyKvStore_ nullptr");
2569 AUDIO_INFO_LOG("Copy mute from private database to shareDatabase");
2570 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
2571 for (auto &streamType : defaultVolumeTypeList_) {
2572 std::string muteKey = GetMuteKeyForKvStore(deviceType, streamType);
2573 Key key = muteKey;
2574 Value value;
2575 Status status = audioPolicyKvStore_->Get(key, value);
2576 if (status != SUCCESS) {
2577 AUDIO_WARNING_LOG("get muteStatus:failed, deviceType:%{public}d, streanType:%{public}d",
2578 deviceType, streamType);
2579 continue;
2580 }
2581 bool muteStatus = TransferByteArrayToType<int>(value.Data());
2582 // clone data to VolumeToShareData
2583 if (currentActiveDevice_.deviceType_ == deviceType) {
2584 volumeDataMaintainer_.SetStreamMuteStatus(streamType, muteStatus);
2585 }
2586 volumeDataMaintainer_.SaveMuteStatus(deviceType, streamType, muteStatus, currentActiveDevice_.networkId_);
2587 }
2588 }
2589 isNeedCopyMuteData_ = false;
2590 }
2591
LoadMuteStatusMap(void)2592 bool AudioAdapterManager::LoadMuteStatusMap(void)
2593 {
2594 if (isNeedCopyMuteData_ && (audioPolicyKvStore_ != nullptr)) {
2595 CloneMuteStatusMap();
2596 }
2597
2598 TransferMuteStatus();
2599
2600 for (auto &streamType: defaultVolumeTypeList_) {
2601 bool result = volumeDataMaintainer_.GetMuteStatus(currentActiveDevice_.deviceType_, streamType,
2602 currentActiveDevice_.networkId_);
2603 if (!result) {
2604 AUDIO_WARNING_LOG("Could not load mute status for stream type %{public}d from database.", streamType);
2605 }
2606 if (streamType == STREAM_RING && VolumeUtils::GetVolumeTypeFromStreamType(streamType) == STREAM_RING) {
2607 bool muteStateForStreamRing = (ringerMode_ == RINGER_MODE_NORMAL) ? false : true;
2608 if (currentActiveDevice_.deviceType_ != DEVICE_TYPE_SPEAKER) {
2609 continue;
2610 }
2611 AUDIO_INFO_LOG("ringer mode:%{public}d, stream ring mute state:%{public}d", ringerMode_,
2612 muteStateForStreamRing);
2613 if (muteStateForStreamRing == GetStreamMute(streamType)) {
2614 continue;
2615 }
2616 // set local speaker mute state in ring scene when ringermode change
2617 volumeDataMaintainer_.SaveMuteStatus(currentActiveDevice_.deviceType_, streamType, muteStateForStreamRing);
2618 SetStreamMute(streamType, muteStateForStreamRing);
2619 }
2620 }
2621 return true;
2622 }
2623
LoadMuteStatusMap(std::shared_ptr<AudioDeviceDescriptor> & device)2624 bool AudioAdapterManager::LoadMuteStatusMap(std::shared_ptr<AudioDeviceDescriptor> &device)
2625 {
2626 for (auto &streamType: defaultVolumeTypeList_) {
2627 bool result = volumeDataExtMaintainer_[device->GetKey()]->GetMuteStatus(device->deviceType_, streamType);
2628 if (!result) {
2629 AUDIO_WARNING_LOG("Could not load mute status for stream type %{public}d from database.", streamType);
2630 }
2631 }
2632 return true;
2633 }
2634
InitSafeStatus(bool isFirstBoot)2635 void AudioAdapterManager::InitSafeStatus(bool isFirstBoot)
2636 {
2637 if (isFirstBoot) {
2638 AUDIO_INFO_LOG("Wrote default safe status to KvStore");
2639 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
2640 // Adapt to safe volume upgrade scenarios
2641 if (!volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_) &&
2642 (deviceType == DEVICE_TYPE_WIRED_HEADSET)) {
2643 volumeDataMaintainer_.SaveSafeStatus(DEVICE_TYPE_WIRED_HEADSET, SAFE_ACTIVE);
2644 }
2645 if (!volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_) &&
2646 (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP)) {
2647 volumeDataMaintainer_.SaveSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, SAFE_ACTIVE);
2648 }
2649 }
2650 } else {
2651 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
2652 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
2653 }
2654 }
2655
InitSafeTime(bool isFirstBoot)2656 void AudioAdapterManager::InitSafeTime(bool isFirstBoot)
2657 {
2658 if (isFirstBoot) {
2659 AUDIO_INFO_LOG("Wrote default safe status to KvStore");
2660 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
2661 if (!volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_) &&
2662 (deviceType == DEVICE_TYPE_WIRED_HEADSET)) {
2663 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, 0);
2664 }
2665 if (!volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_) &&
2666 (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP)) {
2667 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, 0);
2668 }
2669 ConvertSafeTime();
2670 isNeedConvertSafeTime_ = false;
2671 }
2672 } else {
2673 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_);
2674 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_);
2675 if (isNeedConvertSafeTime_) {
2676 ConvertSafeTime();
2677 isNeedConvertSafeTime_ = false;
2678 }
2679 }
2680 }
2681
ConvertSafeTime(void)2682 void AudioAdapterManager::ConvertSafeTime(void)
2683 {
2684 // Adapt to safe volume time when upgrade scenarios
2685 if (safeActiveTime_ > 0) {
2686 safeActiveTime_ = safeActiveTime_ / CONVERT_FROM_MS_TO_SECONDS;
2687 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_);
2688 }
2689 if (safeActiveBtTime_ > 0) {
2690 safeActiveBtTime_ = safeActiveBtTime_ / CONVERT_FROM_MS_TO_SECONDS;
2691 volumeDataMaintainer_.SaveSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_);
2692 }
2693 }
2694
GetCurrentDeviceSafeStatus(DeviceType deviceType)2695 SafeStatus AudioAdapterManager::GetCurrentDeviceSafeStatus(DeviceType deviceType)
2696 {
2697 switch (deviceType) {
2698 case DEVICE_TYPE_WIRED_HEADSET:
2699 case DEVICE_TYPE_WIRED_HEADPHONES:
2700 case DEVICE_TYPE_USB_HEADSET:
2701 case DEVICE_TYPE_USB_ARM_HEADSET:
2702 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_WIRED_HEADSET, safeStatus_);
2703 return safeStatus_;
2704 case DEVICE_TYPE_BLUETOOTH_SCO:
2705 case DEVICE_TYPE_BLUETOOTH_A2DP:
2706 case DEVICE_TYPE_NEARLINK:
2707 volumeDataMaintainer_.GetSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP, safeStatusBt_);
2708 return safeStatusBt_;
2709 default:
2710 AUDIO_ERR_LOG("current device : %{public}d is not support", deviceType);
2711 break;
2712 }
2713
2714 return SAFE_UNKNOWN;
2715 }
2716
GetCurentDeviceSafeTime(DeviceType deviceType)2717 int64_t AudioAdapterManager::GetCurentDeviceSafeTime(DeviceType deviceType)
2718 {
2719 switch (deviceType) {
2720 case DEVICE_TYPE_WIRED_HEADSET:
2721 case DEVICE_TYPE_WIRED_HEADPHONES:
2722 case DEVICE_TYPE_USB_HEADSET:
2723 case DEVICE_TYPE_USB_ARM_HEADSET:
2724 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_WIRED_HEADSET, safeActiveTime_);
2725 return safeActiveTime_;
2726 case DEVICE_TYPE_BLUETOOTH_SCO:
2727 case DEVICE_TYPE_BLUETOOTH_A2DP:
2728 volumeDataMaintainer_.GetSafeVolumeTime(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtTime_);
2729 return safeActiveBtTime_;
2730 default:
2731 AUDIO_ERR_LOG("current device : %{public}d is not support", deviceType);
2732 break;
2733 }
2734
2735 return -1;
2736 }
2737
GetRestoreVolumeLevel(DeviceType deviceType)2738 int32_t AudioAdapterManager::GetRestoreVolumeLevel(DeviceType deviceType)
2739 {
2740 switch (deviceType) {
2741 case DEVICE_TYPE_WIRED_HEADSET:
2742 case DEVICE_TYPE_WIRED_HEADPHONES:
2743 case DEVICE_TYPE_USB_HEADSET:
2744 case DEVICE_TYPE_USB_ARM_HEADSET:
2745 volumeDataMaintainer_.GetRestoreVolumeLevel(DEVICE_TYPE_WIRED_HEADSET, safeActiveVolume_);
2746 return safeActiveVolume_;
2747 case DEVICE_TYPE_BLUETOOTH_SCO:
2748 case DEVICE_TYPE_BLUETOOTH_A2DP:
2749 volumeDataMaintainer_.GetRestoreVolumeLevel(DEVICE_TYPE_BLUETOOTH_A2DP, safeActiveBtVolume_);
2750 return safeActiveBtVolume_;
2751 default:
2752 AUDIO_ERR_LOG("current device : %{public}d is not support", deviceType);
2753 break;
2754 }
2755
2756 return SAFE_UNKNOWN;
2757 }
2758
SetDeviceSafeStatus(DeviceType deviceType,SafeStatus status)2759 int32_t AudioAdapterManager::SetDeviceSafeStatus(DeviceType deviceType, SafeStatus status)
2760 {
2761 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
2762 safeStatusBt_ = status;
2763 } else if (deviceType == DEVICE_TYPE_WIRED_HEADSET) {
2764 safeStatus_ = status;
2765 }
2766 bool ret = volumeDataMaintainer_.SaveSafeStatus(deviceType, status);
2767 CHECK_AND_RETURN_RET(ret, ERROR, "SaveSafeStatus failed");
2768 return SUCCESS;
2769 }
2770
SetDeviceSafeTime(DeviceType deviceType,int64_t time)2771 int32_t AudioAdapterManager::SetDeviceSafeTime(DeviceType deviceType, int64_t time)
2772 {
2773 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
2774 safeActiveBtTime_ = time;
2775 } else if (deviceType == DEVICE_TYPE_WIRED_HEADSET) {
2776 safeActiveTime_ = time;
2777 }
2778 bool ret = volumeDataMaintainer_.SaveSafeVolumeTime(deviceType, time);
2779 CHECK_AND_RETURN_RET(ret, ERROR, "SetDeviceSafeTime failed");
2780 return SUCCESS;
2781 }
2782
SetRestoreVolumeLevel(DeviceType deviceType,int32_t volume)2783 int32_t AudioAdapterManager::SetRestoreVolumeLevel(DeviceType deviceType, int32_t volume)
2784 {
2785 if (deviceType == DEVICE_TYPE_BLUETOOTH_A2DP) {
2786 safeActiveBtVolume_ = volume;
2787 } else if (deviceType == DEVICE_TYPE_WIRED_HEADSET) {
2788 safeActiveVolume_ = volume;
2789 }
2790 bool ret = volumeDataMaintainer_.SetRestoreVolumeLevel(deviceType, volume);
2791 CHECK_AND_RETURN_RET(ret, ERROR, "SetRestoreVolumeLevel failed");
2792 return SUCCESS;
2793 }
2794
GetMuteKeyForKvStore(DeviceType deviceType,AudioStreamType streamType)2795 std::string AudioAdapterManager::GetMuteKeyForKvStore(DeviceType deviceType, AudioStreamType streamType)
2796 {
2797 std::string type = "";
2798 GetMuteKeyForDeviceType(deviceType, type);
2799 if (type == "") {
2800 return type;
2801 }
2802
2803 switch (streamType) {
2804 case STREAM_MUSIC:
2805 return type + "_music_mute_status";
2806 case STREAM_RING:
2807 case STREAM_VOICE_RING:
2808 return type + "_ring_mute_status";
2809 case STREAM_SYSTEM:
2810 return type + "_system_mute_status";
2811 case STREAM_NOTIFICATION:
2812 return type + "_notification_mute_status";
2813 case STREAM_ALARM:
2814 return type + "_alarm_mute_status";
2815 case STREAM_DTMF:
2816 return type + "_dtmf_mute_status";
2817 case STREAM_VOICE_CALL:
2818 case STREAM_VOICE_COMMUNICATION:
2819 return type + "_voice_call_mute_status";
2820 case STREAM_VOICE_ASSISTANT:
2821 return type + "_voice_assistant_mute_status";
2822 case STREAM_ACCESSIBILITY:
2823 return type + "_accessibility_mute_status";
2824 case STREAM_ULTRASONIC:
2825 return type + "_unltrasonic_mute_status";
2826 default:
2827 AUDIO_ERR_LOG("GetMuteKeyForKvStore: streamType %{public}d is not supported for kvStore", streamType);
2828 return "";
2829 }
2830 }
2831
GetMuteKeyForDeviceType(DeviceType deviceType,std::string & type)2832 std::string AudioAdapterManager::GetMuteKeyForDeviceType(DeviceType deviceType, std::string &type)
2833 {
2834 switch (deviceType) {
2835 case DEVICE_TYPE_EARPIECE:
2836 case DEVICE_TYPE_SPEAKER:
2837 case DEVICE_TYPE_DP:
2838 case DEVICE_TYPE_HDMI:
2839 type = "build-in";
2840 break;
2841 case DEVICE_TYPE_BLUETOOTH_A2DP:
2842 case DEVICE_TYPE_BLUETOOTH_SCO:
2843 case DEVICE_TYPE_ACCESSORY:
2844 type = "wireless";
2845 break;
2846 case DEVICE_TYPE_WIRED_HEADSET:
2847 case DEVICE_TYPE_WIRED_HEADPHONES:
2848 case DEVICE_TYPE_USB_HEADSET:
2849 case DEVICE_TYPE_USB_ARM_HEADSET:
2850 type = "wired";
2851 break;
2852 default:
2853 AUDIO_ERR_LOG("GetMuteKeyForKvStore: device %{public}d is not supported for kvStore", deviceType);
2854 return "";
2855 }
2856 return type;
2857 }
2858
CalculateVolumeDb(int32_t volumeLevel,int32_t maxDegree)2859 float AudioAdapterManager::CalculateVolumeDb(int32_t volumeLevel, int32_t maxDegree)
2860 {
2861 if (maxDegree == 0) {
2862 maxDegree = MAX_VOLUME_LEVEL;
2863 }
2864
2865 float value = static_cast<float>(volumeLevel) / maxDegree;
2866 float roundValue = static_cast<int>(value * CONST_FACTOR);
2867
2868 return static_cast<float>(roundValue) / CONST_FACTOR;
2869 }
2870
CloneSystemSoundUrl(void)2871 void AudioAdapterManager::CloneSystemSoundUrl(void)
2872 {
2873 CHECK_AND_RETURN_LOG(isNeedCopySystemUrlData_ && (audioPolicyKvStore_ != nullptr),
2874 "audioPolicyKvStore_ is nullptr,clone systemurl failed");
2875 for (auto &key: SYSTEM_SOUND_KEY_LIST) {
2876 Value value;
2877 Status status = audioPolicyKvStore_->Get(key, value);
2878 if (status == Status::SUCCESS) {
2879 std::string systemSoundUri = value.ToString();
2880 systemSoundUriMap_[key] = systemSoundUri;
2881 volumeDataMaintainer_.SaveSystemSoundUrl(key, systemSoundUri);
2882 }
2883 }
2884 isNeedCopySystemUrlData_ = false;
2885 }
2886
InitSystemSoundUriMap()2887 void AudioAdapterManager::InitSystemSoundUriMap()
2888 {
2889 for (auto &key: SYSTEM_SOUND_KEY_LIST) {
2890 std::string systemSoundUri = "";
2891 volumeDataMaintainer_.GetSystemSoundUrl(key, systemSoundUri);
2892 if (systemSoundUri == "") {
2893 AUDIO_WARNING_LOG("Could not load system sound uri for %{public}s from kvStore", key.c_str());
2894 }
2895 systemSoundUriMap_[key] = systemSoundUri;
2896 }
2897 }
2898
SetSystemSoundUri(const std::string & key,const std::string & uri)2899 int32_t AudioAdapterManager::SetSystemSoundUri(const std::string &key, const std::string &uri)
2900 {
2901 auto pos = std::find(SYSTEM_SOUND_KEY_LIST.begin(), SYSTEM_SOUND_KEY_LIST.end(), key);
2902 if (pos == SYSTEM_SOUND_KEY_LIST.end()) {
2903 AUDIO_ERR_LOG("Invalid key %{public}s for system sound uri", key.c_str());
2904 return ERR_INVALID_PARAM;
2905 }
2906 std::lock_guard<std::mutex> lock(systemSoundMutex_);
2907 if (systemSoundUriMap_.size() == 0) {
2908 InitSystemSoundUriMap();
2909 CHECK_AND_RETURN_RET_LOG(systemSoundUriMap_.size() != 0, ERR_OPERATION_FAILED,
2910 "Failed to init system sound uri map.");
2911 }
2912 systemSoundUriMap_[key] = uri;
2913 if (!volumeDataMaintainer_.SaveSystemSoundUrl(key, uri)) {
2914 AUDIO_ERR_LOG("SetSystemSoundUri failed");
2915 return ERROR;
2916 }
2917 return SUCCESS;
2918 }
2919
GetSystemSoundUri(const std::string & key)2920 std::string AudioAdapterManager::GetSystemSoundUri(const std::string &key)
2921 {
2922 auto pos = std::find(SYSTEM_SOUND_KEY_LIST.begin(), SYSTEM_SOUND_KEY_LIST.end(), key);
2923 if (pos == SYSTEM_SOUND_KEY_LIST.end()) {
2924 AUDIO_ERR_LOG("Invalid key %{public}s for system sound uri", key.c_str());
2925 return "";
2926 }
2927 std::lock_guard<std::mutex> lock(systemSoundMutex_);
2928 if (systemSoundUriMap_.size() == 0) {
2929 InitSystemSoundUriMap();
2930 CHECK_AND_RETURN_RET_LOG(systemSoundUriMap_.size() != 0, "",
2931 "Failed to init system sound uri map.");
2932 }
2933 return systemSoundUriMap_[key];
2934 }
2935
GetMinStreamVolume() const2936 float AudioAdapterManager::GetMinStreamVolume() const
2937 {
2938 return MIN_STREAM_VOLUME;
2939 }
2940
GetMaxStreamVolume() const2941 float AudioAdapterManager::GetMaxStreamVolume() const
2942 {
2943 return MAX_STREAM_VOLUME;
2944 }
2945
IsVolumeUnadjustable()2946 bool AudioAdapterManager::IsVolumeUnadjustable()
2947 {
2948 return isVolumeUnadjustable_;
2949 }
2950
GetSystemVolumeInDb(AudioVolumeType volumeType,int32_t volumeLevel,DeviceType deviceType)2951 float AudioAdapterManager::GetSystemVolumeInDb(AudioVolumeType volumeType, int32_t volumeLevel, DeviceType deviceType)
2952 {
2953 AUDIO_DEBUG_LOG("for volumeType: %{public}d deviceType:%{public}d volumeLevel:%{public}d",
2954 volumeType, deviceType, volumeLevel);
2955 if (useNonlinearAlgo_) {
2956 getSystemVolumeInDb_ = CalculateVolumeDbNonlinear(volumeType, deviceType, volumeLevel);
2957 } else {
2958 getSystemVolumeInDb_ = CalculateVolumeDb(volumeLevel);
2959 }
2960
2961 AUDIO_DEBUG_LOG("Get system volume in db success %{public}f", getSystemVolumeInDb_.load());
2962
2963 return getSystemVolumeInDb_;
2964 }
2965
GetPositionInVolumePoints(std::vector<VolumePoint> & volumePoints,int32_t idx)2966 uint32_t AudioAdapterManager::GetPositionInVolumePoints(std::vector<VolumePoint> &volumePoints, int32_t idx)
2967 {
2968 int32_t leftPos = 0;
2969 int32_t rightPos = static_cast<int32_t>(volumePoints.size() - 1);
2970 while (leftPos <= rightPos) {
2971 int32_t midPos = leftPos + (rightPos - leftPos)/NUMBER_TWO;
2972 int32_t c = static_cast<int32_t>(volumePoints[midPos].index) - idx;
2973 if (c == 0) {
2974 leftPos = midPos;
2975 break;
2976 } else if (c < 0) {
2977 leftPos = midPos + 1;
2978 } else {
2979 rightPos = midPos - 1;
2980 }
2981 }
2982 return leftPos;
2983 }
2984
CalculateVolumeDbNonlinear(AudioStreamType streamType,DeviceType deviceType,int32_t volumeLevel)2985 float AudioAdapterManager::CalculateVolumeDbNonlinear(AudioStreamType streamType,
2986 DeviceType deviceType, int32_t volumeLevel)
2987 {
2988 AUDIO_DEBUG_LOG("CalculateVolumeDbNonlinear for stream: %{public}d devicetype:%{public}d volumeLevel:%{public}d",
2989 streamType, deviceType, volumeLevel);
2990 AudioStreamType streamAlias = VolumeUtils::GetVolumeTypeFromStreamType(streamType);
2991 int32_t minVolIndex = GetMinVolumeLevel(streamAlias);
2992 int32_t maxVolIndex = GetMaxVolumeLevel(streamAlias);
2993 if (minVolIndex < 0 || maxVolIndex < 0 || minVolIndex >= maxVolIndex) {
2994 return 0.0f;
2995 }
2996 if (volumeLevel < minVolIndex) {
2997 volumeLevel = minVolIndex;
2998 }
2999 if (volumeLevel > maxVolIndex) {
3000 volumeLevel = maxVolIndex;
3001 }
3002
3003 DeviceVolumeType deviceCategory = GetDeviceCategory(deviceType);
3004 std::vector<VolumePoint> volumePoints;
3005 GetVolumePoints(streamAlias, deviceCategory, volumePoints);
3006 uint32_t pointSize = volumePoints.size();
3007
3008 CHECK_AND_RETURN_RET_LOG(pointSize != 0, 1.0f, "pointSize is 0");
3009 int32_t volSteps = static_cast<int32_t>(1 + volumePoints[pointSize - 1].index - volumePoints[0].index);
3010 int32_t idxRatio = (volSteps * (volumeLevel - minVolIndex)) / (maxVolIndex - minVolIndex);
3011 int32_t position = static_cast<int32_t>(GetPositionInVolumePoints(volumePoints, idxRatio));
3012 if (position == 0) {
3013 if (minVolIndex != 0) {
3014 AUDIO_INFO_LOG("Min volume index not zero, use min db: %{public}0.1f", volumePoints[0].dbValue / 100.0f);
3015 return exp((volumePoints[0].dbValue / 100.0f) * 0.115129f);
3016 }
3017 AUDIO_DEBUG_LOG("position = 0, return 0.0");
3018 return 0.0f;
3019 } else if (position >= static_cast<int32_t>(pointSize)) {
3020 AUDIO_DEBUG_LOG("position > pointSize, return %{public}f",
3021 exp(volumePoints[pointSize - 1].dbValue * 0.115129f));
3022 return exp((volumePoints[pointSize - 1].dbValue / 100.0f) * 0.115129f);
3023 }
3024 float indexFactor = (static_cast<float>(idxRatio - static_cast<int32_t>(volumePoints[position - 1].index))) /
3025 (static_cast<float>(volumePoints[position].index - volumePoints[position - 1].index));
3026
3027 float dbValue = (volumePoints[position - 1].dbValue / 100.0f) +
3028 indexFactor * ((volumePoints[position].dbValue / 100.0f) - (volumePoints[position - 1].dbValue / 100.0f));
3029
3030 AUDIO_DEBUG_LOG(" index=[%{public}d, %{public}d, %{public}d]"
3031 "db=[%{public}0.1f %{public}0.1f %{public}0.1f] factor=[%{public}f]",
3032 volumePoints[position - 1].index, idxRatio, volumePoints[position].index,
3033 (static_cast<float>(volumePoints[position - 1].dbValue) / 100.0f), dbValue,
3034 (static_cast<float>(volumePoints[position].dbValue) / 100.0f), exp(dbValue * 0.115129f));
3035
3036 return exp(dbValue * 0.115129f);
3037 }
3038
InitVolumeMapIndex()3039 void AudioAdapterManager::InitVolumeMapIndex()
3040 {
3041 useNonlinearAlgo_ = 0;
3042 for (auto streamType : defaultVolumeTypeList_) {
3043 minVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)] = MIN_VOLUME_LEVEL;
3044 maxVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)] = MAX_VOLUME_LEVEL;
3045 volumeDataMaintainer_.SetStreamVolume(streamType, DEFAULT_VOLUME_LEVEL);
3046 AUDIO_DEBUG_LOG("streamType %{public}d index = [%{public}d, %{public}d, %{public}d]",
3047 streamType, minVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)],
3048 maxVolumeIndexMap_[VolumeUtils::GetVolumeTypeFromStreamType(streamType)],
3049 volumeDataMaintainer_.GetStreamVolume(streamType));
3050 }
3051
3052 volumeDataMaintainer_.SetStreamVolume(STREAM_VOICE_CALL_ASSISTANT, MAX_VOLUME_LEVEL);
3053 volumeDataMaintainer_.SetStreamVolume(STREAM_ULTRASONIC, MAX_VOLUME_LEVEL);
3054 }
3055
UpdateVolumeMapIndex()3056 void AudioAdapterManager::UpdateVolumeMapIndex()
3057 {
3058 bool isAppConfigVolumeInit = false;
3059 for (auto streamVolInfoPair : streamVolumeInfos_) {
3060 auto streamVolInfo = streamVolInfoPair.second;
3061 if (streamVolInfo->streamType == STREAM_APP) {
3062 appConfigVolume_.defaultVolume = streamVolInfo->defaultLevel;
3063 appConfigVolume_.maxVolume = streamVolInfo->maxLevel;
3064 appConfigVolume_.minVolume = streamVolInfo->minLevel;
3065 isAppConfigVolumeInit = true;
3066 AUDIO_DEBUG_LOG("AppConfigVolume default = %{public}d, max = %{public}d, min = %{public}d",
3067 appConfigVolume_.defaultVolume, appConfigVolume_.maxVolume, appConfigVolume_.minVolume);
3068 continue;
3069 }
3070 AudioVolumeType CurStreamType = VolumeUtils::GetVolumeTypeFromStreamType(streamVolInfo->streamType);
3071 minVolumeIndexMap_[CurStreamType] = streamVolInfo->minLevel;
3072 maxVolumeIndexMap_[CurStreamType] = streamVolInfo->maxLevel;
3073 volumeDataMaintainer_.SetStreamVolume(streamVolInfo->streamType, streamVolInfo->defaultLevel);
3074 AUDIO_DEBUG_LOG("update streamType %{public}d index = [%{public}d, %{public}d, %{public}d]",
3075 streamVolInfo->streamType, minVolumeIndexMap_[CurStreamType], maxVolumeIndexMap_[CurStreamType],
3076 volumeDataMaintainer_.GetStreamVolume(CurStreamType));
3077 }
3078 if (isAppConfigVolumeInit) {
3079 return;
3080 } else {
3081 appConfigVolume_.defaultVolume = APP_DEFAULT_VOLUME_LEVEL;
3082 appConfigVolume_.maxVolume = APP_MAX_VOLUME_LEVEL;
3083 appConfigVolume_.minVolume = APP_MIN_VOLUME_LEVEL;
3084 isAppConfigVolumeInit = true;
3085 AUDIO_DEBUG_LOG("isAppConfigVolumeInit default = %{public}d, max = %{public}d, min = %{public}d",
3086 appConfigVolume_.defaultVolume, appConfigVolume_.maxVolume, appConfigVolume_.minVolume);
3087 return;
3088 }
3089 if (minVolumeIndexMap_.find(STREAM_MUSIC) != minVolumeIndexMap_.end() &&
3090 maxVolumeIndexMap_.find(STREAM_MUSIC) != maxVolumeIndexMap_.end()) {
3091 appConfigVolume_.defaultVolume = maxVolumeIndexMap_[STREAM_MUSIC];
3092 appConfigVolume_.maxVolume = maxVolumeIndexMap_[STREAM_MUSIC];
3093 appConfigVolume_.minVolume = minVolumeIndexMap_[STREAM_MUSIC];
3094 } else {
3095 appConfigVolume_.defaultVolume = MAX_VOLUME_LEVEL;
3096 appConfigVolume_.maxVolume = MAX_VOLUME_LEVEL;
3097 appConfigVolume_.minVolume = MIN_VOLUME_LEVEL;
3098 }
3099 isAppConfigVolumeInit = true;
3100 AUDIO_DEBUG_LOG("next AppConfigVolume default = %{public}d, max = %{public}d, min = %{public}d",
3101 appConfigVolume_.defaultVolume, appConfigVolume_.maxVolume, appConfigVolume_.minVolume);
3102 }
3103
GetVolumePoints(AudioVolumeType streamType,DeviceVolumeType deviceType,std::vector<VolumePoint> & volumePoints)3104 void AudioAdapterManager::GetVolumePoints(AudioVolumeType streamType, DeviceVolumeType deviceType,
3105 std::vector<VolumePoint> &volumePoints)
3106 {
3107 auto streamVolInfo = streamVolumeInfos_.find(streamType);
3108 if (streamVolInfo == streamVolumeInfos_.end()) {
3109 AUDIO_DEBUG_LOG("Cannot find stream type %{public}d and try to use STREAM_MUSIC", streamType);
3110 streamVolInfo = streamVolumeInfos_.find(STREAM_MUSIC);
3111 CHECK_AND_RETURN_LOG(streamVolInfo != streamVolumeInfos_.end(),
3112 "Cannot find stream type STREAM_MUSIC");
3113 }
3114 auto deviceVolInfo = streamVolInfo->second->deviceVolumeInfos.find(deviceType);
3115 if (deviceVolInfo == streamVolInfo->second->deviceVolumeInfos.end()) {
3116 AUDIO_ERR_LOG("Cannot find device type %{public}d", deviceType);
3117 return;
3118 }
3119 volumePoints = deviceVolInfo->second->volumePoints;
3120 }
3121
GetStreamVolumeInfoMap(StreamVolumeInfoMap & streamVolumeInfos)3122 void AudioAdapterManager::GetStreamVolumeInfoMap(StreamVolumeInfoMap &streamVolumeInfos)
3123 {
3124 streamVolumeInfos = streamVolumeInfos_;
3125 }
3126
SetActiveDeviceDescriptor(AudioDeviceDescriptor deviceDescriptor)3127 void AudioAdapterManager::SetActiveDeviceDescriptor(AudioDeviceDescriptor deviceDescriptor)
3128 {
3129 AUDIO_PRERELEASE_LOGI("SetActiveDevice deviceType %{public}d", deviceDescriptor.deviceType_);
3130 SetVolumeForSwitchDevice(deviceDescriptor);
3131 }
3132
GetActiveDeviceDescriptor()3133 AudioDeviceDescriptor AudioAdapterManager::GetActiveDeviceDescriptor()
3134 {
3135 return currentActiveDevice_;
3136 }
3137
GetCurrentOutputDeviceCategory()3138 DeviceCategory AudioAdapterManager::GetCurrentOutputDeviceCategory()
3139 {
3140 return currentActiveDevice_.deviceCategory_;
3141 }
3142
GetActiveDevice()3143 DeviceType AudioAdapterManager::GetActiveDevice()
3144 {
3145 return currentActiveDevice_.deviceType_;
3146 }
3147
SetAbsVolumeScene(bool isAbsVolumeScene)3148 void AudioAdapterManager::SetAbsVolumeScene(bool isAbsVolumeScene)
3149 {
3150 AUDIO_PRERELEASE_LOGI("SetAbsVolumeScene: %{public}d", isAbsVolumeScene);
3151 isAbsVolumeScene_ = isAbsVolumeScene;
3152 CHECK_AND_RETURN_LOG(audioServiceAdapter_ != nullptr, "SetAbsVolumeScene audio adapter null");
3153 audioServiceAdapter_->SetAbsVolumeStateToEffect(isAbsVolumeScene);
3154 AudioVolumeManager::GetInstance().SetSharedAbsVolumeScene(isAbsVolumeScene_);
3155 if (currentActiveDevice_.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP) {
3156 volumeDataMaintainer_.GetVolume(DEVICE_TYPE_BLUETOOTH_A2DP, STREAM_MUSIC);
3157 SetVolumeDb(STREAM_MUSIC);
3158 } else {
3159 AUDIO_INFO_LOG("The currentActiveDevice is not A2DP or nearlink device");
3160 }
3161 if (currentActiveDevice_.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP && IsAbsVolumeScene()
3162 && !VolumeUtils::IsPCVolumeEnable()) {
3163 volumeDataMaintainer_.SetStreamVolume(STREAM_VOICE_ASSISTANT, MAX_VOLUME_LEVEL);
3164 SetVolumeDb(STREAM_VOICE_ASSISTANT);
3165 AUDIO_INFO_LOG("a2dp ok");
3166 }
3167 }
3168
IsAbsVolumeScene() const3169 bool AudioAdapterManager::IsAbsVolumeScene() const
3170 {
3171 return isAbsVolumeScene_;
3172 }
3173
SetAbsVolumeMute(bool mute)3174 void AudioAdapterManager::SetAbsVolumeMute(bool mute)
3175 {
3176 AUDIO_INFO_LOG("SetAbsVolumeMute: %{public}d", mute);
3177 isAbsVolumeMute_ = mute;
3178 if (currentActiveDevice_.deviceType_ == DEVICE_TYPE_BLUETOOTH_A2DP ||
3179 currentActiveDevice_.deviceType_ == DEVICE_TYPE_NEARLINK) {
3180 SetVolumeDb(STREAM_MUSIC);
3181 } else {
3182 AUDIO_INFO_LOG("The currentActiveDevice is not A2DP or nearlink device");
3183 }
3184 }
3185
3186
IsAbsVolumeMute() const3187 bool AudioAdapterManager::IsAbsVolumeMute() const
3188 {
3189 return isAbsVolumeMute_;
3190 }
3191
NotifyAccountsChanged(const int & id)3192 void AudioAdapterManager::NotifyAccountsChanged(const int &id)
3193 {
3194 AUDIO_INFO_LOG("start reload the kv data, current id:%{public}d", id);
3195 LoadVolumeMap();
3196 for (auto &deviceType : VOLUME_GROUP_TYPE_LIST) {
3197 for (auto &streamType : defaultVolumeTypeList_) {
3198 CheckAndDealMuteStatus(deviceType, streamType);
3199 }
3200 }
3201 }
3202
DoRestoreData()3203 int32_t AudioAdapterManager::DoRestoreData()
3204 {
3205 isLoaded_ = false;
3206 isNeedConvertSafeTime_ = true; // reset convert safe volume status
3207 volumeDataMaintainer_.SaveMuteTransferStatus(true); // reset mute convert status
3208 InitKVStore();
3209 return SUCCESS;
3210 }
3211
GetSafeVolumeLevel() const3212 int32_t AudioAdapterManager::GetSafeVolumeLevel() const
3213 {
3214 return safeVolume_;
3215 }
3216
GetSafeVolumeTimeout() const3217 int32_t AudioAdapterManager::GetSafeVolumeTimeout() const
3218 {
3219 if (safeVolumeTimeout_ <= 0) {
3220 AUDIO_INFO_LOG("safeVolumeTimeout is invalid, return default value:%{public}d", DEFAULT_SAFE_VOLUME_TIMEOUT);
3221 return DEFAULT_SAFE_VOLUME_TIMEOUT;
3222 }
3223 return safeVolumeTimeout_;
3224 }
3225
SetFirstBoot(bool isFirst)3226 void AudioAdapterManager::SetFirstBoot(bool isFirst)
3227 {
3228 int32_t ret = 0;
3229 if (isFirst) {
3230 ret = SetParameter("persist.multimedia.audio.firstboot", std::to_string(1).c_str());
3231 } else {
3232 ret = SetParameter("persist.multimedia.audio.firstboot", std::to_string(0).c_str());
3233 }
3234 if (ret == 0) {
3235 AUDIO_INFO_LOG("Set first boot %{public}d success", isFirst);
3236 } else {
3237 AUDIO_ERR_LOG("Set first boot %{public}d failed, result %{public}d", isFirst, ret);
3238 }
3239 }
3240
SafeVolumeDump(std::string & dumpString)3241 void AudioAdapterManager::SafeVolumeDump(std::string &dumpString)
3242 {
3243 dumpString += "SafeVolume info:\n";
3244 for (auto &streamType : defaultVolumeTypeList_) {
3245 AppendFormat(dumpString, " - samplingAudioStreamTypeate: %d", streamType);
3246 AppendFormat(dumpString, " volumeLevel: %d\n", volumeDataMaintainer_.GetStreamVolume(streamType));
3247 AppendFormat(dumpString, " - AudioStreamType: %d", streamType);
3248 AppendFormat(dumpString, " streamMuteStatus: %d\n", volumeDataMaintainer_.GetStreamMute(streamType));
3249 }
3250 if (isSafeBoot_) {
3251 safeStatusBt_ = GetCurrentDeviceSafeStatus(DEVICE_TYPE_BLUETOOTH_A2DP);
3252 safeStatus_ = GetCurrentDeviceSafeStatus(DEVICE_TYPE_WIRED_HEADSET);
3253 safeActiveBtTime_ = GetCurentDeviceSafeTime(DEVICE_TYPE_BLUETOOTH_A2DP);
3254 safeActiveTime_ = GetCurentDeviceSafeTime(DEVICE_TYPE_WIRED_HEADSET);
3255 isSafeBoot_ = false;
3256 }
3257 std::string statusBt = (safeStatusBt_ == SAFE_ACTIVE) ? "SAFE_ACTIVE" : "SAFE_INACTIVE";
3258 std::string status = (safeStatus_ == SAFE_ACTIVE) ? "SAFE_ACTIVE" : "SAFE_INACTIVE";
3259 AppendFormat(dumpString, " - ringerMode: %d\n", ringerMode_);
3260 AppendFormat(dumpString, " - SafeVolume: %d\n", safeVolume_);
3261 AppendFormat(dumpString, " - BtSafeStatus: %s\n", statusBt.c_str());
3262 AppendFormat(dumpString, " - SafeStatus: %s\n", status.c_str());
3263 AppendFormat(dumpString, " - ActiveBtSafeTime: %lld\n", safeActiveBtTime_);
3264 AppendFormat(dumpString, " - ActiveSafeTime: %lld\n", safeActiveTime_);
3265 }
3266
SetVgsVolumeSupported(bool isVgsSupported)3267 void AudioAdapterManager::SetVgsVolumeSupported(bool isVgsSupported)
3268 {
3269 AUDIO_INFO_LOG("Set Vgs Supported: %{public}d", isVgsSupported);
3270 isVgsVolumeSupported_ = isVgsSupported;
3271 AudioVolume::GetInstance()->SetVgsVolumeSupported(isVgsSupported);
3272 }
3273
IsVgsVolumeSupported() const3274 bool AudioAdapterManager::IsVgsVolumeSupported() const
3275 {
3276 if (currentActiveDevice_.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO) {
3277 return false;
3278 }
3279 return isVgsVolumeSupported_;
3280 }
3281
GetStreamVolumeInfo(AdjustStreamVolume volumeType)3282 std::vector<AdjustStreamVolumeInfo> AudioAdapterManager::GetStreamVolumeInfo(AdjustStreamVolume volumeType)
3283 {
3284 return AudioVolume::GetInstance()->GetStreamVolumeInfo(volumeType);
3285 }
3286
UpdateVolumeForLowLatency()3287 void AudioAdapterManager::UpdateVolumeForLowLatency()
3288 {
3289 Trace trace("AudioAdapterManager::UpdateVolumeForLowLatency");
3290 // update volumes for low latency streams when loading volumes from the database.
3291 Volume vol = {false, 1.0f, 0};
3292 DeviceType curOutputDeviceType = currentActiveDevice_.deviceType_;
3293 for (auto iter = VOLUME_TYPE_LIST.begin(); iter != VOLUME_TYPE_LIST.end(); iter++) {
3294 vol.isMute = GetStreamMute(*iter);
3295 vol.volumeInt = static_cast<uint32_t>(GetSystemVolumeLevelNoMuteState(*iter));
3296 vol.volumeFloat = GetSystemVolumeInDb(*iter, (vol.isMute ? 0 : vol.volumeInt), curOutputDeviceType);
3297 AudioVolumeManager::GetInstance().SetSharedVolume(*iter, curOutputDeviceType, vol);
3298 }
3299 AudioVolumeManager::GetInstance().SetSharedAbsVolumeScene(IsAbsVolumeScene());
3300 }
3301
RegisterDoNotDisturbStatus()3302 void AudioAdapterManager::RegisterDoNotDisturbStatus()
3303 {
3304 AudioSettingProvider &settingProvider = AudioSettingProvider::GetInstance(AUDIO_POLICY_SERVICE_ID);
3305 AudioSettingObserver::UpdateFunc updateFuncDoNotDisturb = [&](const std::string &key) {
3306 int32_t isDoNotDisturb = 0;
3307 int32_t ret = settingProvider.GetIntValue(DO_NOT_DISTURB_STATUS, isDoNotDisturb, "secure");
3308 CHECK_AND_RETURN_LOG(ret == SUCCESS, "get doNotDisturbStatus failed");
3309 AUDIO_INFO_LOG("doNotDisturbStatus = %{public}s", isDoNotDisturb != 0 ? "true" : "false");
3310 auto audioVolume = AudioVolume::GetInstance();
3311 CHECK_AND_RETURN_LOG(audioVolume != nullptr, "audioVolume handle null, set DoNotDisturbStatus failed");
3312 audioVolume->SetDoNotDisturbStatus(isDoNotDisturb != 0);
3313 };
3314 sptr observer = settingProvider.CreateObserver(DO_NOT_DISTURB_STATUS, updateFuncDoNotDisturb);
3315 ErrCode ret = settingProvider.RegisterObserver(observer, "secure");
3316 if (ret != ERR_OK) {
3317 AUDIO_ERR_LOG("RegisterObserver doNotDisturbStatus failed! Err: %{public}d", ret);
3318 } else {
3319 AUDIO_INFO_LOG("Register doNotDisturbStatus successfully");
3320 }
3321 }
3322
RegisterDoNotDisturbStatusWhiteList()3323 void AudioAdapterManager::RegisterDoNotDisturbStatusWhiteList()
3324 {
3325 AudioSettingProvider &settingProvider = AudioSettingProvider::GetInstance(AUDIO_POLICY_SERVICE_ID);
3326 AudioSettingObserver::UpdateFunc updateFuncDoNotDisturbWhiteList = [&](const std::string &key) {
3327 std::vector<std::map<std::string, std::string>> doNotDisturbWhiteList;
3328 int32_t ret = settingProvider.GetMapValue(DO_NOT_DISTURB_STATUS_WHITE_LIST,
3329 doNotDisturbWhiteList, "secure");
3330 CHECK_AND_RETURN_LOG(ret == SUCCESS, "get doNotDisturbStatus WhiteList failed");
3331 AUDIO_INFO_LOG("doNotDisturbStatusWhiteList changed");
3332 auto audioVolume = AudioVolume::GetInstance();
3333 CHECK_AND_RETURN_LOG(audioVolume != nullptr, "audioVolume handle null, \
3334 set doNotDisturbStatusWhiteList failed");
3335 audioVolume->SetDoNotDisturbStatusWhiteListVolume(doNotDisturbWhiteList);
3336 };
3337 sptr observer = settingProvider.CreateObserver(DO_NOT_DISTURB_STATUS_WHITE_LIST,
3338 updateFuncDoNotDisturbWhiteList);
3339 ErrCode ret = settingProvider.RegisterObserver(observer, "secure");
3340 if (ret != ERR_OK) {
3341 AUDIO_ERR_LOG("RegisterObserver doNotDisturbStatus WhiteList failed! Err: %{public}d", ret);
3342 } else {
3343 AUDIO_INFO_LOG("Register doNotDisturbStatus WhiteList successfully");
3344 }
3345 }
3346
HandleHearingAidVolume(AudioStreamType streamType)3347 void AudioAdapterManager::HandleHearingAidVolume(AudioStreamType streamType)
3348 {
3349 if (currentActiveDevice_.deviceType_ == DEVICE_TYPE_HEARING_AID) {
3350 if (streamType == STREAM_MUSIC || streamType == STREAM_VOICE_CALL ||
3351 streamType == STREAM_VOICE_ASSISTANT) {
3352 int32_t defaultVolume = static_cast<int32_t>(std::ceil(GetMaxVolumeLevel(streamType) * 0.8));
3353 AUDIO_INFO_LOG("first time switch hearingAid, use default volume");
3354 SetSystemVolumeLevel(streamType, defaultVolume);
3355 }
3356 }
3357 }
3358
SetSystemVolumeDegree(AudioStreamType streamType,int32_t volumeDegree)3359 int32_t AudioAdapterManager::SetSystemVolumeDegree(AudioStreamType streamType, int32_t volumeDegree)
3360 {
3361 Trace trace("streamType:" + std::to_string(streamType) + ", volumeDegree:" + std::to_string(volumeDegree));
3362 AUDIO_INFO_LOG("streamType: %{public}d, deviceType: %{public}d, volumeDegree:%{public}d",
3363 streamType, currentActiveDevice_.deviceType_, volumeDegree);
3364 if (GetSystemVolumeDegree(streamType) == volumeDegree &&
3365 currentActiveDevice_.deviceType_ != DEVICE_TYPE_BLUETOOTH_SCO &&
3366 currentActiveDevice_.deviceType_ != DEVICE_TYPE_BLUETOOTH_A2DP && !VolumeUtils::IsPCVolumeEnable()) {
3367 AUDIO_INFO_LOG("The volume is the same as before.");
3368 return SUCCESS;
3369 }
3370
3371 if (volumeDegree == 0 && !VolumeUtils::IsPCVolumeEnable() &&
3372 (streamType == STREAM_VOICE_CALL ||
3373 streamType == STREAM_ALARM || streamType == STREAM_ACCESSIBILITY ||
3374 streamType == STREAM_VOICE_COMMUNICATION)) {
3375 // these types can not set to mute, but don't return error
3376 AUDIO_ERR_LOG("this type can not set mute");
3377 return SUCCESS;
3378 }
3379
3380 int32_t minRet = GetMinVolumeDegree(streamType);
3381 CHECK_AND_RETURN_RET_LOG(volumeDegree >= minRet && volumeDegree <= MAX_VOLUME_DEGREE, ERR_OPERATION_FAILED,
3382 "volume not in scope, mimRet:%{public}d", minRet);
3383
3384 volumeDataMaintainer_.SetVolumeDegree(streamType, volumeDegree);
3385
3386 if (handler_ != nullptr) {
3387 if (Util::IsDualToneStreamType(streamType) && currentActiveDevice_.deviceType_ != DEVICE_TYPE_REMOTE_CAST) {
3388 AUDIO_INFO_LOG("DualToneStreamType. Save volume for speaker.");
3389 handler_->SendSaveVolumeDegree(DEVICE_TYPE_SPEAKER, streamType, volumeDegree, "LocalDevice");
3390 } else {
3391 handler_->SendSaveVolumeDegree(currentActiveDevice_.deviceType_, streamType, volumeDegree,
3392 currentActiveDevice_.networkId_);
3393 }
3394 }
3395
3396 float volumeDb = CalculateVolumeDb(volumeDegree, MAX_VOLUME_DEGREE);
3397 if (streamType == STREAM_VOICE_CALL_ASSISTANT) {
3398 volumeDb = 1.0f;
3399 }
3400 AUDIO_INFO_LOG("streamType:%{public}d volumeDb:%{public}f volumeDegree:%{public}d devicetype:%{public}d",
3401 streamType, volumeDb, volumeDegree, currentActiveDevice_.deviceType_);
3402 SetAudioVolume(streamType, volumeDb);
3403 return SUCCESS;
3404 }
3405
GetSystemVolumeDegree(AudioStreamType streamType)3406 int32_t AudioAdapterManager::GetSystemVolumeDegree(AudioStreamType streamType)
3407 {
3408 if (GetStreamMuteInternal(streamType)) {
3409 return MIN_VOLUME_LEVEL;
3410 }
3411
3412 return volumeDataMaintainer_.GetVolumeDegree(streamType);
3413 }
3414
GetMinVolumeDegree(AudioVolumeType volumeType)3415 int32_t AudioAdapterManager::GetMinVolumeDegree(AudioVolumeType volumeType)
3416 {
3417 CHECK_AND_RETURN_RET_LOG(volumeType >= STREAM_VOICE_CALL && volumeType <= STREAM_TYPE_MAX,
3418 MIN_VOLUME_LEVEL, "Invalid stream type");
3419 return MIN_VOLUME_LEVEL;
3420 }
3421
3422 // LCOV_EXCL_STOP
3423 } // namespace AudioStandard
3424 } // namespace OHOS
3425