1 /*  Bluetooth Audio Broadcast Sink */
2 
3 /*
4  * Copyright (c) 2021-2023 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 /* any value above 0xFFFFFF is invalid, so we can just use 0xFFFFFFFF to denote
55  * invalid broadcast ID
56  */
57 #define INVALID_BROADCAST_ID 0xFFFFFFFF
58 
59 static struct bt_bap_ep broadcast_sink_eps[CONFIG_BT_BAP_BROADCAST_SNK_COUNT]
60 					  [CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT];
61 static struct bt_bap_broadcast_sink broadcast_sinks[CONFIG_BT_BAP_BROADCAST_SNK_COUNT];
62 
63 struct codec_cap_lookup_id_data {
64 	uint8_t id;
65 	const struct bt_audio_codec_cap *codec_cap;
66 };
67 
68 static sys_slist_t sink_cbs = SYS_SLIST_STATIC_INIT(&sink_cbs);
69 
70 static void broadcast_sink_cleanup(struct bt_bap_broadcast_sink *sink);
71 
find_recv_state_by_sink_cb(const struct bt_bap_scan_delegator_recv_state * recv_state,void * user_data)72 static bool find_recv_state_by_sink_cb(const struct bt_bap_scan_delegator_recv_state *recv_state,
73 				       void *user_data)
74 {
75 	const struct bt_bap_broadcast_sink *sink = user_data;
76 
77 	if (atomic_test_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID) &&
78 	    sink->bass_src_id == recv_state->src_id) {
79 		return true;
80 	}
81 
82 	return false;
83 }
84 
find_recv_state_by_pa_sync_cb(const struct bt_bap_scan_delegator_recv_state * recv_state,void * user_data)85 static bool find_recv_state_by_pa_sync_cb(const struct bt_bap_scan_delegator_recv_state *recv_state,
86 					  void *user_data)
87 {
88 	struct bt_le_per_adv_sync *sync = user_data;
89 	struct bt_le_per_adv_sync_info sync_info;
90 	int err;
91 
92 	err = bt_le_per_adv_sync_get_info(sync, &sync_info);
93 	if (err != 0) {
94 		LOG_DBG("Failed to get sync info: %d", err);
95 
96 		return false;
97 	}
98 
99 	if (bt_addr_le_eq(&recv_state->addr, &sync_info.addr) &&
100 	    recv_state->adv_sid == sync_info.sid) {
101 		return true;
102 	}
103 
104 	return false;
105 };
106 
update_recv_state_big_synced(const struct bt_bap_broadcast_sink * sink)107 static void update_recv_state_big_synced(const struct bt_bap_broadcast_sink *sink)
108 {
109 	const struct bt_bap_scan_delegator_recv_state *recv_state;
110 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = {0};
111 	int err;
112 
113 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
114 	if (recv_state == NULL) {
115 		LOG_WRN("Failed to find receive state for sink %p", sink);
116 
117 		return;
118 	}
119 
120 	mod_src_param.num_subgroups = sink->subgroup_count;
121 	for (uint8_t i = 0U; i < sink->subgroup_count; i++) {
122 		struct bt_bap_bass_subgroup *subgroup_param = &mod_src_param.subgroups[i];
123 		const struct bt_bap_broadcast_sink_subgroup *sink_subgroup = &sink->subgroups[i];
124 
125 		/* Set the bis_sync value to the indexes available per subgroup */
126 		subgroup_param->bis_sync = sink_subgroup->bis_indexes & sink->indexes_bitfield;
127 	}
128 
129 	if (recv_state->encrypt_state == BT_BAP_BIG_ENC_STATE_BCODE_REQ) {
130 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_DEC;
131 	} else {
132 		mod_src_param.encrypt_state = recv_state->encrypt_state;
133 	}
134 
135 	/* Since the mod_src_param struct is 0-initialized the metadata won't
136 	 * be modified by this
137 	 */
138 
139 	/* Copy existing unchanged data */
140 	mod_src_param.src_id = recv_state->src_id;
141 	mod_src_param.broadcast_id = recv_state->broadcast_id;
142 
143 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
144 	if (err != 0) {
145 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
146 	}
147 }
148 
update_recv_state_big_cleared(const struct bt_bap_broadcast_sink * sink,uint8_t reason)149 static void update_recv_state_big_cleared(const struct bt_bap_broadcast_sink *sink,
150 					  uint8_t reason)
151 {
152 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
153 	const struct bt_bap_scan_delegator_recv_state *recv_state;
154 	int err;
155 
156 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
157 	if (recv_state == NULL) {
158 		/* This is likely due to the receive state being removed while we are BIG synced */
159 		LOG_DBG("Could not find receive state for sink %p", sink);
160 
161 		return;
162 	}
163 
164 	if ((recv_state->encrypt_state == BT_BAP_BIG_ENC_STATE_BCODE_REQ ||
165 	     recv_state->encrypt_state == BT_BAP_BIG_ENC_STATE_DEC) &&
166 	    reason == BT_HCI_ERR_TERM_DUE_TO_MIC_FAIL) {
167 		/* Sync failed due to bad broadcast code */
168 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_BAD_CODE;
169 	} else {
170 		mod_src_param.encrypt_state = recv_state->encrypt_state;
171 	}
172 
173 	/* BIS syncs will be automatically cleared since the mod_src_param
174 	 * struct is 0-initialized
175 	 *
176 	 * Since the metadata_len is also 0, then the metadata won't be
177 	 * modified by the operation either.
178 	 */
179 
180 	/* Copy existing unchanged data */
181 	mod_src_param.num_subgroups = recv_state->num_subgroups;
182 	mod_src_param.src_id = recv_state->src_id;
183 	mod_src_param.broadcast_id = recv_state->broadcast_id;
184 
185 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
186 	if (err != 0) {
187 		LOG_WRN("Failed to modify Receive State for sink %p: %d",
188 			sink, err);
189 	}
190 }
191 
broadcast_sink_clear_big(struct bt_bap_broadcast_sink * sink,uint8_t reason)192 static void broadcast_sink_clear_big(struct bt_bap_broadcast_sink *sink,
193 				     uint8_t reason)
194 {
195 	sink->big = NULL;
196 
197 	update_recv_state_big_cleared(sink, reason);
198 }
199 
broadcast_sink_lookup_iso_chan(const struct bt_iso_chan * chan)200 static struct bt_bap_broadcast_sink *broadcast_sink_lookup_iso_chan(
201 	const struct bt_iso_chan *chan)
202 {
203 	for (size_t i = 0U; i < ARRAY_SIZE(broadcast_sinks); i++) {
204 		for (uint8_t j = 0U; j < broadcast_sinks[i].stream_count; j++) {
205 			if (broadcast_sinks[i].bis[j].chan == chan) {
206 				return &broadcast_sinks[i];
207 			}
208 		}
209 	}
210 
211 	return NULL;
212 }
213 
broadcast_sink_set_ep_state(struct bt_bap_ep * ep,uint8_t state)214 static void broadcast_sink_set_ep_state(struct bt_bap_ep *ep, uint8_t state)
215 {
216 	uint8_t old_state;
217 
218 	old_state = ep->status.state;
219 
220 	LOG_DBG("ep %p id 0x%02x %s -> %s", ep, ep->status.id, bt_bap_ep_state_str(old_state),
221 		bt_bap_ep_state_str(state));
222 
223 	switch (old_state) {
224 	case BT_BAP_EP_STATE_IDLE:
225 		if (state != BT_BAP_EP_STATE_QOS_CONFIGURED) {
226 			LOG_DBG("Invalid broadcast sync endpoint state transition");
227 			return;
228 		}
229 		break;
230 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
231 		if (state != BT_BAP_EP_STATE_IDLE && state != BT_BAP_EP_STATE_STREAMING) {
232 			LOG_DBG("Invalid broadcast sync endpoint state transition");
233 			return;
234 		}
235 		break;
236 	case BT_BAP_EP_STATE_STREAMING:
237 		if (state != BT_BAP_EP_STATE_IDLE) {
238 			LOG_DBG("Invalid broadcast sync endpoint state transition");
239 			return;
240 		}
241 		break;
242 	default:
243 		LOG_ERR("Invalid broadcast sync endpoint state: %s",
244 			bt_bap_ep_state_str(old_state));
245 		return;
246 	}
247 
248 	ep->status.state = state;
249 
250 	if (state == BT_BAP_EP_STATE_IDLE) {
251 		struct bt_bap_stream *stream = ep->stream;
252 
253 		if (stream != NULL) {
254 			bt_bap_iso_unbind_ep(ep->iso, ep);
255 			stream->ep = NULL;
256 			stream->codec_cfg = NULL;
257 			ep->stream = NULL;
258 		}
259 	}
260 }
261 
broadcast_sink_iso_recv(struct bt_iso_chan * chan,const struct bt_iso_recv_info * info,struct net_buf * buf)262 static void broadcast_sink_iso_recv(struct bt_iso_chan *chan,
263 				    const struct bt_iso_recv_info *info,
264 				    struct net_buf *buf)
265 {
266 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
267 	const struct bt_bap_stream_ops *ops;
268 	struct bt_bap_stream *stream;
269 	struct bt_bap_ep *ep = iso->rx.ep;
270 	size_t buf_len;
271 
272 	if (ep == NULL) {
273 		LOG_ERR("iso %p not bound with ep", chan);
274 		return;
275 	}
276 
277 	stream = ep->stream;
278 	if (stream == NULL) {
279 		LOG_ERR("No stream for ep %p", ep);
280 		return;
281 	}
282 
283 	ops = stream->ops;
284 
285 	buf_len = net_buf_frags_len(buf);
286 	if (IS_ENABLED(CONFIG_BT_BAP_DEBUG_STREAM_DATA)) {
287 		LOG_DBG("stream %p ep %p len %zu", stream, stream->ep, buf_len);
288 	}
289 
290 	if (buf_len > stream->qos->sdu) {
291 		LOG_WRN("Received %u octets but stream %p was only configured for %u", buf_len,
292 			stream, stream->qos->sdu);
293 	}
294 
295 	if (ops != NULL && ops->recv != NULL) {
296 		ops->recv(stream, info, buf);
297 	} else {
298 		LOG_WRN("No callback for recv set");
299 	}
300 }
301 
302 /** Gets the "highest" state of all BIS in the broadcast sink */
broadcast_sink_get_state(struct bt_bap_broadcast_sink * sink)303 static enum bt_bap_ep_state broadcast_sink_get_state(struct bt_bap_broadcast_sink *sink)
304 {
305 	enum bt_bap_ep_state state = BT_BAP_EP_STATE_IDLE;
306 	struct bt_bap_stream *stream;
307 
308 	if (sink == NULL) {
309 		LOG_DBG("sink is NULL");
310 
311 		return state;
312 	}
313 
314 	if (sys_slist_is_empty(&sink->streams)) {
315 		LOG_DBG("Sink does not have any streams");
316 
317 		return state;
318 	}
319 
320 	SYS_SLIST_FOR_EACH_CONTAINER(&sink->streams, stream, _node) {
321 		if (stream->ep != NULL) {
322 			state = MAX(state, stream->ep->status.state);
323 		}
324 	}
325 
326 	return state;
327 }
328 
broadcast_sink_iso_connected(struct bt_iso_chan * chan)329 static void broadcast_sink_iso_connected(struct bt_iso_chan *chan)
330 {
331 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
332 	const struct bt_bap_stream_ops *ops;
333 	struct bt_bap_broadcast_sink *sink;
334 	struct bt_bap_stream *stream;
335 	struct bt_bap_ep *ep = iso->rx.ep;
336 
337 	if (ep == NULL) {
338 		LOG_ERR("iso %p not bound with ep", chan);
339 		return;
340 	}
341 
342 	stream = ep->stream;
343 	if (stream == NULL) {
344 		LOG_ERR("No stream for ep %p", ep);
345 		return;
346 	}
347 
348 	LOG_DBG("stream %p", stream);
349 
350 	ops = stream->ops;
351 	if (ops != NULL && ops->connected != NULL) {
352 		ops->connected(stream);
353 	}
354 
355 	sink = broadcast_sink_lookup_iso_chan(chan);
356 	if (sink == NULL) {
357 		LOG_ERR("Could not lookup sink by iso %p", chan);
358 		return;
359 	}
360 
361 	broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_STREAMING);
362 
363 	if (ops != NULL && ops->started != NULL) {
364 		ops->started(stream);
365 	} else {
366 		LOG_WRN("No callback for started set");
367 	}
368 
369 	if (broadcast_sink_get_state(sink) != BT_BAP_EP_STATE_STREAMING) {
370 		update_recv_state_big_synced(sink);
371 	}
372 }
373 
broadcast_sink_iso_disconnected(struct bt_iso_chan * chan,uint8_t reason)374 static void broadcast_sink_iso_disconnected(struct bt_iso_chan *chan,
375 					    uint8_t reason)
376 {
377 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
378 	const struct bt_bap_stream_ops *ops;
379 	struct bt_bap_stream *stream;
380 	struct bt_bap_ep *ep = iso->rx.ep;
381 	struct bt_bap_broadcast_sink *sink;
382 
383 	if (ep == NULL) {
384 		LOG_ERR("iso %p not bound with ep", chan);
385 		return;
386 	}
387 
388 	stream = ep->stream;
389 	if (stream == NULL) {
390 		LOG_ERR("No stream for ep %p", ep);
391 		return;
392 	}
393 
394 	LOG_DBG("stream %p ep %p reason 0x%02x", stream, ep, reason);
395 
396 	ops = stream->ops;
397 	if (ops != NULL && ops->disconnected != NULL) {
398 		ops->disconnected(stream, reason);
399 	}
400 
401 	broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_IDLE);
402 
403 	sink = broadcast_sink_lookup_iso_chan(chan);
404 	if (sink == NULL) {
405 		LOG_ERR("Could not lookup sink by iso %p", chan);
406 	} else {
407 		if (!sys_slist_find_and_remove(&sink->streams, &stream->_node)) {
408 			LOG_DBG("Could not find and remove stream %p from sink %p", stream, sink);
409 		}
410 
411 		/* Clear sink->big if not already cleared */
412 		if (sys_slist_is_empty(&sink->streams) && sink->big) {
413 			broadcast_sink_clear_big(sink, reason);
414 		}
415 	}
416 
417 	if (ops != NULL && ops->stopped != NULL) {
418 		ops->stopped(stream, reason);
419 	} else {
420 		LOG_WRN("No callback for stopped set");
421 	}
422 }
423 
424 static struct bt_iso_chan_ops broadcast_sink_iso_ops = {
425 	.recv		= broadcast_sink_iso_recv,
426 	.connected	= broadcast_sink_iso_connected,
427 	.disconnected	= broadcast_sink_iso_disconnected,
428 };
429 
broadcast_sink_free_get(void)430 static struct bt_bap_broadcast_sink *broadcast_sink_free_get(void)
431 {
432 	/* Find free entry */
433 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
434 		if (!atomic_test_bit(broadcast_sinks[i].flags,
435 				     BT_BAP_BROADCAST_SINK_FLAG_INITIALIZED)) {
436 			broadcast_sinks[i].index = i;
437 			broadcast_sinks[i].broadcast_id = INVALID_BROADCAST_ID;
438 
439 			return &broadcast_sinks[i];
440 		}
441 	}
442 
443 	return NULL;
444 }
445 
broadcast_sink_get_by_pa(struct bt_le_per_adv_sync * sync)446 static struct bt_bap_broadcast_sink *broadcast_sink_get_by_pa(struct bt_le_per_adv_sync *sync)
447 {
448 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
449 		if (broadcast_sinks[i].pa_sync == sync) {
450 			return &broadcast_sinks[i];
451 		}
452 	}
453 
454 	return NULL;
455 }
456 
broadcast_sink_add_src(struct bt_bap_broadcast_sink * sink)457 static void broadcast_sink_add_src(struct bt_bap_broadcast_sink *sink)
458 {
459 	struct bt_bap_scan_delegator_add_src_param add_src_param;
460 	struct bt_le_per_adv_sync_info sync_info;
461 	int err;
462 
463 	err = bt_le_per_adv_sync_get_info(sink->pa_sync, &sync_info);
464 	__ASSERT_NO_MSG(err == 0);
465 
466 	bt_addr_le_copy(&add_src_param.addr, &sync_info.addr);
467 	add_src_param.sid = sync_info.sid;
468 	add_src_param.broadcast_id = sink->broadcast_id;
469 	/* Will be updated when we receive the BASE */
470 	add_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_NO_ENC;
471 	add_src_param.num_subgroups = 0U;
472 
473 	err = bt_bap_scan_delegator_add_src(&add_src_param);
474 	if (err < 0) {
475 		LOG_WRN("Failed to add sync as Receive State for sink %p: %d",
476 			sink, err);
477 	} else {
478 		sink->bass_src_id = (uint8_t)err;
479 		atomic_set_bit(sink->flags,
480 			       BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID);
481 	}
482 }
483 
base_subgroup_meta_cb(const struct bt_bap_base_subgroup * subgroup,void * user_data)484 static bool base_subgroup_meta_cb(const struct bt_bap_base_subgroup *subgroup, void *user_data)
485 {
486 	struct bt_bap_scan_delegator_mod_src_param *mod_src_param = user_data;
487 	struct bt_bap_bass_subgroup *subgroup_param;
488 	uint8_t *meta;
489 	int ret;
490 
491 	ret = bt_bap_base_get_subgroup_codec_meta(subgroup, &meta);
492 	if (ret < 0) {
493 		return false;
494 	}
495 
496 	subgroup_param = &mod_src_param->subgroups[mod_src_param->num_subgroups++];
497 	subgroup_param->metadata_len = (uint8_t)ret;
498 	memcpy(subgroup_param->metadata, meta, subgroup_param->metadata_len);
499 
500 	return true;
501 }
502 
update_recv_state_base_copy_meta(const struct bt_bap_base * base,struct bt_bap_scan_delegator_mod_src_param * param)503 static int update_recv_state_base_copy_meta(const struct bt_bap_base *base,
504 					    struct bt_bap_scan_delegator_mod_src_param *param)
505 {
506 	int err;
507 
508 	err = bt_bap_base_foreach_subgroup(base, base_subgroup_meta_cb, param);
509 	if (err != 0) {
510 		LOG_DBG("Failed to parse subgroups: %d", err);
511 		return err;
512 	}
513 
514 	return 0;
515 }
516 
update_recv_state_base(const struct bt_bap_broadcast_sink * sink,const struct bt_bap_base * base)517 static void update_recv_state_base(const struct bt_bap_broadcast_sink *sink,
518 				   const struct bt_bap_base *base)
519 {
520 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
521 	const struct bt_bap_scan_delegator_recv_state *recv_state;
522 	int err;
523 
524 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
525 	if (recv_state == NULL) {
526 		LOG_WRN("Failed to find receive state for sink %p", sink);
527 
528 		return;
529 	}
530 
531 	err = update_recv_state_base_copy_meta(base, &mod_src_param);
532 	if (err != 0) {
533 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
534 		return;
535 	}
536 
537 	/* Copy existing unchanged data */
538 	mod_src_param.src_id = recv_state->src_id;
539 	mod_src_param.encrypt_state = recv_state->encrypt_state;
540 	mod_src_param.broadcast_id = recv_state->broadcast_id;
541 	mod_src_param.num_subgroups = sink->subgroup_count;
542 	for (uint8_t i = 0U; i < sink->subgroup_count; i++) {
543 		struct bt_bap_bass_subgroup *subgroup_param = &mod_src_param.subgroups[i];
544 		const struct bt_bap_broadcast_sink_subgroup *sink_subgroup = &sink->subgroups[i];
545 
546 		/* Set the bis_sync value to the indexes available per subgroup */
547 		subgroup_param->bis_sync = sink_subgroup->bis_indexes & sink->indexes_bitfield;
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->codec_qos.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->codec_qos.framing = biginfo->framing;
947 	sink->codec_qos.phy = biginfo->phy;
948 	sink->codec_qos.sdu = biginfo->max_sdu;
949 	sink->codec_qos.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_ms;
961 	uint32_t timeout;
962 
963 	/* Add retries and convert to unit in 10's of ms */
964 	interval_ms = BT_GAP_PER_ADV_INTERVAL_TO_MS(interval);
965 	timeout = (interval_ms * PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO) / 10;
966 
967 	/* Enforce restraints */
968 	timeout = CLAMP(timeout, BT_GAP_PER_ADV_MIN_TIMEOUT, BT_GAP_PER_ADV_MAX_TIMEOUT);
969 
970 	return (uint16_t)timeout;
971 }
972 
bt_bap_broadcast_sink_register_cb(struct bt_bap_broadcast_sink_cb * cb)973 int bt_bap_broadcast_sink_register_cb(struct bt_bap_broadcast_sink_cb *cb)
974 {
975 	CHECKIF(cb == NULL) {
976 		LOG_DBG("cb is NULL");
977 		return -EINVAL;
978 	}
979 
980 	sys_slist_append(&sink_cbs, &cb->_node);
981 
982 	return 0;
983 }
984 
bt_bap_ep_is_broadcast_snk(const struct bt_bap_ep * ep)985 bool bt_bap_ep_is_broadcast_snk(const struct bt_bap_ep *ep)
986 {
987 	for (int i = 0; i < ARRAY_SIZE(broadcast_sink_eps); i++) {
988 		if (PART_OF_ARRAY(broadcast_sink_eps[i], ep)) {
989 			return true;
990 		}
991 	}
992 
993 	return false;
994 }
995 
broadcast_sink_ep_init(struct bt_bap_ep * ep)996 static void broadcast_sink_ep_init(struct bt_bap_ep *ep)
997 {
998 	LOG_DBG("ep %p", ep);
999 
1000 	(void)memset(ep, 0, sizeof(*ep));
1001 	ep->dir = BT_AUDIO_DIR_SINK;
1002 	ep->iso = NULL;
1003 }
1004 
broadcast_sink_new_ep(uint8_t index)1005 static struct bt_bap_ep *broadcast_sink_new_ep(uint8_t index)
1006 {
1007 	for (size_t i = 0; i < ARRAY_SIZE(broadcast_sink_eps[index]); i++) {
1008 		struct bt_bap_ep *ep = &broadcast_sink_eps[index][i];
1009 
1010 		/* If ep->stream is NULL the endpoint is unallocated */
1011 		if (ep->stream == NULL) {
1012 			broadcast_sink_ep_init(ep);
1013 			return ep;
1014 		}
1015 	}
1016 
1017 	return NULL;
1018 }
1019 
bt_bap_broadcast_sink_setup_stream(struct bt_bap_broadcast_sink * sink,struct bt_bap_stream * stream,struct bt_audio_codec_cfg * codec_cfg)1020 static int bt_bap_broadcast_sink_setup_stream(struct bt_bap_broadcast_sink *sink,
1021 					      struct bt_bap_stream *stream,
1022 					      struct bt_audio_codec_cfg *codec_cfg)
1023 {
1024 	struct bt_bap_iso *iso;
1025 	struct bt_bap_ep *ep;
1026 
1027 	if (stream->group != NULL) {
1028 		LOG_DBG("Stream %p already in group %p", stream, stream->group);
1029 		return -EALREADY;
1030 	}
1031 
1032 	ep = broadcast_sink_new_ep(sink->index);
1033 	if (ep == NULL) {
1034 		LOG_DBG("Could not allocate new broadcast endpoint");
1035 		return -ENOMEM;
1036 	}
1037 
1038 	iso = bt_bap_iso_new();
1039 	if (iso == NULL) {
1040 		LOG_DBG("Could not allocate iso");
1041 		return -ENOMEM;
1042 	}
1043 
1044 	bt_bap_iso_init(iso, &broadcast_sink_iso_ops);
1045 	bt_bap_iso_bind_ep(iso, ep);
1046 
1047 	bt_audio_codec_qos_to_iso_qos(iso->chan.qos->rx, &sink->codec_qos);
1048 	bt_bap_iso_configure_data_path(ep, codec_cfg);
1049 
1050 	bt_bap_iso_unref(iso);
1051 
1052 	bt_bap_stream_attach(NULL, stream, ep, codec_cfg);
1053 	stream->qos = &sink->codec_qos;
1054 
1055 	return 0;
1056 }
1057 
broadcast_sink_cleanup_streams(struct bt_bap_broadcast_sink * sink)1058 static void broadcast_sink_cleanup_streams(struct bt_bap_broadcast_sink *sink)
1059 {
1060 	struct bt_bap_stream *stream, *next;
1061 
1062 	SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sink->streams, stream, next, _node) {
1063 		if (stream->ep != NULL) {
1064 			bt_bap_iso_unbind_ep(stream->ep->iso, stream->ep);
1065 			stream->ep->stream = NULL;
1066 			stream->ep = NULL;
1067 		}
1068 
1069 		stream->qos = NULL;
1070 		stream->codec_cfg = NULL;
1071 		stream->group = NULL;
1072 
1073 		sys_slist_remove(&sink->streams, NULL, &stream->_node);
1074 	}
1075 
1076 	sink->stream_count = 0;
1077 	sink->indexes_bitfield = 0U;
1078 }
1079 
broadcast_sink_cleanup(struct bt_bap_broadcast_sink * sink)1080 static void broadcast_sink_cleanup(struct bt_bap_broadcast_sink *sink)
1081 {
1082 	if (sink->stream_count > 0U) {
1083 		broadcast_sink_cleanup_streams(sink);
1084 	}
1085 
1086 	(void)memset(sink, 0, sizeof(*sink)); /* also clears flags */
1087 }
1088 
codec_cfg_from_base_by_index(struct bt_bap_broadcast_sink * sink,uint8_t index)1089 static struct bt_audio_codec_cfg *codec_cfg_from_base_by_index(struct bt_bap_broadcast_sink *sink,
1090 							       uint8_t index)
1091 {
1092 	for (size_t i = 0U; i < ARRAY_SIZE(sink->bis); i++) {
1093 		struct bt_bap_broadcast_sink_bis *bis = &sink->bis[i];
1094 
1095 		if (bis->index == index) {
1096 			return &bis->codec_cfg;
1097 		} else if (bis->index == 0) {
1098 			/* index 0 is invalid, so we can use that as a terminator in the array */
1099 			break;
1100 		}
1101 	}
1102 
1103 	return NULL;
1104 }
1105 
bt_bap_broadcast_sink_create(struct bt_le_per_adv_sync * pa_sync,uint32_t broadcast_id,struct bt_bap_broadcast_sink ** out_sink)1106 int bt_bap_broadcast_sink_create(struct bt_le_per_adv_sync *pa_sync, uint32_t broadcast_id,
1107 				 struct bt_bap_broadcast_sink **out_sink)
1108 {
1109 	const struct bt_bap_scan_delegator_recv_state *recv_state;
1110 	struct bt_bap_broadcast_sink *sink;
1111 
1112 	CHECKIF(pa_sync == NULL) {
1113 		LOG_DBG("pa_sync is NULL");
1114 
1115 		return -EINVAL;
1116 	}
1117 
1118 	CHECKIF(broadcast_id > BT_AUDIO_BROADCAST_ID_MAX) {
1119 		LOG_DBG("Invalid broadcast_id: 0x%X", broadcast_id);
1120 
1121 		return -EINVAL;
1122 	}
1123 
1124 	CHECKIF(out_sink == NULL) {
1125 		LOG_DBG("sink was NULL");
1126 
1127 		return -EINVAL;
1128 	}
1129 
1130 	sink = broadcast_sink_free_get();
1131 	if (sink == NULL) {
1132 		LOG_DBG("No more free broadcast sinks");
1133 
1134 		return -ENOMEM;
1135 	}
1136 
1137 	sink->broadcast_id = broadcast_id;
1138 	sink->pa_sync = pa_sync;
1139 
1140 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_pa_sync_cb,
1141 						      (void *)pa_sync);
1142 	if (recv_state == NULL) {
1143 		broadcast_sink_add_src(sink);
1144 	} else {
1145 		/* The PA sync is known by the Scan Delegator */
1146 		if (recv_state->broadcast_id != broadcast_id) {
1147 			LOG_DBG("Broadcast ID mismatch: 0x%X != 0x%X",
1148 				recv_state->broadcast_id, broadcast_id);
1149 
1150 			broadcast_sink_cleanup(sink);
1151 			return -EINVAL;
1152 		}
1153 
1154 		sink->bass_src_id = recv_state->src_id;
1155 		atomic_set_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID);
1156 	}
1157 	atomic_set_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_INITIALIZED);
1158 
1159 	*out_sink = sink;
1160 	return 0;
1161 }
1162 
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[16])1163 int bt_bap_broadcast_sink_sync(struct bt_bap_broadcast_sink *sink, uint32_t indexes_bitfield,
1164 			       struct bt_bap_stream *streams[], const uint8_t broadcast_code[16])
1165 {
1166 	struct bt_iso_big_sync_param param;
1167 	struct bt_audio_codec_cfg *codec_cfgs[CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT] = {NULL};
1168 	struct bt_iso_chan *bis_channels[CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT];
1169 	uint8_t stream_count;
1170 	int err;
1171 
1172 	CHECKIF(sink == NULL) {
1173 		LOG_DBG("sink is NULL");
1174 		return -EINVAL;
1175 	}
1176 
1177 	CHECKIF(indexes_bitfield == 0U || indexes_bitfield > BIT_MASK(BT_ISO_BIS_INDEX_MAX)) {
1178 		LOG_DBG("Invalid indexes_bitfield: 0x%08X", indexes_bitfield);
1179 		return -EINVAL;
1180 	}
1181 
1182 	CHECKIF(streams == NULL) {
1183 		LOG_DBG("streams is NULL");
1184 		return -EINVAL;
1185 	}
1186 
1187 	if (sink->pa_sync == NULL) {
1188 		LOG_DBG("Sink is not PA synced");
1189 		return -EINVAL;
1190 	}
1191 
1192 	if (!atomic_test_bit(sink->flags,
1193 			     BT_BAP_BROADCAST_SINK_FLAG_BIGINFO_RECEIVED)) {
1194 		/* TODO: We could store the request to sync and start the sync
1195 		 * once the BIGInfo has been received, and then do the sync
1196 		 * then. This would be similar how LE Create Connection works.
1197 		 */
1198 		LOG_DBG("BIGInfo not received, cannot sync yet");
1199 		return -EAGAIN;
1200 	}
1201 
1202 	if (atomic_test_bit(sink->flags,
1203 			    BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED) &&
1204 	    broadcast_code == NULL) {
1205 		LOG_DBG("Broadcast code required");
1206 
1207 		return -EINVAL;
1208 	}
1209 
1210 	/* Validate that number of bits set is less than number of streams */
1211 	if ((indexes_bitfield & sink->valid_indexes_bitfield) != indexes_bitfield) {
1212 		LOG_DBG("Request BIS indexes 0x%08X contains bits not support by the Broadcast "
1213 			"Sink 0x%08X",
1214 			indexes_bitfield, sink->valid_indexes_bitfield);
1215 		return -EINVAL;
1216 	}
1217 
1218 	stream_count = 0;
1219 	for (int i = 1; i < BT_ISO_MAX_GROUP_ISO_COUNT; i++) {
1220 		if ((indexes_bitfield & BT_ISO_BIS_INDEX_BIT(i)) != 0) {
1221 			struct bt_audio_codec_cfg *codec_cfg =
1222 				codec_cfg_from_base_by_index(sink, i);
1223 
1224 			__ASSERT(codec_cfg != NULL, "Index %d not found in sink", i);
1225 
1226 			codec_cfgs[stream_count++] = codec_cfg;
1227 
1228 			if (stream_count > CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT) {
1229 				LOG_DBG("Cannot sync to more than %d streams (%u was requested)",
1230 					CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT, stream_count);
1231 				return -EINVAL;
1232 			}
1233 		}
1234 	}
1235 
1236 	for (size_t i = 0; i < stream_count; i++) {
1237 		CHECKIF(streams[i] == NULL) {
1238 			LOG_DBG("streams[%zu] is NULL", i);
1239 			return -EINVAL;
1240 		}
1241 	}
1242 
1243 	sink->stream_count = 0U;
1244 	for (size_t i = 0; i < stream_count; i++) {
1245 		struct bt_bap_stream *stream;
1246 		struct bt_audio_codec_cfg *codec_cfg;
1247 
1248 		stream = streams[i];
1249 		codec_cfg = codec_cfgs[i];
1250 
1251 		err = bt_bap_broadcast_sink_setup_stream(sink, stream, codec_cfg);
1252 		if (err != 0) {
1253 			LOG_DBG("Failed to setup streams[%zu]: %d", i, err);
1254 			broadcast_sink_cleanup_streams(sink);
1255 			return err;
1256 		}
1257 
1258 		sink->bis[i].chan = bt_bap_stream_iso_chan_get(stream);
1259 		sys_slist_append(&sink->streams, &stream->_node);
1260 		sink->stream_count++;
1261 
1262 		bis_channels[i] = sink->bis[i].chan;
1263 	}
1264 
1265 	param.bis_channels = bis_channels;
1266 	param.num_bis = sink->stream_count;
1267 	param.bis_bitfield = indexes_bitfield;
1268 	param.mse = 0; /* Let controller decide */
1269 	param.sync_timeout = interval_to_sync_timeout(sink->iso_interval);
1270 	param.encryption = atomic_test_bit(sink->flags,
1271 					   BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED);
1272 	if (param.encryption) {
1273 		memcpy(param.bcode, broadcast_code, sizeof(param.bcode));
1274 	} else {
1275 		memset(param.bcode, 0, sizeof(param.bcode));
1276 	}
1277 
1278 	err = bt_iso_big_sync(sink->pa_sync, &param, &sink->big);
1279 	if (err != 0) {
1280 		broadcast_sink_cleanup_streams(sink);
1281 		return err;
1282 	}
1283 
1284 	sink->indexes_bitfield = indexes_bitfield;
1285 	for (size_t i = 0; i < stream_count; i++) {
1286 		struct bt_bap_ep *ep = streams[i]->ep;
1287 
1288 		ep->broadcast_sink = sink;
1289 		broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_QOS_CONFIGURED);
1290 	}
1291 
1292 	return 0;
1293 }
1294 
bt_bap_broadcast_sink_stop(struct bt_bap_broadcast_sink * sink)1295 int bt_bap_broadcast_sink_stop(struct bt_bap_broadcast_sink *sink)
1296 {
1297 	enum bt_bap_ep_state state;
1298 	int err;
1299 
1300 	CHECKIF(sink == NULL) {
1301 		LOG_DBG("sink is NULL");
1302 		return -EINVAL;
1303 	}
1304 
1305 	if (sys_slist_is_empty(&sink->streams)) {
1306 		LOG_DBG("Source does not have any streams (already stopped)");
1307 		return -EALREADY;
1308 	}
1309 
1310 	state = broadcast_sink_get_state(sink);
1311 	if (state != BT_BAP_EP_STATE_STREAMING && state != BT_BAP_EP_STATE_QOS_CONFIGURED) {
1312 		LOG_DBG("Broadcast sink %p invalid state: %u", sink, state);
1313 		return -EBADMSG;
1314 	}
1315 
1316 	err = bt_iso_big_terminate(sink->big);
1317 	if (err) {
1318 		LOG_DBG("Failed to terminate BIG (err %d)", err);
1319 		return err;
1320 	}
1321 
1322 	broadcast_sink_clear_big(sink, BT_HCI_ERR_LOCALHOST_TERM_CONN);
1323 	/* Channel states will be updated in the broadcast_sink_iso_disconnected function */
1324 
1325 	return 0;
1326 }
1327 
bt_bap_broadcast_sink_delete(struct bt_bap_broadcast_sink * sink)1328 int bt_bap_broadcast_sink_delete(struct bt_bap_broadcast_sink *sink)
1329 {
1330 	enum bt_bap_ep_state state;
1331 
1332 	CHECKIF(sink == NULL) {
1333 		LOG_DBG("sink is NULL");
1334 		return -EINVAL;
1335 	}
1336 
1337 	state = broadcast_sink_get_state(sink);
1338 	if (state != BT_BAP_EP_STATE_IDLE) {
1339 		LOG_DBG("Broadcast sink %p invalid state: %u", sink, state);
1340 		return -EBADMSG;
1341 	}
1342 
1343 	/* Reset the broadcast sink */
1344 	broadcast_sink_cleanup(sink);
1345 
1346 	return 0;
1347 }
1348 
broadcast_sink_init(void)1349 static int broadcast_sink_init(void)
1350 {
1351 	static struct bt_le_per_adv_sync_cb cb = {
1352 		.recv = pa_recv,
1353 		.biginfo = biginfo_recv,
1354 		.term = pa_term_cb,
1355 	};
1356 
1357 	bt_le_per_adv_sync_cb_register(&cb);
1358 
1359 	return 0;
1360 }
1361 
1362 SYS_INIT(broadcast_sink_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY);
1363