• 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 <bluetooth/log.h>
26 #include <stdint.h>
27 
28 #include <bit>
29 #include <bitset>
30 #include <map>
31 #include <memory>
32 #include <optional>
33 #include <string>
34 #include <variant>
35 #include <vector>
36 
37 #include "bta/include/bta_le_audio_uuids.h"
38 #include "osi/include/alarm.h"
39 #include "stack/include/bt_types.h"
40 #include "stack/include/btm_iso_api_types.h"
41 #include "types/bluetooth/uuid.h"
42 
43 namespace bluetooth::le_audio {
44 
45 #define UINT8_TO_VEC_UINT8(u8) \
46   std::vector<uint8_t> { u8 }
47 #define UINT16_TO_VEC_UINT8(u16) \
48   std::vector<uint8_t>((uint8_t*)&u16, (uint8_t*)&u16 + sizeof(uint16_t))
49 #define UINT32_TO_VEC_UINT8(u32) \
50   std::vector<uint8_t>((uint8_t*)&u32, (uint8_t*)&u32 + sizeof(uint32_t))
51 
52 #define VEC_UINT8_TO_UINT8(vec) vec.data()[0]
53 #define VEC_UINT8_TO_UINT16(vec) ((vec.data()[1] << 8) + vec.data()[0])
54 #define OFF_VEC_UINT8_TO_UINT16(vec, off) ((vec.data()[1 + off] << 8) + vec.data()[0 + off])
55 #define VEC_UINT8_TO_UINT32(vec) \
56   ((vec.data()[3] << 24) + (vec.data()[2] << 16) + (vec.data()[1] << 8) + vec.data()[0])
57 
58 enum class DsaMode { DISABLED = 0, ACL, ISO_SW, ISO_HW };
59 typedef std::vector<DsaMode> DsaModes;
60 
61 namespace uuid {
62 /* CAP service
63  * This service is used to identify peer role (which we are not using for now)
64  * and to wrap CSIS service as this is required to understand the context of the
65  * CSIS
66  */
67 static const bluetooth::Uuid kCapServiceUuid =
68         bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE);
69 
70 /* Assigned numbers for attributes */
71 static const bluetooth::Uuid kPublishedAudioCapabilityServiceUuid =
72         bluetooth::Uuid::From16Bit(0x1850);
73 static const bluetooth::Uuid kAudioStreamControlServiceUuid = bluetooth::Uuid::From16Bit(0x184E);
74 
75 static const bluetooth::Uuid kTelephonyMediaAudioServiceUuid = bluetooth::Uuid::From16Bit(0x1855);
76 
77 static const bluetooth::Uuid kGamingAudioServiceUuid = bluetooth::Uuid::From16Bit(0x1858);
78 
79 /* Published Audio Capabilities Service Characteristics */
80 static const bluetooth::Uuid kSinkPublishedAudioCapabilityCharacteristicUuid =
81         bluetooth::Uuid::From16Bit(0x2BC9);
82 static const bluetooth::Uuid kSourcePublishedAudioCapabilityCharacteristicUuid =
83         bluetooth::Uuid::From16Bit(0x2BCB);
84 static const bluetooth::Uuid kSinkAudioLocationCharacteristicUuid =
85         bluetooth::Uuid::From16Bit(0x2BCA);
86 static const bluetooth::Uuid kSourceAudioLocationCharacteristicUuid =
87         bluetooth::Uuid::From16Bit(0x2BCC);
88 
89 /* Audio Stream Control Service Characteristics */
90 static const bluetooth::Uuid kAudioContextAvailabilityCharacteristicUuid =
91         bluetooth::Uuid::From16Bit(0x2BCD);
92 static const bluetooth::Uuid kAudioSupportedContextCharacteristicUuid =
93         bluetooth::Uuid::From16Bit(0x2BCE);
94 
95 /* Audio Stream Control Service Characteristics */
96 static const bluetooth::Uuid kSinkAudioStreamEndpointUuid = bluetooth::Uuid::From16Bit(0x2BC4);
97 static const bluetooth::Uuid kSourceAudioStreamEndpointUuid = bluetooth::Uuid::From16Bit(0x2BC5);
98 static const bluetooth::Uuid kAudioStreamEndpointControlPointCharacteristicUuid =
99         bluetooth::Uuid::From16Bit(0x2BC6);
100 
101 /* Telephony and Media Audio Service Characteristics */
102 static const bluetooth::Uuid kTelephonyMediaAudioProfileRoleCharacteristicUuid =
103         bluetooth::Uuid::From16Bit(0x2B51);
104 
105 /* Gaming Audio Service Characteristics */
106 static const bluetooth::Uuid kRoleCharacteristicUuid = bluetooth::Uuid::From16Bit(0x2C00);
107 static const bluetooth::Uuid kUnicastGameGatewayCharacteristicUuid =
108         bluetooth::Uuid::From16Bit(0x2C01);
109 static const bluetooth::Uuid kUnicastGameTerminalCharacteristicUuid =
110         bluetooth::Uuid::From16Bit(0x2C02);
111 }  // namespace uuid
112 
113 namespace codec_spec_conf {
114 constexpr uint8_t SingleCapaToConfigHelper(uint16_t single_capability, uint8_t offset = 0) {
115   if (!single_capability || std::popcount(single_capability) > 1) {
116     return 0;
117   }
118   return std::countr_zero(single_capability) + offset;
119 }
120 
SingleSamplingFreqCapability2Config(uint16_t single_capability)121 constexpr uint8_t SingleSamplingFreqCapability2Config(uint16_t single_capability) {
122   return SingleCapaToConfigHelper(single_capability, 1);
123 }
124 
SingleFrameDurationCapability2Config(uint16_t single_capability)125 constexpr uint8_t SingleFrameDurationCapability2Config(uint16_t single_capability) {
126   return SingleCapaToConfigHelper(single_capability);
127 }
128 
SingleChannelCountCapability2Config(uint16_t single_capability)129 constexpr uint8_t SingleChannelCountCapability2Config(uint16_t single_capability) {
130   return SingleCapaToConfigHelper(single_capability, 1);
131 }
132 
133 /* LTV Types */
134 constexpr uint8_t kLeAudioLtvTypeSamplingFreq = 0x01;
135 constexpr uint8_t kLeAudioLtvTypeFrameDuration = 0x02;
136 constexpr uint8_t kLeAudioLtvTypeAudioChannelAllocation = 0x03;
137 constexpr uint8_t kLeAudioLtvTypeOctetsPerCodecFrame = 0x04;
138 constexpr uint8_t kLeAudioLtvTypeCodecFrameBlocksPerSdu = 0x05;
139 
140 /* Sampling Frequencies */
141 constexpr uint8_t kLeAudioSamplingFreq8000Hz = 0x01;
142 constexpr uint8_t kLeAudioSamplingFreq11025Hz = 0x02;
143 constexpr uint8_t kLeAudioSamplingFreq16000Hz = 0x03;
144 constexpr uint8_t kLeAudioSamplingFreq22050Hz = 0x04;
145 constexpr uint8_t kLeAudioSamplingFreq24000Hz = 0x05;
146 constexpr uint8_t kLeAudioSamplingFreq32000Hz = 0x06;
147 constexpr uint8_t kLeAudioSamplingFreq44100Hz = 0x07;
148 constexpr uint8_t kLeAudioSamplingFreq48000Hz = 0x08;
149 constexpr uint8_t kLeAudioSamplingFreq88200Hz = 0x09;
150 constexpr uint8_t kLeAudioSamplingFreq96000Hz = 0x0A;
151 constexpr uint8_t kLeAudioSamplingFreq176400Hz = 0x0B;
152 constexpr uint8_t kLeAudioSamplingFreq192000Hz = 0x0C;
153 constexpr uint8_t kLeAudioSamplingFreq384000Hz = 0x0D;
154 
155 /* Frame Durations */
156 constexpr uint8_t kLeAudioCodecFrameDur7500us = 0x00;
157 constexpr uint8_t kLeAudioCodecFrameDur10000us = 0x01;
158 
159 /* Audio Allocations */
160 constexpr uint32_t kLeAudioLocationMonoAudio = 0x00000000;
161 constexpr uint32_t kLeAudioLocationFrontLeft = 0x00000001;
162 constexpr uint32_t kLeAudioLocationFrontRight = 0x00000002;
163 constexpr uint32_t kLeAudioLocationFrontCenter = 0x00000004;
164 constexpr uint32_t kLeAudioLocationLowFreqEffects1 = 0x00000008;
165 constexpr uint32_t kLeAudioLocationBackLeft = 0x00000010;
166 constexpr uint32_t kLeAudioLocationBackRight = 0x00000020;
167 constexpr uint32_t kLeAudioLocationFrontLeftOfCenter = 0x00000040;
168 constexpr uint32_t kLeAudioLocationFrontRightOfCenter = 0x00000080;
169 constexpr uint32_t kLeAudioLocationBackCenter = 0x00000100;
170 constexpr uint32_t kLeAudioLocationLowFreqEffects2 = 0x00000200;
171 constexpr uint32_t kLeAudioLocationSideLeft = 0x00000400;
172 constexpr uint32_t kLeAudioLocationSideRight = 0x00000800;
173 constexpr uint32_t kLeAudioLocationTopFrontLeft = 0x00001000;
174 constexpr uint32_t kLeAudioLocationTopFrontRight = 0x00002000;
175 constexpr uint32_t kLeAudioLocationTopFrontCenter = 0x00004000;
176 constexpr uint32_t kLeAudioLocationTopCenter = 0x00008000;
177 constexpr uint32_t kLeAudioLocationTopBackLeft = 0x00010000;
178 constexpr uint32_t kLeAudioLocationTopBackRight = 0x00020000;
179 constexpr uint32_t kLeAudioLocationTopSideLeft = 0x00040000;
180 constexpr uint32_t kLeAudioLocationTopSideRight = 0x00080000;
181 constexpr uint32_t kLeAudioLocationTopBackCenter = 0x00100000;
182 constexpr uint32_t kLeAudioLocationBottomFrontCenter = 0x00200000;
183 constexpr uint32_t kLeAudioLocationBottomFrontLeft = 0x00400000;
184 constexpr uint32_t kLeAudioLocationBottomFrontRight = 0x00800000;
185 constexpr uint32_t kLeAudioLocationFrontLeftWide = 0x01000000;
186 constexpr uint32_t kLeAudioLocationFrontRightWide = 0x02000000;
187 constexpr uint32_t kLeAudioLocationLeftSurround = 0x04000000;
188 constexpr uint32_t kLeAudioLocationRightSurround = 0x08000000;
189 
190 constexpr uint32_t kLeAudioLocationAnyLeft =
191         kLeAudioLocationFrontLeft | kLeAudioLocationBackLeft | kLeAudioLocationFrontLeftOfCenter |
192         kLeAudioLocationSideLeft | kLeAudioLocationTopFrontLeft | kLeAudioLocationTopBackLeft |
193         kLeAudioLocationTopSideLeft | kLeAudioLocationBottomFrontLeft |
194         kLeAudioLocationFrontLeftWide | kLeAudioLocationLeftSurround;
195 
196 constexpr uint32_t kLeAudioLocationAnyRight =
197         kLeAudioLocationFrontRight | kLeAudioLocationBackRight |
198         kLeAudioLocationFrontRightOfCenter | kLeAudioLocationSideRight |
199         kLeAudioLocationTopFrontRight | kLeAudioLocationTopBackRight |
200         kLeAudioLocationTopSideRight | kLeAudioLocationBottomFrontRight |
201         kLeAudioLocationFrontRightWide | kLeAudioLocationRightSurround;
202 
203 constexpr uint32_t kLeAudioLocationStereo = kLeAudioLocationFrontLeft | kLeAudioLocationFrontRight;
204 
205 /* Octets Per Frame */
206 constexpr uint16_t kLeAudioCodecFrameLen30 = 30;
207 constexpr uint16_t kLeAudioCodecFrameLen40 = 40;
208 constexpr uint16_t kLeAudioCodecFrameLen60 = 60;
209 constexpr uint16_t kLeAudioCodecFrameLen80 = 80;
210 constexpr uint16_t kLeAudioCodecFrameLen100 = 100;
211 constexpr uint16_t kLeAudioCodecFrameLen120 = 120;
212 
213 }  // namespace codec_spec_conf
214 
215 constexpr uint8_t kInvalidCisId = 0xFF;
216 constexpr uint16_t kInvalidCisConnHandle = 0xFFFF;
217 
218 namespace codec_spec_caps {
SamplingFreqConfig2Capability(uint8_t conf)219 uint16_t constexpr SamplingFreqConfig2Capability(uint8_t conf) {
220   if (!conf) {
221     return 0;
222   }
223   return 0x01 << (conf - 1);
224 }
225 
FrameDurationConfig2Capability(uint8_t conf)226 uint8_t constexpr FrameDurationConfig2Capability(uint8_t conf) { return 0x01 << (conf); }
227 
ChannelCountConfig2Capability(uint8_t conf)228 uint16_t constexpr ChannelCountConfig2Capability(uint8_t conf) {
229   if (!conf) {
230     return 0;
231   }
232   return 0x01 << (conf - 1);
233 }
234 
235 /* LTV Types - same values as in Codec Specific Configurations but 0x03 is
236  * named differently.
237  */
238 constexpr uint8_t kLeAudioLtvTypeSupportedSamplingFrequencies =
239         codec_spec_conf::kLeAudioLtvTypeSamplingFreq;
240 constexpr uint8_t kLeAudioLtvTypeSupportedFrameDurations =
241         codec_spec_conf::kLeAudioLtvTypeFrameDuration;
242 constexpr uint8_t kLeAudioLtvTypeSupportedAudioChannelCounts =
243         codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation;
244 constexpr uint8_t kLeAudioLtvTypeSupportedOctetsPerCodecFrame =
245         codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame;
246 constexpr uint8_t kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu =
247         codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu;
248 
249 /* Sampling Frequencies */
250 constexpr uint16_t kLeAudioSamplingFreq8000Hz =
251         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq8000Hz);
252 constexpr uint16_t kLeAudioSamplingFreq11025Hz =
253         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq11025Hz);
254 constexpr uint16_t kLeAudioSamplingFreq16000Hz =
255         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq16000Hz);
256 constexpr uint16_t kLeAudioSamplingFreq22050Hz =
257         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq22050Hz);
258 constexpr uint16_t kLeAudioSamplingFreq24000Hz =
259         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq24000Hz);
260 constexpr uint16_t kLeAudioSamplingFreq32000Hz =
261         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq32000Hz);
262 constexpr uint16_t kLeAudioSamplingFreq44100Hz =
263         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq44100Hz);
264 constexpr uint16_t kLeAudioSamplingFreq48000Hz =
265         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq48000Hz);
266 constexpr uint16_t kLeAudioSamplingFreq88200Hz =
267         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq88200Hz);
268 constexpr uint16_t kLeAudioSamplingFreq96000Hz =
269         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq96000Hz);
270 constexpr uint16_t kLeAudioSamplingFreq176400Hz =
271         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq176400Hz);
272 constexpr uint16_t kLeAudioSamplingFreq192000Hz =
273         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq192000Hz);
274 constexpr uint16_t kLeAudioSamplingFreq384000Hz =
275         SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq384000Hz);
276 
277 /* Frame Durations */
278 constexpr uint8_t kLeAudioCodecFrameDur7500us =
279         FrameDurationConfig2Capability(codec_spec_conf::kLeAudioCodecFrameDur7500us);
280 constexpr uint8_t kLeAudioCodecFrameDur10000us =
281         FrameDurationConfig2Capability(codec_spec_conf::kLeAudioCodecFrameDur10000us);
282 constexpr uint8_t kLeAudioCodecFrameDurPrefer7500us = 0x10;
283 constexpr uint8_t kLeAudioCodecFrameDurPrefer10000us = 0x20;
284 
285 /* Audio Channel Counts */
286 /* Each bit represents support for additional channel: bit 0 - one channel,
287  * bit 1 - two, bit 3 - four channels. Multiple bits can be enabled at once.
288  */
289 constexpr uint8_t kLeAudioCodecChannelCountNone = 0x00;
290 constexpr uint8_t kLeAudioCodecChannelCountSingleChannel = 0x01;
291 constexpr uint8_t kLeAudioCodecChannelCountTwoChannel = 0x02;
292 constexpr uint8_t kLeAudioCodecChannelCountThreeChannel = 0x04;
293 constexpr uint8_t kLeAudioCodecChannelCountFourChannel = 0x08;
294 constexpr uint8_t kLeAudioCodecChannelCountFiveChannel = 0x10;
295 constexpr uint8_t kLeAudioCodecChannelCountSixChannel = 0x20;
296 constexpr uint8_t kLeAudioCodecChannelCountSevenChannel = 0x40;
297 constexpr uint8_t kLeAudioCodecChannelCountEightChannel = 0x80;
298 
299 /* Octets Per Frame */
300 constexpr uint16_t kLeAudioCodecFrameLen30 = codec_spec_conf::kLeAudioCodecFrameLen30;
301 constexpr uint16_t kLeAudioCodecFrameLen40 = codec_spec_conf::kLeAudioCodecFrameLen40;
302 constexpr uint16_t kLeAudioCodecFrameLen60 = codec_spec_conf::kLeAudioCodecFrameLen60;
303 constexpr uint16_t kLeAudioCodecFrameLen80 = codec_spec_conf::kLeAudioCodecFrameLen80;
304 constexpr uint16_t kLeAudioCodecFrameLen120 = codec_spec_conf::kLeAudioCodecFrameLen120;
305 
306 };  // namespace codec_spec_caps
307 
308 namespace types {
309 constexpr uint8_t kLeAudioCodingFormatLC3 = bluetooth::hci::kIsoCodingFormatLc3;
310 constexpr uint8_t kLeAudioCodingFormatVendorSpecific =
311         bluetooth::hci::kIsoCodingFormatVendorSpecific;
312 constexpr uint16_t kLeAudioVendorCompanyIdUndefined = 0x00;
313 constexpr uint16_t kLeAudioVendorCodecIdUndefined = 0x00;
314 
315 constexpr uint16_t kLeAudioVendorCompanyIdGoogle = 0x00E0;
316 constexpr uint16_t kLeAudioVendorCodecIdHeadtracking = 0x0001;
317 
318 /* Metadata types from Assigned Numbers */
319 constexpr uint8_t kLeAudioMetadataTypePreferredAudioContext = 0x01;
320 constexpr uint8_t kLeAudioMetadataTypeStreamingAudioContext = 0x02;
321 constexpr uint8_t kLeAudioMetadataTypeProgramInfo = 0x03;
322 constexpr uint8_t kLeAudioMetadataTypeLanguage = 0x04;
323 constexpr uint8_t kLeAudioMetadataTypeCcidList = 0x05;
324 constexpr uint8_t kLeAudioMetadataTypeparentalRating = 0x06;
325 constexpr uint8_t kLeAudioMetadataTypeProgramInfoUri = 0x07;
326 constexpr uint8_t kLeAudioMetadataTypeAudioActiveState = 0x08;
327 constexpr uint8_t kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag = 0x09;
328 constexpr uint8_t kLeAudioMetadataTypeExtendedMetadata = 0xFE;
329 constexpr uint8_t kLeAudioMetadataTypeVendorSpecific = 0xFF;
330 
331 constexpr uint8_t kLeAudioMetadataTypeLen = 1;
332 constexpr uint8_t kLeAudioMetadataLenLen = 1;
333 
334 constexpr uint8_t kLeAudioMetadataStreamingAudioContextLen = 2;
335 
336 /* Android Headtracker Codec metadata */
337 constexpr uint8_t kLeAudioMetadataHeadtrackerTransportLen = 1;
338 constexpr uint8_t kLeAudioMetadataHeadtrackerTransportVal = 1;
339 constexpr uint8_t kLeAudioMetadataHeadtrackerTransportLeAcl = 1;
340 constexpr uint8_t kLeAudioMetadataHeadtrackerTransportLeIso = 2;
341 
342 /* Android Headtracker config parameters */
343 constexpr uint32_t kLeAudioHeadtrackerSduItv = 20000;
344 constexpr uint16_t kLeAudioHeadtrackerMaxTransLat = 20;
345 constexpr uint16_t kLeAudioHeadtrackerMaxSduSize = 13;
346 constexpr uint8_t kLeAudioHeadtrackerRtn = 2;
347 
348 /* CSIS Types */
349 constexpr uint8_t kDefaultScanDurationS = 5;
350 constexpr uint8_t kDefaultCsisSetSize = 2;
351 
352 constexpr uint8_t kLeAudioDirectionSink = 0x01;
353 constexpr uint8_t kLeAudioDirectionSource = 0x02;
354 constexpr uint8_t kLeAudioDirectionBoth = kLeAudioDirectionSink | kLeAudioDirectionSource;
355 
356 /* Audio stream config types */
357 constexpr uint8_t kFramingUnframedPduSupported = 0x00;
358 constexpr uint8_t kFramingUnframedPduUnsupported = 0x01;
359 
360 constexpr uint8_t kTargetLatencyUndefined = 0x00;
361 constexpr uint8_t kTargetLatencyLower = 0x01;
362 constexpr uint8_t kTargetLatencyBalancedLatencyReliability = 0x02;
363 constexpr uint8_t kTargetLatencyHigherReliability = 0x03;
364 
365 constexpr uint8_t kTargetPhyUndefined = 0x00;
366 constexpr uint8_t kTargetPhy1M = 0x01;
367 constexpr uint8_t kTargetPhy2M = 0x02;
368 constexpr uint8_t kTargetPhyCoded = 0x03;
369 
370 constexpr uint32_t kPresDelayNoPreference = 0x00000000;
371 
372 constexpr uint16_t kMaxTransportLatencyMin = 0x0005;
373 constexpr uint16_t kMaxTransportLatencyMax = 0x0FA0;
374 
375 enum class CigState : uint8_t { NONE, CREATING, CREATED, REMOVING, RECOVERING };
376 
377 /* ASE states according to BAP defined state machine states */
378 enum class AseState : uint8_t {
379   BTA_LE_AUDIO_ASE_STATE_IDLE = 0x00,
380   BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED = 0x01,
381   BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED = 0x02,
382   BTA_LE_AUDIO_ASE_STATE_ENABLING = 0x03,
383   BTA_LE_AUDIO_ASE_STATE_STREAMING = 0x04,
384   BTA_LE_AUDIO_ASE_STATE_DISABLING = 0x05,
385   BTA_LE_AUDIO_ASE_STATE_RELEASING = 0x06,
386 };
387 
388 enum class CisState {
389   IDLE,
390   ASSIGNED,
391   CONNECTING,
392   CONNECTED,
393   DISCONNECTING,
394 };
395 
396 enum class DataPathState {
397   IDLE,
398   CONFIGURING,
399   CONFIGURED,
400   REMOVING,
401 };
402 
403 enum class CisType {
404   CIS_TYPE_BIDIRECTIONAL,
405   CIS_TYPE_UNIDIRECTIONAL_SINK,
406   CIS_TYPE_UNIDIRECTIONAL_SOURCE,
407 };
408 
409 struct cis {
410   uint8_t id;
411   CisType type;
412   uint16_t conn_handle;
413   RawAddress addr;
414 };
415 
416 enum class CodecLocation {
417   HOST,
418   ADSP,
419   CONTROLLER,
420 };
421 
422 /* Context Types */
423 enum class LeAudioContextType : uint16_t {
424   UNINITIALIZED = 0x0000,
425   UNSPECIFIED = 0x0001,
426   CONVERSATIONAL = 0x0002,
427   MEDIA = 0x0004,
428   GAME = 0x0008,
429   INSTRUCTIONAL = 0x0010,
430   VOICEASSISTANTS = 0x0020,
431   LIVE = 0x0040,
432   SOUNDEFFECTS = 0x0080,
433   NOTIFICATIONS = 0x0100,
434   RINGTONE = 0x0200,
435   ALERTS = 0x0400,
436   EMERGENCYALARM = 0x0800,
437   RFU = 0x1000,
438 };
439 
440 class AudioContexts {
441   using T = std::underlying_type<LeAudioContextType>::type;
442   T mValue;
443 
444 public:
AudioContexts()445   explicit constexpr AudioContexts() : mValue(static_cast<T>(LeAudioContextType::UNINITIALIZED)) {}
AudioContexts(const T & v)446   explicit constexpr AudioContexts(const T& v) : mValue(v) {}
AudioContexts(const LeAudioContextType & v)447   explicit constexpr AudioContexts(const LeAudioContextType& v) : mValue(static_cast<T>(v)) {}
AudioContexts(const AudioContexts & other)448   constexpr AudioContexts(const AudioContexts& other) : mValue(static_cast<T>(other.value())) {}
449 
value()450   constexpr T value() const { return mValue; }
value_ref()451   T& value_ref() { return mValue; }
none()452   bool none() const { return mValue == static_cast<T>(LeAudioContextType::UNINITIALIZED); }
any()453   bool any() const { return !none(); }
454 
set(const LeAudioContextType & v)455   void set(const LeAudioContextType& v) { mValue |= static_cast<T>(v); }
set_all(const AudioContexts & v)456   void set_all(const AudioContexts& v) { mValue |= v.value(); }
unset(const LeAudioContextType & v)457   void unset(const LeAudioContextType& v) { mValue &= ~static_cast<T>(v); }
unset_all(const AudioContexts & v)458   void unset_all(const AudioContexts& v) { mValue &= ~v.value(); }
459 
test(const LeAudioContextType & v)460   bool test(const LeAudioContextType& v) const { return (mValue & static_cast<T>(v)) != 0; }
test_all(const AudioContexts & v)461   bool test_all(const AudioContexts& v) const { return (mValue & v.value()) == v.value(); }
test_any(const AudioContexts & v)462   bool test_any(const AudioContexts& v) const { return (mValue & v.value()) != 0; }
clear()463   void clear() { mValue = static_cast<T>(LeAudioContextType::UNINITIALIZED); }
464 
465   std::string to_string() const;
466 
467   AudioContexts& operator=(AudioContexts&& other) = default;
468   AudioContexts& operator=(const AudioContexts&) = default;
469   bool operator==(const AudioContexts& other) const { return value() == other.value(); }
470   bool operator!=(const AudioContexts& other) const { return value() != other.value(); }
471   constexpr AudioContexts operator~() const { return AudioContexts(~value()); }
472 };
473 
474 AudioContexts operator|(std::underlying_type<LeAudioContextType>::type lhs,
475                         const LeAudioContextType rhs);
476 AudioContexts& operator|=(AudioContexts& lhs, AudioContexts const& rhs);
477 AudioContexts& operator&=(AudioContexts& lhs, AudioContexts const& rhs);
478 
479 constexpr AudioContexts operator^(const AudioContexts& lhs, const AudioContexts& rhs) {
480   return AudioContexts(lhs.value() ^ rhs.value());
481 }
482 constexpr AudioContexts operator|(const AudioContexts& lhs, const AudioContexts& rhs) {
483   return AudioContexts(lhs.value() | rhs.value());
484 }
485 constexpr AudioContexts operator&(const AudioContexts& lhs, const AudioContexts& rhs) {
486   return AudioContexts(lhs.value() & rhs.value());
487 }
488 constexpr AudioContexts operator|(const LeAudioContextType& lhs, const LeAudioContextType& rhs) {
489   using T = std::underlying_type<LeAudioContextType>::type;
490   return AudioContexts(static_cast<T>(lhs) | static_cast<T>(rhs));
491 }
492 constexpr AudioContexts operator|(const LeAudioContextType& lhs, const AudioContexts& rhs) {
493   return AudioContexts(lhs) | rhs;
494 }
495 constexpr AudioContexts operator|(const AudioContexts& lhs, const LeAudioContextType& rhs) {
496   return lhs | AudioContexts(rhs);
497 }
498 
499 std::string ToHexString(const types::LeAudioContextType& value);
500 
501 template <typename T>
502 struct BidirectionalPair {
503   T sink;
504   T source;
505 
getBidirectionalPair506   const T& get(uint8_t direction) const {
507     log::assert_that(direction < types::kLeAudioDirectionBoth,
508                      "Unsupported complex direction. Consider using "
509                      "get_bidirectional<>() instead.");
510     return (direction == types::kLeAudioDirectionSink) ? sink : source;
511   }
512 
getBidirectionalPair513   T& get(uint8_t direction) {
514     log::assert_that(direction < types::kLeAudioDirectionBoth,
515                      "Unsupported complex direction. Reference to a single "
516                      "complex direction value is not supported.");
517     return (direction == types::kLeAudioDirectionSink) ? sink : source;
518   }
519 };
520 
521 template <typename T>
522 T get_bidirectional(BidirectionalPair<T> p);
523 
524 template <typename T>
525 bool operator==(const types::BidirectionalPair<T>& lhs, const types::BidirectionalPair<T>& rhs) {
526   return (lhs.sink == rhs.sink) && (lhs.source == rhs.source);
527 }
528 
529 /* Configuration strategy */
530 enum class LeAudioConfigurationStrategy : uint8_t {
531   MONO_ONE_CIS_PER_DEVICE = 0x00,     /* Common true wireless speakers */
532   STEREO_TWO_CISES_PER_DEVICE = 0x01, /* Requires 2 ASEs and 2 Audio Allocation for left/right */
533   STEREO_ONE_CIS_PER_DEVICE = 0x02,   /* Requires channel count 2*/
534   RFU = 0x03,
535 };
536 
537 constexpr LeAudioContextType kLeAudioContextAllTypesArray[] = {
538         LeAudioContextType::UNSPECIFIED,   LeAudioContextType::CONVERSATIONAL,
539         LeAudioContextType::MEDIA,         LeAudioContextType::GAME,
540         LeAudioContextType::INSTRUCTIONAL, LeAudioContextType::VOICEASSISTANTS,
541         LeAudioContextType::LIVE,          LeAudioContextType::SOUNDEFFECTS,
542         LeAudioContextType::NOTIFICATIONS, LeAudioContextType::RINGTONE,
543         LeAudioContextType::ALERTS,        LeAudioContextType::EMERGENCYALARM,
544 };
545 
546 constexpr AudioContexts kLeAudioContextAllTypes =
547         LeAudioContextType::UNSPECIFIED | LeAudioContextType::CONVERSATIONAL |
548         LeAudioContextType::MEDIA | LeAudioContextType::GAME | LeAudioContextType::INSTRUCTIONAL |
549         LeAudioContextType::VOICEASSISTANTS | LeAudioContextType::LIVE |
550         LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::NOTIFICATIONS |
551         LeAudioContextType::RINGTONE | LeAudioContextType::ALERTS |
552         LeAudioContextType::EMERGENCYALARM;
553 
554 constexpr AudioContexts kLeAudioContextAllBidir =
555         LeAudioContextType::GAME | LeAudioContextType::LIVE | LeAudioContextType::CONVERSATIONAL |
556         LeAudioContextType::VOICEASSISTANTS;
557 
558 constexpr AudioContexts kLeAudioContextAllRemoteSource =
559         LeAudioContextType::GAME | LeAudioContextType::LIVE | LeAudioContextType::CONVERSATIONAL |
560         LeAudioContextType::VOICEASSISTANTS;
561 
562 constexpr AudioContexts kLeAudioContextAllRemoteSinkOnly =
563         LeAudioContextType::MEDIA | LeAudioContextType::INSTRUCTIONAL |
564         LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::NOTIFICATIONS |
565         LeAudioContextType::RINGTONE | LeAudioContextType::ALERTS |
566         LeAudioContextType::EMERGENCYALARM;
567 
568 /* Print formaters for LTV data */
569 std::string CodecCapabilitiesLtvFormat(const uint8_t& type, const std::vector<uint8_t>& value);
570 
571 /* Structures */
572 /** LE Audio ASE codec configuration parameters, built from LTV types defined
573  * in the BT Assigned Numbers.
574  * NOTE: This base structure does not support the vendor specific parameters.
575  */
576 struct LeAudioCoreCodecConfig {
577   static const std::map<uint8_t, uint32_t> sampling_freq_map;
578   static const std::map<uint32_t, uint8_t> sample_rate_map;
579 
580   static const std::map<uint8_t, uint32_t> frame_duration_map;
581   static const std::map<uint32_t, uint8_t> data_interval_map;
582 
583   std::optional<uint8_t> sampling_frequency;
584   std::optional<uint8_t> frame_duration;
585   std::optional<uint32_t> audio_channel_allocation;
586   std::optional<uint16_t> octets_per_codec_frame;
587   std::optional<uint8_t> codec_frames_blocks_per_sdu;
588 
GetSamplingFrequencyHzLeAudioCoreCodecConfig589   static uint32_t GetSamplingFrequencyHz(uint8_t sample_freq) {
590     return sampling_freq_map.count(sample_freq) ? sampling_freq_map.at(sample_freq) : 0;
591   }
592 
GetFrameDurationUsLeAudioCoreCodecConfig593   static uint32_t GetFrameDurationUs(uint8_t framn_dur) {
594     return frame_duration_map.count(framn_dur) ? frame_duration_map.at(framn_dur) : 0;
595   }
596 
GetOctetsPerFrameLeAudioCoreCodecConfig597   uint16_t GetOctetsPerFrame() const { return octets_per_codec_frame.value_or(0); }
598 
599   /** Returns the sampling frequency representation in Hz */
GetSamplingFrequencyHzLeAudioCoreCodecConfig600   uint32_t GetSamplingFrequencyHz() const {
601     if (sampling_frequency) {
602       return sampling_freq_map.count(*sampling_frequency)
603                      ? sampling_freq_map.at(*sampling_frequency)
604                      : 0;
605     }
606     return 0;
607   }
608 
609   /** Returns the frame duration representation in us */
GetFrameDurationUsLeAudioCoreCodecConfig610   uint32_t GetFrameDurationUs() const {
611     if (frame_duration) {
612       return frame_duration_map.count(*frame_duration) ? frame_duration_map.at(*frame_duration) : 0;
613     }
614 
615     return 0;
616   }
617 
618   /** Returns the audio channel allocation bitmask */
GetAudioChannelAllocationLeAudioCoreCodecConfig619   inline uint32_t GetAudioChannelAllocation() const { return audio_channel_allocation.value_or(0); }
620   /** Returns the number of codec frame blocks */
GetCodecFrameBlocksPerSduLeAudioCoreCodecConfig621   inline uint8_t GetCodecFrameBlocksPerSdu() const {
622     return codec_frames_blocks_per_sdu.value_or(0);
623   }
624 };
625 
626 struct LeAudioCoreCodecCapabilities {
HasSupportedSamplingFrequenciesLeAudioCoreCodecCapabilities627   bool HasSupportedSamplingFrequencies() const {
628     return supported_sampling_frequencies.has_value();
629   }
HasSupportedFrameDurationsLeAudioCoreCodecCapabilities630   bool HasSupportedFrameDurations() const { return supported_frame_durations.has_value(); }
HasSupportedOctetsPerCodecFrameLeAudioCoreCodecCapabilities631   bool HasSupportedOctetsPerCodecFrame() const {
632     return supported_min_octets_per_codec_frame.has_value() &&
633            supported_max_octets_per_codec_frame.has_value();
634   }
HasSupportedAudioChannelCountsLeAudioCoreCodecCapabilities635   bool HasSupportedAudioChannelCounts() const { return supported_audio_channel_counts.has_value(); }
HasSupportedMaxCodecFramesPerSduLeAudioCoreCodecCapabilities636   bool HasSupportedMaxCodecFramesPerSdu() const {
637     return supported_max_codec_frames_per_sdu.has_value();
638   }
639 
IsSamplingFrequencyConfigSupportedLeAudioCoreCodecCapabilities640   bool IsSamplingFrequencyConfigSupported(uint8_t value) const {
641     return supported_sampling_frequencies.value_or(0) &
642            codec_spec_caps::SamplingFreqConfig2Capability(value);
643   }
IsFrameDurationConfigSupportedLeAudioCoreCodecCapabilities644   bool IsFrameDurationConfigSupported(uint8_t value) const {
645     return supported_frame_durations.value_or(0) &
646            codec_spec_caps::FrameDurationConfig2Capability(value);
647   }
IsAudioChannelCountsSupportedLeAudioCoreCodecCapabilities648   bool IsAudioChannelCountsSupported(uint8_t value) const {
649     if (value > 0) {
650       return supported_audio_channel_counts.value_or(0) & (0b1 << (value - 1));
651     }
652 
653     return false;
654   }
IsOctetsPerCodecFrameConfigSupportedLeAudioCoreCodecCapabilities655   bool IsOctetsPerCodecFrameConfigSupported(uint16_t value) const {
656     return (value >= supported_min_octets_per_codec_frame.value_or(0)) &&
657            (value <= supported_max_octets_per_codec_frame.value_or(0));
658   }
IsCodecFramesPerSduSupportedLeAudioCoreCodecCapabilities659   bool IsCodecFramesPerSduSupported(uint8_t value) const {
660     return value <= supported_max_codec_frames_per_sdu.value_or(1);
661   }
662 
663   std::optional<uint16_t> supported_sampling_frequencies;
664   std::optional<uint8_t> supported_frame_durations;
665   std::optional<uint8_t> supported_audio_channel_counts;
666   std::optional<uint16_t> supported_min_octets_per_codec_frame;
667   std::optional<uint16_t> supported_max_octets_per_codec_frame;
668   std::optional<uint8_t> supported_max_codec_frames_per_sdu;
669 };
670 
671 struct LeAudioMetadata {
672   std::optional<AudioContexts> preferred_audio_context;
673   std::optional<AudioContexts> streaming_audio_context;
674   std::optional<std::string> program_info;
675   std::optional<std::string> language;  // ISO 639-3 (3 lowercase letter codes)
676   std::optional<std::vector<uint8_t>> ccid_list;
677   std::optional<uint8_t> parental_rating;
678   std::optional<std::string> program_info_uri;
679   std::optional<std::vector<uint8_t>> extended_metadata;
680   std::optional<std::vector<uint8_t>> vendor_specific;
681   std::optional<bool> audio_active_state;
682   std::optional<bool> broadcast_audio_immediate_rendering;
683 };
684 
685 std::ostream& operator<<(std::ostream& os, const LeAudioMetadata& config);
686 
687 #define LTV_ENTRY_SAMPLING_FREQUENCY(value) \
688   { le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, std::vector<uint8_t>({(value) & 0xFF}) }
689 
690 #define LTV_ENTRY_FRAME_DURATION(value)                      \
691   {                                                          \
692     le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, \
693             std::vector<uint8_t>({(value) & 0xFF})           \
694   }
695 
696 #define LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(value)                                          \
697   {                                                                                        \
698     le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation,                      \
699             std::vector<uint8_t>({(uint8_t)(value) & 0xFF, (uint8_t)((value) << 8) & 0xFF, \
700                                   (uint8_t)((value) << 16) & 0xFF,                         \
701                                   (uint8_t)((value) << 24) & 0xFF})                        \
702   }
703 
704 #define LTV_ENTRY_OCTETS_PER_CODEC_FRAME(value)                                             \
705   {                                                                                         \
706     le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame,                          \
707             std::vector<uint8_t>({(uint8_t)(value) & 0xFF, (uint8_t)((value) << 8) & 0xFF}) \
708   }
709 
710 #define LTV_ENTRY_FRAME_BLOCKS_PER_SDU(value)                         \
711   {                                                                   \
712     le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, \
713             std::vector<uint8_t>({(value) & 0xFF})                    \
714   }
715 
716 class LeAudioLtvMap {
717 public:
LeAudioLtvMap(std::map<uint8_t,std::vector<uint8_t>> values)718   LeAudioLtvMap(std::map<uint8_t, std::vector<uint8_t>> values)
719       : values(values),
720         value_hash(0),
721         core_config(std::nullopt),
722         core_capabilities(std::nullopt),
723         metadata(std::nullopt) {}
724   LeAudioLtvMap() = default;
725   ~LeAudioLtvMap() = default;
726 
727   bool operator==(const LeAudioLtvMap& other) const { return GetHash() == other.GetHash(); }
728 
729   bool operator!=(const LeAudioLtvMap& other) const { return GetHash() != other.GetHash(); }
730 
731   std::optional<std::vector<uint8_t>> Find(uint8_t type) const;
At(uint8_t type)732   const auto& At(uint8_t type) const { return values.at(type); }
733 
Add(uint8_t type,std::vector<uint8_t> value)734   LeAudioLtvMap& Add(uint8_t type, std::vector<uint8_t> value) {
735     values.insert_or_assign(type, std::move(value));
736     invalidate();
737     return *this;
738   }
739 
740   // Add vendor specific data preceded with 2 octets of company ID
Add(uint8_t type,uint16_t vendorCompanyId,std::vector<uint8_t> value)741   LeAudioLtvMap& Add(uint8_t type, uint16_t vendorCompanyId, std::vector<uint8_t> value) {
742     std::vector<uint8_t> data(value.size() + 2);
743     auto ptr = data.data();
744     UINT16_TO_STREAM(ptr, vendorCompanyId);
745     ARRAY_TO_STREAM(ptr, value.data(), (int)value.size());
746     return Add(type, data);
747   }
748 
Add(uint8_t type,const std::string & value)749   LeAudioLtvMap& Add(uint8_t type, const std::string& value) {
750     std::vector<uint8_t> v(value.size());
751     auto ptr = v.data();
752     ARRAY_TO_STREAM(ptr, value.c_str(), (int)value.size());
753     values.insert_or_assign(type, v);
754     invalidate();
755     return *this;
756   }
757 
Add(uint8_t type,bool value)758   LeAudioLtvMap& Add(uint8_t type, bool value) {
759     std::vector<uint8_t> v(1);
760     auto ptr = v.data();
761     UINT8_TO_STREAM(ptr, value ? 0x01 : 0x00);
762     values.insert_or_assign(type, v);
763     invalidate();
764     return *this;
765   }
766 
Add(uint8_t type,uint8_t value)767   LeAudioLtvMap& Add(uint8_t type, uint8_t value) {
768     std::vector<uint8_t> v(sizeof(value));
769     auto ptr = v.data();
770 
771     UINT8_TO_STREAM(ptr, value);
772     values.insert_or_assign(type, v);
773     invalidate();
774     return *this;
775   }
Add(uint8_t type,uint16_t value)776   LeAudioLtvMap& Add(uint8_t type, uint16_t value) {
777     std::vector<uint8_t> v(sizeof(value));
778     auto ptr = v.data();
779 
780     UINT16_TO_STREAM(ptr, value);
781     values.insert_or_assign(type, std::move(v));
782     invalidate();
783     return *this;
784   }
Add(uint8_t type,uint32_t value)785   LeAudioLtvMap& Add(uint8_t type, uint32_t value) {
786     std::vector<uint8_t> v(sizeof(value));
787     auto ptr = v.data();
788 
789     UINT32_TO_STREAM(ptr, value);
790     values.insert_or_assign(type, std::move(v));
791     invalidate();
792     return *this;
793   }
Remove(uint8_t type)794   void Remove(uint8_t type) {
795     values.erase(type);
796     invalidate();
797   }
798   void RemoveAllTypes(const LeAudioLtvMap& other);
IsEmpty()799   bool IsEmpty() const { return values.empty(); }
Clear()800   void Clear() {
801     invalidate();
802     values.clear();
803   }
Size()804   size_t Size() const { return values.size(); }
Values()805   const std::map<uint8_t, std::vector<uint8_t>>& Values() const { return values; }
806 
807   const struct LeAudioCoreCodecConfig& GetAsCoreCodecConfig() const;
808   const struct LeAudioCoreCodecCapabilities& GetAsCoreCodecCapabilities() const;
809   const struct LeAudioMetadata& GetAsLeAudioMetadata() const;
810   LeAudioLtvMap GetIntersection(const LeAudioLtvMap& other) const;
811 
812   std::string ToString(const std::string& indent_string = "",
813                        std::string (*format)(const uint8_t&,
814                                              const std::vector<uint8_t>&) = nullptr) const;
815   size_t RawPacketSize() const;
816   uint8_t* RawPacket(uint8_t* p_buf) const;
817   std::vector<uint8_t> RawPacket() const;
818   static LeAudioLtvMap Parse(const uint8_t* value, uint8_t len, bool& success);
819   bool Parse(const uint8_t* value, uint8_t len);
820   void Append(const LeAudioLtvMap& other);
GetHash()821   size_t GetHash() const {
822     if (value_hash == 0) {
823       RecalculateValueHash();
824     }
825     return value_hash;
826   }
827 
828 private:
invalidate()829   void invalidate() {
830     core_config = std::nullopt;
831     core_capabilities = std::nullopt;
832     metadata = std::nullopt;
833     value_hash = 0;
834   }
835 
LtvMapToMetadata(const LeAudioLtvMap & ltvs)836   static LeAudioMetadata LtvMapToMetadata(const LeAudioLtvMap& ltvs) {
837     LeAudioMetadata metadata;
838 
839     auto vec_opt = ltvs.Find(types::kLeAudioMetadataTypePreferredAudioContext);
840     if (vec_opt && (vec_opt->size() == sizeof(uint16_t))) {
841       auto ptr = vec_opt->data();
842       uint16_t raw_ctx;
843       STREAM_TO_UINT16(raw_ctx, ptr);
844       AudioContexts ctx(raw_ctx);
845       metadata.preferred_audio_context = ctx;
846     }
847 
848     vec_opt = ltvs.Find(types::kLeAudioMetadataTypeStreamingAudioContext);
849     if (vec_opt && (vec_opt->size() == sizeof(uint16_t))) {
850       auto ptr = vec_opt->data();
851       uint16_t raw_ctx;
852       STREAM_TO_UINT16(raw_ctx, ptr);
853       AudioContexts ctx(raw_ctx);
854       metadata.streaming_audio_context = ctx;
855     }
856 
857     vec_opt = ltvs.Find(types::kLeAudioMetadataTypeProgramInfo);
858     if (vec_opt) {
859       metadata.program_info =
860               std::string(reinterpret_cast<const char*>(vec_opt->data()), vec_opt->size());
861     }
862 
863     vec_opt = ltvs.Find(types::kLeAudioMetadataTypeLanguage);
864     if (vec_opt && (vec_opt->size() == 3)) {  // it is always 3 in ISO 639-3
865       metadata.language =
866               std::string(reinterpret_cast<const char*>(vec_opt->data()), vec_opt->size());
867     }
868 
869     metadata.ccid_list = ltvs.Find(types::kLeAudioMetadataTypeCcidList);
870 
871     vec_opt = ltvs.Find(types::kLeAudioMetadataTypeparentalRating);
872     if (vec_opt && (vec_opt->size() == sizeof(decltype(metadata.parental_rating)::value_type))) {
873       auto ptr = vec_opt->data();
874       STREAM_TO_UINT8(metadata.parental_rating, ptr);
875     }
876 
877     vec_opt = ltvs.Find(types::kLeAudioMetadataTypeProgramInfoUri);
878     if (vec_opt) {
879       metadata.program_info_uri =
880               std::string(reinterpret_cast<const char*>(vec_opt->data()), vec_opt->size());
881     }
882 
883     vec_opt = ltvs.Find(types::kLeAudioMetadataTypeAudioActiveState);
884     if (vec_opt && (vec_opt->size() == sizeof(decltype(metadata.audio_active_state)::value_type))) {
885       auto ptr = vec_opt->data();
886       uint8_t val;
887       STREAM_TO_UINT8(val, ptr);
888       metadata.audio_active_state = val ? true : false;
889     }
890 
891     vec_opt = ltvs.Find(types::kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag);
892     if (vec_opt) {
893       metadata.broadcast_audio_immediate_rendering = true;
894     }
895 
896     metadata.extended_metadata = ltvs.Find(types::kLeAudioMetadataTypeExtendedMetadata);
897     metadata.vendor_specific = ltvs.Find(types::kLeAudioMetadataTypeVendorSpecific);
898 
899     return metadata;
900   }
901 
LtvMapToCoreCodecConfig(const LeAudioLtvMap & ltvs)902   static LeAudioCoreCodecConfig LtvMapToCoreCodecConfig(const LeAudioLtvMap& ltvs) {
903     LeAudioCoreCodecConfig core;
904 
905     auto vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeSamplingFreq);
906     if (vec_opt && (vec_opt->size() == sizeof(decltype(core.sampling_frequency)::value_type))) {
907       auto ptr = vec_opt->data();
908       STREAM_TO_UINT8(core.sampling_frequency, ptr);
909     }
910 
911     vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeFrameDuration);
912     if (vec_opt && (vec_opt->size() == sizeof(decltype(core.frame_duration)::value_type))) {
913       auto ptr = vec_opt->data();
914       STREAM_TO_UINT8(core.frame_duration, ptr);
915     }
916 
917     vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation);
918     if (vec_opt &&
919         (vec_opt->size() == sizeof(decltype(core.audio_channel_allocation)::value_type))) {
920       auto ptr = vec_opt->data();
921       STREAM_TO_UINT32(core.audio_channel_allocation, ptr);
922     }
923 
924     vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame);
925     if (vec_opt && (vec_opt->size() == sizeof(decltype(core.octets_per_codec_frame)::value_type))) {
926       auto ptr = vec_opt->data();
927       STREAM_TO_UINT16(core.octets_per_codec_frame, ptr);
928     }
929 
930     vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu);
931     if (vec_opt &&
932         (vec_opt->size() == sizeof(decltype(core.codec_frames_blocks_per_sdu)::value_type))) {
933       auto ptr = vec_opt->data();
934       STREAM_TO_UINT8(core.codec_frames_blocks_per_sdu, ptr);
935     }
936 
937     return core;
938   }
939 
LtvMapToCoreCodecCapabilities(const LeAudioLtvMap & pacs)940   static LeAudioCoreCodecCapabilities LtvMapToCoreCodecCapabilities(const LeAudioLtvMap& pacs) {
941     LeAudioCoreCodecCapabilities core;
942 
943     auto pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedSamplingFrequencies);
944     if (pac &&
945         (pac.value().size() == sizeof(decltype(core.supported_sampling_frequencies)::value_type))) {
946       core.supported_sampling_frequencies = VEC_UINT8_TO_UINT16(pac.value());
947     }
948 
949     pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedFrameDurations);
950     if (pac &&
951         (pac.value().size() == sizeof(decltype(core.supported_frame_durations)::value_type))) {
952       core.supported_frame_durations = VEC_UINT8_TO_UINT8(pac.value());
953     }
954 
955     pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedOctetsPerCodecFrame);
956     if (pac && (pac.value().size() ==
957                 (sizeof(decltype(core.supported_min_octets_per_codec_frame)::value_type) +
958                  sizeof(decltype(core.supported_max_octets_per_codec_frame)::value_type)))) {
959       core.supported_min_octets_per_codec_frame = VEC_UINT8_TO_UINT16(pac.value());
960       core.supported_max_octets_per_codec_frame = OFF_VEC_UINT8_TO_UINT16(
961               pac.value(), sizeof(decltype(core.supported_min_octets_per_codec_frame)::value_type));
962     }
963 
964     /*
965      * BAP_1.0.1 4.3.1 Codec_Specific_Capabilities LTV requirements:
966      * The absence of the Supported_Audio_Channel_Counts LTV structure shall be
967      * interpreted as equivalent to a Supported_Audio_Channel_Counts value of
968      * 0x01 (one Audio Channel supported).
969      */
970     pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedAudioChannelCounts);
971     if (pac &&
972         (pac.value().size() == sizeof(decltype(core.supported_audio_channel_counts)::value_type))) {
973       core.supported_audio_channel_counts = VEC_UINT8_TO_UINT8(pac.value());
974     } else {
975       core.supported_audio_channel_counts = 0b1;
976     }
977 
978     /*
979      * BAP_1.0.1 4.3.1 Codec_Specific_Capabilities LTV requirements:
980      * The absence of the Supported_Max_Codec_Frames_Per_SDU LTV structure shall
981      * be interpreted as equivalent to a Supported_Max_Codec_Frames_Per_SDU
982      * value of 1 codec frame per Audio Channel per SDU maximum.
983      */
984     pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu);
985     if (pac && (pac.value().size() ==
986                 sizeof(decltype(core.supported_max_codec_frames_per_sdu)::value_type))) {
987       core.supported_max_codec_frames_per_sdu = VEC_UINT8_TO_UINT8(pac.value());
988     } else {
989       core.supported_max_codec_frames_per_sdu = 1;
990     }
991 
992     return core;
993   }
994 
RecalculateValueHash()995   void RecalculateValueHash() const {
996     if (IsEmpty()) {
997       value_hash = 0;
998       return;
999     }
1000 
1001     auto value_vec = RawPacket();
1002     value_hash = std::hash<std::string_view>{}(
1003             {reinterpret_cast<const char*>(value_vec.data()), value_vec.size()});
1004   }
1005 
1006   std::map<uint8_t, std::vector<uint8_t>> values = {};
1007   mutable size_t value_hash = 0;
1008   // Lazy-constructed views of the LTV data
1009   mutable std::optional<struct LeAudioCoreCodecConfig> core_config = std::nullopt;
1010   mutable std::optional<struct LeAudioCoreCodecCapabilities> core_capabilities = std::nullopt;
1011   mutable std::optional<struct LeAudioMetadata> metadata = std::nullopt;
1012 };
1013 
1014 struct LeAudioCodecId {
1015   uint8_t coding_format;
1016   uint16_t vendor_company_id;
1017   uint16_t vendor_codec_id;
1018 
1019   friend bool operator==(const LeAudioCodecId& lhs, const LeAudioCodecId& rhs) {
1020     if (lhs.coding_format != rhs.coding_format) {
1021       return false;
1022     }
1023 
1024     if (lhs.coding_format == kLeAudioCodingFormatVendorSpecific &&
1025         (lhs.vendor_company_id != rhs.vendor_company_id ||
1026          lhs.vendor_codec_id != rhs.vendor_codec_id)) {
1027       return false;
1028     }
1029 
1030     return true;
1031   }
1032 
1033   friend bool operator!=(const LeAudioCodecId& lhs, const LeAudioCodecId& rhs) {
1034     return !(lhs == rhs);
1035   }
1036 };
1037 
1038 /* Google vendor specific codec for Headtracking */
1039 constexpr LeAudioCodecId kLeAudioCodecHeadtracking = {kLeAudioCodingFormatVendorSpecific,
1040                                                       kLeAudioVendorCompanyIdGoogle,
1041                                                       kLeAudioVendorCodecIdHeadtracking};
1042 
1043 struct IsoDataPathConfiguration {
1044   types::LeAudioCodecId codecId = {0, 0, 0};
1045   bool isTransparent = true;
1046   uint32_t controllerDelayUs = 0;
1047   std::vector<uint8_t> configuration = {};
1048 
1049   bool operator==(const IsoDataPathConfiguration& other) const {
1050     if (codecId != other.codecId) {
1051       return false;
1052     }
1053     if (isTransparent != other.isTransparent) {
1054       return false;
1055     }
1056     if (controllerDelayUs != other.controllerDelayUs) {
1057       return false;
1058     }
1059     if (configuration.size() != other.configuration.size()) {
1060       return false;
1061     }
1062     if ((!other.configuration.empty()) &&
1063         memcmp(configuration.data(), other.configuration.data(), other.configuration.size())) {
1064       return false;
1065     }
1066     return true;
1067   }
1068 
1069   bool operator!=(const IsoDataPathConfiguration& other) const { return !(*this == other); }
1070 };
1071 
1072 std::ostream& operator<<(std::ostream& os, const le_audio::types::IsoDataPathConfiguration& config);
1073 
1074 struct DataPathConfiguration {
1075   uint8_t dataPathId = 0;
1076   std::vector<uint8_t> dataPathConfig = {};
1077   IsoDataPathConfiguration isoDataPathConfig;
1078 
1079   bool operator==(const DataPathConfiguration& other) const {
1080     if (dataPathId != other.dataPathId) {
1081       return false;
1082     }
1083     if (isoDataPathConfig != other.isoDataPathConfig) {
1084       return false;
1085     }
1086     if (dataPathConfig.size() != other.dataPathConfig.size()) {
1087       return false;
1088     }
1089     if ((!other.dataPathConfig.empty()) &&
1090         memcmp(dataPathConfig.data(), other.dataPathConfig.data(), other.dataPathConfig.size())) {
1091       return false;
1092     }
1093     return true;
1094   }
1095 
1096   bool operator!=(const DataPathConfiguration& other) const { return !(*this == other); }
1097 };
1098 
1099 std::ostream& operator<<(std::ostream& os, const le_audio::types::DataPathConfiguration& config);
1100 
1101 struct hdl_pair {
1102   hdl_pair() = default;
hdl_pairhdl_pair1103   hdl_pair(uint16_t val_hdl, uint16_t ccc_hdl) : val_hdl(val_hdl), ccc_hdl(ccc_hdl) {}
1104 
1105   uint16_t val_hdl = 0;
1106   uint16_t ccc_hdl = 0;
1107 };
1108 
1109 template <typename T>
1110 struct hdl_pair_wrapper {
1111   hdl_pair handles;
1112   T value;
1113 };
1114 
1115 struct AseQosConfiguration {
1116   uint32_t presentation_delay = 0;
1117   uint32_t sdu_interval = 0;
1118   uint16_t max_transport_latency = 0;
1119   uint16_t max_sdu_size = 0;
1120   uint8_t retrans_nb = 0;
1121   uint8_t framing = 0;
1122   uint8_t phy = 0;
1123 };
1124 
1125 struct AseQosPreferences {
1126   uint8_t supported_framing = 0;
1127   uint8_t preferred_phy = 0;
1128   uint8_t preferred_retrans_nb = 0;
1129   uint32_t pres_delay_min = 0;
1130   uint32_t pres_delay_max = 0;
1131   uint32_t preferred_pres_delay_min = 0;
1132   uint32_t preferred_pres_delay_max = 0;
1133 };
1134 
1135 struct CodecConfigSetting {
1136   /* Codec identifier */
1137   types::LeAudioCodecId id;
1138 
1139   /* Codec Specific Configuration */
1140   types::LeAudioLtvMap params;
1141   /* Vendor Specific Configuration */
1142   std::vector<uint8_t> vendor_params;
1143 
1144   /* Channel count per device */
1145   uint8_t channel_count_per_iso_stream;
1146 
1147   /* Octets per fram for codec */
1148   uint16_t GetOctetsPerFrame() const;
1149   /* Sampling frequency requested for codec */
1150   uint32_t GetSamplingFrequencyHz() const;
1151   /* Data fetch/feed interval for codec in microseconds */
1152   uint32_t GetDataIntervalUs() const;
1153   /* Audio bit depth required for codec */
1154   uint8_t GetBitsPerSample() const;
1155   /* Audio channel allocation bitmask */
GetAudioChannelAllocationCodecConfigSetting1156   inline uint32_t GetAudioChannelAllocation() const {
1157     return params.GetAsCoreCodecConfig().GetAudioChannelAllocation();
1158   }
GetCodecFrameBlocksPerSduCodecConfigSetting1159   inline uint8_t GetCodecFrameBlocksPerSdu() const {
1160     return params.GetAsCoreCodecConfig().GetCodecFrameBlocksPerSdu();
1161   }
1162 
1163   /* Audio channels number for a device */
GetChannelCountPerIsoStreamCodecConfigSetting1164   uint8_t GetChannelCountPerIsoStream() const { return channel_count_per_iso_stream; }
1165 
1166   bool operator==(const CodecConfigSetting& other) const {
1167     return (id == other.id) &&
1168            (channel_count_per_iso_stream == other.channel_count_per_iso_stream) &&
1169            (vendor_params == other.vendor_params) && (params == other.params);
1170   }
1171 
1172   bool operator!=(const CodecConfigSetting& other) const { return !(*this == other); }
1173 };
1174 
1175 std::ostream& operator<<(std::ostream& os, const CodecConfigSetting& config);
1176 
1177 struct ase {
1178   static constexpr uint8_t kAseIdInvalid = 0x00;
1179 
1180   ase(uint16_t val_hdl, uint16_t ccc_hdl, uint8_t direction, uint8_t initial_id = kAseIdInvalid)
hdlsase1181       : hdls(val_hdl, ccc_hdl),
1182         id(initial_id),
1183         cis_id(kInvalidCisId),
1184         direction(direction),
1185         target_latency(types::kTargetLatencyBalancedLatencyReliability),
1186         active(false),
1187         reconfigure(false),
1188         cis_state(CisState::IDLE),
1189         data_path_state(DataPathState::IDLE),
1190         configured_for_context_type(LeAudioContextType::UNINITIALIZED),
1191         state(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {}
1192 
1193   struct hdl_pair hdls;
1194   uint8_t id;
1195   uint8_t cis_id;
1196   const uint8_t direction;
1197   uint8_t target_latency;
1198   uint16_t cis_conn_hdl = kInvalidCisConnHandle;
1199 
1200   bool active;
1201   bool reconfigure;
1202   CisState cis_state;
1203   DataPathState data_path_state;
1204   LeAudioContextType configured_for_context_type;
1205 
1206   /* Codec configuration */
1207   CodecConfigSetting codec_config;
1208 
1209   /* Data path configuration */
1210   DataPathConfiguration data_path_configuration;
1211 
1212   /* Qos configuration */
1213   AseQosConfiguration qos_config;
1214 
1215   /* QoS requirements in Codec Configured state */
1216   AseQosPreferences qos_preferences;
1217 
1218   LeAudioLtvMap metadata;
1219 
1220   AseState state;
1221 };
1222 
1223 struct acs_ac_record {
1224   LeAudioCodecId codec_id;
1225   LeAudioLtvMap codec_spec_caps;
1226   std::vector<uint8_t> codec_spec_caps_raw;
1227   LeAudioLtvMap metadata;
1228 };
1229 
1230 using PublishedAudioCapabilities = std::vector<std::tuple<hdl_pair, std::vector<acs_ac_record>>>;
1231 using AudioLocations = std::bitset<32>;
1232 
1233 std::ostream& operator<<(std::ostream& os, const AseState& state);
1234 std::ostream& operator<<(std::ostream& os, const CigState& state);
1235 std::ostream& operator<<(std::ostream& os, const LeAudioCodecId& codec_id);
1236 std::ostream& operator<<(std::ostream& os, const LeAudioCoreCodecConfig& config);
1237 std::string contextTypeToStr(const LeAudioContextType& context);
1238 std::ostream& operator<<(std::ostream& os, const LeAudioContextType& context);
1239 std::ostream& operator<<(std::ostream& os, const DataPathState& state);
1240 std::ostream& operator<<(std::ostream& os, const CisState& state);
1241 std::ostream& operator<<(std::ostream& os, const AudioContexts& contexts);
1242 
1243 struct QosConfigSetting {
1244   uint8_t target_latency;
1245   uint8_t retransmission_number;
1246   uint16_t max_transport_latency;
1247   int sduIntervalUs;
1248   int maxSdu;
1249 
1250   bool operator!=(const QosConfigSetting& other) { return !(*this == other); }
1251 
1252   bool operator==(const QosConfigSetting& other) const {
1253     return (target_latency == other.target_latency) &&
1254            (retransmission_number == other.retransmission_number) &&
1255            (max_transport_latency == other.max_transport_latency);
1256   }
1257 };
1258 
1259 std::ostream& operator<<(std::ostream& os, const QosConfigSetting& config);
1260 
1261 struct AseConfiguration {
1262   AseConfiguration(CodecConfigSetting codec, QosConfigSetting qos = {.target_latency = 0,
1263                                                                      .retransmission_number = 0,
1264                                                                      .max_transport_latency = 0})
codecAseConfiguration1265       : codec(codec), qos(qos) {}
1266   types::DataPathConfiguration data_path_configuration;
1267   CodecConfigSetting codec;
1268   QosConfigSetting qos;
1269   types::LeAudioLtvMap metadata;
1270 
1271   bool operator!=(const AseConfiguration& other) { return !(*this == other); }
1272 
1273   bool operator==(const AseConfiguration& other) const {
1274     return (data_path_configuration == other.data_path_configuration) && (codec == other.codec) &&
1275            (qos == other.qos) && (metadata == other.metadata);
1276   }
1277 };
1278 
1279 std::ostream& operator<<(std::ostream& os, const AseConfiguration& config);
1280 
1281 /* Defined audio scenarios */
1282 struct AudioSetConfiguration {
1283   std::string name = "";
1284   /* ISO data packing within the CIG */
1285   uint8_t packing = bluetooth::hci::kIsoCigPackingSequential;
1286   types::BidirectionalPair<std::vector<struct AseConfiguration>> confs;
1287 
1288   bool operator!=(const AudioSetConfiguration& other) { return !(*this == other); }
1289 
1290   bool operator==(const AudioSetConfiguration& other) const {
1291     return (packing == other.packing) && (confs == other.confs);
1292   }
1293 };
1294 
1295 std::ostream& operator<<(std::ostream& os, const AudioSetConfiguration& config);
1296 
1297 using AudioSetConfigurations = std::vector<const AudioSetConfiguration*>;
1298 
1299 const types::LeAudioCodecId LeAudioCodecIdLc3 = {
1300         .coding_format = types::kLeAudioCodingFormatLC3,
1301         .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined,
1302         .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined};
1303 
1304 static constexpr uint32_t kChannelAllocationStereo =
1305         codec_spec_conf::kLeAudioLocationFrontLeft | codec_spec_conf::kLeAudioLocationFrontRight;
1306 }  // namespace types
1307 
1308 struct stream_map_info {
stream_map_infostream_map_info1309   stream_map_info(uint16_t stream_handle, uint32_t audio_channel_allocation, bool is_stream_active)
1310       : stream_handle(stream_handle),
1311         audio_channel_allocation(audio_channel_allocation),
1312         is_stream_active(is_stream_active) {}
1313   uint16_t stream_handle;
1314   uint32_t audio_channel_allocation;
1315   bool is_stream_active;
1316 
1317   /* The non-legacy codec extensibility feature of a stream map allows us to update the stream
1318    * parameters more granularly for each CIS handle
1319    */
1320   types::CodecConfigSetting codec_config;
1321   uint8_t target_latency;
1322   uint8_t target_phy;
1323   types::LeAudioLtvMap metadata;
1324   RawAddress address;
1325   uint8_t address_type;
1326 };
1327 
1328 struct stream_config {
1329   std::vector<stream_map_info> stream_map;
1330   /* For a legacy reason we have always same frequency for all the channels */
1331   uint8_t bits_per_sample;
1332   uint32_t sampling_frequency_hz;
1333   uint32_t frame_duration_us;
1334   uint16_t octets_per_codec_frame;
1335   uint8_t codec_frames_blocks_per_sdu;
1336   uint16_t peer_delay_ms;
1337 
clearstream_config1338   void clear() {
1339     stream_map.clear();
1340     bits_per_sample = 0;
1341     sampling_frequency_hz = 0;
1342     frame_duration_us = 0;
1343     octets_per_codec_frame = 0;
1344     codec_frames_blocks_per_sdu = 0;
1345     peer_delay_ms = 0;
1346   }
1347 };
1348 
1349 struct stream_parameters {
1350   uint32_t audio_channel_allocation;
1351 
1352   /* Stream parameters and CIS to Audio Allocation map */
1353   stream_config stream_config;
1354 
1355   /* Total number of channels we request from the audio framework */
1356   uint8_t num_of_channels;
1357   int num_of_devices;
1358 
clearstream_parameters1359   void clear() {
1360     num_of_channels = 0;
1361     num_of_devices = 0;
1362     stream_config.clear();
1363   }
1364 };
1365 
1366 struct stream_configuration {
1367   /* Whether the group should be reconfigured once the streaming stops */
1368   bool pending_configuration;
1369 
1370   /* Currently selected remote device set configuration */
1371   std::shared_ptr<const bluetooth::le_audio::types::AudioSetConfiguration> conf;
1372 
1373   /* Currently selected local audio codec */
1374   types::LeAudioCodecId codec_id;
1375 
1376   /* Currently selected local Sink & Source configuration */
1377   types::BidirectionalPair<stream_parameters> stream_params;
1378 };
1379 
1380 void AppendMetadataLtvEntryForCcidList(std::vector<uint8_t>& metadata,
1381                                        const std::vector<uint8_t>& ccid_list);
1382 void AppendMetadataLtvEntryForStreamingContext(std::vector<uint8_t>& metadata,
1383                                                types::AudioContexts context_type);
1384 uint8_t GetMaxCodecFramesPerSduFromPac(const types::acs_ac_record* pac_record);
1385 }  // namespace bluetooth::le_audio
1386 
1387 namespace std {
1388 template <>
1389 struct formatter<bluetooth::le_audio::DsaMode> : enum_formatter<bluetooth::le_audio::DsaMode> {};
1390 template <>
1391 struct formatter<bluetooth::le_audio::types::CisType>
1392     : enum_formatter<bluetooth::le_audio::types::CisType> {};
1393 template <>
1394 struct formatter<bluetooth::le_audio::types::LeAudioConfigurationStrategy>
1395     : enum_formatter<bluetooth::le_audio::types::LeAudioConfigurationStrategy> {};
1396 }  // namespace std
1397