1 /*  Bluetooth Audio Broadcast Sink */
2 
3 /*
4  * Copyright (c) 2021-2024 Nordic Semiconductor ASA
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include <errno.h>
10 #include <stdbool.h>
11 #include <stddef.h>
12 #include <stdint.h>
13 #include <string.h>
14 
15 #include <zephyr/autoconf.h>
16 #include <zephyr/bluetooth/addr.h>
17 #include <zephyr/bluetooth/bluetooth.h>
18 #include <zephyr/bluetooth/conn.h>
19 #include <zephyr/bluetooth/gap.h>
20 #include <zephyr/bluetooth/gatt.h>
21 #include <zephyr/bluetooth/audio/audio.h>
22 #include <zephyr/bluetooth/audio/bap.h>
23 #include <zephyr/bluetooth/audio/pacs.h>
24 #include <zephyr/bluetooth/audio/bap.h>
25 #include <zephyr/bluetooth/hci_types.h>
26 #include <zephyr/bluetooth/iso.h>
27 #include <zephyr/bluetooth/uuid.h>
28 #include <zephyr/init.h>
29 #include <zephyr/kernel.h>
30 #include <zephyr/logging/log.h>
31 #include <zephyr/net_buf.h>
32 #include <zephyr/sys/__assert.h>
33 #include <zephyr/sys/atomic.h>
34 #include <zephyr/sys/byteorder.h>
35 #include <zephyr/sys/check.h>
36 #include <zephyr/sys/slist.h>
37 #include <zephyr/sys/util.h>
38 #include <zephyr/sys/util_macro.h>
39 
40 #include "../host/conn_internal.h"
41 #include "../host/iso_internal.h"
42 
43 #include "audio_internal.h"
44 #include "bap_iso.h"
45 #include "bap_endpoint.h"
46 
47 LOG_MODULE_REGISTER(bt_bap_broadcast_sink, CONFIG_BT_BAP_BROADCAST_SINK_LOG_LEVEL);
48 
49 #include "common/bt_str.h"
50 
51 #define PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO 20 /* Set the timeout relative to interval */
52 #define BROADCAST_SYNC_MIN_INDEX  (BIT(1))
53 
54 static struct bt_bap_ep broadcast_sink_eps[CONFIG_BT_BAP_BROADCAST_SNK_COUNT]
55 					  [CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT];
56 static struct bt_bap_broadcast_sink broadcast_sinks[CONFIG_BT_BAP_BROADCAST_SNK_COUNT];
57 
58 struct codec_cap_lookup_id_data {
59 	uint8_t id;
60 	const struct bt_audio_codec_cap *codec_cap;
61 };
62 
63 static sys_slist_t sink_cbs = SYS_SLIST_STATIC_INIT(&sink_cbs);
64 
65 static void broadcast_sink_cleanup(struct bt_bap_broadcast_sink *sink);
66 
find_recv_state_by_sink_cb(const struct bt_bap_scan_delegator_recv_state * recv_state,void * user_data)67 static bool find_recv_state_by_sink_cb(const struct bt_bap_scan_delegator_recv_state *recv_state,
68 				       void *user_data)
69 {
70 	const struct bt_bap_broadcast_sink *sink = user_data;
71 
72 	if (atomic_test_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID) &&
73 	    sink->bass_src_id == recv_state->src_id) {
74 		return true;
75 	}
76 
77 	return false;
78 }
79 
find_recv_state_by_pa_sync_cb(const struct bt_bap_scan_delegator_recv_state * recv_state,void * user_data)80 static bool find_recv_state_by_pa_sync_cb(const struct bt_bap_scan_delegator_recv_state *recv_state,
81 					  void *user_data)
82 {
83 	struct bt_le_per_adv_sync *sync = user_data;
84 	struct bt_le_per_adv_sync_info sync_info;
85 	int err;
86 
87 	err = bt_le_per_adv_sync_get_info(sync, &sync_info);
88 	if (err != 0) {
89 		LOG_DBG("Failed to get sync info: %d", err);
90 
91 		return false;
92 	}
93 
94 	if (bt_addr_le_eq(&recv_state->addr, &sync_info.addr) &&
95 	    recv_state->adv_sid == sync_info.sid) {
96 		return true;
97 	}
98 
99 	return false;
100 };
101 
update_recv_state_big_synced(const struct bt_bap_broadcast_sink * sink)102 static void update_recv_state_big_synced(const struct bt_bap_broadcast_sink *sink)
103 {
104 	const struct bt_bap_scan_delegator_recv_state *recv_state;
105 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = {0};
106 	int err;
107 
108 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
109 	if (recv_state == NULL) {
110 		LOG_WRN("Failed to find receive state for sink %p", sink);
111 
112 		return;
113 	}
114 
115 	mod_src_param.num_subgroups = sink->subgroup_count;
116 	for (uint8_t i = 0U; i < sink->subgroup_count; i++) {
117 		struct bt_bap_bass_subgroup *subgroup_param = &mod_src_param.subgroups[i];
118 		const struct bt_bap_broadcast_sink_subgroup *sink_subgroup = &sink->subgroups[i];
119 
120 		/* Set the bis_sync value to the indexes available per subgroup */
121 		subgroup_param->bis_sync = sink_subgroup->bis_indexes & sink->indexes_bitfield;
122 	}
123 
124 	if (recv_state->encrypt_state == BT_BAP_BIG_ENC_STATE_BCODE_REQ) {
125 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_DEC;
126 	} else {
127 		mod_src_param.encrypt_state = recv_state->encrypt_state;
128 	}
129 
130 	/* Since the mod_src_param struct is 0-initialized the metadata won't
131 	 * be modified by this
132 	 */
133 
134 	/* Copy existing unchanged data */
135 	mod_src_param.src_id = recv_state->src_id;
136 	mod_src_param.broadcast_id = recv_state->broadcast_id;
137 
138 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
139 	if (err != 0) {
140 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
141 	}
142 }
143 
update_recv_state_big_cleared(const struct bt_bap_broadcast_sink * sink,uint8_t reason)144 static void update_recv_state_big_cleared(const struct bt_bap_broadcast_sink *sink,
145 					  uint8_t reason)
146 {
147 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
148 	const struct bt_bap_scan_delegator_recv_state *recv_state;
149 	int err;
150 
151 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
152 	if (recv_state == NULL) {
153 		/* This is likely due to the receive state being removed while we are BIG synced */
154 		LOG_DBG("Could not find receive state for sink %p", sink);
155 
156 		return;
157 	}
158 
159 	if ((recv_state->encrypt_state == BT_BAP_BIG_ENC_STATE_BCODE_REQ ||
160 	     recv_state->encrypt_state == BT_BAP_BIG_ENC_STATE_DEC) &&
161 	    reason == BT_HCI_ERR_TERM_DUE_TO_MIC_FAIL) {
162 		/* Sync failed due to bad broadcast code */
163 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_BAD_CODE;
164 	} else {
165 		mod_src_param.encrypt_state = recv_state->encrypt_state;
166 	}
167 
168 	if (reason != BT_HCI_ERR_LOCALHOST_TERM_CONN) {
169 		for (uint8_t i = 0U; i < recv_state->num_subgroups; i++) {
170 			mod_src_param.subgroups[i].bis_sync = BT_BAP_BIS_SYNC_FAILED;
171 		}
172 	}
173 
174 	/* Since the metadata_len is 0 then the metadata won't be modified by the operation either*/
175 
176 	/* Copy existing unchanged data */
177 	mod_src_param.num_subgroups = recv_state->num_subgroups;
178 	mod_src_param.src_id = recv_state->src_id;
179 	mod_src_param.broadcast_id = recv_state->broadcast_id;
180 
181 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
182 	if (err != 0) {
183 		LOG_WRN("Failed to modify Receive State for sink %p: %d",
184 			sink, err);
185 	}
186 }
187 
broadcast_sink_clear_big(struct bt_bap_broadcast_sink * sink,uint8_t reason)188 static void broadcast_sink_clear_big(struct bt_bap_broadcast_sink *sink,
189 				     uint8_t reason)
190 {
191 	sink->big = NULL;
192 
193 	update_recv_state_big_cleared(sink, reason);
194 }
195 
broadcast_sink_lookup_iso_chan(const struct bt_iso_chan * chan)196 static struct bt_bap_broadcast_sink *broadcast_sink_lookup_iso_chan(
197 	const struct bt_iso_chan *chan)
198 {
199 	for (size_t i = 0U; i < ARRAY_SIZE(broadcast_sinks); i++) {
200 		for (uint8_t j = 0U; j < broadcast_sinks[i].stream_count; j++) {
201 			if (broadcast_sinks[i].bis[j].chan == chan) {
202 				return &broadcast_sinks[i];
203 			}
204 		}
205 	}
206 
207 	return NULL;
208 }
209 
broadcast_sink_set_ep_state(struct bt_bap_ep * ep,uint8_t state)210 static void broadcast_sink_set_ep_state(struct bt_bap_ep *ep, uint8_t state)
211 {
212 	uint8_t old_state;
213 
214 	old_state = ep->status.state;
215 
216 	LOG_DBG("ep %p id 0x%02x %s -> %s", ep, ep->status.id, bt_bap_ep_state_str(old_state),
217 		bt_bap_ep_state_str(state));
218 
219 	switch (old_state) {
220 	case BT_BAP_EP_STATE_IDLE:
221 		if (state != BT_BAP_EP_STATE_QOS_CONFIGURED) {
222 			LOG_DBG("Invalid broadcast sync endpoint state transition");
223 			return;
224 		}
225 		break;
226 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
227 		if (state != BT_BAP_EP_STATE_IDLE && state != BT_BAP_EP_STATE_STREAMING) {
228 			LOG_DBG("Invalid broadcast sync endpoint state transition");
229 			return;
230 		}
231 		break;
232 	case BT_BAP_EP_STATE_STREAMING:
233 		if (state != BT_BAP_EP_STATE_IDLE) {
234 			LOG_DBG("Invalid broadcast sync endpoint state transition");
235 			return;
236 		}
237 		break;
238 	default:
239 		LOG_ERR("Invalid broadcast sync endpoint state: %s",
240 			bt_bap_ep_state_str(old_state));
241 		return;
242 	}
243 
244 	ep->status.state = state;
245 
246 	if (state == BT_BAP_EP_STATE_IDLE) {
247 		struct bt_bap_stream *stream = ep->stream;
248 
249 		if (stream != NULL) {
250 			bt_bap_iso_unbind_ep(ep->iso, ep);
251 			stream->ep = NULL;
252 			stream->codec_cfg = NULL;
253 			ep->stream = NULL;
254 		}
255 	}
256 }
257 
broadcast_sink_iso_recv(struct bt_iso_chan * chan,const struct bt_iso_recv_info * info,struct net_buf * buf)258 static void broadcast_sink_iso_recv(struct bt_iso_chan *chan,
259 				    const struct bt_iso_recv_info *info,
260 				    struct net_buf *buf)
261 {
262 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
263 	const struct bt_bap_stream_ops *ops;
264 	struct bt_bap_stream *stream;
265 	struct bt_bap_ep *ep = iso->rx.ep;
266 	size_t buf_len;
267 
268 	if (ep == NULL) {
269 		LOG_ERR("iso %p not bound with ep", chan);
270 		return;
271 	}
272 
273 	stream = ep->stream;
274 	if (stream == NULL) {
275 		LOG_ERR("No stream for ep %p", ep);
276 		return;
277 	}
278 
279 	ops = stream->ops;
280 
281 	buf_len = net_buf_frags_len(buf);
282 	if (IS_ENABLED(CONFIG_BT_BAP_DEBUG_STREAM_DATA)) {
283 		LOG_DBG("stream %p ep %p len %zu", stream, stream->ep, buf_len);
284 	}
285 
286 	if (buf_len > stream->qos->sdu) {
287 		LOG_WRN("Received %u octets but stream %p was only configured for %u", buf_len,
288 			stream, stream->qos->sdu);
289 	}
290 
291 	if (ops != NULL && ops->recv != NULL) {
292 		ops->recv(stream, info, buf);
293 	} else {
294 		LOG_WRN("No callback for recv set");
295 	}
296 }
297 
broadcast_sink_is_in_state(struct bt_bap_broadcast_sink * sink,enum bt_bap_ep_state state)298 static bool broadcast_sink_is_in_state(struct bt_bap_broadcast_sink *sink,
299 				       enum bt_bap_ep_state state)
300 {
301 	struct bt_bap_stream *stream;
302 
303 	if (sink == NULL) {
304 		LOG_DBG("sink is NULL");
305 
306 		return state == BT_BAP_EP_STATE_IDLE;
307 	}
308 
309 	if (sys_slist_is_empty(&sink->streams)) {
310 		LOG_DBG("Sink does not have any streams");
311 
312 		return state == BT_BAP_EP_STATE_IDLE;
313 	}
314 
315 	SYS_SLIST_FOR_EACH_CONTAINER(&sink->streams, stream, _node) {
316 		if (stream->ep != NULL && stream->ep->status.state != state) {
317 			return false;
318 		}
319 	}
320 
321 	return true;
322 }
323 
broadcast_sink_iso_connected(struct bt_iso_chan * chan)324 static void broadcast_sink_iso_connected(struct bt_iso_chan *chan)
325 {
326 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
327 	const struct bt_bap_stream_ops *ops;
328 	struct bt_bap_broadcast_sink *sink;
329 	struct bt_bap_stream *stream;
330 	struct bt_bap_ep *ep = iso->rx.ep;
331 
332 	if (ep == NULL) {
333 		LOG_ERR("iso %p not bound with ep", chan);
334 		return;
335 	}
336 
337 	stream = ep->stream;
338 	if (stream == NULL) {
339 		LOG_ERR("No stream for ep %p", ep);
340 		return;
341 	}
342 
343 	LOG_DBG("stream %p", stream);
344 
345 	ops = stream->ops;
346 	if (ops != NULL && ops->connected != NULL) {
347 		ops->connected(stream);
348 	}
349 
350 	sink = broadcast_sink_lookup_iso_chan(chan);
351 	if (sink == NULL) {
352 		LOG_ERR("Could not lookup sink by iso %p", chan);
353 		return;
354 	}
355 
356 	broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_STREAMING);
357 
358 	if (ops != NULL && ops->started != NULL) {
359 		ops->started(stream);
360 	} else {
361 		LOG_WRN("No callback for started set");
362 	}
363 
364 	if (broadcast_sink_is_in_state(sink, BT_BAP_EP_STATE_STREAMING)) {
365 		update_recv_state_big_synced(sink);
366 	}
367 }
368 
broadcast_sink_iso_disconnected(struct bt_iso_chan * chan,uint8_t reason)369 static void broadcast_sink_iso_disconnected(struct bt_iso_chan *chan,
370 					    uint8_t reason)
371 {
372 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
373 	const struct bt_bap_stream_ops *ops;
374 	struct bt_bap_stream *stream;
375 	struct bt_bap_ep *ep = iso->rx.ep;
376 	struct bt_bap_broadcast_sink *sink;
377 
378 	if (ep == NULL) {
379 		LOG_ERR("iso %p not bound with ep", chan);
380 		return;
381 	}
382 
383 	stream = ep->stream;
384 	if (stream == NULL) {
385 		LOG_ERR("No stream for ep %p", ep);
386 		return;
387 	}
388 
389 	LOG_DBG("stream %p ep %p reason 0x%02x", stream, ep, reason);
390 
391 	ops = stream->ops;
392 	if (ops != NULL && ops->disconnected != NULL) {
393 		ops->disconnected(stream, reason);
394 	}
395 
396 	broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_IDLE);
397 
398 	sink = broadcast_sink_lookup_iso_chan(chan);
399 	if (sink == NULL) {
400 		LOG_ERR("Could not lookup sink by iso %p", chan);
401 	} else {
402 		if (!sys_slist_find_and_remove(&sink->streams, &stream->_node)) {
403 			LOG_DBG("Could not find and remove stream %p from sink %p", stream, sink);
404 		}
405 	}
406 
407 	if (ops != NULL && ops->stopped != NULL) {
408 		ops->stopped(stream, reason);
409 	} else {
410 		LOG_WRN("No callback for stopped set");
411 	}
412 }
413 
414 static struct bt_iso_chan_ops broadcast_sink_iso_ops = {
415 	.recv		= broadcast_sink_iso_recv,
416 	.connected	= broadcast_sink_iso_connected,
417 	.disconnected	= broadcast_sink_iso_disconnected,
418 };
419 
broadcast_sink_free_get(void)420 static struct bt_bap_broadcast_sink *broadcast_sink_free_get(void)
421 {
422 	/* Find free entry */
423 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
424 		if (!atomic_test_bit(broadcast_sinks[i].flags,
425 				     BT_BAP_BROADCAST_SINK_FLAG_INITIALIZED)) {
426 			broadcast_sinks[i].index = i;
427 			broadcast_sinks[i].broadcast_id = BT_BAP_INVALID_BROADCAST_ID;
428 
429 			return &broadcast_sinks[i];
430 		}
431 	}
432 
433 	return NULL;
434 }
435 
broadcast_sink_get_by_pa(struct bt_le_per_adv_sync * sync)436 static struct bt_bap_broadcast_sink *broadcast_sink_get_by_pa(struct bt_le_per_adv_sync *sync)
437 {
438 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
439 		if (broadcast_sinks[i].pa_sync == sync) {
440 			return &broadcast_sinks[i];
441 		}
442 	}
443 
444 	return NULL;
445 }
446 
broadcast_sink_get_by_big(const struct bt_iso_big * big)447 static struct bt_bap_broadcast_sink *broadcast_sink_get_by_big(const struct bt_iso_big *big)
448 {
449 	for (size_t i = 0U; i < ARRAY_SIZE(broadcast_sinks); i++) {
450 		if (broadcast_sinks[i].big == big) {
451 			return &broadcast_sinks[i];
452 		}
453 	}
454 
455 	return NULL;
456 }
457 
broadcast_sink_add_src(struct bt_bap_broadcast_sink * sink)458 static void broadcast_sink_add_src(struct bt_bap_broadcast_sink *sink)
459 {
460 	struct bt_bap_scan_delegator_add_src_param add_src_param;
461 	struct bt_le_per_adv_sync_info sync_info;
462 	int err;
463 
464 	err = bt_le_per_adv_sync_get_info(sink->pa_sync, &sync_info);
465 	__ASSERT_NO_MSG(err == 0);
466 
467 	bt_addr_le_copy(&add_src_param.addr, &sync_info.addr);
468 	add_src_param.sid = sync_info.sid;
469 	add_src_param.broadcast_id = sink->broadcast_id;
470 	/* Will be updated when we receive the BASE */
471 	add_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_NO_ENC;
472 	add_src_param.num_subgroups = 0U;
473 
474 	err = bt_bap_scan_delegator_add_src(&add_src_param);
475 	if (err < 0) {
476 		LOG_WRN("Failed to add sync as Receive State for sink %p: %d",
477 			sink, err);
478 	} else {
479 		sink->bass_src_id = (uint8_t)err;
480 		atomic_set_bit(sink->flags,
481 			       BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID);
482 	}
483 }
484 
base_subgroup_meta_cb(const struct bt_bap_base_subgroup * subgroup,void * user_data)485 static bool base_subgroup_meta_cb(const struct bt_bap_base_subgroup *subgroup, void *user_data)
486 {
487 	struct bt_bap_scan_delegator_mod_src_param *mod_src_param = user_data;
488 	struct bt_bap_bass_subgroup *subgroup_param;
489 	uint8_t *meta;
490 	int ret;
491 
492 	ret = bt_bap_base_get_subgroup_codec_meta(subgroup, &meta);
493 	if (ret < 0) {
494 		return false;
495 	}
496 
497 	subgroup_param = &mod_src_param->subgroups[mod_src_param->num_subgroups++];
498 	subgroup_param->metadata_len = (uint8_t)ret;
499 	memcpy(subgroup_param->metadata, meta, subgroup_param->metadata_len);
500 
501 	return true;
502 }
503 
update_recv_state_base_copy_meta(const struct bt_bap_base * base,struct bt_bap_scan_delegator_mod_src_param * param)504 static int update_recv_state_base_copy_meta(const struct bt_bap_base *base,
505 					    struct bt_bap_scan_delegator_mod_src_param *param)
506 {
507 	int err;
508 
509 	err = bt_bap_base_foreach_subgroup(base, base_subgroup_meta_cb, param);
510 	if (err != 0) {
511 		LOG_DBG("Failed to parse subgroups: %d", err);
512 		return err;
513 	}
514 
515 	return 0;
516 }
517 
update_recv_state_base(const struct bt_bap_broadcast_sink * sink,const struct bt_bap_base * base)518 static void update_recv_state_base(const struct bt_bap_broadcast_sink *sink,
519 				   const struct bt_bap_base *base)
520 {
521 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
522 	const struct bt_bap_scan_delegator_recv_state *recv_state;
523 	int err;
524 
525 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
526 	if (recv_state == NULL) {
527 		LOG_WRN("Failed to find receive state for sink %p", sink);
528 
529 		return;
530 	}
531 
532 	err = update_recv_state_base_copy_meta(base, &mod_src_param);
533 	if (err != 0) {
534 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
535 		return;
536 	}
537 
538 	/* Copy existing unchanged data */
539 	mod_src_param.src_id = recv_state->src_id;
540 	mod_src_param.encrypt_state = recv_state->encrypt_state;
541 	mod_src_param.broadcast_id = recv_state->broadcast_id;
542 	mod_src_param.num_subgroups = sink->subgroup_count;
543 	for (uint8_t i = 0U; i < sink->subgroup_count; i++) {
544 		struct bt_bap_bass_subgroup *subgroup_param = &mod_src_param.subgroups[i];
545 
546 		/* Leave the bis_sync unchanged */
547 		subgroup_param->bis_sync = recv_state->subgroups[i].bis_sync;
548 	}
549 
550 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
551 	if (err != 0) {
552 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
553 	}
554 }
555 
codec_lookup_id(const struct bt_pacs_cap * cap,void * user_data)556 static bool codec_lookup_id(const struct bt_pacs_cap *cap, void *user_data)
557 {
558 	struct codec_cap_lookup_id_data *data = user_data;
559 
560 	if (cap->codec_cap->id == data->id) {
561 		data->codec_cap = cap->codec_cap;
562 
563 		return false;
564 	}
565 
566 	return true;
567 }
568 
569 struct store_base_info_data {
570 	struct bt_bap_broadcast_sink_bis bis[CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT];
571 	struct bt_bap_broadcast_sink_subgroup subgroups[CONFIG_BT_BAP_BROADCAST_SNK_SUBGROUP_COUNT];
572 	struct bt_audio_codec_cfg *subgroup_codec_cfg;
573 	uint32_t valid_indexes_bitfield;
574 	uint8_t subgroup_count;
575 	uint8_t bis_count;
576 };
577 
merge_bis_and_subgroup_data_cb(struct bt_data * data,void * user_data)578 static bool merge_bis_and_subgroup_data_cb(struct bt_data *data, void *user_data)
579 {
580 	struct bt_audio_codec_cfg *codec_cfg = user_data;
581 	int err;
582 
583 	err = bt_audio_codec_cfg_set_val(codec_cfg, data->type, data->data, data->data_len);
584 	if (err < 0) {
585 		LOG_DBG("Failed to set type %u with len %u in codec_cfg: %d", data->type,
586 			data->data_len, err);
587 
588 		return false;
589 	}
590 
591 	return true;
592 }
593 
base_subgroup_bis_index_cb(const struct bt_bap_base_subgroup_bis * bis,void * user_data)594 static bool base_subgroup_bis_index_cb(const struct bt_bap_base_subgroup_bis *bis, void *user_data)
595 {
596 	struct bt_bap_broadcast_sink_subgroup *sink_subgroup;
597 	struct store_base_info_data *data = user_data;
598 	struct bt_bap_broadcast_sink_bis *sink_bis;
599 
600 	if (data->bis_count == ARRAY_SIZE(data->bis)) {
601 		/* We've parsed as many subgroups as we support */
602 		LOG_DBG("Could only store %u BIS", data->bis_count);
603 		return false;
604 	}
605 
606 	sink_bis = &data->bis[data->bis_count];
607 	sink_subgroup = &data->subgroups[data->subgroup_count];
608 
609 	sink_bis->index = bis->index;
610 	sink_subgroup->bis_indexes |= BT_ISO_BIS_INDEX_BIT(bis->index);
611 
612 #if CONFIG_BT_AUDIO_CODEC_CFG_MAX_DATA_SIZE > 0
613 
614 	memcpy(&sink_bis->codec_cfg, data->subgroup_codec_cfg, sizeof(sink_bis->codec_cfg));
615 
616 	if (bis->data_len > 0) {
617 		/* Merge subgroup codec configuration with the BIS configuration
618 		 * As per the BAP spec, if a value exist at level 2 (subgroup) and 3 (BIS), then it
619 		 * is the value at level 3 that shall be used
620 		 */
621 		if (sink_bis->codec_cfg.id == BT_HCI_CODING_FORMAT_LC3) {
622 			int err;
623 
624 			memcpy(&sink_bis->codec_cfg, data->subgroup_codec_cfg,
625 			       sizeof(sink_bis->codec_cfg));
626 
627 			err = bt_audio_data_parse(bis->data, bis->data_len,
628 						  merge_bis_and_subgroup_data_cb,
629 						  &sink_bis->codec_cfg);
630 			if (err != 0) {
631 				LOG_DBG("Could not merge BIS and subgroup config in codec_cfg: %d",
632 					err);
633 
634 				return false;
635 			}
636 		} else {
637 			/* If it is not LC3, then we don't know how to merge the subgroup and BIS
638 			 * codecs, so we just append them
639 			 */
640 			if (sink_bis->codec_cfg.data_len + bis->data_len >
641 			    sizeof(sink_bis->codec_cfg.data)) {
642 				LOG_DBG("Could not store BIS and subgroup config in codec_cfg (%u "
643 					"> %u)",
644 					sink_bis->codec_cfg.data_len + bis->data_len,
645 					sizeof(sink_bis->codec_cfg.data));
646 
647 				return false;
648 			}
649 
650 			memcpy(&sink_bis->codec_cfg.data[sink_bis->codec_cfg.data_len], bis->data,
651 			       bis->data_len);
652 			sink_bis->codec_cfg.data_len += bis->data_len;
653 		}
654 	}
655 #endif /* CONFIG_BT_AUDIO_CODEC_CFG_MAX_DATA_SIZE > 0 */
656 
657 	data->bis_count++;
658 
659 	return true;
660 }
661 
base_subgroup_cb(const struct bt_bap_base_subgroup * subgroup,void * user_data)662 static bool base_subgroup_cb(const struct bt_bap_base_subgroup *subgroup, void *user_data)
663 {
664 	struct bt_bap_broadcast_sink_subgroup *sink_subgroup;
665 	struct codec_cap_lookup_id_data lookup_data = {0};
666 	struct store_base_info_data *data = user_data;
667 	struct bt_audio_codec_cfg codec_cfg;
668 	int ret;
669 
670 	if (data->subgroup_count == ARRAY_SIZE(data->subgroups)) {
671 		/* We've parsed as many subgroups as we support */
672 		LOG_DBG("Could only store %u subgroups", data->subgroup_count);
673 		return false;
674 	}
675 
676 	sink_subgroup = &data->subgroups[data->subgroup_count];
677 
678 	ret = bt_bap_base_subgroup_codec_to_codec_cfg(subgroup, &codec_cfg);
679 	if (ret < 0) {
680 		LOG_DBG("Could not store codec_cfg: %d", ret);
681 		return false;
682 	}
683 
684 	/* Lookup and assign path_id based on capabilities */
685 	lookup_data.id = codec_cfg.id;
686 
687 	bt_pacs_cap_foreach(BT_AUDIO_DIR_SINK, codec_lookup_id, &lookup_data);
688 	if (lookup_data.codec_cap == NULL) {
689 		LOG_DBG("Codec with id %u is not supported by our capabilities", lookup_data.id);
690 	} else {
691 		codec_cfg.path_id = lookup_data.codec_cap->path_id;
692 		codec_cfg.ctlr_transcode = lookup_data.codec_cap->ctlr_transcode;
693 
694 		data->subgroup_codec_cfg = &codec_cfg;
695 
696 		ret = bt_bap_base_subgroup_foreach_bis(subgroup, base_subgroup_bis_index_cb, data);
697 		if (ret < 0) {
698 			LOG_DBG("Could not parse BISes: %d", ret);
699 			return false;
700 		}
701 
702 		/* Add BIS to bitfield of valid BIS indexes we support */
703 		data->valid_indexes_bitfield |= sink_subgroup->bis_indexes;
704 		data->subgroup_count++;
705 	}
706 
707 	return true;
708 }
709 
store_base_info(struct bt_bap_broadcast_sink * sink,const struct bt_bap_base * base)710 static int store_base_info(struct bt_bap_broadcast_sink *sink, const struct bt_bap_base *base)
711 {
712 	/* data is static due to its size, which easily can exceed the stack size */
713 	static struct store_base_info_data data;
714 	uint32_t pres_delay;
715 	int ret;
716 
717 	ret = bt_bap_base_get_pres_delay(base);
718 	if (ret < 0) {
719 		LOG_DBG("Could not get presentation delay: %d", ret);
720 		return ret;
721 	}
722 
723 	pres_delay = (uint32_t)ret;
724 
725 	memset(&data, 0, sizeof(data));
726 
727 	ret = bt_bap_base_foreach_subgroup(base, base_subgroup_cb, &data);
728 	if (ret != 0) {
729 		LOG_DBG("Failed to parse all subgroups: %d", ret);
730 		return ret;
731 	}
732 
733 	/* Ensure that we have not synced while parsing the BASE */
734 	if (sink->big == NULL) {
735 		sink->qos_cfg.pd = pres_delay;
736 		memcpy(sink->bis, data.bis, sizeof(sink->bis));
737 		memcpy(sink->subgroups, data.subgroups, sizeof(sink->subgroups));
738 		sink->subgroup_count = data.subgroup_count;
739 		sink->valid_indexes_bitfield = data.valid_indexes_bitfield;
740 	}
741 
742 	return 0;
743 }
744 
base_subgroup_bis_count_cb(const struct bt_bap_base_subgroup * subgroup,void * user_data)745 static bool base_subgroup_bis_count_cb(const struct bt_bap_base_subgroup *subgroup, void *user_data)
746 {
747 	uint8_t *bis_cnt = user_data;
748 	int ret;
749 
750 	ret = bt_bap_base_get_subgroup_bis_count(subgroup);
751 	if (ret < 0) {
752 		return false;
753 	}
754 
755 	*bis_cnt += (uint8_t)ret;
756 
757 	return true;
758 }
759 
base_get_bis_count(const struct bt_bap_base * base)760 static int base_get_bis_count(const struct bt_bap_base *base)
761 {
762 	uint8_t bis_cnt = 0U;
763 	int err;
764 
765 	err = bt_bap_base_foreach_subgroup(base, base_subgroup_bis_count_cb, &bis_cnt);
766 	if (err != 0) {
767 		LOG_DBG("Failed to parse subgroups: %d", err);
768 		return err;
769 	}
770 
771 	return bis_cnt;
772 }
773 
pa_decode_base(struct bt_data * data,void * user_data)774 static bool pa_decode_base(struct bt_data *data, void *user_data)
775 {
776 	struct bt_bap_broadcast_sink *sink = (struct bt_bap_broadcast_sink *)user_data;
777 	const struct bt_bap_base *base = bt_bap_base_get_base_from_ad(data);
778 	struct bt_bap_broadcast_sink_cb *listener;
779 	int base_size;
780 	int ret;
781 
782 	/* Base is NULL if the data does not contain a valid BASE */
783 	if (base == NULL) {
784 		return true;
785 	}
786 
787 	if (atomic_test_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_BIGINFO_RECEIVED)) {
788 		ret = base_get_bis_count(base);
789 
790 		if (ret < 0) {
791 			LOG_DBG("Invalid BASE: %d", ret);
792 			return false;
793 		} else if (ret != sink->biginfo_num_bis) {
794 			LOG_DBG("BASE contains different amount of BIS (%u) than reported by "
795 				"BIGInfo (%u)",
796 				ret, sink->biginfo_num_bis);
797 			return false;
798 		}
799 	}
800 
801 	/* Store newest BASE info until we are BIG synced */
802 	if (sink->big == NULL) {
803 		LOG_DBG("Updating BASE for sink %p with %d subgroups\n", sink,
804 			bt_bap_base_get_subgroup_count(base));
805 
806 		ret = store_base_info(sink, base);
807 		if (ret < 0) {
808 			LOG_DBG("Could not store BASE information: %d", ret);
809 
810 			/* If it returns -ECANCELED it means that we stopped parsing ourselves due
811 			 * to lack of memory. In this case we can still provide the BASE to the
812 			 * application else abort
813 			 */
814 			if (ret != -ECANCELED) {
815 				return false;
816 			}
817 		}
818 	}
819 
820 	if (atomic_test_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID)) {
821 		update_recv_state_base(sink, base);
822 	}
823 
824 	/* We provide the BASE without the service data UUID */
825 	base_size = bt_bap_base_get_size(base);
826 	if (base_size < 0) {
827 		LOG_DBG("BASE get size failed (%d)", base_size);
828 
829 		return false;
830 	}
831 
832 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
833 		if (listener->base_recv != NULL) {
834 			listener->base_recv(sink, base, (size_t)base_size);
835 		}
836 	}
837 
838 	return false;
839 }
840 
pa_recv(struct bt_le_per_adv_sync * sync,const struct bt_le_per_adv_sync_recv_info * info,struct net_buf_simple * buf)841 static void pa_recv(struct bt_le_per_adv_sync *sync,
842 		    const struct bt_le_per_adv_sync_recv_info *info,
843 		    struct net_buf_simple *buf)
844 {
845 	struct bt_bap_broadcast_sink *sink = broadcast_sink_get_by_pa(sync);
846 
847 	if (sink == NULL) {
848 		/* Not a PA sync that we control */
849 		return;
850 	}
851 
852 	if (sys_slist_is_empty(&sink_cbs)) {
853 		/* Terminate early if we do not have any broadcast sink listeners */
854 		return;
855 	}
856 
857 	bt_data_parse(buf, pa_decode_base, (void *)sink);
858 }
859 
pa_term_cb(struct bt_le_per_adv_sync * sync,const struct bt_le_per_adv_sync_term_info * info)860 static void pa_term_cb(struct bt_le_per_adv_sync *sync,
861 		       const struct bt_le_per_adv_sync_term_info *info)
862 {
863 	struct bt_bap_broadcast_sink *sink = broadcast_sink_get_by_pa(sync);
864 
865 	if (sink != NULL) {
866 		sink->pa_sync = NULL;
867 	}
868 }
869 
update_recv_state_encryption(const struct bt_bap_broadcast_sink * sink)870 static void update_recv_state_encryption(const struct bt_bap_broadcast_sink *sink)
871 {
872 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
873 	const struct bt_bap_scan_delegator_recv_state *recv_state;
874 	int err;
875 
876 	__ASSERT(sink->big == NULL, "Encryption state shall not be updated while synced");
877 
878 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
879 	if (recv_state == NULL) {
880 		LOG_WRN("Failed to find receive state for sink %p", sink);
881 
882 		return;
883 	}
884 
885 	/* Only change the encrypt state, and leave the rest as is */
886 	if (atomic_test_bit(sink->flags,
887 			    BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED)) {
888 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_BCODE_REQ;
889 	} else {
890 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_NO_ENC;
891 	}
892 
893 	if (mod_src_param.encrypt_state == recv_state->encrypt_state) {
894 		/* No change, abort*/
895 		return;
896 	}
897 
898 	/* Copy existing data */
899 	/* TODO: Maybe we need more refined functions to set only specific fields? */
900 	mod_src_param.src_id = recv_state->src_id;
901 	mod_src_param.broadcast_id = recv_state->broadcast_id;
902 	mod_src_param.num_subgroups = recv_state->num_subgroups;
903 	(void)memcpy(mod_src_param.subgroups,
904 		     recv_state->subgroups,
905 		     sizeof(recv_state->num_subgroups));
906 
907 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
908 	if (err != 0) {
909 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
910 	}
911 }
912 
biginfo_recv(struct bt_le_per_adv_sync * sync,const struct bt_iso_biginfo * biginfo)913 static void biginfo_recv(struct bt_le_per_adv_sync *sync,
914 			 const struct bt_iso_biginfo *biginfo)
915 {
916 	struct bt_bap_broadcast_sink_cb *listener;
917 	struct bt_bap_broadcast_sink *sink;
918 
919 	sink = broadcast_sink_get_by_pa(sync);
920 	if (sink == NULL) {
921 		/* Not ours */
922 		return;
923 	}
924 
925 	if (sink->big != NULL) {
926 		/* Already synced - ignore */
927 		return;
928 	}
929 
930 	atomic_set_bit(sink->flags,
931 		       BT_BAP_BROADCAST_SINK_FLAG_BIGINFO_RECEIVED);
932 	sink->iso_interval = biginfo->iso_interval;
933 	sink->biginfo_num_bis = biginfo->num_bis;
934 	if (biginfo->encryption != atomic_test_bit(sink->flags,
935 						   BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED)) {
936 		atomic_set_bit_to(sink->flags,
937 				  BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED,
938 				  biginfo->encryption);
939 
940 		if (atomic_test_bit(sink->flags,
941 				    BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID)) {
942 			update_recv_state_encryption(sink);
943 		}
944 	}
945 
946 	sink->qos_cfg.framing = biginfo->framing;
947 	sink->qos_cfg.phy = biginfo->phy;
948 	sink->qos_cfg.sdu = biginfo->max_sdu;
949 	sink->qos_cfg.interval = biginfo->sdu_interval;
950 
951 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
952 		if (listener->syncable != NULL) {
953 			listener->syncable(sink, biginfo);
954 		}
955 	}
956 }
957 
interval_to_sync_timeout(uint16_t interval)958 static uint16_t interval_to_sync_timeout(uint16_t interval)
959 {
960 	uint32_t interval_us;
961 	uint32_t timeout;
962 
963 	/* Add retries and convert to unit in 10's of ms */
964 	interval_us = BT_GAP_PER_ADV_INTERVAL_TO_US(interval);
965 	timeout =
966 		BT_GAP_US_TO_PER_ADV_SYNC_TIMEOUT(interval_us) * PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO;
967 
968 	/* Enforce restraints */
969 	timeout = CLAMP(timeout, BT_GAP_PER_ADV_MIN_TIMEOUT, BT_GAP_PER_ADV_MAX_TIMEOUT);
970 
971 	return (uint16_t)timeout;
972 }
973 
big_started_cb(struct bt_iso_big * big)974 static void big_started_cb(struct bt_iso_big *big)
975 {
976 	struct bt_bap_broadcast_sink *sink = broadcast_sink_get_by_big(big);
977 	struct bt_bap_broadcast_sink_cb *listener;
978 
979 	if (sink == NULL) {
980 		/* Not one of ours */
981 		return;
982 	}
983 
984 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
985 		if (listener->started != NULL) {
986 			listener->started(sink);
987 		}
988 	}
989 }
990 
big_stopped_cb(struct bt_iso_big * big,uint8_t reason)991 static void big_stopped_cb(struct bt_iso_big *big, uint8_t reason)
992 {
993 	struct bt_bap_broadcast_sink *sink = broadcast_sink_get_by_big(big);
994 	struct bt_bap_broadcast_sink_cb *listener;
995 
996 	if (sink == NULL) {
997 		/* Not one of ours */
998 		return;
999 	}
1000 
1001 	broadcast_sink_clear_big(sink, reason);
1002 
1003 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
1004 		if (listener->stopped != NULL) {
1005 			listener->stopped(sink, reason);
1006 		}
1007 	}
1008 }
1009 
bt_bap_broadcast_sink_register_cb(struct bt_bap_broadcast_sink_cb * cb)1010 int bt_bap_broadcast_sink_register_cb(struct bt_bap_broadcast_sink_cb *cb)
1011 {
1012 	static bool iso_big_cb_registered;
1013 
1014 	CHECKIF(cb == NULL) {
1015 		LOG_DBG("cb is NULL");
1016 
1017 		return -EINVAL;
1018 	}
1019 
1020 	if (sys_slist_find(&sink_cbs, &cb->_node, NULL)) {
1021 		LOG_DBG("cb %p is already registered", cb);
1022 
1023 		return -EEXIST;
1024 	}
1025 
1026 	if (!iso_big_cb_registered) {
1027 		static struct bt_iso_big_cb big_cb = {
1028 			.started = big_started_cb,
1029 			.stopped = big_stopped_cb,
1030 		};
1031 		const int err = bt_iso_big_register_cb(&big_cb);
1032 
1033 		if (err != 0) {
1034 			__ASSERT(false, "Failed to register ISO BIG callbacks: %d", err);
1035 		}
1036 
1037 		iso_big_cb_registered = true;
1038 	}
1039 
1040 	sys_slist_append(&sink_cbs, &cb->_node);
1041 
1042 	return 0;
1043 }
1044 
bt_bap_ep_is_broadcast_snk(const struct bt_bap_ep * ep)1045 bool bt_bap_ep_is_broadcast_snk(const struct bt_bap_ep *ep)
1046 {
1047 	for (int i = 0; i < ARRAY_SIZE(broadcast_sink_eps); i++) {
1048 		if (PART_OF_ARRAY(broadcast_sink_eps[i], ep)) {
1049 			return true;
1050 		}
1051 	}
1052 
1053 	return false;
1054 }
1055 
broadcast_sink_ep_init(struct bt_bap_ep * ep)1056 static void broadcast_sink_ep_init(struct bt_bap_ep *ep)
1057 {
1058 	LOG_DBG("ep %p", ep);
1059 
1060 	(void)memset(ep, 0, sizeof(*ep));
1061 	ep->dir = BT_AUDIO_DIR_SINK;
1062 	ep->iso = NULL;
1063 }
1064 
broadcast_sink_new_ep(uint8_t index)1065 static struct bt_bap_ep *broadcast_sink_new_ep(uint8_t index)
1066 {
1067 	for (size_t i = 0; i < ARRAY_SIZE(broadcast_sink_eps[index]); i++) {
1068 		struct bt_bap_ep *ep = &broadcast_sink_eps[index][i];
1069 
1070 		/* If ep->stream is NULL the endpoint is unallocated */
1071 		if (ep->stream == NULL) {
1072 			broadcast_sink_ep_init(ep);
1073 			return ep;
1074 		}
1075 	}
1076 
1077 	return NULL;
1078 }
1079 
bt_bap_broadcast_sink_setup_stream(struct bt_bap_broadcast_sink * sink,struct bt_bap_stream * stream,struct bt_audio_codec_cfg * codec_cfg)1080 static int bt_bap_broadcast_sink_setup_stream(struct bt_bap_broadcast_sink *sink,
1081 					      struct bt_bap_stream *stream,
1082 					      struct bt_audio_codec_cfg *codec_cfg)
1083 {
1084 	struct bt_bap_iso *iso;
1085 	struct bt_bap_ep *ep;
1086 
1087 	if (stream->group != NULL) {
1088 		LOG_DBG("Stream %p already in group %p", stream, stream->group);
1089 		return -EALREADY;
1090 	}
1091 
1092 	ep = broadcast_sink_new_ep(sink->index);
1093 	if (ep == NULL) {
1094 		LOG_DBG("Could not allocate new broadcast endpoint");
1095 		return -ENOMEM;
1096 	}
1097 
1098 	iso = bt_bap_iso_new();
1099 	if (iso == NULL) {
1100 		LOG_DBG("Could not allocate iso");
1101 		return -ENOMEM;
1102 	}
1103 
1104 	bt_bap_iso_init(iso, &broadcast_sink_iso_ops);
1105 	bt_bap_iso_bind_ep(iso, ep);
1106 
1107 	bt_bap_qos_cfg_to_iso_qos(iso->chan.qos->rx, &sink->qos_cfg);
1108 	bt_bap_iso_configure_data_path(ep, codec_cfg);
1109 
1110 	bt_bap_iso_unref(iso);
1111 
1112 	bt_bap_stream_attach(NULL, stream, ep, codec_cfg);
1113 	stream->qos = &sink->qos_cfg;
1114 
1115 	return 0;
1116 }
1117 
broadcast_sink_cleanup_streams(struct bt_bap_broadcast_sink * sink)1118 static void broadcast_sink_cleanup_streams(struct bt_bap_broadcast_sink *sink)
1119 {
1120 	struct bt_bap_stream *stream, *next;
1121 
1122 	SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sink->streams, stream, next, _node) {
1123 		if (stream->ep != NULL) {
1124 			bt_bap_iso_unbind_ep(stream->ep->iso, stream->ep);
1125 			stream->ep->stream = NULL;
1126 			stream->ep = NULL;
1127 		}
1128 
1129 		stream->qos = NULL;
1130 		stream->codec_cfg = NULL;
1131 		stream->group = NULL;
1132 
1133 		sys_slist_remove(&sink->streams, NULL, &stream->_node);
1134 	}
1135 
1136 	sink->stream_count = 0;
1137 	sink->indexes_bitfield = 0U;
1138 }
1139 
broadcast_sink_cleanup(struct bt_bap_broadcast_sink * sink)1140 static void broadcast_sink_cleanup(struct bt_bap_broadcast_sink *sink)
1141 {
1142 	if (sink->stream_count > 0U) {
1143 		broadcast_sink_cleanup_streams(sink);
1144 	}
1145 
1146 	(void)memset(sink, 0, sizeof(*sink)); /* also clears flags */
1147 }
1148 
codec_cfg_from_base_by_index(struct bt_bap_broadcast_sink * sink,uint8_t index)1149 static struct bt_audio_codec_cfg *codec_cfg_from_base_by_index(struct bt_bap_broadcast_sink *sink,
1150 							       uint8_t index)
1151 {
1152 	for (size_t i = 0U; i < ARRAY_SIZE(sink->bis); i++) {
1153 		struct bt_bap_broadcast_sink_bis *bis = &sink->bis[i];
1154 
1155 		if (bis->index == index) {
1156 			return &bis->codec_cfg;
1157 		} else if (bis->index == 0) {
1158 			/* index 0 is invalid, so we can use that as a terminator in the array */
1159 			break;
1160 		}
1161 	}
1162 
1163 	return NULL;
1164 }
1165 
bt_bap_broadcast_sink_create(struct bt_le_per_adv_sync * pa_sync,uint32_t broadcast_id,struct bt_bap_broadcast_sink ** out_sink)1166 int bt_bap_broadcast_sink_create(struct bt_le_per_adv_sync *pa_sync, uint32_t broadcast_id,
1167 				 struct bt_bap_broadcast_sink **out_sink)
1168 {
1169 	const struct bt_bap_scan_delegator_recv_state *recv_state;
1170 	struct bt_bap_broadcast_sink *sink;
1171 
1172 	CHECKIF(pa_sync == NULL) {
1173 		LOG_DBG("pa_sync is NULL");
1174 
1175 		return -EINVAL;
1176 	}
1177 
1178 	CHECKIF(broadcast_id > BT_AUDIO_BROADCAST_ID_MAX) {
1179 		LOG_DBG("Invalid broadcast_id: 0x%X", broadcast_id);
1180 
1181 		return -EINVAL;
1182 	}
1183 
1184 	CHECKIF(out_sink == NULL) {
1185 		LOG_DBG("sink was NULL");
1186 
1187 		return -EINVAL;
1188 	}
1189 
1190 	sink = broadcast_sink_free_get();
1191 	if (sink == NULL) {
1192 		LOG_DBG("No more free broadcast sinks");
1193 
1194 		return -ENOMEM;
1195 	}
1196 
1197 	sink->broadcast_id = broadcast_id;
1198 	sink->pa_sync = pa_sync;
1199 
1200 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_pa_sync_cb,
1201 						      (void *)pa_sync);
1202 	if (recv_state == NULL) {
1203 		broadcast_sink_add_src(sink);
1204 	} else {
1205 		/* The PA sync is known by the Scan Delegator */
1206 		if (recv_state->broadcast_id != broadcast_id) {
1207 			LOG_DBG("Broadcast ID mismatch: 0x%X != 0x%X",
1208 				recv_state->broadcast_id, broadcast_id);
1209 
1210 			broadcast_sink_cleanup(sink);
1211 			return -EINVAL;
1212 		}
1213 
1214 		sink->bass_src_id = recv_state->src_id;
1215 		atomic_set_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID);
1216 	}
1217 	atomic_set_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_INITIALIZED);
1218 
1219 	*out_sink = sink;
1220 	return 0;
1221 }
1222 
bt_bap_broadcast_sink_sync(struct bt_bap_broadcast_sink * sink,uint32_t indexes_bitfield,struct bt_bap_stream * streams[],const uint8_t broadcast_code[BT_ISO_BROADCAST_CODE_SIZE])1223 int bt_bap_broadcast_sink_sync(struct bt_bap_broadcast_sink *sink, uint32_t indexes_bitfield,
1224 			       struct bt_bap_stream *streams[],
1225 			       const uint8_t broadcast_code[BT_ISO_BROADCAST_CODE_SIZE])
1226 {
1227 	struct bt_iso_big_sync_param param;
1228 	struct bt_audio_codec_cfg *codec_cfgs[CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT] = {NULL};
1229 	struct bt_iso_chan *bis_channels[CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT];
1230 	uint8_t stream_count;
1231 	int err;
1232 
1233 	CHECKIF(sink == NULL) {
1234 		LOG_DBG("sink is NULL");
1235 		return -EINVAL;
1236 	}
1237 
1238 	CHECKIF(indexes_bitfield == 0U || indexes_bitfield > BIT_MASK(BT_ISO_BIS_INDEX_MAX)) {
1239 		LOG_DBG("Invalid indexes_bitfield: 0x%08X", indexes_bitfield);
1240 		return -EINVAL;
1241 	}
1242 
1243 	CHECKIF(streams == NULL) {
1244 		LOG_DBG("streams is NULL");
1245 		return -EINVAL;
1246 	}
1247 
1248 	if (sink->pa_sync == NULL) {
1249 		LOG_DBG("Sink is not PA synced");
1250 		return -EINVAL;
1251 	}
1252 
1253 	if (!atomic_test_bit(sink->flags,
1254 			     BT_BAP_BROADCAST_SINK_FLAG_BIGINFO_RECEIVED)) {
1255 		/* TODO: We could store the request to sync and start the sync
1256 		 * once the BIGInfo has been received, and then do the sync
1257 		 * then. This would be similar how LE Create Connection works.
1258 		 */
1259 		LOG_DBG("BIGInfo not received, cannot sync yet");
1260 		return -EAGAIN;
1261 	}
1262 
1263 	if (atomic_test_bit(sink->flags,
1264 			    BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED) &&
1265 	    broadcast_code == NULL) {
1266 		LOG_DBG("Broadcast code required");
1267 
1268 		return -EINVAL;
1269 	}
1270 
1271 	/* Validate that number of bits set is less than number of streams */
1272 	if ((indexes_bitfield & sink->valid_indexes_bitfield) != indexes_bitfield) {
1273 		LOG_DBG("Request BIS indexes 0x%08X contains bits not support by the Broadcast "
1274 			"Sink 0x%08X",
1275 			indexes_bitfield, sink->valid_indexes_bitfield);
1276 		return -EINVAL;
1277 	}
1278 
1279 	stream_count = 0;
1280 	for (int i = 1; i < BT_ISO_MAX_GROUP_ISO_COUNT; i++) {
1281 		if ((indexes_bitfield & BT_ISO_BIS_INDEX_BIT(i)) != 0) {
1282 			struct bt_audio_codec_cfg *codec_cfg =
1283 				codec_cfg_from_base_by_index(sink, i);
1284 
1285 			__ASSERT(codec_cfg != NULL, "Index %d not found in sink", i);
1286 
1287 			codec_cfgs[stream_count++] = codec_cfg;
1288 
1289 			if (stream_count > CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT) {
1290 				LOG_DBG("Cannot sync to more than %d streams (%u was requested)",
1291 					CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT, stream_count);
1292 				return -EINVAL;
1293 			}
1294 		}
1295 	}
1296 
1297 	for (size_t i = 0; i < stream_count; i++) {
1298 		CHECKIF(streams[i] == NULL) {
1299 			LOG_DBG("streams[%zu] is NULL", i);
1300 			return -EINVAL;
1301 		}
1302 	}
1303 
1304 	sink->stream_count = 0U;
1305 	for (size_t i = 0; i < stream_count; i++) {
1306 		struct bt_bap_stream *stream;
1307 		struct bt_audio_codec_cfg *codec_cfg;
1308 
1309 		stream = streams[i];
1310 		codec_cfg = codec_cfgs[i];
1311 
1312 		err = bt_bap_broadcast_sink_setup_stream(sink, stream, codec_cfg);
1313 		if (err != 0) {
1314 			LOG_DBG("Failed to setup streams[%zu]: %d", i, err);
1315 			broadcast_sink_cleanup_streams(sink);
1316 			return err;
1317 		}
1318 
1319 		sink->bis[i].chan = bt_bap_stream_iso_chan_get(stream);
1320 		sys_slist_append(&sink->streams, &stream->_node);
1321 		sink->stream_count++;
1322 
1323 		bis_channels[i] = sink->bis[i].chan;
1324 	}
1325 
1326 	param.bis_channels = bis_channels;
1327 	param.num_bis = sink->stream_count;
1328 	param.bis_bitfield = indexes_bitfield;
1329 	param.mse = 0; /* Let controller decide */
1330 	param.sync_timeout = interval_to_sync_timeout(sink->iso_interval);
1331 	param.encryption = atomic_test_bit(sink->flags,
1332 					   BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED);
1333 	if (param.encryption) {
1334 		memcpy(param.bcode, broadcast_code, sizeof(param.bcode));
1335 	} else {
1336 		memset(param.bcode, 0, sizeof(param.bcode));
1337 	}
1338 
1339 	err = bt_iso_big_sync(sink->pa_sync, &param, &sink->big);
1340 	if (err != 0) {
1341 		broadcast_sink_cleanup_streams(sink);
1342 		return err;
1343 	}
1344 
1345 	sink->indexes_bitfield = indexes_bitfield;
1346 	for (size_t i = 0; i < stream_count; i++) {
1347 		struct bt_bap_ep *ep = streams[i]->ep;
1348 
1349 		ep->broadcast_sink = sink;
1350 		broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_QOS_CONFIGURED);
1351 	}
1352 
1353 	return 0;
1354 }
1355 
bt_bap_broadcast_sink_stop(struct bt_bap_broadcast_sink * sink)1356 int bt_bap_broadcast_sink_stop(struct bt_bap_broadcast_sink *sink)
1357 {
1358 	int err;
1359 
1360 	CHECKIF(sink == NULL) {
1361 		LOG_DBG("sink is NULL");
1362 		return -EINVAL;
1363 	}
1364 
1365 	if (sys_slist_is_empty(&sink->streams)) {
1366 		LOG_DBG("Source does not have any streams (already stopped)");
1367 		return -EALREADY;
1368 	}
1369 
1370 	if (broadcast_sink_is_in_state(sink, BT_BAP_EP_STATE_IDLE)) {
1371 		LOG_DBG("Broadcast sink %p in idle state", sink);
1372 		return -EBADMSG;
1373 	}
1374 
1375 	err = bt_iso_big_terminate(sink->big);
1376 	if (err) {
1377 		LOG_DBG("Failed to terminate BIG (err %d)", err);
1378 		return err;
1379 	}
1380 
1381 	return 0;
1382 }
1383 
bt_bap_broadcast_sink_delete(struct bt_bap_broadcast_sink * sink)1384 int bt_bap_broadcast_sink_delete(struct bt_bap_broadcast_sink *sink)
1385 {
1386 
1387 	CHECKIF(sink == NULL) {
1388 		LOG_DBG("sink is NULL");
1389 		return -EINVAL;
1390 	}
1391 
1392 	if (!broadcast_sink_is_in_state(sink, BT_BAP_EP_STATE_IDLE)) {
1393 		LOG_DBG("Broadcast sink %p not in idle state", sink);
1394 		return -EBADMSG;
1395 	}
1396 
1397 	/* Reset the broadcast sink */
1398 	broadcast_sink_cleanup(sink);
1399 
1400 	return 0;
1401 }
1402 
broadcast_sink_init(void)1403 static int broadcast_sink_init(void)
1404 {
1405 	static struct bt_le_per_adv_sync_cb cb = {
1406 		.recv = pa_recv,
1407 		.biginfo = biginfo_recv,
1408 		.term = pa_term_cb,
1409 	};
1410 
1411 	bt_le_per_adv_sync_cb_register(&cb);
1412 
1413 	return 0;
1414 }
1415 
1416 SYS_INIT(broadcast_sink_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY);
1417