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
506 const T& get(uint8_t direction) const;
507 T& get(uint8_t direction);
508 };
509
510 template <typename T>
511 T get_bidirectional(BidirectionalPair<T> p);
512
513 template <typename T>
514 bool operator==(const types::BidirectionalPair<T>& lhs, const types::BidirectionalPair<T>& rhs) {
515 return (lhs.sink == rhs.sink) && (lhs.source == rhs.source);
516 }
517
518 /* Configuration strategy */
519 enum class LeAudioConfigurationStrategy : uint8_t {
520 MONO_ONE_CIS_PER_DEVICE = 0x00, /* Common true wireless speakers */
521 STEREO_TWO_CISES_PER_DEVICE = 0x01, /* Requires 2 ASEs and 2 Audio Allocation for left/right */
522 STEREO_ONE_CIS_PER_DEVICE = 0x02, /* Requires channel count 2*/
523 RFU = 0x03,
524 };
525
526 constexpr LeAudioContextType kLeAudioContextAllTypesArray[] = {
527 LeAudioContextType::UNSPECIFIED, LeAudioContextType::CONVERSATIONAL,
528 LeAudioContextType::MEDIA, LeAudioContextType::GAME,
529 LeAudioContextType::INSTRUCTIONAL, LeAudioContextType::VOICEASSISTANTS,
530 LeAudioContextType::LIVE, LeAudioContextType::SOUNDEFFECTS,
531 LeAudioContextType::NOTIFICATIONS, LeAudioContextType::RINGTONE,
532 LeAudioContextType::ALERTS, LeAudioContextType::EMERGENCYALARM,
533 };
534
535 constexpr AudioContexts kLeAudioContextAllTypes =
536 LeAudioContextType::UNSPECIFIED | LeAudioContextType::CONVERSATIONAL |
537 LeAudioContextType::MEDIA | LeAudioContextType::GAME | LeAudioContextType::INSTRUCTIONAL |
538 LeAudioContextType::VOICEASSISTANTS | LeAudioContextType::LIVE |
539 LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::NOTIFICATIONS |
540 LeAudioContextType::RINGTONE | LeAudioContextType::ALERTS |
541 LeAudioContextType::EMERGENCYALARM;
542
543 constexpr AudioContexts kLeAudioContextAllBidir =
544 LeAudioContextType::GAME | LeAudioContextType::LIVE | LeAudioContextType::CONVERSATIONAL |
545 LeAudioContextType::VOICEASSISTANTS;
546
547 constexpr AudioContexts kLeAudioContextAllRemoteSource =
548 LeAudioContextType::GAME | LeAudioContextType::LIVE | LeAudioContextType::CONVERSATIONAL |
549 LeAudioContextType::VOICEASSISTANTS;
550
551 constexpr AudioContexts kLeAudioContextAllRemoteSinkOnly =
552 LeAudioContextType::MEDIA | LeAudioContextType::INSTRUCTIONAL |
553 LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::NOTIFICATIONS |
554 LeAudioContextType::RINGTONE | LeAudioContextType::ALERTS |
555 LeAudioContextType::EMERGENCYALARM;
556
557 /* Print formaters for LTV data */
558 std::string CodecCapabilitiesLtvFormat(const uint8_t& type, const std::vector<uint8_t>& value);
559
560 /* Structures */
561 /** LE Audio ASE codec configuration parameters, built from LTV types defined
562 * in the BT Assigned Numbers.
563 * NOTE: This base structure does not support the vendor specific parameters.
564 */
565 struct LeAudioCoreCodecConfig {
566 static const std::map<uint8_t, uint32_t> sampling_freq_map;
567 static const std::map<uint32_t, uint8_t> sample_rate_map;
568
569 static const std::map<uint8_t, uint32_t> frame_duration_map;
570 static const std::map<uint32_t, uint8_t> data_interval_map;
571
572 std::optional<uint8_t> sampling_frequency;
573 std::optional<uint8_t> frame_duration;
574 std::optional<uint32_t> audio_channel_allocation;
575 std::optional<uint16_t> octets_per_codec_frame;
576 std::optional<uint8_t> codec_frames_blocks_per_sdu;
577
GetSamplingFrequencyHzLeAudioCoreCodecConfig578 static uint32_t GetSamplingFrequencyHz(uint8_t sample_freq) {
579 return sampling_freq_map.count(sample_freq) ? sampling_freq_map.at(sample_freq) : 0;
580 }
581
GetFrameDurationUsLeAudioCoreCodecConfig582 static uint32_t GetFrameDurationUs(uint8_t framn_dur) {
583 return frame_duration_map.count(framn_dur) ? frame_duration_map.at(framn_dur) : 0;
584 }
585
GetOctetsPerFrameLeAudioCoreCodecConfig586 uint16_t GetOctetsPerFrame() const { return octets_per_codec_frame.value_or(0); }
587
588 /** Returns the sampling frequency representation in Hz */
GetSamplingFrequencyHzLeAudioCoreCodecConfig589 uint32_t GetSamplingFrequencyHz() const {
590 if (sampling_frequency) {
591 return sampling_freq_map.count(*sampling_frequency)
592 ? sampling_freq_map.at(*sampling_frequency)
593 : 0;
594 }
595 return 0;
596 }
597
598 /** Returns the frame duration representation in us */
GetFrameDurationUsLeAudioCoreCodecConfig599 uint32_t GetFrameDurationUs() const {
600 if (frame_duration) {
601 return frame_duration_map.count(*frame_duration) ? frame_duration_map.at(*frame_duration) : 0;
602 }
603
604 return 0;
605 }
606 };
607
608 struct LeAudioCoreCodecCapabilities {
HasSupportedSamplingFrequenciesLeAudioCoreCodecCapabilities609 bool HasSupportedSamplingFrequencies() const {
610 return supported_sampling_frequencies.has_value();
611 }
HasSupportedFrameDurationsLeAudioCoreCodecCapabilities612 bool HasSupportedFrameDurations() const { return supported_frame_durations.has_value(); }
HasSupportedOctetsPerCodecFrameLeAudioCoreCodecCapabilities613 bool HasSupportedOctetsPerCodecFrame() const {
614 return supported_min_octets_per_codec_frame.has_value() &&
615 supported_max_octets_per_codec_frame.has_value();
616 }
HasSupportedAudioChannelCountsLeAudioCoreCodecCapabilities617 bool HasSupportedAudioChannelCounts() const { return supported_audio_channel_counts.has_value(); }
HasSupportedMaxCodecFramesPerSduLeAudioCoreCodecCapabilities618 bool HasSupportedMaxCodecFramesPerSdu() const {
619 return supported_max_codec_frames_per_sdu.has_value();
620 }
621
IsSamplingFrequencyConfigSupportedLeAudioCoreCodecCapabilities622 bool IsSamplingFrequencyConfigSupported(uint8_t value) const {
623 return supported_sampling_frequencies.value_or(0) &
624 codec_spec_caps::SamplingFreqConfig2Capability(value);
625 }
IsFrameDurationConfigSupportedLeAudioCoreCodecCapabilities626 bool IsFrameDurationConfigSupported(uint8_t value) const {
627 return supported_frame_durations.value_or(0) &
628 codec_spec_caps::FrameDurationConfig2Capability(value);
629 }
IsAudioChannelCountsSupportedLeAudioCoreCodecCapabilities630 bool IsAudioChannelCountsSupported(uint8_t value) const {
631 if (value > 0) {
632 return supported_audio_channel_counts.value_or(0) & (0b1 << (value - 1));
633 }
634
635 return false;
636 }
IsOctetsPerCodecFrameConfigSupportedLeAudioCoreCodecCapabilities637 bool IsOctetsPerCodecFrameConfigSupported(uint16_t value) const {
638 return (value >= supported_min_octets_per_codec_frame.value_or(0)) &&
639 (value <= supported_max_octets_per_codec_frame.value_or(0));
640 }
IsCodecFramesPerSduSupportedLeAudioCoreCodecCapabilities641 bool IsCodecFramesPerSduSupported(uint8_t value) const {
642 return value <= supported_max_codec_frames_per_sdu.value_or(1);
643 }
644
645 std::optional<uint16_t> supported_sampling_frequencies;
646 std::optional<uint8_t> supported_frame_durations;
647 std::optional<uint8_t> supported_audio_channel_counts;
648 std::optional<uint16_t> supported_min_octets_per_codec_frame;
649 std::optional<uint16_t> supported_max_octets_per_codec_frame;
650 std::optional<uint8_t> supported_max_codec_frames_per_sdu;
651 };
652
653 struct LeAudioMetadata {
654 std::optional<uint16_t> preferred_audio_context;
655 std::optional<uint16_t> streaming_audio_context;
656 std::optional<std::string> program_info;
657 std::optional<std::string> language; // ISO 639-3 (3 lowercase letter codes)
658 std::optional<std::vector<uint8_t>> ccid_list;
659 std::optional<uint8_t> parental_rating;
660 std::optional<std::string> program_info_uri;
661 std::optional<std::vector<uint8_t>> extended_metadata;
662 std::optional<std::vector<uint8_t>> vendor_specific;
663 std::optional<bool> audio_active_state;
664 std::optional<bool> broadcast_audio_immediate_rendering;
665 };
666
667 std::ostream& operator<<(std::ostream& os, const LeAudioMetadata& config);
668
669 #define LTV_ENTRY_SAMPLING_FREQUENCY(value) \
670 { le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, std::vector<uint8_t>({(value) & 0xFF}) }
671
672 #define LTV_ENTRY_FRAME_DURATION(value) \
673 { \
674 le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, \
675 std::vector<uint8_t>({(value) & 0xFF}) \
676 }
677
678 #define LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(value) \
679 { \
680 le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, \
681 std::vector<uint8_t>({(uint8_t)(value) & 0xFF, (uint8_t)((value) << 8) & 0xFF, \
682 (uint8_t)((value) << 16) & 0xFF, \
683 (uint8_t)((value) << 24) & 0xFF}) \
684 }
685
686 #define LTV_ENTRY_OCTETS_PER_CODEC_FRAME(value) \
687 { \
688 le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, \
689 std::vector<uint8_t>({(uint8_t)(value) & 0xFF, (uint8_t)((value) << 8) & 0xFF}) \
690 }
691
692 #define LTV_ENTRY_FRAME_BLOCKS_PER_SDU(value) \
693 { \
694 le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, \
695 std::vector<uint8_t>({(value) & 0xFF}) \
696 }
697
698 class LeAudioLtvMap {
699 public:
LeAudioLtvMap(std::map<uint8_t,std::vector<uint8_t>> values)700 LeAudioLtvMap(std::map<uint8_t, std::vector<uint8_t>> values)
701 : values(values),
702 value_hash(0),
703 core_config(std::nullopt),
704 core_capabilities(std::nullopt),
705 metadata(std::nullopt) {}
706 LeAudioLtvMap() = default;
707 ~LeAudioLtvMap() = default;
708
709 bool operator==(const LeAudioLtvMap& other) const { return GetHash() == other.GetHash(); }
710
711 bool operator!=(const LeAudioLtvMap& other) const { return GetHash() != other.GetHash(); }
712
713 std::optional<std::vector<uint8_t>> Find(uint8_t type) const;
At(uint8_t type)714 const auto& At(uint8_t type) const { return values.at(type); }
715
Add(uint8_t type,std::vector<uint8_t> value)716 LeAudioLtvMap& Add(uint8_t type, std::vector<uint8_t> value) {
717 values.insert_or_assign(type, std::move(value));
718 invalidate();
719 return *this;
720 }
721
722 // Add vendor specific data preceded with 2 octets of company ID
Add(uint8_t type,uint16_t vendorCompanyId,std::vector<uint8_t> value)723 LeAudioLtvMap& Add(uint8_t type, uint16_t vendorCompanyId, std::vector<uint8_t> value) {
724 std::vector<uint8_t> data(value.size() + 2);
725 auto ptr = data.data();
726 UINT16_TO_STREAM(ptr, vendorCompanyId);
727 ARRAY_TO_STREAM(ptr, value.data(), (int)value.size());
728 return Add(type, data);
729 }
730
Add(uint8_t type,const std::string & value)731 LeAudioLtvMap& Add(uint8_t type, const std::string& value) {
732 std::vector<uint8_t> v(value.size());
733 auto ptr = v.data();
734 ARRAY_TO_STREAM(ptr, value.c_str(), (int)value.size());
735 values.insert_or_assign(type, v);
736 invalidate();
737 return *this;
738 }
739
Add(uint8_t type,bool value)740 LeAudioLtvMap& Add(uint8_t type, bool value) {
741 std::vector<uint8_t> v(1);
742 auto ptr = v.data();
743 UINT8_TO_STREAM(ptr, value ? 0x01 : 0x00);
744 values.insert_or_assign(type, v);
745 invalidate();
746 return *this;
747 }
748
Add(uint8_t type,uint8_t value)749 LeAudioLtvMap& Add(uint8_t type, uint8_t value) {
750 std::vector<uint8_t> v(sizeof(value));
751 auto ptr = v.data();
752
753 UINT8_TO_STREAM(ptr, value);
754 values.insert_or_assign(type, v);
755 invalidate();
756 return *this;
757 }
Add(uint8_t type,uint16_t value)758 LeAudioLtvMap& Add(uint8_t type, uint16_t value) {
759 std::vector<uint8_t> v(sizeof(value));
760 auto ptr = v.data();
761
762 UINT16_TO_STREAM(ptr, value);
763 values.insert_or_assign(type, std::move(v));
764 invalidate();
765 return *this;
766 }
Add(uint8_t type,uint32_t value)767 LeAudioLtvMap& Add(uint8_t type, uint32_t value) {
768 std::vector<uint8_t> v(sizeof(value));
769 auto ptr = v.data();
770
771 UINT32_TO_STREAM(ptr, value);
772 values.insert_or_assign(type, std::move(v));
773 invalidate();
774 return *this;
775 }
Remove(uint8_t type)776 void Remove(uint8_t type) {
777 values.erase(type);
778 invalidate();
779 }
780 void RemoveAllTypes(const LeAudioLtvMap& other);
IsEmpty()781 bool IsEmpty() const { return values.empty(); }
Clear()782 void Clear() {
783 invalidate();
784 values.clear();
785 }
Size()786 size_t Size() const { return values.size(); }
Values()787 const std::map<uint8_t, std::vector<uint8_t>>& Values() const { return values; }
788
789 const struct LeAudioCoreCodecConfig& GetAsCoreCodecConfig() const;
790 const struct LeAudioCoreCodecCapabilities& GetAsCoreCodecCapabilities() const;
791 const struct LeAudioMetadata& GetAsLeAudioMetadata() const;
792 LeAudioLtvMap GetIntersection(const LeAudioLtvMap& other) const;
793
794 std::string ToString(const std::string& indent_string,
795 std::string (*format)(const uint8_t&, const std::vector<uint8_t>&)) const;
796 size_t RawPacketSize() const;
797 uint8_t* RawPacket(uint8_t* p_buf) const;
798 std::vector<uint8_t> RawPacket() const;
799 static LeAudioLtvMap Parse(const uint8_t* value, uint8_t len, bool& success);
800 bool Parse(const uint8_t* value, uint8_t len);
801 void Append(const LeAudioLtvMap& other);
GetHash()802 size_t GetHash() const {
803 if (value_hash == 0) {
804 RecalculateValueHash();
805 }
806 return value_hash;
807 }
808
809 private:
invalidate()810 void invalidate() {
811 core_config = std::nullopt;
812 core_capabilities = std::nullopt;
813 metadata = std::nullopt;
814 value_hash = 0;
815 }
816
LtvMapToMetadata(const LeAudioLtvMap & ltvs)817 static LeAudioMetadata LtvMapToMetadata(const LeAudioLtvMap& ltvs) {
818 LeAudioMetadata metadata;
819
820 auto vec_opt = ltvs.Find(types::kLeAudioMetadataTypePreferredAudioContext);
821 if (vec_opt &&
822 (vec_opt->size() == sizeof(decltype(metadata.preferred_audio_context)::value_type))) {
823 auto ptr = vec_opt->data();
824 STREAM_TO_UINT16(metadata.preferred_audio_context, ptr);
825 }
826
827 vec_opt = ltvs.Find(types::kLeAudioMetadataTypeStreamingAudioContext);
828 if (vec_opt &&
829 (vec_opt->size() == sizeof(decltype(metadata.streaming_audio_context)::value_type))) {
830 auto ptr = vec_opt->data();
831 STREAM_TO_UINT16(metadata.streaming_audio_context, ptr);
832 }
833
834 vec_opt = ltvs.Find(types::kLeAudioMetadataTypeProgramInfo);
835 if (vec_opt) {
836 metadata.program_info =
837 std::string(reinterpret_cast<const char*>(vec_opt->data()), vec_opt->size());
838 }
839
840 vec_opt = ltvs.Find(types::kLeAudioMetadataTypeLanguage);
841 if (vec_opt && (vec_opt->size() == 3)) { // it is always 3 in ISO 639-3
842 metadata.language =
843 std::string(reinterpret_cast<const char*>(vec_opt->data()), vec_opt->size());
844 }
845
846 metadata.ccid_list = ltvs.Find(types::kLeAudioMetadataTypeCcidList);
847
848 vec_opt = ltvs.Find(types::kLeAudioMetadataTypeparentalRating);
849 if (vec_opt && (vec_opt->size() == sizeof(decltype(metadata.parental_rating)::value_type))) {
850 auto ptr = vec_opt->data();
851 STREAM_TO_UINT8(metadata.parental_rating, ptr);
852 }
853
854 vec_opt = ltvs.Find(types::kLeAudioMetadataTypeProgramInfoUri);
855 if (vec_opt) {
856 metadata.program_info_uri =
857 std::string(reinterpret_cast<const char*>(vec_opt->data()), vec_opt->size());
858 }
859
860 vec_opt = ltvs.Find(types::kLeAudioMetadataTypeAudioActiveState);
861 if (vec_opt && (vec_opt->size() == sizeof(decltype(metadata.audio_active_state)::value_type))) {
862 auto ptr = vec_opt->data();
863 uint8_t val;
864 STREAM_TO_UINT8(val, ptr);
865 metadata.audio_active_state = val ? true : false;
866 }
867
868 vec_opt = ltvs.Find(types::kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag);
869 if (vec_opt) {
870 metadata.broadcast_audio_immediate_rendering = true;
871 }
872
873 metadata.extended_metadata = ltvs.Find(types::kLeAudioMetadataTypeExtendedMetadata);
874 metadata.vendor_specific = ltvs.Find(types::kLeAudioMetadataTypeVendorSpecific);
875
876 return metadata;
877 }
878
LtvMapToCoreCodecConfig(const LeAudioLtvMap & ltvs)879 static LeAudioCoreCodecConfig LtvMapToCoreCodecConfig(const LeAudioLtvMap& ltvs) {
880 LeAudioCoreCodecConfig core;
881
882 auto vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeSamplingFreq);
883 if (vec_opt && (vec_opt->size() == sizeof(decltype(core.sampling_frequency)::value_type))) {
884 auto ptr = vec_opt->data();
885 STREAM_TO_UINT8(core.sampling_frequency, ptr);
886 }
887
888 vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeFrameDuration);
889 if (vec_opt && (vec_opt->size() == sizeof(decltype(core.frame_duration)::value_type))) {
890 auto ptr = vec_opt->data();
891 STREAM_TO_UINT8(core.frame_duration, ptr);
892 }
893
894 vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation);
895 if (vec_opt &&
896 (vec_opt->size() == sizeof(decltype(core.audio_channel_allocation)::value_type))) {
897 auto ptr = vec_opt->data();
898 STREAM_TO_UINT32(core.audio_channel_allocation, ptr);
899 }
900
901 vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame);
902 if (vec_opt && (vec_opt->size() == sizeof(decltype(core.octets_per_codec_frame)::value_type))) {
903 auto ptr = vec_opt->data();
904 STREAM_TO_UINT16(core.octets_per_codec_frame, ptr);
905 }
906
907 vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu);
908 if (vec_opt &&
909 (vec_opt->size() == sizeof(decltype(core.codec_frames_blocks_per_sdu)::value_type))) {
910 auto ptr = vec_opt->data();
911 STREAM_TO_UINT8(core.codec_frames_blocks_per_sdu, ptr);
912 }
913
914 return core;
915 }
916
LtvMapToCoreCodecCapabilities(const LeAudioLtvMap & pacs)917 static LeAudioCoreCodecCapabilities LtvMapToCoreCodecCapabilities(const LeAudioLtvMap& pacs) {
918 LeAudioCoreCodecCapabilities core;
919
920 auto pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedSamplingFrequencies);
921 if (pac &&
922 (pac.value().size() == sizeof(decltype(core.supported_sampling_frequencies)::value_type))) {
923 core.supported_sampling_frequencies = VEC_UINT8_TO_UINT16(pac.value());
924 }
925
926 pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedFrameDurations);
927 if (pac &&
928 (pac.value().size() == sizeof(decltype(core.supported_frame_durations)::value_type))) {
929 core.supported_frame_durations = VEC_UINT8_TO_UINT8(pac.value());
930 }
931
932 pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedOctetsPerCodecFrame);
933 if (pac && (pac.value().size() ==
934 (sizeof(decltype(core.supported_min_octets_per_codec_frame)::value_type) +
935 sizeof(decltype(core.supported_max_octets_per_codec_frame)::value_type)))) {
936 core.supported_min_octets_per_codec_frame = VEC_UINT8_TO_UINT16(pac.value());
937 core.supported_max_octets_per_codec_frame = OFF_VEC_UINT8_TO_UINT16(
938 pac.value(), sizeof(decltype(core.supported_min_octets_per_codec_frame)::value_type));
939 }
940
941 /*
942 * BAP_1.0.1 4.3.1 Codec_Specific_Capabilities LTV requirements:
943 * The absence of the Supported_Audio_Channel_Counts LTV structure shall be
944 * interpreted as equivalent to a Supported_Audio_Channel_Counts value of
945 * 0x01 (one Audio Channel supported).
946 */
947 pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedAudioChannelCounts);
948 if (pac &&
949 (pac.value().size() == sizeof(decltype(core.supported_audio_channel_counts)::value_type))) {
950 core.supported_audio_channel_counts = VEC_UINT8_TO_UINT8(pac.value());
951 } else {
952 core.supported_audio_channel_counts = 0b1;
953 }
954
955 /*
956 * BAP_1.0.1 4.3.1 Codec_Specific_Capabilities LTV requirements:
957 * The absence of the Supported_Max_Codec_Frames_Per_SDU LTV structure shall
958 * be interpreted as equivalent to a Supported_Max_Codec_Frames_Per_SDU
959 * value of 1 codec frame per Audio Channel per SDU maximum.
960 */
961 pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu);
962 if (pac && (pac.value().size() ==
963 sizeof(decltype(core.supported_max_codec_frames_per_sdu)::value_type))) {
964 core.supported_max_codec_frames_per_sdu = VEC_UINT8_TO_UINT8(pac.value());
965 } else {
966 core.supported_max_codec_frames_per_sdu = 1;
967 }
968
969 return core;
970 }
971
RecalculateValueHash()972 void RecalculateValueHash() const {
973 if (IsEmpty()) {
974 value_hash = 0;
975 return;
976 }
977
978 auto value_vec = RawPacket();
979 value_hash = std::hash<std::string_view>{}(
980 {reinterpret_cast<const char*>(value_vec.data()), value_vec.size()});
981 }
982
983 std::map<uint8_t, std::vector<uint8_t>> values = {};
984 mutable size_t value_hash = 0;
985 // Lazy-constructed views of the LTV data
986 mutable std::optional<struct LeAudioCoreCodecConfig> core_config = std::nullopt;
987 mutable std::optional<struct LeAudioCoreCodecCapabilities> core_capabilities = std::nullopt;
988 mutable std::optional<struct LeAudioMetadata> metadata = std::nullopt;
989 };
990
991 struct LeAudioCodecId {
992 uint8_t coding_format;
993 uint16_t vendor_company_id;
994 uint16_t vendor_codec_id;
995
996 friend bool operator==(const LeAudioCodecId& lhs, const LeAudioCodecId& rhs) {
997 if (lhs.coding_format != rhs.coding_format) {
998 return false;
999 }
1000
1001 if (lhs.coding_format == kLeAudioCodingFormatVendorSpecific &&
1002 (lhs.vendor_company_id != rhs.vendor_company_id ||
1003 lhs.vendor_codec_id != rhs.vendor_codec_id)) {
1004 return false;
1005 }
1006
1007 return true;
1008 }
1009
1010 friend bool operator!=(const LeAudioCodecId& lhs, const LeAudioCodecId& rhs) {
1011 return !(lhs == rhs);
1012 }
1013 };
1014
1015 /* Google vendor specific codec for Headtracking */
1016 constexpr LeAudioCodecId kLeAudioCodecHeadtracking = {kLeAudioCodingFormatVendorSpecific,
1017 kLeAudioVendorCompanyIdGoogle,
1018 kLeAudioVendorCodecIdHeadtracking};
1019
1020 struct IsoDataPathConfiguration {
1021 types::LeAudioCodecId codecId = {0, 0, 0};
1022 bool isTransparent = true;
1023 uint32_t controllerDelayUs = 0;
1024 std::vector<uint8_t> configuration = {};
1025
1026 bool operator==(const IsoDataPathConfiguration& other) const {
1027 if (codecId != other.codecId) {
1028 return false;
1029 }
1030 if (isTransparent != other.isTransparent) {
1031 return false;
1032 }
1033 if (controllerDelayUs != other.controllerDelayUs) {
1034 return false;
1035 }
1036 if (configuration.size() != other.configuration.size()) {
1037 return false;
1038 }
1039 if ((!other.configuration.empty()) &&
1040 memcmp(configuration.data(), other.configuration.data(), other.configuration.size())) {
1041 return false;
1042 }
1043 return true;
1044 }
1045
1046 bool operator!=(const IsoDataPathConfiguration& other) const { return !(*this == other); }
1047 };
1048
1049 std::ostream& operator<<(std::ostream& os, const le_audio::types::IsoDataPathConfiguration& config);
1050
1051 struct DataPathConfiguration {
1052 uint8_t dataPathId = 0;
1053 std::vector<uint8_t> dataPathConfig = {};
1054 IsoDataPathConfiguration isoDataPathConfig;
1055
1056 bool operator==(const DataPathConfiguration& other) const {
1057 if (dataPathId != other.dataPathId) {
1058 return false;
1059 }
1060 if (isoDataPathConfig != other.isoDataPathConfig) {
1061 return false;
1062 }
1063 if (dataPathConfig.size() != other.dataPathConfig.size()) {
1064 return false;
1065 }
1066 if ((!other.dataPathConfig.empty()) &&
1067 memcmp(dataPathConfig.data(), other.dataPathConfig.data(), other.dataPathConfig.size())) {
1068 return false;
1069 }
1070 return true;
1071 }
1072
1073 bool operator!=(const DataPathConfiguration& other) const { return !(*this == other); }
1074 };
1075
1076 std::ostream& operator<<(std::ostream& os, const le_audio::types::DataPathConfiguration& config);
1077
1078 struct hdl_pair {
1079 hdl_pair() = default;
hdl_pairhdl_pair1080 hdl_pair(uint16_t val_hdl, uint16_t ccc_hdl) : val_hdl(val_hdl), ccc_hdl(ccc_hdl) {}
1081
1082 uint16_t val_hdl = 0;
1083 uint16_t ccc_hdl = 0;
1084 };
1085
1086 struct AseQosConfiguration {
1087 uint32_t presentation_delay = 0;
1088 uint32_t sdu_interval = 0;
1089 uint16_t max_transport_latency = 0;
1090 uint16_t max_sdu_size = 0;
1091 uint8_t retrans_nb = 0;
1092 uint8_t framing = 0;
1093 uint8_t phy = 0;
1094 };
1095
1096 struct AseQosPreferences {
1097 uint8_t supported_framing = 0;
1098 uint8_t preferred_phy = 0;
1099 uint8_t preferred_retrans_nb = 0;
1100 uint32_t pres_delay_min = 0;
1101 uint32_t pres_delay_max = 0;
1102 uint32_t preferred_pres_delay_min = 0;
1103 uint32_t preferred_pres_delay_max = 0;
1104 };
1105
1106 struct ase {
1107 static constexpr uint8_t kAseIdInvalid = 0x00;
1108
1109 ase(uint16_t val_hdl, uint16_t ccc_hdl, uint8_t direction, uint8_t initial_id = kAseIdInvalid)
hdlsase1110 : hdls(val_hdl, ccc_hdl),
1111 id(initial_id),
1112 cis_id(kInvalidCisId),
1113 direction(direction),
1114 target_latency(types::kTargetLatencyBalancedLatencyReliability),
1115 active(false),
1116 reconfigure(false),
1117 cis_state(CisState::IDLE),
1118 data_path_state(DataPathState::IDLE),
1119 configured_for_context_type(LeAudioContextType::UNINITIALIZED),
1120 state(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {}
1121
1122 struct hdl_pair hdls;
1123 uint8_t id;
1124 uint8_t cis_id;
1125 const uint8_t direction;
1126 uint8_t target_latency;
1127 uint16_t cis_conn_hdl = kInvalidCisConnHandle;
1128
1129 bool active;
1130 bool reconfigure;
1131 CisState cis_state;
1132 DataPathState data_path_state;
1133 LeAudioContextType configured_for_context_type;
1134
1135 /* Codec configuration */
1136 LeAudioCodecId codec_id;
1137 LeAudioLtvMap codec_config;
1138 std::vector<uint8_t> vendor_codec_config;
1139 uint8_t channel_count;
1140
1141 /* Data path configuration */
1142 DataPathConfiguration data_path_configuration;
1143
1144 /* Qos configuration */
1145 AseQosConfiguration qos_config;
1146
1147 /* QoS requirements in Codec Configured state */
1148 AseQosPreferences qos_preferences;
1149
1150 std::vector<uint8_t> metadata;
1151
1152 AseState state;
1153 };
1154
1155 struct acs_ac_record {
1156 LeAudioCodecId codec_id;
1157 LeAudioLtvMap codec_spec_caps;
1158 std::vector<uint8_t> codec_spec_caps_raw;
1159 std::vector<uint8_t> metadata;
1160 };
1161
1162 using PublishedAudioCapabilities = std::vector<std::tuple<hdl_pair, std::vector<acs_ac_record>>>;
1163 using AudioLocations = std::bitset<32>;
1164
1165 std::ostream& operator<<(std::ostream& os, const AseState& state);
1166 std::ostream& operator<<(std::ostream& os, const CigState& state);
1167 std::ostream& operator<<(std::ostream& os, const LeAudioCodecId& codec_id);
1168 std::ostream& operator<<(std::ostream& os, const LeAudioCoreCodecConfig& config);
1169 std::string contextTypeToStr(const LeAudioContextType& context);
1170 std::ostream& operator<<(std::ostream& os, const LeAudioContextType& context);
1171 std::ostream& operator<<(std::ostream& os, const DataPathState& state);
1172 std::ostream& operator<<(std::ostream& os, const CisState& state);
1173 std::ostream& operator<<(std::ostream& os, const AudioContexts& contexts);
1174 } // namespace types
1175
1176 namespace set_configurations {
1177
1178 struct CodecConfigSetting {
1179 /* Codec identifier */
1180 types::LeAudioCodecId id;
1181
1182 /* Codec Specific Configuration */
1183 types::LeAudioLtvMap params;
1184 /* Vendor Specific Configuration */
1185 std::vector<uint8_t> vendor_params;
1186
1187 /* Channel count per device */
1188 uint8_t channel_count_per_iso_stream;
1189
1190 /* Octets per fram for codec */
1191 uint16_t GetOctetsPerFrame() const;
1192 /* Sampling frequency requested for codec */
1193 uint32_t GetSamplingFrequencyHz() const;
1194 /* Data fetch/feed interval for codec in microseconds */
1195 uint32_t GetDataIntervalUs() const;
1196 /* Audio bit depth required for codec */
1197 uint8_t GetBitsPerSample() const;
1198 /* Audio channels number for a device */
GetChannelCountPerIsoStreamCodecConfigSetting1199 uint8_t GetChannelCountPerIsoStream() const { return channel_count_per_iso_stream; }
1200
1201 bool operator==(const CodecConfigSetting& other) const {
1202 return (id == other.id) &&
1203 (channel_count_per_iso_stream == other.channel_count_per_iso_stream) &&
1204 (vendor_params == other.vendor_params) && (params == other.params);
1205 }
1206
1207 bool operator!=(const CodecConfigSetting& other) const { return !(*this == other); }
1208
1209 /* TODO: Add vendor parameter or Ltv map viewers for
1210 * vendor specific LTV types.
1211 */
1212 };
1213
1214 std::ostream& operator<<(std::ostream& os, const CodecConfigSetting& config);
1215
1216 struct QosConfigSetting {
1217 uint8_t target_latency;
1218 uint8_t retransmission_number;
1219 uint16_t max_transport_latency;
1220 int sduIntervalUs;
1221 int maxSdu;
1222
1223 bool operator!=(const QosConfigSetting& other) { return !(*this == other); }
1224
1225 bool operator==(const QosConfigSetting& other) const {
1226 return (target_latency == other.target_latency) &&
1227 (retransmission_number == other.retransmission_number) &&
1228 (max_transport_latency == other.max_transport_latency);
1229 }
1230 };
1231
1232 std::ostream& operator<<(std::ostream& os, const QosConfigSetting& config);
1233
1234 struct AseConfiguration {
1235 AseConfiguration(CodecConfigSetting codec, QosConfigSetting qos = {.target_latency = 0,
1236 .retransmission_number = 0,
1237 .max_transport_latency = 0})
codecAseConfiguration1238 : codec(codec), qos(qos) {}
1239 types::DataPathConfiguration data_path_configuration;
1240 CodecConfigSetting codec;
1241 QosConfigSetting qos;
1242
1243 bool operator!=(const AseConfiguration& other) { return !(*this == other); }
1244
1245 bool operator==(const AseConfiguration& other) const {
1246 return (data_path_configuration == other.data_path_configuration) && (codec == other.codec) &&
1247 (qos == other.qos);
1248 }
1249 };
1250
1251 std::ostream& operator<<(std::ostream& os, const AseConfiguration& config);
1252
1253 /* Defined audio scenarios */
1254 struct AudioSetConfiguration {
1255 std::string name = "";
1256 /* ISO data packing within the CIG */
1257 uint8_t packing = bluetooth::hci::kIsoCigPackingSequential;
1258 types::BidirectionalPair<std::vector<struct AseConfiguration>> confs;
1259
1260 bool operator!=(const AudioSetConfiguration& other) { return !(*this == other); }
1261
1262 bool operator==(const AudioSetConfiguration& other) const {
1263 return (packing == other.packing) && (confs == other.confs);
1264 }
1265 };
1266
1267 std::ostream& operator<<(std::ostream& os, const AudioSetConfiguration& config);
1268
1269 using AudioSetConfigurations = std::vector<const AudioSetConfiguration*>;
1270
1271 const types::LeAudioCodecId LeAudioCodecIdLc3 = {
1272 .coding_format = types::kLeAudioCodingFormatLC3,
1273 .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined,
1274 .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined};
1275
1276 static constexpr uint32_t kChannelAllocationStereo =
1277 codec_spec_conf::kLeAudioLocationFrontLeft | codec_spec_conf::kLeAudioLocationFrontRight;
1278
1279 /* Declarations */
1280 void get_cis_count(types::LeAudioContextType context_type, uint8_t expected_direction,
1281 int expected_device_cnt, types::LeAudioConfigurationStrategy strategy,
1282 int group_ase_snk_cnt, int group_ase_src_count, uint8_t& cis_count_bidir,
1283 uint8_t& cis_count_unidir_sink, uint8_t& cis_count_unidir_source);
1284 } // namespace set_configurations
1285
1286 struct stream_parameters {
1287 /* For now we have always same frequency for all the channels */
1288 uint32_t sample_frequency_hz;
1289 uint32_t frame_duration_us;
1290 uint16_t octets_per_codec_frame;
1291 uint32_t audio_channel_allocation;
1292 uint8_t codec_frames_blocks_per_sdu;
1293
1294 /* Total number of channels we request from the audio framework */
1295 uint8_t num_of_channels;
1296 int num_of_devices;
1297 /* cis_handle, audio location*/
1298 std::vector<std::pair<uint16_t, uint32_t>> stream_locations;
1299
clearstream_parameters1300 void clear() {
1301 sample_frequency_hz = 0;
1302 frame_duration_us = 0;
1303 octets_per_codec_frame = 0;
1304 audio_channel_allocation = 0;
1305 codec_frames_blocks_per_sdu = 0;
1306 num_of_channels = 0;
1307 num_of_devices = 0;
1308 stream_locations.clear();
1309 }
1310 };
1311
1312 struct stream_configuration {
1313 /* Whether the group should be reconfigured once the streaming stops */
1314 bool pending_configuration;
1315
1316 /* Currently selected remote device set configuration */
1317 std::shared_ptr<const bluetooth::le_audio::set_configurations::AudioSetConfiguration> conf;
1318
1319 /* Currently selected local audio codec */
1320 types::LeAudioCodecId codec_id;
1321
1322 /* Currently selected local Sink & Source configuration */
1323 types::BidirectionalPair<stream_parameters> stream_params;
1324 };
1325
1326 void AppendMetadataLtvEntryForCcidList(std::vector<uint8_t>& metadata,
1327 const std::vector<uint8_t>& ccid_list);
1328 void AppendMetadataLtvEntryForStreamingContext(std::vector<uint8_t>& metadata,
1329 types::AudioContexts context_type);
1330 uint8_t GetMaxCodecFramesPerSduFromPac(const types::acs_ac_record* pac_record);
1331 } // namespace bluetooth::le_audio
1332
1333 namespace std {
1334 template <>
1335 struct formatter<bluetooth::le_audio::DsaMode> : enum_formatter<bluetooth::le_audio::DsaMode> {};
1336 template <>
1337 struct formatter<bluetooth::le_audio::types::CisType>
1338 : enum_formatter<bluetooth::le_audio::types::CisType> {};
1339 template <>
1340 struct formatter<bluetooth::le_audio::types::LeAudioConfigurationStrategy>
1341 : enum_formatter<bluetooth::le_audio::types::LeAudioConfigurationStrategy> {};
1342 } // namespace std
1343