• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 "AudioPolicyConfigManager"
17 #endif
18 
19 #include "audio_policy_config_manager.h"
20 #include "audio_policy_config_parser.h"
21 #include "audio_policy_utils.h"
22 #include "audio_policy_service.h"
23 #include "audio_ec_manager.h"
24 
25 namespace OHOS {
26 namespace AudioStandard {
27 
28 constexpr int32_t MS_PER_S = 1000;
29 static const unsigned int BUFFER_CALC_20MS = 20;
30 static const char* MAX_RENDERERS_NAME = "maxRenderers";
31 static const char* MAX_CAPTURERS_NAME = "maxCapturers";
32 static const char* MAX_FAST_RENDERERS_NAME = "maxFastRenderers";
33 
34 const int32_t DEFAULT_MAX_OUTPUT_NORMAL_INSTANCES = 128;
35 const int32_t DEFAULT_MAX_INPUT_NORMAL_INSTANCES = 16;
36 const int32_t DEFAULT_MAX_FAST_NORMAL_INSTANCES = 6;
37 
38 const uint32_t PC_MIC_CHANNEL_NUM = 4;
39 const uint32_t HEADPHONE_CHANNEL_NUM = 2;
40 
41 const uint32_t FRAMES_PER_SEC = 50;
42 
43 // next: configed in xml
44 const std::set<AudioSampleFormat> FAST_OUTPUT_SUPPORTED_FORMATS = {
45     SAMPLE_S16LE,
46     SAMPLE_S32LE,
47     SAMPLE_F32LE
48 };
49 
50 const std::map<DeviceType, ClassType> dynamicCaptureConfigMap = {
51     { DEVICE_TYPE_USB_ARM_HEADSET, ClassType::TYPE_USB },
52 };
53 
Init(bool isRefresh)54 bool AudioPolicyConfigManager::Init(bool isRefresh)
55 {
56     if (xmlHasLoaded_ && !isRefresh) {
57         AUDIO_WARNING_LOG("Unexpected Duplicate Load AudioPolicyConfig!");
58         return false;
59     }
60     std::unique_ptr<AudioPolicyConfigParser> audioPolicyConfigParser = make_unique<AudioPolicyConfigParser>(this);
61     CHECK_AND_RETURN_RET_LOG(audioPolicyConfigParser != nullptr, false, "AudioPolicyConfigParser create failed");
62     bool ret = audioPolicyConfigParser->LoadConfiguration();
63     if (!ret) {
64         AudioPolicyUtils::GetInstance().WriteServiceStartupError("Audio Policy Config Load Configuration failed");
65         AUDIO_ERR_LOG("Audio Policy Config Load Configuration failed");
66         return ret;
67     }
68     xmlHasLoaded_ = true;
69     return ret;
70 }
71 
OnAudioPolicyConfigXmlParsingCompleted()72 void AudioPolicyConfigManager::OnAudioPolicyConfigXmlParsingCompleted()
73 {
74     AUDIO_INFO_LOG("AdapterInfo num [%{public}zu]", audioPolicyConfig_.adapterInfoMap.size());
75     CHECK_AND_RETURN_LOG(!audioPolicyConfig_.adapterInfoMap.empty(),
76         "Parse audio policy xml failed, received data is empty");
77 
78     audioPolicyConfig_.Reorganize();
79 
80     isAdapterInfoMap_.store(true);
81 
82     OnHasEarpiece();
83 }
84 
OnXmlParsingCompleted(const std::unordered_map<ClassType,std::list<AudioModuleInfo>> & xmlData)85 void AudioPolicyConfigManager::OnXmlParsingCompleted(
86     const std::unordered_map<ClassType, std::list<AudioModuleInfo>> &xmlData)
87 {
88     AUDIO_INFO_LOG("device class num [%{public}zu]", xmlData.size());
89     CHECK_AND_RETURN_LOG(!xmlData.empty(), "failed to parse xml file. Received data is empty");
90 
91     deviceClassInfo_ = xmlData;
92 }
93 
OnAudioLatencyParsed(uint64_t latency)94 void AudioPolicyConfigManager::OnAudioLatencyParsed(uint64_t latency)
95 {
96     audioLatencyInMsec_ = latency;
97 }
98 
OnFastFormatParsed(AudioSampleFormat format)99 void AudioPolicyConfigManager::OnFastFormatParsed(AudioSampleFormat format)
100 {
101     AUDIO_INFO_LOG("fast format is %{public}d", fastFormat_);
102     fastFormat_ = format;
103 }
104 
GetFastFormat() const105 AudioSampleFormat AudioPolicyConfigManager::GetFastFormat() const
106 {
107     return fastFormat_;
108 }
109 
OnSinkLatencyParsed(uint32_t latency)110 void AudioPolicyConfigManager::OnSinkLatencyParsed(uint32_t latency)
111 {
112     sinkLatencyInMsec_ = latency;
113 }
114 
OnVolumeGroupParsed(std::unordered_map<std::string,std::string> & volumeGroupData)115 void AudioPolicyConfigManager::OnVolumeGroupParsed(std::unordered_map<std::string, std::string>& volumeGroupData)
116 {
117     AUDIO_INFO_LOG("group data num [%{public}zu]", volumeGroupData.size());
118     CHECK_AND_RETURN_LOG(!volumeGroupData.empty(), "failed to parse xml file. Received data is empty");
119 
120     volumeGroupData_ = volumeGroupData;
121 }
122 
OnInterruptGroupParsed(std::unordered_map<std::string,std::string> & interruptGroupData)123 void AudioPolicyConfigManager::OnInterruptGroupParsed(std::unordered_map<std::string, std::string>& interruptGroupData)
124 {
125     AUDIO_INFO_LOG("group data num [%{public}zu]", interruptGroupData.size());
126     CHECK_AND_RETURN_LOG(!interruptGroupData.empty(), "failed to parse xml file. Received data is empty");
127 
128     interruptGroupData_ = interruptGroupData;
129 }
130 
OnUpdateRouteSupport(bool isSupported)131 void AudioPolicyConfigManager::OnUpdateRouteSupport(bool isSupported)
132 {
133     isUpdateRouteSupported_ = isSupported;
134 }
135 
OnUpdateDefaultAdapter(bool isEnable)136 void AudioPolicyConfigManager::OnUpdateDefaultAdapter(bool isEnable)
137 {
138     isDefaultAdapterEnable_ = isEnable;
139 }
140 
GetDefaultAdapterEnable()141 bool AudioPolicyConfigManager::GetDefaultAdapterEnable()
142 {
143     return isDefaultAdapterEnable_;
144 }
145 
OnGlobalConfigsParsed(PolicyGlobalConfigs & globalConfigs)146 void AudioPolicyConfigManager::OnGlobalConfigsParsed(PolicyGlobalConfigs &globalConfigs)
147 {
148     globalConfigs_ = globalConfigs;
149 }
150 
OnVoipConfigParsed(bool enableFastVoip)151 void AudioPolicyConfigManager::OnVoipConfigParsed(bool enableFastVoip)
152 {
153     enableFastVoip_ = enableFastVoip;
154 }
155 
OnUpdateAnahsSupport(std::string anahsShowType)156 void AudioPolicyConfigManager::OnUpdateAnahsSupport(std::string anahsShowType)
157 {
158     AUDIO_INFO_LOG("show type: %{public}s", anahsShowType.c_str());
159     AudioPolicyService::GetAudioPolicyService().OnUpdateAnahsSupport(anahsShowType);
160 }
161 
OnUpdateEac3Support(bool isSupported)162 void AudioPolicyConfigManager::OnUpdateEac3Support(bool isSupported)
163 {
164     isSupportEac3_ = isSupported;
165 }
166 
OnHasEarpiece()167 void AudioPolicyConfigManager::OnHasEarpiece()
168 {
169     for (const auto &adapterInfo : audioPolicyConfig_.adapterInfoMap) {
170         hasEarpiece_ = std::any_of(adapterInfo.second->deviceInfos.begin(), adapterInfo.second->deviceInfos.end(),
171             [](const auto& deviceInfo) {
172                 return deviceInfo->type_ == DEVICE_TYPE_EARPIECE;
173             });
174         if (hasEarpiece_) {
175             break;
176         }
177     }
178     audioDeviceManager_.UpdateEarpieceStatus(hasEarpiece_);
179 }
180 
ConvertDeviceStreamInfoToStreamPropInfo(const DeviceStreamInfo & deviceStreamInfo,std::list<std::shared_ptr<PipeStreamPropInfo>> & streamPropInfos)181 static void ConvertDeviceStreamInfoToStreamPropInfo(const DeviceStreamInfo &deviceStreamInfo,
182     std::list<std::shared_ptr<PipeStreamPropInfo>> &streamPropInfos)
183 {
184     for (const auto &rate : deviceStreamInfo.samplingRate) {
185         for (const auto &layout : deviceStreamInfo.channelLayout) {
186             std::shared_ptr<PipeStreamPropInfo> streamProp = std::make_shared<PipeStreamPropInfo>();
187             CHECK_AND_RETURN_LOG(streamProp != nullptr, "alloc fail");
188             streamProp->format_ = deviceStreamInfo.format;
189             streamProp->sampleRate_ = static_cast<uint32_t>(rate);
190             streamProp->channelLayout_ = layout;
191             streamProp->channels_ = AudioDefinitionPolicyUtils::ConvertLayoutToAudioChannel(layout);
192             streamProp->bufferSize_ = AudioDefinitionPolicyUtils::PcmFormatToBytes(streamProp->format_) *
193                 streamProp->sampleRate_ * streamProp->channels_ / FRAMES_PER_SEC;
194             streamPropInfos.push_back(streamProp);
195         }
196     }
197 }
198 
UpdateStreamPropInfo(const std::string & adapterName,const std::string & pipeName,const std::list<DeviceStreamInfo> & deviceStreamInfo,const std::list<std::string> & supportDevices)199 void AudioPolicyConfigManager::UpdateStreamPropInfo(const std::string &adapterName, const std::string &pipeName,
200     const std::list<DeviceStreamInfo> &deviceStreamInfo, const std::list<std::string> &supportDevices)
201 {
202     CHECK_AND_RETURN_LOG(deviceStreamInfo.size() > 0, "deviceStreamInfo is empty");
203     std::list<std::shared_ptr<PipeStreamPropInfo>> streamProps;
204     for (auto &deviceStream : deviceStreamInfo) {
205         std::list<std::shared_ptr<PipeStreamPropInfo>> tmpStreamProps;
206         ConvertDeviceStreamInfoToStreamPropInfo(deviceStream, tmpStreamProps);
207         streamProps.splice(streamProps.end(), tmpStreamProps);
208     }
209     for (auto &streamProp : streamProps) {
210         for (auto &deviceName : supportDevices) {
211             CHECK_AND_CONTINUE_LOG(streamProp != nullptr, "streamProp is nullptr");
212             streamProp->supportDevices_.push_back(deviceName);
213         }
214     }
215     audioPolicyConfig_.UpdateDynamicStreamProps(adapterName, pipeName, streamProps);
216 }
217 
ClearStreamPropInfo(const std::string & adapterName,const std::string & pipeName)218 void AudioPolicyConfigManager::ClearStreamPropInfo(const std::string &adapterName, const std::string &pipeName)
219 {
220     audioPolicyConfig_.ClearDynamicStreamProps(adapterName, pipeName);
221 }
222 
SetNormalVoipFlag(const bool & normalVoipFlag)223 void AudioPolicyConfigManager::SetNormalVoipFlag(const bool &normalVoipFlag)
224 {
225     normalVoipFlag_ = normalVoipFlag;
226 }
227 
228 
GetNormalVoipFlag()229 bool AudioPolicyConfigManager::GetNormalVoipFlag()
230 {
231     return normalVoipFlag_;
232 }
233 
GetModuleListByType(ClassType type,std::list<AudioModuleInfo> & moduleList)234 bool AudioPolicyConfigManager::GetModuleListByType(ClassType type, std::list<AudioModuleInfo>& moduleList)
235 {
236     auto modulesPos = deviceClassInfo_.find(type);
237     if (modulesPos != deviceClassInfo_.end()) {
238         moduleList = modulesPos->second;
239         return true;
240     }
241     return false;
242 }
243 
UpdateDynamicCapturerConfig(ClassType type,const AudioModuleInfo moduleInfo)244 void AudioPolicyConfigManager::UpdateDynamicCapturerConfig(ClassType type, const AudioModuleInfo moduleInfo)
245 {
246     dynamicCapturerConfig_[type] = moduleInfo;
247 }
248 
GetDeviceClassInfo(std::unordered_map<ClassType,std::list<AudioModuleInfo>> & deviceClassInfo)249 void AudioPolicyConfigManager::GetDeviceClassInfo(
250     std::unordered_map<ClassType, std::list<AudioModuleInfo>> &deviceClassInfo)
251 {
252     deviceClassInfo = deviceClassInfo_;
253 }
254 
GetGroupName(const std::string & deviceName,const GroupType type)255 std::string AudioPolicyConfigManager::GetGroupName(const std::string& deviceName, const GroupType type)
256 {
257     std::string groupName = GROUP_NAME_NONE;
258     if (type == VOLUME_TYPE) {
259         auto iter = volumeGroupData_.find(deviceName);
260         if (iter != volumeGroupData_.end()) {
261             groupName = iter->second;
262         }
263     } else {
264         auto iter = interruptGroupData_.find(deviceName);
265         if (iter != interruptGroupData_.end()) {
266             groupName = iter->second;
267         }
268     }
269     return groupName;
270 }
271 
GetMaxRendererInstances()272 int32_t AudioPolicyConfigManager::GetMaxRendererInstances()
273 {
274     for (auto commonConfig : globalConfigs_.commonConfigs_) {
275         if (commonConfig.name_ != MAX_RENDERERS_NAME) {
276             continue;
277         }
278         int32_t convertValue = 0;
279         AUDIO_INFO_LOG("Max instance is %{public}s", commonConfig.value_.c_str());
280         CHECK_AND_RETURN_RET_LOG(StringConverter(commonConfig.value_, convertValue),
281             DEFAULT_MAX_OUTPUT_NORMAL_INSTANCES,
282             "convert invalid configInfo.value_: %{public}s", commonConfig.value_.c_str());
283         return convertValue;
284     }
285     return DEFAULT_MAX_OUTPUT_NORMAL_INSTANCES;
286 }
287 
GetMaxCapturersInstances()288 int32_t AudioPolicyConfigManager::GetMaxCapturersInstances()
289 {
290     for (auto commonConfig : globalConfigs_.commonConfigs_) {
291         if (commonConfig.name_ != MAX_CAPTURERS_NAME) {
292             continue;
293         }
294         int32_t convertValue = 0;
295         AUDIO_INFO_LOG("Max input normal instance is %{public}s", commonConfig.value_.c_str());
296         CHECK_AND_RETURN_RET_LOG(StringConverter(commonConfig.value_, convertValue),
297             DEFAULT_MAX_INPUT_NORMAL_INSTANCES,
298             "convert invalid configInfo.value_: %{public}s", commonConfig.value_.c_str());
299         return convertValue;
300     }
301     return DEFAULT_MAX_INPUT_NORMAL_INSTANCES;
302 }
303 
GetMaxFastRenderersInstances()304 int32_t AudioPolicyConfigManager::GetMaxFastRenderersInstances()
305 {
306     for (auto commonConfig : globalConfigs_.commonConfigs_) {
307         if (commonConfig.name_ != MAX_FAST_RENDERERS_NAME) {
308             continue;
309         }
310         int32_t convertValue = 0;
311         AUDIO_INFO_LOG("Max Fast Renderer instance is %{public}s", commonConfig.value_.c_str());
312         CHECK_AND_RETURN_RET_LOG(StringConverter(commonConfig.value_, convertValue),
313             DEFAULT_MAX_FAST_NORMAL_INSTANCES,
314             "convert invalid configInfo.value_: %{public}s", commonConfig.value_.c_str());
315         return convertValue;
316     }
317     return DEFAULT_MAX_FAST_NORMAL_INSTANCES;
318 }
319 
GetVoipRendererFlag(const std::string & sinkPortName,const std::string & networkId,const AudioSamplingRate & samplingRate)320 int32_t AudioPolicyConfigManager::GetVoipRendererFlag(const std::string &sinkPortName, const std::string &networkId,
321     const AudioSamplingRate &samplingRate)
322 {
323     // VoIP stream has three mode for different products.
324     if (enableFastVoip_ && (sinkPortName == PRIMARY_SPEAKER && networkId == LOCAL_NETWORK_ID)) {
325         if (samplingRate != SAMPLE_RATE_48000 && samplingRate != SAMPLE_RATE_16000) {
326             return AUDIO_FLAG_NORMAL;
327         }
328         return AUDIO_FLAG_VOIP_FAST;
329     } else if (!normalVoipFlag_ && (sinkPortName == PRIMARY_SPEAKER) && (networkId == LOCAL_NETWORK_ID)) {
330         AUDIO_INFO_LOG("Direct VoIP mode is supported for the device");
331         return AUDIO_FLAG_VOIP_DIRECT;
332     }
333 
334     return AUDIO_FLAG_NORMAL;
335 }
336 
GetAudioLatencyFromXml() const337 int32_t AudioPolicyConfigManager::GetAudioLatencyFromXml() const
338 {
339     return audioLatencyInMsec_;
340 }
341 
GetSinkLatencyFromXml() const342 uint32_t AudioPolicyConfigManager::GetSinkLatencyFromXml() const
343 {
344     return sinkLatencyInMsec_;
345 }
346 
GetAudioAdapterInfos(std::unordered_map<AudioAdapterType,std::shared_ptr<PolicyAdapterInfo>> & adapterInfoMap)347 void AudioPolicyConfigManager::GetAudioAdapterInfos(
348     std::unordered_map<AudioAdapterType, std::shared_ptr<PolicyAdapterInfo>> &adapterInfoMap)
349 {
350     adapterInfoMap = audioPolicyConfig_.adapterInfoMap;
351 }
352 
GetVolumeGroupData(std::unordered_map<std::string,std::string> & volumeGroupData)353 void AudioPolicyConfigManager::GetVolumeGroupData(std::unordered_map<std::string, std::string>& volumeGroupData)
354 {
355     volumeGroupData = volumeGroupData_;
356 }
357 
GetInterruptGroupData(std::unordered_map<std::string,std::string> & interruptGroupData)358 void AudioPolicyConfigManager::GetInterruptGroupData(std::unordered_map<std::string, std::string>& interruptGroupData)
359 {
360     interruptGroupData = interruptGroupData_;
361 }
362 
GetGlobalConfigs(PolicyGlobalConfigs & globalConfigs)363 void AudioPolicyConfigManager::GetGlobalConfigs(PolicyGlobalConfigs &globalConfigs)
364 {
365     globalConfigs = globalConfigs_;
366 }
367 
GetVoipConfig()368 bool AudioPolicyConfigManager::GetVoipConfig()
369 {
370     return enableFastVoip_;
371 }
372 
GetUpdateRouteSupport()373 bool AudioPolicyConfigManager::GetUpdateRouteSupport()
374 {
375     return isUpdateRouteSupported_;
376 }
377 
GetAdapterInfoFlag()378 bool AudioPolicyConfigManager::GetAdapterInfoFlag()
379 {
380     return isAdapterInfoMap_.load();
381 }
382 
GetAdapterInfoByType(AudioAdapterType type,std::shared_ptr<PolicyAdapterInfo> & info)383 bool AudioPolicyConfigManager::GetAdapterInfoByType(AudioAdapterType type, std::shared_ptr<PolicyAdapterInfo> &info)
384 {
385     auto it = audioPolicyConfig_.adapterInfoMap.find(type);
386     if (it == audioPolicyConfig_.adapterInfoMap.end()) {
387         AUDIO_ERR_LOG("can not find adapter info");
388         return false;
389     }
390     info = it->second;
391     return true;
392 }
393 
GetHasEarpiece()394 bool AudioPolicyConfigManager::GetHasEarpiece()
395 {
396     return hasEarpiece_;
397 }
398 
IsFastStreamSupported(AudioStreamInfo & streamInfo,std::vector<std::shared_ptr<AudioDeviceDescriptor>> & desc)399 bool AudioPolicyConfigManager::IsFastStreamSupported(AudioStreamInfo &streamInfo,
400     std::vector<std::shared_ptr<AudioDeviceDescriptor>> &desc)
401 {
402     bool isSupported = false;
403     AudioFlag audioFlag;
404     std::shared_ptr<AdapterDeviceInfo> deviceInfo = nullptr;
405 
406     for (auto &audioDeviceDescriptor : desc) {
407         CHECK_AND_CONTINUE_LOG(audioDeviceDescriptor != nullptr, "audioDeviceDescriptor is nullptr");
408         if (audioDeviceDescriptor->deviceRole_ == INPUT_DEVICE) {
409             audioFlag = AUDIO_INPUT_FLAG_FAST;
410         } else if (audioDeviceDescriptor->deviceRole_ == OUTPUT_DEVICE) {
411             audioFlag = AUDIO_OUTPUT_FLAG_FAST;
412         } else {
413             continue;
414         }
415 
416         deviceInfo = audioPolicyConfig_.GetAdapterDeviceInfo(audioDeviceDescriptor->deviceType_,
417             audioDeviceDescriptor->deviceRole_, audioDeviceDescriptor->networkId_, audioFlag);
418         if (deviceInfo == nullptr) {
419             continue;
420         }
421         isSupported = GetFastStreamSupport(streamInfo, deviceInfo);
422         if (isSupported) {
423             break;
424         }
425     }
426 
427     return isSupported;
428 }
429 
GetFastStreamSupport(AudioStreamInfo & streamInfo,std::shared_ptr<AdapterDeviceInfo> & deviceInfo)430 bool AudioPolicyConfigManager::GetFastStreamSupport(AudioStreamInfo &streamInfo,
431     std::shared_ptr<AdapterDeviceInfo> &deviceInfo)
432 {
433     CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, false, "deviceInfo is nullptr");
434     if (deviceInfo->role_ != INPUT_DEVICE && deviceInfo->role_ != OUTPUT_DEVICE) {
435         return false;
436     }
437 
438     for (auto &pipeIt : deviceInfo->supportPipeMap_) {
439         if (pipeIt.second == nullptr) {
440             continue;
441         }
442         if ((pipeIt.second->supportFlags_ != AUDIO_INPUT_FLAG_FAST) &&
443             (pipeIt.second->supportFlags_ != AUDIO_OUTPUT_FLAG_FAST)) {
444             continue;
445         }
446 
447         // consider the logic of path support under format conversion
448         AudioSampleFormat tempFormat = streamInfo.format;
449         AudioChannelLayout tempLayout = streamInfo.channelLayout;
450 
451         tempFormat = ((tempFormat == SAMPLE_S32LE) || (tempFormat == SAMPLE_F32LE)) ? SAMPLE_S16LE : tempFormat;
452         tempLayout = (tempLayout == CH_LAYOUT_MONO) ? CH_LAYOUT_STEREO : tempLayout;
453 
454         for (auto it = pipeIt.second->streamPropInfos_.begin(); it != pipeIt.second->streamPropInfos_.end(); ++it) {
455             if ((*it)->format_ == tempFormat && (*it)->sampleRate_ == streamInfo.samplingRate &&
456                 (*it)->channelLayout_ == tempLayout) {
457                 return true;
458             }
459         }
460     }
461 
462     return false;
463 }
464 
GetStreamPropInfoSize(const std::string & adapterName,const std::string & pipeName)465 uint32_t AudioPolicyConfigManager::GetStreamPropInfoSize(const std::string &adapterName, const std::string &pipeName)
466 {
467     uint32_t size = audioPolicyConfig_.GetConfigStreamPropsSize(adapterName, pipeName);
468     CHECK_AND_RETURN_RET(size == 0, size);
469     AUDIO_INFO_LOG("no stream prop config, get dynamic size");
470     return audioPolicyConfig_.GetDynamicStreamPropsSize(adapterName, pipeName);
471 }
472 
GetRouteFlag(std::shared_ptr<AudioStreamDescriptor> & desc)473 uint32_t AudioPolicyConfigManager::GetRouteFlag(std::shared_ptr<AudioStreamDescriptor> &desc)
474 {
475     // device -> adapter -> flag -> stream
476     uint32_t flag = AUDIO_FLAG_NONE; // input or output? default?
477     auto newDeviceDesc = desc->newDeviceDescs_.front();
478     std::shared_ptr<AdapterDeviceInfo> deviceInfo = audioPolicyConfig_.GetAdapterDeviceInfo(newDeviceDesc->deviceType_,
479         newDeviceDesc->deviceRole_, newDeviceDesc->networkId_, desc->audioFlag_, newDeviceDesc->a2dpOffloadFlag_);
480     CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, flag, "Find device failed; use none flag");
481 
482     for (auto &pipeIt : deviceInfo->supportPipeMap_) {
483         if ((desc->audioMode_ == static_cast<AudioMode>(pipeIt.second->role_)) && (desc->audioFlag_ & pipeIt.first)) {
484             flag = pipeIt.first;
485             break;
486         }
487     }
488     if (flag == AUDIO_FLAG_NONE) {
489         flag = desc->audioMode_ == AUDIO_MODE_PLAYBACK ?
490             AUDIO_OUTPUT_FLAG_NORMAL : AUDIO_INPUT_FLAG_NORMAL;
491     }
492     AUDIO_INFO_LOG("SessionID: %{public}d, flag:0x%{public}x, target flag:0x%{public}x", desc->sessionId_,
493         desc->audioFlag_, flag);
494     return flag;
495 }
496 
GetTargetSourceTypeAndMatchingFlag(SourceType source,bool & useMatchingPropInfo)497 void AudioPolicyConfigManager::GetTargetSourceTypeAndMatchingFlag(SourceType source, bool &useMatchingPropInfo)
498 {
499     switch (source) {
500         case SOURCE_TYPE_VOICE_RECOGNITION:
501             useMatchingPropInfo = true;
502             break;
503         case SOURCE_TYPE_VOICE_COMMUNICATION:
504         case SOURCE_TYPE_VOICE_TRANSCRIPTION:
505             useMatchingPropInfo = AudioEcManager::GetInstance().GetEcFeatureEnable() ? false : true;
506             break;
507         case SOURCE_TYPE_VOICE_CALL:
508             break;
509         case SOURCE_TYPE_CAMCORDER:
510             break;
511         case SOURCE_TYPE_UNPROCESSED:
512             useMatchingPropInfo = AudioEcManager::GetInstance().GetEcFeatureEnable() ? false : true;
513             break;
514         default:
515             break;
516     }
517 }
518 
ParseFormat(std::string format)519 AudioSampleFormat AudioPolicyConfigManager::ParseFormat(std::string format)
520 {
521     auto it = AudioDefinitionPolicyUtils::formatStrToEnum.find(format);
522     if (it != AudioDefinitionPolicyUtils::formatStrToEnum.end()) {
523         return AudioDefinitionPolicyUtils::formatStrToEnum[format];
524     }
525     AUDIO_WARNING_LOG("invalid format:%{public}s, use default SAMPLE_S16LE", format.c_str());
526     return SAMPLE_S16LE;
527 }
CheckDynamicCapturerConfig(std::shared_ptr<AudioStreamDescriptor> desc,std::shared_ptr<PipeStreamPropInfo> & info)528 void AudioPolicyConfigManager::CheckDynamicCapturerConfig(std::shared_ptr<AudioStreamDescriptor> desc,
529     std::shared_ptr<PipeStreamPropInfo> &info)
530 {
531     CHECK_AND_RETURN_LOG(desc != nullptr && desc->newDeviceDescs_.size() > 0 &&
532         desc->newDeviceDescs_[0] != nullptr, "invalid streamDesc");
533     auto it = dynamicCaptureConfigMap.find(desc->newDeviceDescs_.front()->deviceType_);
534     if (it != dynamicCaptureConfigMap.end()) {
535         auto config = dynamicCapturerConfig_.find(it->second);
536         if (config != dynamicCapturerConfig_.end()) {
537             AUDIO_INFO_LOG("use dynamic config for %{public}d", it->first);
538             CHECK_AND_RETURN_LOG(StringConverter(config->second.rate, info->sampleRate_),
539                 "convert invalid sampleRate_: %{public}s", config->second.rate.c_str());
540             info->format_ = ParseFormat(config->second.format);
541         }
542     }
543 }
544 
GetStreamPropInfoForRecord(std::shared_ptr<AudioStreamDescriptor> desc,std::shared_ptr<AdapterPipeInfo> adapterPipeInfo,std::shared_ptr<PipeStreamPropInfo> & info,const AudioChannel & tempChannel)545 void AudioPolicyConfigManager::GetStreamPropInfoForRecord(
546     std::shared_ptr<AudioStreamDescriptor> desc, std::shared_ptr<AdapterPipeInfo> adapterPipeInfo,
547     std::shared_ptr<PipeStreamPropInfo> &info, const AudioChannel &tempChannel)
548 {
549     CHECK_AND_RETURN_LOG(desc != nullptr, "stream desc is nullptr");
550     CHECK_AND_RETURN_LOG(adapterPipeInfo != nullptr, "adapterPipeInfo is nullptr");
551     if (desc->routeFlag_ & AUDIO_INPUT_FLAG_FAST) {
552         auto fastStreamPropinfo = GetStreamPropInfoFromPipe(
553             adapterPipeInfo, desc->streamInfo_.format, desc->streamInfo_.samplingRate, tempChannel);
554         if (fastStreamPropinfo != nullptr) {
555             AUDIO_INFO_LOG("Find fast streamPropInfo from %{public}s", adapterPipeInfo->name_.c_str());
556             // Use *ptr to get copy and avoid modify the source data from XML
557             *info = *fastStreamPropinfo;
558             return;
559         }
560         AUDIO_WARNING_LOG("Find streamPropInfo %{public}s failed, choose normal route", adapterPipeInfo->name_.c_str());
561         desc->routeFlag_ = AUDIO_INPUT_FLAG_NORMAL;
562         adapterPipeInfo = GetNormalRecordAdapterInfo(desc);
563         CHECK_AND_RETURN_LOG(adapterPipeInfo != nullptr, "Get adapter info for normal capture failed");
564     }
565 
566     auto streamPropInfos = adapterPipeInfo->streamPropInfos_;
567     CHECK_AND_RETURN_LOG(streamPropInfos.size() > 0, "streamPropInfos is empty");
568     auto firstStreamPropInfo = streamPropInfos.front();
569     CHECK_AND_RETURN_LOG(firstStreamPropInfo != nullptr, "Get firstStreamPropInfo for normal capture failed");
570     // Use *ptr to get copy and avoid modify the source data from XML
571     *info = *firstStreamPropInfo;
572     bool useMatchingPropInfo = false;
573     GetTargetSourceTypeAndMatchingFlag(desc->capturerInfo_.sourceType, useMatchingPropInfo);
574     if (useMatchingPropInfo) {
575         auto streamProp = GetStreamPropInfoFromPipe(adapterPipeInfo, desc->streamInfo_.format,
576             desc->streamInfo_.samplingRate, tempChannel);
577         if (streamProp != nullptr) {
578             // Use *ptr to get copy and avoid modify the source data from XML
579             *info = *streamProp;
580         }
581     }
582 
583     CheckDynamicCapturerConfig(desc, info);
584 
585     if (AudioEcManager::GetInstance().GetEcFeatureEnable()) {
586         if (desc->newDeviceDescs_.front() != nullptr &&
587             desc->newDeviceDescs_.front()->deviceType_ != DEVICE_TYPE_MIC &&
588             info->channels_ == PC_MIC_CHANNEL_NUM) {
589             // only built-in mic can use 4 channel, update later by using xml to describe
590             info->channels_ = static_cast<AudioChannel>(HEADPHONE_CHANNEL_NUM);
591             info->channelLayout_ = CH_LAYOUT_STEREO;
592         }
593     }
594 
595 #ifndef IS_EMULATOR
596     // need change to use profile for all devices later
597     if (isUpdateRouteSupported_) {
598         uint32_t sampleFormatBits = AudioPolicyUtils::GetInstance().PcmFormatToBytes(info->format_);
599         info->bufferSize_ = BUFFER_CALC_20MS * info->sampleRate_ / static_cast<uint32_t>(MS_PER_S)
600             * info->channels_ * sampleFormatBits;
601     }
602 #endif
603 }
604 
GetNormalRecordAdapterInfo(std::shared_ptr<AudioStreamDescriptor> desc)605 std::shared_ptr<AdapterPipeInfo> AudioPolicyConfigManager::GetNormalRecordAdapterInfo(
606     std::shared_ptr<AudioStreamDescriptor> desc)
607 {
608     CHECK_AND_RETURN_RET_LOG(desc != nullptr && desc->newDeviceDescs_.size() > 0 &&
609         desc->newDeviceDescs_.front() != nullptr, nullptr, "Invalid device desc");
610     std::shared_ptr<AudioDeviceDescriptor> deviceDesc = desc->newDeviceDescs_.front();
611 
612     // Get adapter info for device
613     std::shared_ptr<AdapterDeviceInfo> deviceInfo = audioPolicyConfig_.GetAdapterDeviceInfo(deviceDesc->deviceType_,
614         deviceDesc->deviceRole_, deviceDesc->networkId_, AUDIO_INPUT_FLAG_NORMAL, deviceDesc->a2dpOffloadFlag_);
615     CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, nullptr, "Find device failed, none streamProp");
616 
617     // Get support pipes for normal stream
618     auto pipeIt = deviceInfo->supportPipeMap_.find(AUDIO_INPUT_FLAG_NORMAL);
619     CHECK_AND_RETURN_RET_LOG(pipeIt != deviceInfo->supportPipeMap_.end(), nullptr, "Flag not supported");
620 
621     return pipeIt->second;
622 }
623 
GetStreamPropInfo(std::shared_ptr<AudioStreamDescriptor> & desc,std::shared_ptr<PipeStreamPropInfo> & info)624 void AudioPolicyConfigManager::GetStreamPropInfo(std::shared_ptr<AudioStreamDescriptor> &desc,
625     std::shared_ptr<PipeStreamPropInfo> &info)
626 {
627     auto newDeviceDesc = desc->newDeviceDescs_.front();
628     std::shared_ptr<AdapterDeviceInfo> deviceInfo = audioPolicyConfig_.GetAdapterDeviceInfo(newDeviceDesc->deviceType_,
629         newDeviceDesc->deviceRole_, newDeviceDesc->networkId_, desc->audioFlag_, newDeviceDesc->a2dpOffloadFlag_);
630     CHECK_AND_RETURN_LOG(deviceInfo != nullptr, "Find device failed, none streamProp");
631 
632     auto pipeIt = deviceInfo->supportPipeMap_.find(desc->routeFlag_);
633     CHECK_AND_RETURN_LOG(pipeIt != deviceInfo->supportPipeMap_.end(), "Find pipeInfo failed;none streamProp");
634 
635     AudioStreamInfo temp = desc->streamInfo_;
636     UpdateBasicStreamInfo(desc, pipeIt->second, temp);
637 
638     if (desc->audioMode_ == AUDIO_MODE_RECORD) {
639         GetStreamPropInfoForRecord(desc, pipeIt->second, info, temp.channels);
640         return;
641     }
642 
643     auto streamProp = GetStreamPropInfoFromPipe(pipeIt->second, temp.format, temp.samplingRate, temp.channels);
644     if (streamProp != nullptr) {
645         info = streamProp;
646         return;
647     }
648 
649     if (SupportImplicitConversion(desc->routeFlag_)) {
650         info = pipeIt->second->streamPropInfos_.front();
651     }
652 
653     if (info->format_ == INVALID_WIDTH && info->sampleRate_ == 0 && info->channelLayout_ == CH_LAYOUT_UNKNOWN &&
654         desc->routeFlag_ != (AUDIO_OUTPUT_FLAG_NORMAL || AUDIO_INPUT_FLAG_NORMAL)) {
655         AUDIO_INFO_LOG("Find streamPropInfo failed, choose normal flag");
656         desc->routeFlag_ = desc->audioMode_ == AUDIO_MODE_PLAYBACK ?
657             AUDIO_OUTPUT_FLAG_NORMAL : AUDIO_INPUT_FLAG_NORMAL;
658         auto streamProp = GetStreamPropInfoFromPipe(pipeIt->second, desc->streamInfo_.format,
659             desc->streamInfo_.samplingRate, desc->streamInfo_.channels);
660         if (streamProp != nullptr) {
661             info = streamProp;
662             return;
663         }
664     }
665     if (info->format_ == INVALID_WIDTH && info->sampleRate_ == 0 && info->channelLayout_ == CH_LAYOUT_UNKNOWN &&
666         desc->routeFlag_ == (AUDIO_OUTPUT_FLAG_NORMAL || AUDIO_INPUT_FLAG_NORMAL) &&
667         !pipeIt->second->streamPropInfos_.empty()) {
668         info = pipeIt->second->streamPropInfos_.front();
669     } // if not match, choose first?
670 }
671 
UpdateBasicStreamInfo(std::shared_ptr<AudioStreamDescriptor> desc,std::shared_ptr<AdapterPipeInfo> pipeInfo,AudioStreamInfo & streamInfo)672 void AudioPolicyConfigManager::UpdateBasicStreamInfo(std::shared_ptr<AudioStreamDescriptor> desc,
673     std::shared_ptr<AdapterPipeInfo> pipeInfo, AudioStreamInfo &streamInfo)
674 {
675     if (desc == nullptr || pipeInfo == nullptr) {
676         AUDIO_WARNING_LOG("null desc or pipeInfo!");
677         return;
678     }
679 
680     if ((desc->routeFlag_ == (AUDIO_INPUT_FLAG_VOIP | AUDIO_INPUT_FLAG_FAST)) ||
681         (desc->routeFlag_ == (AUDIO_OUTPUT_FLAG_VOIP | AUDIO_OUTPUT_FLAG_FAST))) {
682         streamInfo.channels = desc->streamInfo_.channels == MONO ? STEREO : desc->streamInfo_.channels;
683     }
684 
685     if (desc->routeFlag_ == AUDIO_INPUT_FLAG_FAST) {
686         streamInfo.channels = desc->streamInfo_.channels == MONO ? STEREO : desc->streamInfo_.channels;
687     }
688 
689     if (pipeInfo->streamPropInfos_.empty()) {
690         AUDIO_WARNING_LOG("streamPropInfos_ is empty!");
691         return;
692     }
693 
694     if (desc->routeFlag_ == AUDIO_OUTPUT_FLAG_FAST) {
695         std::shared_ptr<PipeStreamPropInfo> propInfo = pipeInfo->streamPropInfos_.front();
696         if (propInfo == nullptr) {
697             AUDIO_WARNING_LOG("propInfo is null!");
698             return;
699         }
700         if (FAST_OUTPUT_SUPPORTED_FORMATS.count(streamInfo.format)) {
701             streamInfo.format = propInfo->format_; // for s32 or s16
702         }
703         streamInfo.channels = desc->streamInfo_.channels == MONO ? STEREO : desc->streamInfo_.channels;
704     }
705 }
706 
GetDynamicStreamPropInfoFromPipe(std::shared_ptr<AdapterPipeInfo> & info,AudioSampleFormat format,uint32_t sampleRate,AudioChannel channels)707 std::shared_ptr<PipeStreamPropInfo> AudioPolicyConfigManager::GetDynamicStreamPropInfoFromPipe(
708     std::shared_ptr<AdapterPipeInfo> &info, AudioSampleFormat format, uint32_t sampleRate, AudioChannel channels)
709 {
710     std::unique_lock<std::mutex> lock(info->dynamicMtx_);
711     CHECK_AND_RETURN_RET(info && !info->dynamicStreamPropInfos_.empty(), nullptr);
712 
713     std::shared_ptr<PipeStreamPropInfo> defaultStreamProp = nullptr;
714     AUDIO_INFO_LOG("use dynamic streamProp");
715     for (auto &streamProp : info->dynamicStreamPropInfos_) {
716         CHECK_AND_CONTINUE(streamProp && streamProp->sampleRate_ >= sampleRate);
717         CHECK_AND_RETURN_RET(streamProp->sampleRate_ != sampleRate, streamProp);
718         // find min sampleRate bigger than music sampleRate, eg: 44100 -> 48000 when has 32000, 48000, 96000, 192000
719         CHECK_AND_CONTINUE(defaultStreamProp == nullptr || (defaultStreamProp != nullptr &&
720             defaultStreamProp->sampleRate_ > streamProp->sampleRate_));
721         defaultStreamProp = streamProp;
722     }
723     CHECK_AND_RETURN_RET_LOG(defaultStreamProp != nullptr, info->dynamicStreamPropInfos_.back(),
724         "not match any streamProp");
725     return defaultStreamProp;
726 }
727 
GetStreamPropInfoFromPipe(std::shared_ptr<AdapterPipeInfo> & info,AudioSampleFormat format,uint32_t sampleRate,AudioChannel channels)728 std::shared_ptr<PipeStreamPropInfo> AudioPolicyConfigManager::GetStreamPropInfoFromPipe(
729     std::shared_ptr<AdapterPipeInfo> &info, AudioSampleFormat format, uint32_t sampleRate, AudioChannel channels)
730 {
731     std::shared_ptr<PipeStreamPropInfo> propInfo = GetDynamicStreamPropInfoFromPipe(info, format, sampleRate, channels);
732     CHECK_AND_RETURN_RET(propInfo == nullptr, propInfo);
733 
734     for (auto &streamProp : info->streamPropInfos_) {
735         if (streamProp->format_ == format &&
736             streamProp->sampleRate_ == sampleRate &&
737             streamProp->channels_ == channels) {
738             return streamProp;
739         }
740     }
741     return nullptr;
742 }
743 
SupportImplicitConversion(uint32_t routeFlag)744 bool AudioPolicyConfigManager::SupportImplicitConversion(uint32_t routeFlag)
745 {
746     if ((routeFlag & AUDIO_OUTPUT_FLAG_NORMAL) ||
747         ((routeFlag & AUDIO_OUTPUT_FLAG_DIRECT) && (routeFlag & AUDIO_OUTPUT_FLAG_HD)) ||
748         (routeFlag & AUDIO_OUTPUT_FLAG_MULTICHANNEL) ||
749         (routeFlag & AUDIO_OUTPUT_FLAG_LOWPOWER) ||
750         (routeFlag & AUDIO_INPUT_FLAG_NORMAL) ||
751         (routeFlag & AUDIO_INPUT_FLAG_WAKEUP)) {
752         return true;
753     }
754     return false;
755 }
756 
GetDirectPlaybackSupport(std::shared_ptr<AudioDeviceDescriptor> desc,const AudioStreamInfo & streamInfo)757 DirectPlaybackMode AudioPolicyConfigManager::GetDirectPlaybackSupport(std::shared_ptr<AudioDeviceDescriptor> desc,
758     const AudioStreamInfo &streamInfo)
759 {
760     std::shared_ptr<AdapterDeviceInfo> deviceInfo = audioPolicyConfig_.GetAdapterDeviceInfo(
761         desc->deviceType_, desc->deviceRole_, desc->networkId_, AUDIO_FLAG_NONE);
762     CHECK_AND_RETURN_RET_LOG(deviceInfo != nullptr, DIRECT_PLAYBACK_NOT_SUPPORTED, "Find device failed");
763     CHECK_AND_RETURN_RET_LOG(streamInfo.encoding != ENCODING_EAC3 || desc->deviceType_ == DEVICE_TYPE_HDMI ||
764         desc->deviceType_ == DEVICE_TYPE_LINE_DIGITAL, DIRECT_PLAYBACK_NOT_SUPPORTED, "Not support eac3");
765 
766     if ((streamInfo.encoding == ENCODING_EAC3) &&
767         (desc->deviceType_ == DEVICE_TYPE_HDMI || desc->deviceType_ == DEVICE_TYPE_LINE_DIGITAL)) {
768         for (auto &pipeIt : deviceInfo->supportPipeMap_) {
769             if (pipeIt.second != nullptr && pipeIt.second->supportEncodingEac3_ &&
770                 IsStreamPropMatch(streamInfo, pipeIt.second->streamPropInfos_)) {
771                 AUDIO_INFO_LOG("Support encoding type eac3");
772                 return DIRECT_PLAYBACK_BITSTREAM_SUPPORTED;
773             }
774         }
775         AUDIO_INFO_LOG("Not support eac3");
776     }
777 
778     if (streamInfo.encoding == ENCODING_PCM) {
779         for (auto &pipeIt : deviceInfo->supportPipeMap_) {
780             if ((pipeIt.first & AUDIO_OUTPUT_FLAG_DIRECT) && pipeIt.second != nullptr &&
781                 IsStreamPropMatch(streamInfo, pipeIt.second->streamPropInfos_)) {
782                 AUDIO_INFO_LOG("Support encoding type pcm");
783                 return DIRECT_PLAYBACK_PCM_SUPPORTED;
784             }
785         }
786         AUDIO_INFO_LOG("Not support pcm");
787     }
788 
789     return DIRECT_PLAYBACK_NOT_SUPPORTED;
790 }
791 
IsStreamPropMatch(const AudioStreamInfo & streamInfo,std::list<std::shared_ptr<PipeStreamPropInfo>> & infos)792 bool AudioPolicyConfigManager::IsStreamPropMatch(const AudioStreamInfo &streamInfo,
793     std::list<std::shared_ptr<PipeStreamPropInfo>> &infos)
794 {
795     for (auto info : infos) {
796         if (info != nullptr && info->format_ == streamInfo.format && info->sampleRate_ == streamInfo.samplingRate &&
797             info->channels_ == streamInfo.channels) {
798             return true;
799         }
800     }
801     return false;
802 }
803 }
804 }
805