• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 HIMSA II K/S - www.himsa.com. Represented by EHIMA -
3  * www.ehima.com
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 /*
19  * This file contains definitions for Basic Audio Profile / Audio Stream Control
20  * and Published Audio Capabilities definitions, structures etc.
21  */
22 
23 #pragma once
24 
25 #include <stdint.h>
26 
27 #include <bitset>
28 #include <map>
29 #include <optional>
30 #include <string>
31 #include <variant>
32 #include <vector>
33 
34 #include "bta_groups.h"
35 #include "bta_le_audio_api.h"
36 #include "bta_le_audio_uuids.h"
37 #include "btm_iso_api_types.h"
38 
39 namespace le_audio {
40 
41 #define UINT8_TO_VEC_UINT8(u8) \
42   std::vector<uint8_t> { u8 }
43 #define UINT16_TO_VEC_UINT8(u16) \
44   std::vector<uint8_t>((uint8_t*)&u16, (uint8_t*)&u16 + sizeof(u16))
45 #define UINT32_TO_VEC_UINT8(u32) \
46   std::vector<uint8_t>((uint8_t*)&u32, (uint8_t*)&u32 + sizeof(u32))
47 
48 #define VEC_UINT8_TO_UINT8(vec) vec.data()[0]
49 #define VEC_UINT8_TO_UINT16(vec) ((vec.data()[1] << 8) + vec.data()[0])
50 #define OFF_VEC_UINT8_TO_UINT16(vec, off) \
51   ((vec.data()[1 + off] << 8) + vec.data()[0 + off])
52 #define VEC_UINT8_TO_UINT32(vec)                                          \
53   ((vec.data()[3] << 24) + (vec.data()[2] << 16) + (vec.data()[1] << 8) + \
54    vec.data()[0])
55 
56 namespace uuid {
57 /* CAP service
58  * This service is used to identify peer role (which we are not using for now)
59  * and to wrap CSIS service as this is required to understand the context of the
60  * CSIS
61  */
62 static const bluetooth::Uuid kCapServiceUuid =
63     bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE);
64 
65 /* Assigned numbers for attributes */
66 static const bluetooth::Uuid kPublishedAudioCapabilityServiceUuid =
67     bluetooth::Uuid::From16Bit(0x1850);
68 static const bluetooth::Uuid kAudioStreamControlServiceUuid =
69     bluetooth::Uuid::From16Bit(0x184E);
70 
71 static const bluetooth::Uuid kTelephonyMediaAudioServiceUuid =
72     bluetooth::Uuid::From16Bit(0x1855);
73 
74 /* Published Audio Capabilities Service Characteristics */
75 static const bluetooth::Uuid kSinkPublishedAudioCapabilityCharacteristicUuid =
76     bluetooth::Uuid::From16Bit(0x2BC9);
77 static const bluetooth::Uuid kSourcePublishedAudioCapabilityCharacteristicUuid =
78     bluetooth::Uuid::From16Bit(0x2BCB);
79 static const bluetooth::Uuid kSinkAudioLocationCharacteristicUuid =
80     bluetooth::Uuid::From16Bit(0x2BCA);
81 static const bluetooth::Uuid kSourceAudioLocationCharacteristicUuid =
82     bluetooth::Uuid::From16Bit(0x2BCC);
83 
84 /* Audio Stream Control Service Characteristics */
85 static const bluetooth::Uuid kAudioContextAvailabilityCharacteristicUuid =
86     bluetooth::Uuid::From16Bit(0x2BCD);
87 static const bluetooth::Uuid kAudioSupportedContextCharacteristicUuid =
88     bluetooth::Uuid::From16Bit(0x2BCE);
89 
90 /* Audio Stream Control Service Characteristics */
91 static const bluetooth::Uuid kSinkAudioStreamEndpointUuid =
92     bluetooth::Uuid::From16Bit(0x2BC4);
93 static const bluetooth::Uuid kSourceAudioStreamEndpointUuid =
94     bluetooth::Uuid::From16Bit(0x2BC5);
95 static const bluetooth::Uuid
96     kAudioStreamEndpointControlPointCharacteristicUuid =
97         bluetooth::Uuid::From16Bit(0x2BC6);
98 
99 /* Telephony and Media Audio Service Characteristics */
100 static const bluetooth::Uuid kTelephonyMediaAudioProfileRoleCharacteristicUuid =
101     bluetooth::Uuid::From16Bit(0x2B51);
102 }  // namespace uuid
103 
104 namespace codec_spec_conf {
105 /* LTV Types */
106 constexpr uint8_t kLeAudioCodecLC3TypeSamplingFreq = 0x01;
107 constexpr uint8_t kLeAudioCodecLC3TypeFrameDuration = 0x02;
108 constexpr uint8_t kLeAudioCodecLC3TypeAudioChannelAllocation = 0x03;
109 constexpr uint8_t kLeAudioCodecLC3TypeOctetPerFrame = 0x04;
110 constexpr uint8_t kLeAudioCodecLC3TypeCodecFrameBlocksPerSdu = 0x05;
111 
112 /* Sampling Frequencies */
113 constexpr uint8_t kLeAudioSamplingFreq8000Hz = 0x01;
114 constexpr uint8_t kLeAudioSamplingFreq11025Hz = 0x02;
115 constexpr uint8_t kLeAudioSamplingFreq16000Hz = 0x03;
116 constexpr uint8_t kLeAudioSamplingFreq22050Hz = 0x04;
117 constexpr uint8_t kLeAudioSamplingFreq24000Hz = 0x05;
118 constexpr uint8_t kLeAudioSamplingFreq32000Hz = 0x06;
119 constexpr uint8_t kLeAudioSamplingFreq44100Hz = 0x07;
120 constexpr uint8_t kLeAudioSamplingFreq48000Hz = 0x08;
121 constexpr uint8_t kLeAudioSamplingFreq88200Hz = 0x09;
122 constexpr uint8_t kLeAudioSamplingFreq96000Hz = 0x0A;
123 constexpr uint8_t kLeAudioSamplingFreq176400Hz = 0x0B;
124 constexpr uint8_t kLeAudioSamplingFreq192000Hz = 0x0C;
125 constexpr uint8_t kLeAudioSamplingFreq384000Hz = 0x0D;
126 
127 /* Frame Durations */
128 constexpr uint8_t kLeAudioCodecLC3FrameDur7500us = 0x00;
129 constexpr uint8_t kLeAudioCodecLC3FrameDur10000us = 0x01;
130 
131 /* Audio Allocations */
132 constexpr uint32_t kLeAudioLocationNotAllowed = 0x00000000;
133 constexpr uint32_t kLeAudioLocationFrontLeft = 0x00000001;
134 constexpr uint32_t kLeAudioLocationFrontRight = 0x00000002;
135 constexpr uint32_t kLeAudioLocationFrontCenter = 0x00000004;
136 constexpr uint32_t kLeAudioLocationLowFreqEffects1 = 0x00000008;
137 constexpr uint32_t kLeAudioLocationBackLeft = 0x00000010;
138 constexpr uint32_t kLeAudioLocationBackRight = 0x00000020;
139 constexpr uint32_t kLeAudioLocationFrontLeftOfCenter = 0x00000040;
140 constexpr uint32_t kLeAudioLocationFrontRightOfCenter = 0x00000080;
141 constexpr uint32_t kLeAudioLocationBackCenter = 0x00000100;
142 constexpr uint32_t kLeAudioLocationLowFreqEffects2 = 0x00000200;
143 constexpr uint32_t kLeAudioLocationSideLeft = 0x00000400;
144 constexpr uint32_t kLeAudioLocationSideRight = 0x00000800;
145 constexpr uint32_t kLeAudioLocationTopFrontLeft = 0x00001000;
146 constexpr uint32_t kLeAudioLocationTopFrontRight = 0x00002000;
147 constexpr uint32_t kLeAudioLocationTopFrontCenter = 0x00004000;
148 constexpr uint32_t kLeAudioLocationTopCenter = 0x00008000;
149 constexpr uint32_t kLeAudioLocationTopBackLeft = 0x00010000;
150 constexpr uint32_t kLeAudioLocationTopBackRight = 0x00020000;
151 constexpr uint32_t kLeAudioLocationTopSideLeft = 0x00040000;
152 constexpr uint32_t kLeAudioLocationTopSideRight = 0x00080000;
153 constexpr uint32_t kLeAudioLocationTopBackCenter = 0x00100000;
154 constexpr uint32_t kLeAudioLocationBottomFrontCenter = 0x00200000;
155 constexpr uint32_t kLeAudioLocationBottomFrontLeft = 0x00400000;
156 constexpr uint32_t kLeAudioLocationBottomFrontRight = 0x00800000;
157 constexpr uint32_t kLeAudioLocationFrontLeftWide = 0x01000000;
158 constexpr uint32_t kLeAudioLocationFrontRightWide = 0x02000000;
159 constexpr uint32_t kLeAudioLocationLeftSurround = 0x04000000;
160 constexpr uint32_t kLeAudioLocationRightSurround = 0x08000000;
161 
162 constexpr uint32_t kLeAudioLocationAnyLeft =
163     kLeAudioLocationFrontLeft | kLeAudioLocationBackLeft |
164     kLeAudioLocationFrontLeftOfCenter | kLeAudioLocationSideLeft |
165     kLeAudioLocationTopFrontLeft | kLeAudioLocationTopBackLeft |
166     kLeAudioLocationTopSideLeft | kLeAudioLocationBottomFrontLeft |
167     kLeAudioLocationFrontLeftWide | kLeAudioLocationLeftSurround;
168 
169 constexpr uint32_t kLeAudioLocationAnyRight =
170     kLeAudioLocationFrontRight | kLeAudioLocationBackRight |
171     kLeAudioLocationFrontRightOfCenter | kLeAudioLocationSideRight |
172     kLeAudioLocationTopFrontRight | kLeAudioLocationTopBackRight |
173     kLeAudioLocationTopSideRight | kLeAudioLocationBottomFrontRight |
174     kLeAudioLocationFrontRightWide | kLeAudioLocationRightSurround;
175 
176 constexpr uint32_t kLeAudioLocationStereo =
177     kLeAudioLocationFrontLeft | kLeAudioLocationFrontRight;
178 
179 /* Octets Per Frame */
180 constexpr uint16_t kLeAudioCodecLC3FrameLen30 = 30;
181 constexpr uint16_t kLeAudioCodecLC3FrameLen40 = 40;
182 constexpr uint16_t kLeAudioCodecLC3FrameLen60 = 60;
183 constexpr uint16_t kLeAudioCodecLC3FrameLen80 = 80;
184 constexpr uint16_t kLeAudioCodecLC3FrameLen120 = 120;
185 
186 }  // namespace codec_spec_conf
187 
188 constexpr uint8_t kInvalidCisId = 0xFF;
189 
190 namespace codec_spec_caps {
SamplingFreqConfig2Capability(uint8_t conf)191 uint16_t constexpr SamplingFreqConfig2Capability(uint8_t conf) {
192   return (1 << (conf - 1));
193 }
194 
FrameDurationConfig2Capability(uint8_t conf)195 uint8_t constexpr FrameDurationConfig2Capability(uint8_t conf) {
196   return (0x01 << (conf));
197 }
198 
GetAudioChannelCounts(std::bitset<32> allocation)199 inline uint8_t GetAudioChannelCounts(std::bitset<32> allocation) {
200   /*
201    * BAP d09r07 B4.2.3 Audio_Channel_Allocation
202    * "(...) Audio_Channel_Allocation bitmap value of all zeros or the
203    * absence of the Audio_Channel_Allocation LTV structure within a
204    * Codec_Specific_Configuration field shall be interpreted as defining a
205    * single audio channel of Mono audio (a single channel of no specified
206    * Audio Location).
207    */
208   uint8_t audio_channel_counts = allocation.count() ?: 1;
209   return (0x01 << (audio_channel_counts - 1));
210 }
211 
212 /* LTV Types - same values as in Codec Specific Configurations but 0x03 is
213  * named differently.
214  */
215 constexpr uint8_t kLeAudioCodecLC3TypeSamplingFreq =
216     codec_spec_conf::kLeAudioCodecLC3TypeSamplingFreq;
217 constexpr uint8_t kLeAudioCodecLC3TypeFrameDuration =
218     codec_spec_conf::kLeAudioCodecLC3TypeFrameDuration;
219 constexpr uint8_t kLeAudioCodecLC3TypeAudioChannelCounts =
220     codec_spec_conf::kLeAudioCodecLC3TypeAudioChannelAllocation;
221 constexpr uint8_t kLeAudioCodecLC3TypeOctetPerFrame =
222     codec_spec_conf::kLeAudioCodecLC3TypeOctetPerFrame;
223 constexpr uint8_t kLeAudioCodecLC3TypeMaxCodecFramesPerSdu =
224     codec_spec_conf::kLeAudioCodecLC3TypeCodecFrameBlocksPerSdu;
225 
226 /* Sampling Frequencies */
227 constexpr uint16_t kLeAudioSamplingFreq8000Hz =
228     SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq8000Hz);
229 constexpr uint16_t kLeAudioSamplingFreq16000Hz =
230     SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq16000Hz);
231 constexpr uint16_t kLeAudioSamplingFreq24000Hz =
232     SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq24000Hz);
233 constexpr uint16_t kLeAudioSamplingFreq32000Hz =
234     SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq32000Hz);
235 constexpr uint16_t kLeAudioSamplingFreq44100Hz =
236     SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq44100Hz);
237 constexpr uint16_t kLeAudioSamplingFreq48000Hz =
238     SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq48000Hz);
239 
240 /* Frame Durations */
241 constexpr uint8_t kLeAudioCodecLC3FrameDur7500us =
242     FrameDurationConfig2Capability(
243         codec_spec_conf::kLeAudioCodecLC3FrameDur7500us);
244 constexpr uint8_t kLeAudioCodecLC3FrameDur10000us =
245     FrameDurationConfig2Capability(
246         codec_spec_conf::kLeAudioCodecLC3FrameDur10000us);
247 constexpr uint8_t kLeAudioCodecLC3FrameDurPrefer7500us = 0x10;
248 constexpr uint8_t kLeAudioCodecLC3FrameDurPrefer10000us = 0x20;
249 
250 /* Audio Channel Counts */
251 /* Each bit represents support for additional channel: bit 0 - one channel,
252  * bit 1 - two, bit 3 - four channels. Multiple bits can be enabled at once.
253  */
254 constexpr uint8_t kLeAudioCodecLC3ChannelCountNone = 0x00;
255 constexpr uint8_t kLeAudioCodecLC3ChannelCountSingleChannel = 0x01;
256 constexpr uint8_t kLeAudioCodecLC3ChannelCountTwoChannel = 0x02;
257 
258 /* Octets Per Frame - same as in Codec Specific Configurations but in
259  * capabilities we get two values: min and max.
260  */
261 constexpr uint16_t kLeAudioCodecLC3FrameLen30 =
262     codec_spec_conf::kLeAudioCodecLC3FrameLen30;
263 constexpr uint16_t kLeAudioCodecLC3FrameLen40 =
264     codec_spec_conf::kLeAudioCodecLC3FrameLen40;
265 constexpr uint16_t kLeAudioCodecLC3FrameLen120 =
266     codec_spec_conf::kLeAudioCodecLC3FrameLen120;
267 
268 };  // namespace codec_spec_caps
269 
270 namespace types {
271 constexpr uint8_t kLeAudioCodingFormatLC3 = bluetooth::hci::kIsoCodingFormatLc3;
272 constexpr uint8_t kLeAudioCodingFormatVendorSpecific =
273     bluetooth::hci::kIsoCodingFormatVendorSpecific;
274 constexpr uint16_t kLeAudioVendorCompanyIdUndefined = 0x00;
275 constexpr uint16_t kLeAudioVendorCodecIdUndefined = 0x00;
276 
277 /* Metadata types from Assigned Numbers */
278 constexpr uint8_t kLeAudioMetadataTypePreferredAudioContext = 0x01;
279 constexpr uint8_t kLeAudioMetadataTypeStreamingAudioContext = 0x02;
280 constexpr uint8_t kLeAudioMetadataTypeProgramInfo = 0x03;
281 constexpr uint8_t kLeAudioMetadataTypeLanguage = 0x04;
282 constexpr uint8_t kLeAudioMetadataTypeCcidList = 0x05;
283 
284 constexpr uint8_t kLeAudioMetadataTypeLen = 1;
285 constexpr uint8_t kLeAudioMetadataLenLen = 1;
286 
287 constexpr uint8_t kLeAudioMetadataStreamingAudioContextLen = 2;
288 
289 /* CSIS Types */
290 constexpr uint8_t kDefaultScanDurationS = 5;
291 constexpr uint8_t kDefaultCsisSetSize = 2;
292 
293 constexpr uint8_t kLeAudioDirectionSink = 0x01;
294 constexpr uint8_t kLeAudioDirectionSource = 0x02;
295 
296 /* Audio stream config types */
297 constexpr uint8_t kFramingUnframedPduSupported = 0x00;
298 constexpr uint8_t kFramingUnframedPduUnsupported = 0x01;
299 
300 constexpr uint8_t kTargetLatencyLower = 0x01;
301 constexpr uint8_t kTargetLatencyBalancedLatencyReliability = 0x02;
302 constexpr uint8_t kTargetLatencyHigherReliability = 0x03;
303 
304 constexpr uint8_t kTargetPhy1M = 0x01;
305 constexpr uint8_t kTargetPhy2M = 0x02;
306 constexpr uint8_t kTargetPhyCoded = 0x03;
307 
308 constexpr uint32_t kPresDelayNoPreference = 0x00000000;
309 
310 constexpr uint16_t kMaxTransportLatencyMin = 0x0005;
311 constexpr uint16_t kMaxTransportLatencyMax = 0x0FA0;
312 
313 enum class CigState : uint8_t { NONE, CREATING, CREATED, REMOVING, RECOVERING };
314 
315 /* ASE states according to BAP defined state machine states */
316 enum class AseState : uint8_t {
317   BTA_LE_AUDIO_ASE_STATE_IDLE = 0x00,
318   BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED = 0x01,
319   BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED = 0x02,
320   BTA_LE_AUDIO_ASE_STATE_ENABLING = 0x03,
321   BTA_LE_AUDIO_ASE_STATE_STREAMING = 0x04,
322   BTA_LE_AUDIO_ASE_STATE_DISABLING = 0x05,
323   BTA_LE_AUDIO_ASE_STATE_RELEASING = 0x06,
324 };
325 
326 enum class AudioStreamDataPathState {
327   IDLE,
328   CIS_DISCONNECTING,
329   CIS_ASSIGNED,
330   CIS_PENDING,
331   CIS_ESTABLISHED,
332   DATA_PATH_ESTABLISHED,
333 };
334 
335 enum class CisType {
336   CIS_TYPE_BIDIRECTIONAL,
337   CIS_TYPE_UNIDIRECTIONAL_SINK,
338   CIS_TYPE_UNIDIRECTIONAL_SOURCE,
339 };
340 
341 struct cis {
342   uint8_t id;
343   CisType type;
344   uint16_t conn_handle;
345   RawAddress addr;
346 };
347 
348 enum class CodecLocation {
349   HOST,
350   ADSP,
351   CONTROLLER,
352 };
353 
354 /* Context Types */
355 enum class LeAudioContextType : uint16_t {
356   UNINITIALIZED = 0x0000,
357   UNSPECIFIED = 0x0001,
358   CONVERSATIONAL = 0x0002,
359   MEDIA = 0x0004,
360   GAME = 0x0008,
361   INSTRUCTIONAL = 0x0010,
362   VOICEASSISTANTS = 0x0020,
363   LIVE = 0x0040,
364   SOUNDEFFECTS = 0x0080,
365   NOTIFICATIONS = 0x0100,
366   RINGTONE = 0x0200,
367   ALERTS = 0x0400,
368   EMERGENCYALARM = 0x0800,
369   RFU = 0x1000,
370 };
371 
372 class AudioContexts {
373   using T = std::underlying_type<LeAudioContextType>::type;
374   T mValue;
375 
376  public:
AudioContexts()377   explicit constexpr AudioContexts()
378       : mValue(static_cast<T>(LeAudioContextType::UNINITIALIZED)) {}
AudioContexts(const T & v)379   explicit constexpr AudioContexts(const T& v) : mValue(v) {}
AudioContexts(const LeAudioContextType & v)380   explicit constexpr AudioContexts(const LeAudioContextType& v)
381       : mValue(static_cast<T>(v)) {}
AudioContexts(const AudioContexts & other)382   constexpr AudioContexts(const AudioContexts& other)
383       : mValue(static_cast<T>(other.value())) {}
384 
value()385   constexpr T value() const { return mValue; }
value_ref()386   T& value_ref() { return mValue; }
none()387   bool none() const {
388     return mValue == static_cast<T>(LeAudioContextType::UNINITIALIZED);
389   }
any()390   bool any() const { return !none(); }
391 
set(LeAudioContextType const & v)392   void set(LeAudioContextType const& v) { mValue |= static_cast<T>(v); }
unset(const LeAudioContextType & v)393   void unset(const LeAudioContextType& v) { mValue &= ~static_cast<T>(v); }
394 
test(const LeAudioContextType & v)395   bool test(const LeAudioContextType& v) const {
396     return (mValue & static_cast<T>(v)) != 0;
397   }
test_all(const AudioContexts & v)398   bool test_all(const AudioContexts& v) const {
399     return (mValue & v.value()) == v.value();
400   }
test_any(const AudioContexts & v)401   bool test_any(const AudioContexts& v) const {
402     return (mValue & v.value()) != 0;
403   }
clear()404   void clear() { mValue = static_cast<T>(LeAudioContextType::UNINITIALIZED); }
405 
406   std::string to_string() const;
407 
408   AudioContexts& operator=(AudioContexts&& other) = default;
409   AudioContexts& operator=(const AudioContexts&) = default;
410   bool operator==(const AudioContexts& other) const {
411     return value() == other.value();
412   };
413   constexpr AudioContexts operator~() const { return AudioContexts(~value()); }
414 };
415 
416 AudioContexts operator|(std::underlying_type<LeAudioContextType>::type lhs,
417                         const LeAudioContextType rhs);
418 AudioContexts& operator|=(AudioContexts& lhs, AudioContexts const& rhs);
419 AudioContexts& operator&=(AudioContexts& lhs, AudioContexts const& rhs);
420 
421 constexpr AudioContexts operator^(const AudioContexts& lhs,
422                                   const AudioContexts& rhs) {
423   return AudioContexts(lhs.value() ^ rhs.value());
424 }
425 constexpr AudioContexts operator|(const AudioContexts& lhs,
426                                   const AudioContexts& rhs) {
427   return AudioContexts(lhs.value() | rhs.value());
428 }
429 constexpr AudioContexts operator&(const AudioContexts& lhs,
430                                   const AudioContexts& rhs) {
431   return AudioContexts(lhs.value() & rhs.value());
432 }
433 constexpr AudioContexts operator|(const LeAudioContextType& lhs,
434                                   const LeAudioContextType& rhs) {
435   using T = std::underlying_type<LeAudioContextType>::type;
436   return AudioContexts(static_cast<T>(lhs) | static_cast<T>(rhs));
437 }
438 constexpr AudioContexts operator|(const LeAudioContextType& lhs,
439                                   const AudioContexts& rhs) {
440   return AudioContexts(lhs) | rhs;
441 }
442 constexpr AudioContexts operator|(const AudioContexts& lhs,
443                                   const LeAudioContextType& rhs) {
444   return lhs | AudioContexts(rhs);
445 }
446 
447 std::string ToHexString(const types::LeAudioContextType& value);
448 
449 template <typename T>
450 struct BidirectionalPair {
451   T sink;
452   T source;
453 };
454 
455 template <typename T>
456 T get_bidirectional(BidirectionalPair<T> p);
457 
458 template <>
459 AudioContexts get_bidirectional(BidirectionalPair<AudioContexts> p);
460 
461 /* Configuration strategy */
462 enum class LeAudioConfigurationStrategy : uint8_t {
463   MONO_ONE_CIS_PER_DEVICE = 0x00, /* Common true wireless speakers */
464   STEREO_TWO_CISES_PER_DEVICE =
465       0x01, /* Requires 2 ASEs and 2 Audio Allocation for left/right */
466   STEREO_ONE_CIS_PER_DEVICE = 0x02, /* Requires channel count 2*/
467   RFU = 0x03,
468 };
469 
470 constexpr LeAudioContextType kLeAudioContextAllTypesArray[] = {
471     LeAudioContextType::UNSPECIFIED,   LeAudioContextType::CONVERSATIONAL,
472     LeAudioContextType::MEDIA,         LeAudioContextType::GAME,
473     LeAudioContextType::INSTRUCTIONAL, LeAudioContextType::VOICEASSISTANTS,
474     LeAudioContextType::LIVE,          LeAudioContextType::SOUNDEFFECTS,
475     LeAudioContextType::NOTIFICATIONS, LeAudioContextType::RINGTONE,
476     LeAudioContextType::ALERTS,        LeAudioContextType::EMERGENCYALARM,
477 };
478 
479 constexpr AudioContexts kLeAudioContextAllTypes =
480     LeAudioContextType::UNSPECIFIED | LeAudioContextType::CONVERSATIONAL |
481     LeAudioContextType::MEDIA | LeAudioContextType::GAME |
482     LeAudioContextType::INSTRUCTIONAL | LeAudioContextType::VOICEASSISTANTS |
483     LeAudioContextType::LIVE | LeAudioContextType::SOUNDEFFECTS |
484     LeAudioContextType::NOTIFICATIONS | LeAudioContextType::RINGTONE |
485     LeAudioContextType::ALERTS | LeAudioContextType::EMERGENCYALARM;
486 
487 /* Structures */
488 class LeAudioLtvMap {
489  public:
LeAudioLtvMap()490   LeAudioLtvMap() {}
LeAudioLtvMap(std::map<uint8_t,std::vector<uint8_t>> values)491   LeAudioLtvMap(std::map<uint8_t, std::vector<uint8_t>> values)
492       : values(std::move(values)) {}
493 
494   std::optional<std::vector<uint8_t>> Find(uint8_t type) const;
Add(uint8_t type,std::vector<uint8_t> value)495   void Add(uint8_t type, std::vector<uint8_t> value) {
496     values.insert_or_assign(type, std::move(value));
497   }
Remove(uint8_t type)498   void Remove(uint8_t type) { values.erase(type); }
IsEmpty()499   bool IsEmpty() const { return values.empty(); }
Clear()500   void Clear() { values.clear(); }
Size()501   size_t Size() const { return values.size(); }
Values()502   const std::map<uint8_t, std::vector<uint8_t>>& Values() const {
503     return values;
504   }
505   std::string ToString() const;
506   size_t RawPacketSize() const;
507   uint8_t* RawPacket(uint8_t* p_buf) const;
508   std::vector<uint8_t> RawPacket() const;
509   static LeAudioLtvMap Parse(const uint8_t* value, uint8_t len, bool& success);
510   void Append(const LeAudioLtvMap& other);
511 
512  private:
513   std::map<uint8_t, std::vector<uint8_t>> values;
514 };
515 
516 struct LeAudioLc3Config {
517   static const std::map<uint8_t, uint32_t> sampling_freq_map;
518   static const std::map<uint8_t, uint32_t> frame_duration_map;
519 
520   std::optional<uint8_t> sampling_frequency;
521   std::optional<uint8_t> frame_duration;
522   std::optional<uint32_t> audio_channel_allocation;
523   std::optional<uint16_t> octets_per_codec_frame;
524   std::optional<uint8_t> codec_frames_blocks_per_sdu;
525 
526   uint8_t channel_count;
527 
528   /** Returns the sampling frequency representation in Hz */
GetSamplingFrequencyHzLeAudioLc3Config529   uint32_t GetSamplingFrequencyHz() const {
530     if (sampling_frequency)
531       return sampling_freq_map.count(*sampling_frequency)
532                  ? sampling_freq_map.at(*sampling_frequency)
533                  : 0;
534     return 0;
535   }
536 
537   /** Returns the frame duration representation in us */
GetFrameDurationUsLeAudioLc3Config538   uint32_t GetFrameDurationUs() const {
539     if (frame_duration)
540       return frame_duration_map.count(*frame_duration)
541                  ? frame_duration_map.at(*frame_duration)
542                  : 0;
543 
544     return 0;
545   }
546 
GetChannelCountLeAudioLc3Config547   uint8_t GetChannelCount(void) const {
548     if (channel_count) return channel_count;
549 
550     return 0;
551   }
552 
GetAsLtvMapLeAudioLc3Config553   LeAudioLtvMap GetAsLtvMap() const {
554     std::map<uint8_t, std::vector<uint8_t>> values;
555 
556     if (sampling_frequency) {
557       values[codec_spec_conf::kLeAudioCodecLC3TypeSamplingFreq] =
558           UINT8_TO_VEC_UINT8(*sampling_frequency);
559     }
560 
561     if (frame_duration) {
562       values[codec_spec_conf::kLeAudioCodecLC3TypeFrameDuration] =
563           UINT8_TO_VEC_UINT8(*frame_duration);
564     }
565 
566     if (audio_channel_allocation) {
567       values[codec_spec_conf::kLeAudioCodecLC3TypeAudioChannelAllocation] =
568           UINT32_TO_VEC_UINT8(*audio_channel_allocation);
569     }
570 
571     if (octets_per_codec_frame) {
572       values[codec_spec_conf::kLeAudioCodecLC3TypeOctetPerFrame] =
573           UINT16_TO_VEC_UINT8(*octets_per_codec_frame);
574     }
575 
576     if (codec_frames_blocks_per_sdu) {
577       values[codec_spec_conf::kLeAudioCodecLC3TypeCodecFrameBlocksPerSdu] =
578           UINT8_TO_VEC_UINT8(*codec_frames_blocks_per_sdu);
579     }
580 
581     return LeAudioLtvMap(values);
582   }
583 };
584 
585 struct LeAudioCodecId {
586   uint8_t coding_format;
587   uint16_t vendor_company_id;
588   uint16_t vendor_codec_id;
589 
590   friend bool operator==(const LeAudioCodecId& lhs, const LeAudioCodecId& rhs) {
591     if (lhs.coding_format != rhs.coding_format) return false;
592 
593     if (lhs.coding_format == kLeAudioCodingFormatVendorSpecific &&
594         (lhs.vendor_company_id != rhs.vendor_company_id ||
595          lhs.vendor_codec_id != rhs.vendor_codec_id))
596       return false;
597 
598     return true;
599   }
600 
601   friend bool operator!=(const LeAudioCodecId& lhs, const LeAudioCodecId& rhs) {
602     return !(lhs == rhs);
603   }
604 };
605 
606 struct hdl_pair {
607   hdl_pair() = default;
hdl_pairhdl_pair608   hdl_pair(uint16_t val_hdl, uint16_t ccc_hdl)
609       : val_hdl(val_hdl), ccc_hdl(ccc_hdl) {}
610 
611   uint16_t val_hdl = 0;
612   uint16_t ccc_hdl = 0;
613 };
614 
615 struct ase {
616   static constexpr uint8_t kAseIdInvalid = 0x00;
617 
618   ase(uint16_t val_hdl, uint16_t ccc_hdl, uint8_t direction,
619       uint8_t initial_id = kAseIdInvalid)
hdlsase620       : hdls(val_hdl, ccc_hdl),
621         id(initial_id),
622         cis_id(kInvalidCisId),
623         direction(direction),
624         target_latency(types::kTargetLatencyBalancedLatencyReliability),
625         active(false),
626         reconfigure(false),
627         data_path_state(AudioStreamDataPathState::IDLE),
628         configured_for_context_type(LeAudioContextType::UNINITIALIZED),
629         preferred_phy(0),
630         max_sdu_size(0),
631         retrans_nb(0),
632         max_transport_latency(0),
633         pres_delay_min(0),
634         pres_delay_max(0),
635         preferred_pres_delay_min(0),
636         preferred_pres_delay_max(0),
637         state(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {}
638 
639   struct hdl_pair hdls;
640   uint8_t id;
641   uint8_t cis_id;
642   const uint8_t direction;
643   uint8_t target_latency;
644   uint16_t cis_conn_hdl = 0;
645 
646   bool active;
647   bool reconfigure;
648   AudioStreamDataPathState data_path_state;
649   LeAudioContextType configured_for_context_type;
650 
651   /* Codec configuration */
652   LeAudioCodecId codec_id;
653   LeAudioLc3Config codec_config;
654   uint8_t framing;
655   uint8_t preferred_phy;
656 
657   /* Qos configuration */
658   uint16_t max_sdu_size;
659   uint8_t retrans_nb;
660   uint16_t max_transport_latency;
661   uint32_t pres_delay_min;
662   uint32_t pres_delay_max;
663   uint32_t preferred_pres_delay_min;
664   uint32_t preferred_pres_delay_max;
665 
666   std::vector<uint8_t> metadata;
667 
668   AseState state;
669 };
670 
671 struct BidirectAsesPair {
672   struct ase* sink;
673   struct ase* source;
674 };
675 
676 struct acs_ac_record {
677   LeAudioCodecId codec_id;
678   LeAudioLtvMap codec_spec_caps;
679   std::vector<uint8_t> metadata;
680 };
681 
682 using PublishedAudioCapabilities =
683     std::vector<std::tuple<hdl_pair, std::vector<acs_ac_record>>>;
684 using AudioLocations = std::bitset<32>;
685 
686 std::ostream& operator<<(std::ostream& os, const AseState& state);
687 std::ostream& operator<<(std::ostream& os, const CigState& state);
688 std::ostream& operator<<(std::ostream& os, const LeAudioLc3Config& config);
689 std::ostream& operator<<(std::ostream& os, const LeAudioContextType& context);
690 std::ostream& operator<<(std::ostream& os,
691                          const AudioStreamDataPathState& state);
692 std::ostream& operator<<(std::ostream& os, const AudioContexts& contexts);
693 }  // namespace types
694 
695 namespace set_configurations {
696 
697 struct CodecCapabilitySetting {
698   types::LeAudioCodecId id;
699 
700   /* Codec Specific Configuration variant */
701   std::variant<types::LeAudioLc3Config> config;
702 
703   /* Sampling freqency requested for codec */
704   uint32_t GetConfigSamplingFrequency() const;
705   /* Data fetch/feed interval for codec in microseconds */
706   uint32_t GetConfigDataIntervalUs() const;
707   /* Audio bit depth required for codec */
708   uint8_t GetConfigBitsPerSample() const;
709   /* Audio channels number for stream */
710   uint8_t GetConfigChannelCount() const;
711 };
712 
713 struct QosConfigSetting {
714   uint8_t retransmission_number;
715   uint16_t max_transport_latency;
716 };
717 
718 struct SetConfiguration {
719   SetConfiguration(uint8_t direction, uint8_t device_cnt, uint8_t ase_cnt,
720                    uint8_t target_latency, CodecCapabilitySetting codec,
721                    QosConfigSetting qos = {.retransmission_number = 0,
722                                            .max_transport_latency = 0},
723                    le_audio::types::LeAudioConfigurationStrategy strategy =
724                        le_audio::types::LeAudioConfigurationStrategy::
725                            MONO_ONE_CIS_PER_DEVICE)
directionSetConfiguration726       : direction(direction),
727         device_cnt(device_cnt),
728         ase_cnt(ase_cnt),
729         target_latency(target_latency),
730         codec(codec),
731         qos(qos),
732         strategy(strategy) {}
733 
734   uint8_t direction;  /* Direction of set */
735   uint8_t device_cnt; /* How many devices must be in set */
736   uint8_t ase_cnt;    /* How many ASE we need in configuration */
737   uint8_t target_latency;
738   CodecCapabilitySetting codec;
739   QosConfigSetting qos;
740   types::LeAudioConfigurationStrategy strategy;
741 };
742 
743 /* Defined audio scenarios */
744 struct AudioSetConfiguration {
745   std::string name;
746   std::vector<struct SetConfiguration> confs;
747 };
748 
749 using AudioSetConfigurations = std::vector<const AudioSetConfiguration*>;
750 
751 const types::LeAudioCodecId LeAudioCodecIdLc3 = {
752     .coding_format = types::kLeAudioCodingFormatLC3,
753     .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined,
754     .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined};
755 
756 static constexpr uint32_t kChannelAllocationStereo =
757     codec_spec_conf::kLeAudioLocationFrontLeft |
758     codec_spec_conf::kLeAudioLocationFrontRight;
759 
760 /* Declarations */
761 void get_cis_count(const AudioSetConfigurations& audio_set_configurations,
762                    int expected_device_cnt,
763                    types::LeAudioConfigurationStrategy strategy,
764                    int group_ase_snk_cnt, int group_ase_src_count,
765                    uint8_t& cis_count_bidir, uint8_t& cis_count_unidir_sink,
766                    uint8_t& cis_count_unidir_source);
767 bool check_if_may_cover_scenario(
768     const AudioSetConfigurations* audio_set_configurations, uint8_t group_size);
769 bool check_if_may_cover_scenario(
770     const AudioSetConfiguration* audio_set_configuration, uint8_t group_size);
771 bool IsCodecCapabilitySettingSupported(
772     const types::acs_ac_record& pac_record,
773     const CodecCapabilitySetting& codec_capability_setting);
774 uint8_t get_num_of_devices_in_configuration(
775     const AudioSetConfiguration* audio_set_configuration);
776 }  // namespace set_configurations
777 
778 struct stream_configuration {
779   bool pending_configuration;
780 
781   types::LeAudioCodecId id;
782 
783   /* Pointer to chosen req */
784   const le_audio::set_configurations::AudioSetConfiguration* conf;
785 
786   /* Sink configuration */
787   /* For now we have always same frequency for all the channels */
788   uint32_t sink_sample_frequency_hz;
789   uint32_t sink_frame_duration_us;
790   uint16_t sink_octets_per_codec_frame;
791   uint32_t sink_audio_channel_allocation;
792   uint8_t sink_codec_frames_blocks_per_sdu;
793   /* Number of channels is what we will request from audio framework */
794   uint8_t sink_num_of_channels;
795   int sink_num_of_devices;
796   /* cis_handle, audio location*/
797   std::vector<std::pair<uint16_t, uint32_t>> sink_streams;
798   /* cis_handle, target allocation */
799   std::vector<std::pair<uint16_t, uint32_t>>
800       sink_offloader_streams_target_allocation;
801   /* cis_handle, current allocation */
802   std::vector<std::pair<uint16_t, uint32_t>>
803       sink_offloader_streams_current_allocation;
804   bool sink_offloader_changed;
805   bool sink_is_initial;
806 
807   /* Source configuration */
808   /* For now we have always same frequency for all the channels */
809   uint32_t source_sample_frequency_hz;
810   uint32_t source_frame_duration_us;
811   uint16_t source_octets_per_codec_frame;
812   uint32_t source_audio_channel_allocation;
813   uint8_t source_codec_frames_blocks_per_sdu;
814   /* Number of channels is what we will request from audio framework */
815   uint8_t source_num_of_channels;
816   int source_num_of_devices;
817   /* cis_handle, audio location*/
818   std::vector<std::pair<uint16_t, uint32_t>> source_streams;
819   /* cis_handle, target allocation */
820   std::vector<std::pair<uint16_t, uint32_t>>
821       source_offloader_streams_target_allocation;
822   /* cis_handle, current allocation */
823   std::vector<std::pair<uint16_t, uint32_t>>
824       source_offloader_streams_current_allocation;
825   bool source_offloader_changed;
826   bool source_is_initial;
827 };
828 
829 void AppendMetadataLtvEntryForCcidList(std::vector<uint8_t>& metadata,
830                                        const std::vector<uint8_t>& ccid_list);
831 void AppendMetadataLtvEntryForStreamingContext(
832     std::vector<uint8_t>& metadata, types::AudioContexts context_type);
833 uint8_t GetMaxCodecFramesPerSduFromPac(const types::acs_ac_record* pac_record);
834 uint32_t AdjustAllocationForOffloader(uint32_t allocation);
835 }  // namespace le_audio