1 /*
2  * Copyright 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "le_audio_utils.h"
18 
19 #include <bluetooth/log.h>
20 
21 #include <cstdint>
22 #include <sstream>
23 #include <string>
24 #include <type_traits>
25 #include <vector>
26 
27 #include "audio_hal_client/audio_hal_client.h"
28 #include "common/strings.h"
29 #include "hardware/bt_le_audio.h"
30 #include "le_audio/codec_manager.h"
31 #include "le_audio_types.h"
32 
33 using bluetooth::common::ToString;
34 using bluetooth::le_audio::types::AudioContexts;
35 using bluetooth::le_audio::types::LeAudioContextType;
36 
37 namespace std {
38 template <>
39 struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
40 template <>
41 struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {};
42 template <>
43 struct formatter<audio_source_t> : enum_formatter<audio_source_t> {};
44 template <>
45 struct formatter<audio_devices_t> : enum_formatter<audio_devices_t> {};
46 }  // namespace std
47 
48 namespace bluetooth::le_audio {
49 namespace utils {
50 
51 /* The returned LeAudioContextType should have its entry in the
52  * AudioSetConfigurationProvider's ContextTypeToScenario mapping table.
53  * Otherwise the AudioSetConfigurationProvider will fall back
54  * to default scenario.
55  */
AudioContentToLeAudioContext(audio_content_type_t content_type,audio_usage_t usage)56 LeAudioContextType AudioContentToLeAudioContext(audio_content_type_t content_type,
57                                                 audio_usage_t usage) {
58   /* Check audio attribute usage of stream */
59   switch (usage) {
60     case AUDIO_USAGE_MEDIA:
61       return LeAudioContextType::MEDIA;
62     case AUDIO_USAGE_ASSISTANT:
63       return LeAudioContextType::VOICEASSISTANTS;
64     case AUDIO_USAGE_VOICE_COMMUNICATION:
65     case AUDIO_USAGE_CALL_ASSISTANT:
66       return LeAudioContextType::CONVERSATIONAL;
67     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
68       if (content_type == AUDIO_CONTENT_TYPE_SPEECH) {
69         return LeAudioContextType::CONVERSATIONAL;
70       }
71 
72       if (content_type == AUDIO_CONTENT_TYPE_SONIFICATION) {
73         return LeAudioContextType::RINGTONE;
74       }
75 
76       return LeAudioContextType::SOUNDEFFECTS;
77     case AUDIO_USAGE_GAME:
78       return LeAudioContextType::GAME;
79     case AUDIO_USAGE_NOTIFICATION:
80       return LeAudioContextType::NOTIFICATIONS;
81     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
82       return LeAudioContextType::RINGTONE;
83     case AUDIO_USAGE_ALARM:
84       return LeAudioContextType::ALERTS;
85     case AUDIO_USAGE_EMERGENCY:
86       return LeAudioContextType::EMERGENCYALARM;
87     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
88       return LeAudioContextType::INSTRUCTIONAL;
89     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
90       return LeAudioContextType::SOUNDEFFECTS;
91     default:
92       break;
93   }
94 
95   return LeAudioContextType::MEDIA;
96 }
97 
usageToString(audio_usage_t usage)98 static std::string usageToString(audio_usage_t usage) {
99   switch (usage) {
100     case AUDIO_USAGE_UNKNOWN:
101       return "USAGE_UNKNOWN";
102     case AUDIO_USAGE_MEDIA:
103       return "USAGE_MEDIA";
104     case AUDIO_USAGE_VOICE_COMMUNICATION:
105       return "USAGE_VOICE_COMMUNICATION";
106     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
107       return "USAGE_VOICE_COMMUNICATION_SIGNALLING";
108     case AUDIO_USAGE_ALARM:
109       return "USAGE_ALARM";
110     case AUDIO_USAGE_NOTIFICATION:
111       return "USAGE_NOTIFICATION";
112     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
113       return "USAGE_NOTIFICATION_TELEPHONY_RINGTONE";
114     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
115       return "USAGE_NOTIFICATION_COMMUNICATION_REQUEST";
116     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
117       return "USAGE_NOTIFICATION_COMMUNICATION_INSTANT";
118     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
119       return "USAGE_NOTIFICATION_COMMUNICATION_DELAYED";
120     case AUDIO_USAGE_NOTIFICATION_EVENT:
121       return "USAGE_NOTIFICATION_EVENT";
122     case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
123       return "USAGE_ASSISTANCE_ACCESSIBILITY";
124     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
125       return "USAGE_ASSISTANCE_NAVIGATION_GUIDANCE";
126     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
127       return "USAGE_ASSISTANCE_SONIFICATION";
128     case AUDIO_USAGE_GAME:
129       return "USAGE_GAME";
130     case AUDIO_USAGE_ASSISTANT:
131       return "USAGE_ASSISTANT";
132     case AUDIO_USAGE_CALL_ASSISTANT:
133       return "USAGE_CALL_ASSISTANT";
134     case AUDIO_USAGE_EMERGENCY:
135       return "USAGE_EMERGENCY";
136     case AUDIO_USAGE_SAFETY:
137       return "USAGE_SAFETY";
138     case AUDIO_USAGE_VEHICLE_STATUS:
139       return "USAGE_VEHICLE_STATUS";
140     case AUDIO_USAGE_ANNOUNCEMENT:
141       return "USAGE_ANNOUNCEMENT";
142     default:
143       return "unknown usage ";
144   }
145 }
146 
contentTypeToString(audio_content_type_t content_type)147 static std::string contentTypeToString(audio_content_type_t content_type) {
148   switch (content_type) {
149     case AUDIO_CONTENT_TYPE_UNKNOWN:
150       return "CONTENT_TYPE_UNKNOWN";
151     case AUDIO_CONTENT_TYPE_SPEECH:
152       return "CONTENT_TYPE_SPEECH";
153     case AUDIO_CONTENT_TYPE_MUSIC:
154       return "CONTENT_TYPE_MUSIC";
155     case AUDIO_CONTENT_TYPE_MOVIE:
156       return "CONTENT_TYPE_MOVIE";
157     case AUDIO_CONTENT_TYPE_SONIFICATION:
158       return "CONTENT_TYPE_SONIFICATION";
159     default:
160       return "unknown content type ";
161   }
162 }
163 
audioSourceToStr(audio_source_t source)164 static const char* audioSourceToStr(audio_source_t source) {
165   const char* strArr[] = {"AUDIO_SOURCE_DEFAULT",           "AUDIO_SOURCE_MIC",
166                           "AUDIO_SOURCE_VOICE_UPLINK",      "AUDIO_SOURCE_VOICE_DOWNLINK",
167                           "AUDIO_SOURCE_VOICE_CALL",        "AUDIO_SOURCE_CAMCORDER",
168                           "AUDIO_SOURCE_VOICE_RECOGNITION", "AUDIO_SOURCE_VOICE_COMMUNICATION",
169                           "AUDIO_SOURCE_REMOTE_SUBMIX",     "AUDIO_SOURCE_UNPROCESSED",
170                           "AUDIO_SOURCE_VOICE_PERFORMANCE"};
171 
172   if (static_cast<uint32_t>(source) < (sizeof(strArr) / sizeof(strArr[0]))) {
173     return strArr[source];
174   }
175   return "UNKNOWN";
176 }
177 
isMetadataTagPresent(const char * tags,const char * tag)178 static bool isMetadataTagPresent(const char* tags, const char* tag) {
179   std::istringstream iss(tags);
180   std::string t;
181   while (std::getline(iss, t, AUDIO_ATTRIBUTES_TAGS_SEPARATOR)) {
182     log::verbose("Tag {}", t);
183     if (t.compare(tag) == 0) {
184       return true;
185     }
186   }
187   return false;
188 }
189 
GetAudioContextsFromSourceMetadata(const std::vector<struct playback_track_metadata_v7> & source_metadata)190 AudioContexts GetAudioContextsFromSourceMetadata(
191         const std::vector<struct playback_track_metadata_v7>& source_metadata) {
192   AudioContexts track_contexts;
193   for (const auto& entry : source_metadata) {
194     auto track = entry.base;
195     if (track.content_type == 0 && track.usage == 0) {
196       continue;
197     }
198 
199     log::info("usage={}({}), content_type={}({}), gain={:f}, tag:{}", usageToString(track.usage),
200               track.usage, contentTypeToString(track.content_type), track.content_type, track.gain,
201               entry.tags);
202 
203     if (isMetadataTagPresent(entry.tags, "VX_AOSP_SAMPLESOUND")) {
204       track_contexts.set(LeAudioContextType::SOUNDEFFECTS);
205     } else {
206       track_contexts.set(AudioContentToLeAudioContext(track.content_type, track.usage));
207     }
208   }
209   return track_contexts;
210 }
211 
GetAudioContextsFromSinkMetadata(const std::vector<struct record_track_metadata_v7> & sink_metadata)212 AudioContexts GetAudioContextsFromSinkMetadata(
213         const std::vector<struct record_track_metadata_v7>& sink_metadata) {
214   AudioContexts all_track_contexts;
215 
216   for (const auto& entry : sink_metadata) {
217     auto track = entry.base;
218     if (track.source == AUDIO_SOURCE_INVALID) {
219       continue;
220     }
221     LeAudioContextType track_context;
222 
223     log::debug(
224             "source={}(0x{:02x}), gain={:f}, destination device=0x{:08x}, "
225             "destination device address={:32s}",
226             audioSourceToStr(track.source), track.source, track.gain, track.dest_device,
227             track.dest_device_address);
228 
229     if (track.source == AUDIO_SOURCE_MIC) {
230       track_context = LeAudioContextType::LIVE;
231 
232     } else if (track.source == AUDIO_SOURCE_VOICE_COMMUNICATION) {
233       track_context = LeAudioContextType::CONVERSATIONAL;
234 
235     } else {
236       /* Fallback to voice assistant
237        * This will handle also a case when the device is
238        * AUDIO_SOURCE_VOICE_RECOGNITION
239        */
240       track_context = LeAudioContextType::VOICEASSISTANTS;
241       log::warn(
242               "Could not match the recording track type to group available "
243               "context. Using context {}.",
244               ToString(track_context));
245     }
246 
247     all_track_contexts.set(track_context);
248   }
249 
250   if (all_track_contexts.none()) {
251     all_track_contexts = AudioContexts(static_cast<std::underlying_type<LeAudioContextType>::type>(
252             LeAudioContextType::UNSPECIFIED));
253     log::debug(
254             "Unable to find supported audio source context for the remote audio "
255             "sink device. This may result in voice back channel malfunction.");
256   }
257 
258   log::info("Allowed contexts from sink metadata: {} (0x{:08x})",
259             bluetooth::common::ToString(all_track_contexts), all_track_contexts.value());
260   return all_track_contexts;
261 }
262 
translateBluetoothCodecFormatToCodecType(uint8_t codec_format)263 bluetooth::le_audio::btle_audio_codec_index_t translateBluetoothCodecFormatToCodecType(
264         uint8_t codec_format) {
265   switch (codec_format) {
266     case types::kLeAudioCodingFormatLC3:
267       return bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3;
268   }
269   return bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_INVALID;
270 }
271 
translateToBtLeAudioCodecConfigSampleRate(uint32_t sample_rate)272 bluetooth::le_audio::btle_audio_sample_rate_index_t translateToBtLeAudioCodecConfigSampleRate(
273         uint32_t sample_rate) {
274   log::info("{}", sample_rate);
275   switch (sample_rate) {
276     case LeAudioCodecConfiguration::kSampleRate8000:
277       return LE_AUDIO_SAMPLE_RATE_INDEX_8000HZ;
278     case LeAudioCodecConfiguration::kSampleRate16000:
279       return LE_AUDIO_SAMPLE_RATE_INDEX_16000HZ;
280     case LeAudioCodecConfiguration::kSampleRate24000:
281       return LE_AUDIO_SAMPLE_RATE_INDEX_24000HZ;
282     case LeAudioCodecConfiguration::kSampleRate32000:
283       return LE_AUDIO_SAMPLE_RATE_INDEX_32000HZ;
284     case LeAudioCodecConfiguration::kSampleRate44100:
285       return LE_AUDIO_SAMPLE_RATE_INDEX_44100HZ;
286     case LeAudioCodecConfiguration::kSampleRate48000:
287       return LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ;
288   }
289 
290   return LE_AUDIO_SAMPLE_RATE_INDEX_NONE;
291 }
292 
translateToBtLeAudioCodecConfigBitPerSample(uint8_t bits_per_sample)293 bluetooth::le_audio::btle_audio_bits_per_sample_index_t translateToBtLeAudioCodecConfigBitPerSample(
294         uint8_t bits_per_sample) {
295   switch (bits_per_sample) {
296     case 16:
297       return bluetooth::le_audio::LE_AUDIO_BITS_PER_SAMPLE_INDEX_16;
298     case 24:
299       return bluetooth::le_audio::LE_AUDIO_BITS_PER_SAMPLE_INDEX_24;
300     case 32:
301       return bluetooth::le_audio::LE_AUDIO_BITS_PER_SAMPLE_INDEX_32;
302   }
303   return bluetooth::le_audio::LE_AUDIO_BITS_PER_SAMPLE_INDEX_NONE;
304 }
305 
translateToBtLeAudioCodecConfigChannelCount(uint8_t channel_count)306 bluetooth::le_audio::btle_audio_channel_count_index_t translateToBtLeAudioCodecConfigChannelCount(
307         uint8_t channel_count) {
308   switch (channel_count) {
309     case 1:
310       return bluetooth::le_audio::LE_AUDIO_CHANNEL_COUNT_INDEX_1;
311     case 2:
312       return bluetooth::le_audio::LE_AUDIO_CHANNEL_COUNT_INDEX_2;
313   }
314   return bluetooth::le_audio::LE_AUDIO_CHANNEL_COUNT_INDEX_NONE;
315 }
316 
translateToBtLeAudioCodecConfigFrameDuration(int frame_duration)317 bluetooth::le_audio::btle_audio_frame_duration_index_t translateToBtLeAudioCodecConfigFrameDuration(
318         int frame_duration) {
319   switch (frame_duration) {
320     case 7500:
321       return bluetooth::le_audio::LE_AUDIO_FRAME_DURATION_INDEX_7500US;
322     case 10000:
323       return bluetooth::le_audio::LE_AUDIO_FRAME_DURATION_INDEX_10000US;
324   }
325   return bluetooth::le_audio::LE_AUDIO_FRAME_DURATION_INDEX_NONE;
326 }
327 
fillStreamParamsToBtLeAudioCodecConfig(const std::vector<struct set_configurations::AseConfiguration> & confs,bluetooth::le_audio::btle_audio_codec_config_t & out_config)328 void fillStreamParamsToBtLeAudioCodecConfig(
329         const std::vector<struct set_configurations::AseConfiguration>& confs,
330         bluetooth::le_audio::btle_audio_codec_config_t& out_config) {
331   if (confs.size() == 0) {
332     log::warn("Stream params are null");
333     return;
334   }
335 
336   auto config = confs.at(0).codec;
337 
338   out_config.codec_type = translateBluetoothCodecFormatToCodecType(config.id.coding_format);
339   if (out_config.codec_type != bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3) {
340     return;
341   }
342 
343   out_config.sample_rate =
344           translateToBtLeAudioCodecConfigSampleRate(config.GetSamplingFrequencyHz());
345   out_config.bits_per_sample =
346           translateToBtLeAudioCodecConfigBitPerSample(config.GetBitsPerSample());
347   out_config.frame_duration =
348           translateToBtLeAudioCodecConfigFrameDuration(config.GetDataIntervalUs());
349   out_config.octets_per_frame = config.GetOctetsPerFrame();
350   out_config.channel_count =
351           translateToBtLeAudioCodecConfigChannelCount(config.GetChannelCountPerIsoStream());
352 }
353 
is_known_codec(const types::LeAudioCodecId & codec_id)354 static bool is_known_codec(const types::LeAudioCodecId& codec_id) {
355   switch (codec_id.coding_format) {
356     case types::kLeAudioCodingFormatLC3:
357       return true;
358   }
359   return false;
360 }
361 
fillRemotePacsCapabilitiesToBtLeAudioCodecConfig(const struct types::acs_ac_record & record,std::vector<bluetooth::le_audio::btle_audio_codec_config_t> & vec)362 static void fillRemotePacsCapabilitiesToBtLeAudioCodecConfig(
363         const struct types::acs_ac_record& record,
364         std::vector<bluetooth::le_audio::btle_audio_codec_config_t>& vec) {
365   if (!utils::IsCodecUsingLtvFormat(record.codec_id)) {
366     log::warn(
367             "Unknown codec capability format. Unable to report known codec "
368             "parameters.");
369     return;
370   }
371   log::assert_that(!record.codec_spec_caps.IsEmpty(),
372                    "Codec specific capabilities are not parsed appropriately.");
373 
374   const struct types::LeAudioCoreCodecCapabilities capa =
375           record.codec_spec_caps.GetAsCoreCodecCapabilities();
376   for (uint8_t freq_bit = codec_spec_conf::kLeAudioSamplingFreq8000Hz;
377        freq_bit <= codec_spec_conf::kLeAudioSamplingFreq384000Hz; freq_bit++) {
378     if (!capa.IsSamplingFrequencyConfigSupported(freq_bit)) {
379       continue;
380     }
381     for (uint8_t fd_bit = codec_spec_conf::kLeAudioCodecFrameDur7500us;
382          fd_bit <= codec_spec_conf::kLeAudioCodecFrameDur10000us; fd_bit++) {
383       if (!capa.IsFrameDurationConfigSupported(fd_bit)) {
384         continue;
385       }
386       if (!capa.HasSupportedAudioChannelCounts()) {
387         bluetooth::le_audio::btle_audio_codec_config_t config = {
388                 .codec_type = utils::translateBluetoothCodecFormatToCodecType(
389                         record.codec_id.coding_format),
390                 .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate(
391                         types::LeAudioCoreCodecConfig::GetSamplingFrequencyHz(freq_bit)),
392                 .bits_per_sample = utils::translateToBtLeAudioCodecConfigBitPerSample(16),
393                 .channel_count = utils::translateToBtLeAudioCodecConfigChannelCount(1),
394                 .frame_duration = utils::translateToBtLeAudioCodecConfigFrameDuration(
395                         types::LeAudioCoreCodecConfig::GetFrameDurationUs(fd_bit)),
396         };
397         vec.push_back(config);
398       } else {
399         for (int chan_bit = 1; chan_bit <= 2; chan_bit++) {
400           if (!capa.IsAudioChannelCountsSupported(chan_bit)) {
401             continue;
402           }
403 
404           bluetooth::le_audio::btle_audio_codec_config_t config = {
405                   .codec_type = utils::translateBluetoothCodecFormatToCodecType(
406                           record.codec_id.coding_format),
407                   .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate(
408                           types::LeAudioCoreCodecConfig::GetSamplingFrequencyHz(freq_bit)),
409                   .bits_per_sample = utils::translateToBtLeAudioCodecConfigBitPerSample(16),
410                   .channel_count = utils::translateToBtLeAudioCodecConfigChannelCount(chan_bit),
411                   .frame_duration = utils::translateToBtLeAudioCodecConfigFrameDuration(
412                           types::LeAudioCoreCodecConfig::GetFrameDurationUs(fd_bit)),
413           };
414           vec.push_back(config);
415         }
416       }
417     }
418   }
419 }
420 
GetRemoteBtLeAudioCodecConfigFromPac(const types::PublishedAudioCapabilities & group_pacs)421 std::vector<bluetooth::le_audio::btle_audio_codec_config_t> GetRemoteBtLeAudioCodecConfigFromPac(
422         const types::PublishedAudioCapabilities& group_pacs) {
423   std::vector<bluetooth::le_audio::btle_audio_codec_config_t> vec;
424 
425   for (auto& [handles, pacs_record] : group_pacs) {
426     for (auto& pac : pacs_record) {
427       if (!is_known_codec(pac.codec_id)) {
428         continue;
429       }
430 
431       fillRemotePacsCapabilitiesToBtLeAudioCodecConfig(pac, vec);
432     }
433   }
434   return vec;
435 }
436 
IsCodecUsingLtvFormat(const types::LeAudioCodecId & codec_id)437 bool IsCodecUsingLtvFormat(const types::LeAudioCodecId& codec_id) {
438   if (codec_id == set_configurations::LeAudioCodecIdLc3) {
439     return true;
440   }
441   return false;
442 }
443 
444 ::bluetooth::le_audio::LeAudioCodecConfiguration
GetAudioSessionCodecConfigFromAudioSetConfiguration(const bluetooth::le_audio::set_configurations::AudioSetConfiguration & audio_set_conf,uint8_t remote_direction)445 GetAudioSessionCodecConfigFromAudioSetConfiguration(
446         const bluetooth::le_audio::set_configurations::AudioSetConfiguration& audio_set_conf,
447         uint8_t remote_direction) {
448   /* Note: For now we expect that each ASE in a particular direction needs
449    *       exactly the same audio codec parameters.
450    */
451 
452   LeAudioCodecConfiguration group_config = {0, 0, 0, 0};
453   for (const auto& conf : audio_set_conf.confs.get(remote_direction)) {
454     if (group_config.sample_rate != 0 &&
455         conf.codec.GetSamplingFrequencyHz() != group_config.sample_rate) {
456       log::warn(
457               "Stream configuration could not be determined (multiple, different "
458               "sampling frequencies) for remote_direction: {:#x}",
459               remote_direction);
460       break;
461     }
462     group_config.sample_rate = conf.codec.GetSamplingFrequencyHz();
463 
464     if (group_config.data_interval_us != 0 &&
465         conf.codec.GetDataIntervalUs() != group_config.data_interval_us) {
466       log::warn(
467               "Stream configuration could not be determined (multiple, different "
468               "data intervals) for remote_direction: {:#x}",
469               remote_direction);
470       break;
471     }
472     group_config.data_interval_us = conf.codec.GetDataIntervalUs();
473 
474     if (group_config.bits_per_sample != 0 &&
475         conf.codec.GetBitsPerSample() != group_config.bits_per_sample) {
476       log::warn(
477               "Stream configuration could not be determined (multiple, different "
478               "bits per sample) for remote_direction: {:#x}",
479               remote_direction);
480       break;
481     }
482     group_config.bits_per_sample = conf.codec.GetBitsPerSample();
483     group_config.num_channels += conf.codec.GetChannelCountPerIsoStream();
484   }
485   if (group_config.num_channels > 2) {
486     group_config.num_channels = 2;
487   }
488 
489   return group_config;
490 }
491 
GetStrategyForAseConfig(const std::vector<le_audio::set_configurations::AseConfiguration> & cfgs,uint8_t device_cnt)492 types::LeAudioConfigurationStrategy GetStrategyForAseConfig(
493         const std::vector<le_audio::set_configurations::AseConfiguration>& cfgs,
494         uint8_t device_cnt) {
495   if (cfgs.size() == 0) {
496     return types::LeAudioConfigurationStrategy::RFU;
497   }
498 
499   /* Banded headphones or the Classic TWS style topology (a single device) */
500   if (device_cnt == 1) {
501     if (cfgs.at(0).codec.GetChannelCountPerIsoStream() == 1) {
502       /* One mono ASE - could be a single channel microphone */
503       if (cfgs.size() == 1) {
504         return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE;
505       }
506 
507       /* Each channel on a dedicated ASE - TWS style split channel re-routing */
508       return types::LeAudioConfigurationStrategy::STEREO_TWO_CISES_PER_DEVICE;
509     }
510 
511     /* Banded headphones with 1 ASE - requires two channels per CIS */
512     return types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE;
513   }
514 
515   // We need at least 2 ASEs in the group config to set up more than one device
516   if (cfgs.size() == 1) {
517     return types::LeAudioConfigurationStrategy::RFU;
518   }
519 
520   /* The common one channel per device topology */
521   return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE;
522 }
523 
IsCodecConfigSupported(const types::LeAudioLtvMap & pacs,const types::LeAudioLtvMap & reqs,uint8_t channel_cnt_per_ase)524 static bool IsCodecConfigSupported(const types::LeAudioLtvMap& pacs,
525                                    const types::LeAudioLtvMap& reqs, uint8_t channel_cnt_per_ase) {
526   auto caps = pacs.GetAsCoreCodecCapabilities();
527   auto config = reqs.GetAsCoreCodecConfig();
528 
529   /* Sampling frequency */
530   if (!caps.HasSupportedSamplingFrequencies() || !config.sampling_frequency) {
531     log::debug("Missing supported sampling frequencies capability");
532     return false;
533   }
534   if (!caps.IsSamplingFrequencyConfigSupported(config.sampling_frequency.value())) {
535     log::debug("Cfg: SamplingFrequency= {:#x}", config.sampling_frequency.value());
536     log::debug("Cap: SupportedSamplingFrequencies= {:#x}",
537                caps.supported_sampling_frequencies.value());
538     log::debug("Sampling frequency not supported");
539     return false;
540   }
541 
542   /* Channel counts */
543   if (!caps.IsAudioChannelCountsSupported(channel_cnt_per_ase)) {
544     log::debug("Cfg: Allocated channel count= {:#x}", channel_cnt_per_ase);
545     log::debug("Cap: Supported channel counts= {:#x}",
546                caps.supported_audio_channel_counts.value_or(1));
547     log::debug("Channel count not supported");
548     return false;
549   }
550 
551   /* Frame duration */
552   if (!caps.HasSupportedFrameDurations() || !config.frame_duration) {
553     log::debug("Missing supported frame durations capability");
554     return false;
555   }
556   if (!caps.IsFrameDurationConfigSupported(config.frame_duration.value())) {
557     log::debug("Cfg: FrameDuration= {:#x}", config.frame_duration.value());
558     log::debug("Cap: SupportedFrameDurations= {:#x}", caps.supported_frame_durations.value());
559     log::debug("Frame duration not supported");
560     return false;
561   }
562 
563   /* Octets per frame */
564   if (!caps.HasSupportedOctetsPerCodecFrame() || !config.octets_per_codec_frame) {
565     log::debug("Missing supported octets per codec frame");
566     return false;
567   }
568   if (!caps.IsOctetsPerCodecFrameConfigSupported(config.octets_per_codec_frame.value())) {
569     log::debug("Cfg: Octets per frame={}", config.octets_per_codec_frame.value());
570     log::debug("Cap: Min octets per frame={}", caps.supported_min_octets_per_codec_frame.value());
571     log::debug("Cap: Max octets per frame={}", caps.supported_max_octets_per_codec_frame.value());
572     log::debug("Octets per codec frame outside the capabilities");
573     return false;
574   }
575 
576   return true;
577 }
578 
IsCodecConfigSettingSupported(const types::acs_ac_record & pac,const set_configurations::CodecConfigSetting & codec_config_setting)579 static bool IsCodecConfigSettingSupported(
580         const types::acs_ac_record& pac,
581         const set_configurations::CodecConfigSetting& codec_config_setting) {
582   const auto& codec_id = codec_config_setting.id;
583   if (codec_id != pac.codec_id) {
584     return false;
585   }
586 
587   log::debug("Verifying coding format: {:#02x} ", codec_id.coding_format);
588 
589   if (utils::IsCodecUsingLtvFormat(codec_id)) {
590     log::assert_that(!pac.codec_spec_caps.IsEmpty(),
591                      "Codec specific capabilities are not parsed appropriately.");
592     return IsCodecConfigSupported(pac.codec_spec_caps, codec_config_setting.params,
593                                   codec_config_setting.GetChannelCountPerIsoStream());
594   }
595 
596   log::error("Codec {}, seems to be not supported here.", bluetooth::common::ToString(codec_id));
597   return false;
598 }
599 
GetConfigurationSupportedPac(const types::PublishedAudioCapabilities & pacs,const set_configurations::CodecConfigSetting & codec_config_setting)600 const struct types::acs_ac_record* GetConfigurationSupportedPac(
601         const types::PublishedAudioCapabilities& pacs,
602         const set_configurations::CodecConfigSetting& codec_config_setting) {
603   for (const auto& pac_tuple : pacs) {
604     for (const auto& pac : std::get<1>(pac_tuple)) {
605       if (utils::IsCodecConfigSettingSupported(pac, codec_config_setting)) {
606         return &pac;
607       }
608     };
609   }
610   /* Doesn't match required configuration with any PAC */
611   if (pacs.size() == 0) {
612     log::error("No PAC records");
613   }
614   return nullptr;
615 }
616 
IsAseConfigMatchedWithPreferredRequirements(const std::vector<struct set_configurations::AseConfiguration> & ase_confs,const std::vector<CodecManager::UnicastConfigurationRequirements::DeviceDirectionRequirements> & reqs,uint8_t channel_cnt_per_ase)617 bool IsAseConfigMatchedWithPreferredRequirements(
618         const std::vector<struct set_configurations::AseConfiguration>& ase_confs,
619         const std::vector<
620                 CodecManager::UnicastConfigurationRequirements::DeviceDirectionRequirements>& reqs,
621         uint8_t channel_cnt_per_ase) {
622   if (ase_confs.empty() || reqs.empty() || ase_confs.size() != reqs.size()) {
623     return false;
624   }
625 
626   for (auto i = 0; i < static_cast<int>(ase_confs.size()); ++i) {
627     const auto& ase_config = ase_confs.at(i).codec.params.GetAsCoreCodecConfig();
628     const auto& req_config = reqs.at(i).params.GetAsCoreCodecConfig();
629 
630     /* Sampling frequency */
631     if (!ase_config.sampling_frequency || !req_config.sampling_frequency) {
632       log::debug("Missing sampling frequencies capability");
633       return false;
634     }
635     if (ase_config.sampling_frequency.value() != req_config.sampling_frequency.value()) {
636       log::debug("Ase cfg: SamplingFrequency= {:#x}", ase_config.sampling_frequency.value());
637       log::debug("Req cfg: SamplingFrequency= {:#x}", req_config.sampling_frequency.value());
638       log::debug("Sampling frequency not supported");
639       return false;
640     }
641 
642     /* Channel counts */
643     if (ase_confs.at(i).codec.GetChannelCountPerIsoStream() != channel_cnt_per_ase) {
644       log::debug("Ase cfg: Allocated channel count= {:#x}",
645                  ase_confs.at(i).codec.GetChannelCountPerIsoStream());
646       log::debug("Req cfg: Allocated channel counts= {:#x}", channel_cnt_per_ase);
647       log::debug("Channel count not supported");
648       return false;
649     }
650 
651     /* Frame duration */
652     if (!ase_config.frame_duration || !req_config.frame_duration) {
653       log::debug("Missing frame duration capability");
654       return false;
655     }
656     if (ase_config.frame_duration.value() != ase_config.frame_duration.value()) {
657       log::debug("Ase cfg: FrameDuration= {:#x}", ase_config.frame_duration.value());
658       log::debug("Req cfg: FrameDuration= {:#x}", req_config.frame_duration.value());
659       log::debug("Frame duration not supported");
660       return false;
661     }
662 
663     /* Octets per frame */
664     if (!ase_config.octets_per_codec_frame || !req_config.octets_per_codec_frame) {
665       log::debug("Missing octets per codec frame");
666       return false;
667     }
668     if (ase_config.octets_per_codec_frame.value() != req_config.octets_per_codec_frame.value()) {
669       log::debug("Ase cfg: Octets per frame={}", ase_config.octets_per_codec_frame.value());
670       log::debug("Req cfg: Octets per frame={}", req_config.octets_per_codec_frame.value());
671       return false;
672     }
673   }
674 
675   return true;
676 }
677 
678 }  // namespace utils
679 }  // namespace bluetooth::le_audio
680