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 <zephyr/device.h>
10 #include <zephyr/kernel.h>
11 #include <zephyr/sys/byteorder.h>
12 #include <zephyr/sys/check.h>
13 
14 #include <zephyr/bluetooth/bluetooth.h>
15 #include <zephyr/bluetooth/conn.h>
16 #include <zephyr/bluetooth/gatt.h>
17 #include <zephyr/bluetooth/audio/audio.h>
18 #include <zephyr/bluetooth/audio/bap.h>
19 #include <zephyr/bluetooth/audio/pacs.h>
20 #include <zephyr/bluetooth/audio/bap.h>
21 
22 #include "../host/conn_internal.h"
23 #include "../host/iso_internal.h"
24 
25 #include "bap_iso.h"
26 #include "bap_endpoint.h"
27 #include "audio_internal.h"
28 
29 #include <zephyr/logging/log.h>
30 
31 LOG_MODULE_REGISTER(bt_bap_broadcast_sink, CONFIG_BT_BAP_BROADCAST_SINK_LOG_LEVEL);
32 
33 #include "common/bt_str.h"
34 
35 #define PA_SYNC_SKIP              5
36 #define SYNC_RETRY_COUNT          6 /* similar to retries for connections */
37 #define BROADCAST_SYNC_MIN_INDEX  (BIT(1))
38 
39 /* any value above 0xFFFFFF is invalid, so we can just use 0xFFFFFFFF to denote
40  * invalid broadcast ID
41  */
42 #define INVALID_BROADCAST_ID 0xFFFFFFFF
43 
44 static struct bt_bap_ep broadcast_sink_eps[CONFIG_BT_BAP_BROADCAST_SNK_COUNT]
45 					    [BROADCAST_SNK_STREAM_CNT];
46 static struct bt_bap_broadcast_sink broadcast_sinks[CONFIG_BT_BAP_BROADCAST_SNK_COUNT];
47 static struct bt_le_scan_cb broadcast_scan_cb;
48 
49 struct codec_lookup_id_data {
50 	uint8_t id;
51 	struct bt_codec *codec;
52 };
53 
54 static sys_slist_t sink_cbs = SYS_SLIST_STATIC_INIT(&sink_cbs);
55 
56 static void broadcast_sink_cleanup(struct bt_bap_broadcast_sink *sink);
57 
58 static enum bt_bap_scan_delegator_iter
find_recv_state_by_sink_cb(const struct bt_bap_scan_delegator_recv_state * recv_state,void * user_data)59 find_recv_state_by_sink_cb(const struct bt_bap_scan_delegator_recv_state *recv_state,
60 			   void *user_data)
61 {
62 	const struct bt_bap_broadcast_sink *sink = user_data;
63 
64 	if (atomic_test_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID) &&
65 	    sink->bass_src_id == recv_state->src_id) {
66 		return BT_BAP_SCAN_DELEGATOR_ITER_STOP;
67 	}
68 
69 	return BT_BAP_SCAN_DELEGATOR_ITER_CONTINUE;
70 }
71 
72 static enum bt_bap_scan_delegator_iter
find_recv_state_by_pa_sync_cb(const struct bt_bap_scan_delegator_recv_state * recv_state,void * user_data)73 find_recv_state_by_pa_sync_cb(const struct bt_bap_scan_delegator_recv_state *recv_state,
74 			      void *user_data)
75 {
76 	struct bt_le_per_adv_sync *sync = user_data;
77 	struct bt_le_per_adv_sync_info sync_info;
78 	int err;
79 
80 	err = bt_le_per_adv_sync_get_info(sync, &sync_info);
81 	if (err != 0) {
82 		LOG_DBG("Failed to get sync info: %d", err);
83 
84 		return BT_BAP_SCAN_DELEGATOR_ITER_CONTINUE;
85 	}
86 
87 	if (bt_addr_le_eq(&recv_state->addr, &sync_info.addr) &&
88 	    recv_state->adv_sid == sync_info.sid) {
89 		return BT_BAP_SCAN_DELEGATOR_ITER_STOP;
90 	}
91 
92 	return BT_BAP_SCAN_DELEGATOR_ITER_CONTINUE;
93 };
94 
update_recv_state_big_synced(const struct bt_bap_broadcast_sink * sink)95 static void update_recv_state_big_synced(const struct bt_bap_broadcast_sink *sink)
96 {
97 	const struct bt_bap_scan_delegator_recv_state *recv_state;
98 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
99 	const struct bt_bap_base *base;
100 	int err;
101 
102 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
103 	if (recv_state == NULL) {
104 		LOG_WRN("Failed to find receive state for sink %p", sink);
105 
106 		return;
107 	}
108 
109 	base = &sink->base;
110 
111 	mod_src_param.num_subgroups = base->subgroup_count;
112 	for (uint8_t i = 0U; i < base->subgroup_count; i++) {
113 		struct bt_bap_scan_delegator_subgroup *subgroup_param = &mod_src_param.subgroups[i];
114 		const struct bt_bap_base_subgroup *subgroup = &base->subgroups[i];
115 
116 		/* Update the BIS sync indexes for the subgroup */
117 		for (size_t j = 0U; j < subgroup->bis_count; j++) {
118 			const struct bt_bap_base_bis_data *bis_data = &subgroup->bis_data[j];
119 
120 			subgroup_param->bis_sync |= BIT(bis_data->index);
121 		}
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 		LOG_WRN("Failed to find receive state for sink %p", sink);
154 
155 		return;
156 	}
157 
158 	if (recv_state->encrypt_state == BT_BAP_BIG_ENC_STATE_BCODE_REQ &&
159 	    reason == BT_HCI_ERR_TERM_DUE_TO_MIC_FAIL) {
160 		/* Sync failed due to bad broadcast code */
161 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_BAD_CODE;
162 	} else {
163 		mod_src_param.encrypt_state = recv_state->encrypt_state;
164 	}
165 
166 	/* BIS syncs will be automatically cleared since the mod_src_param
167 	 * struct is 0-initialized
168 	 *
169 	 * Since the metadata_len is also 0, then the metadata won't be
170 	 * modified by the operation either.
171 	 */
172 
173 	/* Copy existing unchanged data */
174 	mod_src_param.num_subgroups = recv_state->num_subgroups;
175 	mod_src_param.src_id = recv_state->src_id;
176 	mod_src_param.broadcast_id = recv_state->broadcast_id;
177 
178 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
179 	if (err != 0) {
180 		LOG_WRN("Failed to modify Receive State for sink %p: %d",
181 			sink, err);
182 	}
183 }
184 
broadcast_sink_clear_big(struct bt_bap_broadcast_sink * sink,uint8_t reason)185 static void broadcast_sink_clear_big(struct bt_bap_broadcast_sink *sink,
186 				     uint8_t reason)
187 {
188 	sink->big = NULL;
189 
190 	update_recv_state_big_cleared(sink, reason);
191 }
192 
broadcast_sink_lookup_iso_chan(const struct bt_iso_chan * chan)193 static struct bt_bap_broadcast_sink *broadcast_sink_lookup_iso_chan(
194 	const struct bt_iso_chan *chan)
195 {
196 	for (size_t i = 0U; i < ARRAY_SIZE(broadcast_sinks); i++) {
197 		for (uint8_t j = 0U; j < broadcast_sinks[i].stream_count; j++) {
198 			if (broadcast_sinks[i].bis[j] == chan) {
199 				return &broadcast_sinks[i];
200 			}
201 		}
202 	}
203 
204 	return NULL;
205 }
206 
broadcast_sink_set_ep_state(struct bt_bap_ep * ep,uint8_t state)207 static void broadcast_sink_set_ep_state(struct bt_bap_ep *ep, uint8_t state)
208 {
209 	uint8_t old_state;
210 
211 	old_state = ep->status.state;
212 
213 	LOG_DBG("ep %p id 0x%02x %s -> %s", ep, ep->status.id, bt_bap_ep_state_str(old_state),
214 		bt_bap_ep_state_str(state));
215 
216 	switch (old_state) {
217 	case BT_BAP_EP_STATE_IDLE:
218 		if (state != BT_BAP_EP_STATE_QOS_CONFIGURED) {
219 			LOG_DBG("Invalid broadcast sync endpoint state transition");
220 			return;
221 		}
222 		break;
223 	case BT_BAP_EP_STATE_QOS_CONFIGURED:
224 		if (state != BT_BAP_EP_STATE_IDLE && state != BT_BAP_EP_STATE_STREAMING) {
225 			LOG_DBG("Invalid broadcast sync endpoint state transition");
226 			return;
227 		}
228 		break;
229 	case BT_BAP_EP_STATE_STREAMING:
230 		if (state != BT_BAP_EP_STATE_IDLE) {
231 			LOG_DBG("Invalid broadcast sync endpoint state transition");
232 			return;
233 		}
234 		break;
235 	default:
236 		LOG_ERR("Invalid broadcast sync endpoint state: %s",
237 			bt_bap_ep_state_str(old_state));
238 		return;
239 	}
240 
241 	ep->status.state = state;
242 
243 	if (state == BT_BAP_EP_STATE_IDLE) {
244 		struct bt_bap_stream *stream = ep->stream;
245 
246 		if (stream != NULL) {
247 			bt_bap_iso_unbind_ep(ep->iso, ep);
248 			stream->ep = NULL;
249 			stream->codec = NULL;
250 			ep->stream = NULL;
251 		}
252 	}
253 }
254 
broadcast_sink_iso_recv(struct bt_iso_chan * chan,const struct bt_iso_recv_info * info,struct net_buf * buf)255 static void broadcast_sink_iso_recv(struct bt_iso_chan *chan,
256 				    const struct bt_iso_recv_info *info,
257 				    struct net_buf *buf)
258 {
259 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
260 	const struct bt_bap_stream_ops *ops;
261 	struct bt_bap_stream *stream;
262 	struct bt_bap_ep *ep = iso->rx.ep;
263 
264 	if (ep == NULL) {
265 		LOG_ERR("iso %p not bound with ep", chan);
266 		return;
267 	}
268 
269 	stream = ep->stream;
270 	if (stream == NULL) {
271 		LOG_ERR("No stream for ep %p", ep);
272 		return;
273 	}
274 
275 	ops = stream->ops;
276 
277 	if (IS_ENABLED(CONFIG_BT_BAP_DEBUG_STREAM_DATA)) {
278 		LOG_DBG("stream %p ep %p len %zu", stream, stream->ep, net_buf_frags_len(buf));
279 	}
280 
281 	if (ops != NULL && ops->recv != NULL) {
282 		ops->recv(stream, info, buf);
283 	} else {
284 		LOG_WRN("No callback for recv set");
285 	}
286 }
287 
broadcast_sink_iso_connected(struct bt_iso_chan * chan)288 static void broadcast_sink_iso_connected(struct bt_iso_chan *chan)
289 {
290 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
291 	const struct bt_bap_stream_ops *ops;
292 	struct bt_bap_broadcast_sink *sink;
293 	struct bt_bap_stream *stream;
294 	struct bt_bap_ep *ep = iso->rx.ep;
295 	bool all_connected;
296 
297 	if (ep == NULL) {
298 		LOG_ERR("iso %p not bound with ep", chan);
299 		return;
300 	}
301 
302 	stream = ep->stream;
303 	if (stream == NULL) {
304 		LOG_ERR("No stream for ep %p", ep);
305 		return;
306 	}
307 
308 	ops = stream->ops;
309 
310 	LOG_DBG("stream %p", stream);
311 
312 	sink = broadcast_sink_lookup_iso_chan(chan);
313 	if (sink == NULL) {
314 		LOG_ERR("Could not lookup sink by iso %p", chan);
315 		return;
316 	}
317 
318 	broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_STREAMING);
319 
320 	if (ops != NULL && ops->started != NULL) {
321 		ops->started(stream);
322 	} else {
323 		LOG_WRN("No callback for connected set");
324 	}
325 
326 	all_connected = true;
327 	SYS_SLIST_FOR_EACH_CONTAINER(&sink->streams, stream, _node) {
328 		__ASSERT(stream->ep, "Endpoint is NULL");
329 
330 		if (stream->ep->status.state != BT_BAP_EP_STATE_STREAMING) {
331 			all_connected = false;
332 			break;
333 		}
334 	}
335 
336 	if (all_connected) {
337 		update_recv_state_big_synced(sink);
338 	}
339 }
340 
broadcast_sink_iso_disconnected(struct bt_iso_chan * chan,uint8_t reason)341 static void broadcast_sink_iso_disconnected(struct bt_iso_chan *chan,
342 					    uint8_t reason)
343 {
344 	struct bt_bap_iso *iso = CONTAINER_OF(chan, struct bt_bap_iso, chan);
345 	const struct bt_bap_stream_ops *ops;
346 	struct bt_bap_stream *stream;
347 	struct bt_bap_ep *ep = iso->rx.ep;
348 	struct bt_bap_broadcast_sink *sink;
349 
350 	if (ep == NULL) {
351 		LOG_ERR("iso %p not bound with ep", chan);
352 		return;
353 	}
354 
355 	stream = ep->stream;
356 	if (stream == NULL) {
357 		LOG_ERR("No stream for ep %p", ep);
358 		return;
359 	}
360 
361 	ops = stream->ops;
362 
363 	LOG_DBG("stream %p ep %p reason 0x%02x", stream, ep, reason);
364 
365 	broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_IDLE);
366 
367 	if (ops != NULL && ops->stopped != NULL) {
368 		ops->stopped(stream, reason);
369 	} else {
370 		LOG_WRN("No callback for stopped set");
371 	}
372 
373 	sink = broadcast_sink_lookup_iso_chan(chan);
374 	if (sink == NULL) {
375 		LOG_ERR("Could not lookup sink by iso %p", chan);
376 		return;
377 	}
378 
379 	if (!sys_slist_find_and_remove(&sink->streams, &stream->_node)) {
380 		LOG_DBG("Could not find and remove stream %p from sink %p", stream, sink);
381 	}
382 
383 	/* Clear sink->big if not already cleared */
384 	if (sys_slist_is_empty(&sink->streams) && sink->big) {
385 		broadcast_sink_clear_big(sink, reason);
386 	}
387 }
388 
389 static struct bt_iso_chan_ops broadcast_sink_iso_ops = {
390 	.recv		= broadcast_sink_iso_recv,
391 	.connected	= broadcast_sink_iso_connected,
392 	.disconnected	= broadcast_sink_iso_disconnected,
393 };
394 
broadcast_sink_syncing_get(void)395 static struct bt_bap_broadcast_sink *broadcast_sink_syncing_get(void)
396 {
397 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
398 		if (atomic_test_bit(broadcast_sinks[i].flags,
399 				    BT_BAP_BROADCAST_SINK_FLAG_SYNCING)) {
400 			return &broadcast_sinks[i];
401 		}
402 	}
403 
404 	return NULL;
405 }
406 
broadcast_sink_scanning_get(void)407 static struct bt_bap_broadcast_sink *broadcast_sink_scanning_get(void)
408 {
409 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
410 		if (atomic_test_bit(broadcast_sinks[i].flags,
411 				    BT_BAP_BROADCAST_SINK_FLAG_SCANNING)) {
412 			return &broadcast_sinks[i];
413 		}
414 	}
415 
416 	return NULL;
417 }
418 
broadcast_sink_free_get(void)419 static struct bt_bap_broadcast_sink *broadcast_sink_free_get(void)
420 {
421 	/* Find free entry */
422 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
423 		if (!atomic_test_bit(broadcast_sinks[i].flags,
424 				     BT_BAP_BROADCAST_SINK_FLAG_INITIALIZED)) {
425 			broadcast_sinks[i].index = i;
426 			broadcast_sinks[i].broadcast_id = INVALID_BROADCAST_ID;
427 
428 			return &broadcast_sinks[i];
429 		}
430 	}
431 
432 	return NULL;
433 }
434 
broadcast_sink_get_by_pa(struct bt_le_per_adv_sync * sync)435 static struct bt_bap_broadcast_sink *broadcast_sink_get_by_pa(struct bt_le_per_adv_sync *sync)
436 {
437 	for (int i = 0; i < ARRAY_SIZE(broadcast_sinks); i++) {
438 		if (broadcast_sinks[i].pa_sync == sync) {
439 			return &broadcast_sinks[i];
440 		}
441 	}
442 
443 	return NULL;
444 }
445 
broadcast_sink_get_by_broadcast_id(uint32_t broadcast_id)446 static struct bt_bap_broadcast_sink *broadcast_sink_get_by_broadcast_id(uint32_t broadcast_id)
447 {
448 	for (size_t i = 0U; i < ARRAY_SIZE(broadcast_sinks); i++) {
449 		if (broadcast_sinks[i].broadcast_id == broadcast_id) {
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 	int err;
461 
462 	add_src_param.pa_sync = sink->pa_sync;
463 	add_src_param.broadcast_id = sink->broadcast_id;
464 	/* Will be updated when we receive the BASE */
465 	add_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_NO_ENC;
466 	add_src_param.num_subgroups = 0U;
467 
468 	err = bt_bap_scan_delegator_add_src(&add_src_param);
469 	if (err < 0) {
470 		LOG_WRN("Failed to add sync as Receive State for sink %p: %d",
471 			sink, err);
472 	} else {
473 		sink->bass_src_id = (uint8_t)err;
474 		atomic_set_bit(sink->flags,
475 			       BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID);
476 	}
477 }
478 
handle_past_sync(struct bt_le_per_adv_sync * sync)479 static void handle_past_sync(struct bt_le_per_adv_sync *sync)
480 {
481 	const struct bt_bap_scan_delegator_recv_state *recv_state;
482 
483 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_pa_sync_cb, (void *)sync);
484 	if (recv_state != NULL) {
485 		/* If we receive a PAST transfer that fits a
486 		 * known BASS Receive State, then we create it
487 		 * as a Broadcast Sink
488 		 *
489 		 * The PA state in the Receive State will be
490 		 * updated by the Scan Delegator
491 		 */
492 		int err;
493 
494 		err = bt_bap_broadcast_sink_create(sync, recv_state->broadcast_id);
495 		if (err != 0) {
496 			LOG_WRN("Failed to create Broadcast Sink: %d", err);
497 		}
498 	}
499 }
500 
pa_synced(struct bt_le_per_adv_sync * sync,struct bt_le_per_adv_sync_synced_info * info)501 static void pa_synced(struct bt_le_per_adv_sync *sync,
502 		      struct bt_le_per_adv_sync_synced_info *info)
503 {
504 	const struct bt_bap_scan_delegator_recv_state *recv_state;
505 	struct bt_bap_broadcast_sink_cb *listener;
506 	struct bt_bap_broadcast_sink *sink;
507 	int err;
508 
509 	sink = broadcast_sink_syncing_get();
510 	if (sink == NULL || sync != sink->pa_sync) {
511 		if (info->conn) { /* PAST */
512 			handle_past_sync(sync);
513 		} else {
514 			/* Not ours */
515 		}
516 
517 		return;
518 	}
519 
520 	LOG_DBG("Synced to broadcast source with ID 0x%06X", sink->broadcast_id);
521 
522 	atomic_clear_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SYNCING);
523 
524 	err = bt_bap_broadcast_sink_scan_stop();
525 	if (err != 0 && err != -EALREADY) {
526 		LOG_WRN("Failed to stop sink scan: %d", err);
527 		/* Even if we cannot stop scanning here, we can still move on */
528 	}
529 
530 	/* Add the PA sync to the scan delegator or modify if it already exists */
531 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_pa_sync_cb, (void *)sync);
532 	if (recv_state == NULL) {
533 		broadcast_sink_add_src(sink);
534 	} else {
535 		/* Set PA sync state */
536 		err = bt_bap_scan_delegator_set_pa_state(recv_state->src_id,
537 							 BT_BAP_PA_STATE_SYNCED);
538 		if (err != 0) {
539 			LOG_WRN("Failed to set PA state: %d", err);
540 		}
541 	}
542 
543 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
544 		if (listener->pa_synced != NULL) {
545 			listener->pa_synced(sink, sink->pa_sync, sink->broadcast_id);
546 		}
547 	}
548 
549 	/* TBD: What if sync to a bad broadcast source that does not send
550 	 * properly formatted (or any) BASE?
551 	 */
552 }
553 
pa_term(struct bt_le_per_adv_sync * sync,const struct bt_le_per_adv_sync_term_info * info)554 static void pa_term(struct bt_le_per_adv_sync *sync,
555 		    const struct bt_le_per_adv_sync_term_info *info)
556 {
557 	struct bt_bap_broadcast_sink_cb *listener;
558 	struct bt_bap_broadcast_sink *sink;
559 
560 	sink = broadcast_sink_get_by_pa(sync);
561 	if (sink == NULL) {
562 		/* Not ours */
563 		return;
564 	}
565 
566 	LOG_DBG("PA sync with broadcast source with ID 0x%06X lost", sink->broadcast_id);
567 
568 	if (sink->big != NULL) {
569 		const int err = bt_iso_big_terminate(sink->big);
570 
571 		if (err != 0) {
572 			LOG_ERR("Failed to disconnect BIG sync: %d", err);
573 		}
574 	}
575 
576 	broadcast_sink_cleanup(sink);
577 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
578 		if (listener->pa_sync_lost != NULL) {
579 			listener->pa_sync_lost(sink);
580 		}
581 	}
582 }
583 
update_recv_state_base_copy_meta(const struct bt_bap_base * base,struct bt_bap_scan_delegator_mod_src_param * param)584 static void update_recv_state_base_copy_meta(const struct bt_bap_base *base,
585 					     struct bt_bap_scan_delegator_mod_src_param *param)
586 {
587 	for (uint8_t i = 0U; i < base->subgroup_count; i++) {
588 		struct bt_bap_scan_delegator_subgroup *subgroup_param = &param->subgroups[i];
589 		const struct bt_bap_base_subgroup *subgroup = &base->subgroups[i];
590 		uint8_t *metadata_param = subgroup_param->metadata;
591 		size_t total_len;
592 
593 		/* Copy metadata into subgroup_param, changing it from an array
594 		 * of bt_codec_data to a uint8_t buffer
595 		 */
596 		total_len = 0U;
597 		for (size_t j = 0; j < subgroup->codec.meta_count; j++) {
598 			const struct bt_codec_data *meta = &subgroup->codec.meta[j];
599 			const struct bt_data *data = &meta->data;
600 			const uint8_t len = data->data_len;
601 			const uint8_t type = data->type;
602 			const size_t ltv_len = sizeof(len) + sizeof(type) + len;
603 
604 			if (total_len + ltv_len > sizeof(subgroup_param->metadata)) {
605 				LOG_WRN("Could not fit entire metadata for subgroup[%u]", i);
606 
607 				return;
608 			}
609 
610 			metadata_param[total_len++] = len + 1;
611 			metadata_param[total_len++] = type;
612 			(void)memcpy(&metadata_param[total_len], data->data,
613 				     len);
614 			total_len += len;
615 		}
616 
617 		subgroup_param->metadata_len = total_len;
618 	}
619 }
620 
update_recv_state_base(const struct bt_bap_broadcast_sink * sink)621 static void update_recv_state_base(const struct bt_bap_broadcast_sink *sink)
622 {
623 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
624 	const struct bt_bap_scan_delegator_recv_state *recv_state;
625 	const struct bt_bap_base *base;
626 	int err;
627 
628 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
629 	if (recv_state == NULL) {
630 		LOG_WRN("Failed to find receive state for sink %p", sink);
631 
632 		return;
633 	}
634 
635 	base = &sink->base;
636 
637 	mod_src_param.num_subgroups = base->subgroup_count;
638 	update_recv_state_base_copy_meta(base, &mod_src_param);
639 
640 	/* Copy existing unchanged data */
641 	mod_src_param.src_id = recv_state->src_id;
642 	mod_src_param.encrypt_state = recv_state->encrypt_state;
643 	mod_src_param.broadcast_id = recv_state->broadcast_id;
644 
645 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
646 	if (err != 0) {
647 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
648 	}
649 }
650 
pa_decode_base(struct bt_data * data,void * user_data)651 static bool pa_decode_base(struct bt_data *data, void *user_data)
652 {
653 	struct bt_bap_broadcast_sink *sink = (struct bt_bap_broadcast_sink *)user_data;
654 	struct bt_bap_broadcast_sink_cb *listener;
655 	struct bt_bap_base base = { 0 };
656 
657 	if (data->type != BT_DATA_SVC_DATA16) {
658 		return true;
659 	}
660 
661 	if (data->data_len < BT_BAP_BASE_MIN_SIZE) {
662 		return true;
663 	}
664 
665 	if (bt_bap_decode_base(data, &base) != 0) {
666 		return false;
667 	}
668 
669 	if (atomic_test_bit(sink->flags,
670 			    BT_BAP_BROADCAST_SINK_FLAG_BIGINFO_RECEIVED)) {
671 		uint8_t num_bis = 0;
672 
673 		for (int i = 0; i < base.subgroup_count; i++) {
674 			num_bis += base.subgroups[i].bis_count;
675 		}
676 
677 		if (num_bis > sink->biginfo_num_bis) {
678 			LOG_WRN("BASE contains more BIS than reported by BIGInfo");
679 			return false;
680 		}
681 	}
682 
683 	sink->codec_qos.pd = base.pd;
684 	if (memcmp(&sink->base, &base, sizeof(base)) != 0) {
685 		/* We only overwrite the sink->base data once the base has
686 		 * successfully been decoded to avoid overwriting it with
687 		 * invalid data
688 		 */
689 		(void)memcpy(&sink->base, &base, sizeof(base));
690 
691 		if (atomic_test_bit(sink->flags,
692 				    BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID)) {
693 			update_recv_state_base(sink);
694 		}
695 	}
696 
697 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
698 		if (listener->base_recv != NULL) {
699 			listener->base_recv(sink, &base);
700 		}
701 	}
702 
703 	return false;
704 }
705 
pa_recv(struct bt_le_per_adv_sync * sync,const struct bt_le_per_adv_sync_recv_info * info,struct net_buf_simple * buf)706 static void pa_recv(struct bt_le_per_adv_sync *sync,
707 		    const struct bt_le_per_adv_sync_recv_info *info,
708 		    struct net_buf_simple *buf)
709 {
710 	struct bt_bap_broadcast_sink *sink = broadcast_sink_get_by_pa(sync);
711 
712 	if (sink == NULL) {
713 		/* Not a PA sync that we control */
714 		return;
715 	}
716 
717 	if (sys_slist_is_empty(&sink_cbs)) {
718 		/* Terminate early if we do not have any broadcast sink listeners */
719 		return;
720 	}
721 
722 	bt_data_parse(buf, pa_decode_base, (void *)sink);
723 }
724 
update_recv_state_encryption(const struct bt_bap_broadcast_sink * sink)725 static void update_recv_state_encryption(const struct bt_bap_broadcast_sink *sink)
726 {
727 	struct bt_bap_scan_delegator_mod_src_param mod_src_param = { 0 };
728 	const struct bt_bap_scan_delegator_recv_state *recv_state;
729 	int err;
730 
731 	__ASSERT(sink->big == NULL, "Encryption state shall not be updated while synced");
732 
733 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_sink_cb, (void *)sink);
734 	if (recv_state == NULL) {
735 		LOG_WRN("Failed to find receive state for sink %p", sink);
736 
737 		return;
738 	}
739 
740 	/* Only change the encrypt state, and leave the rest as is */
741 	if (atomic_test_bit(sink->flags,
742 			    BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED)) {
743 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_BCODE_REQ;
744 	} else {
745 		mod_src_param.encrypt_state = BT_BAP_BIG_ENC_STATE_NO_ENC;
746 	}
747 
748 	if (mod_src_param.encrypt_state == recv_state->encrypt_state) {
749 		/* No change, abort*/
750 		return;
751 	}
752 
753 	/* Copy existing data */
754 	/* TODO: Maybe we need more refined functions to set only specific fields? */
755 	mod_src_param.src_id = recv_state->src_id;
756 	mod_src_param.broadcast_id = recv_state->broadcast_id;
757 	mod_src_param.num_subgroups = recv_state->num_subgroups;
758 	(void)memcpy(mod_src_param.subgroups,
759 		     recv_state->subgroups,
760 		     sizeof(recv_state->num_subgroups));
761 
762 	err = bt_bap_scan_delegator_mod_src(&mod_src_param);
763 	if (err != 0) {
764 		LOG_WRN("Failed to modify Receive State for sink %p: %d", sink, err);
765 	}
766 }
767 
biginfo_recv(struct bt_le_per_adv_sync * sync,const struct bt_iso_biginfo * biginfo)768 static void biginfo_recv(struct bt_le_per_adv_sync *sync,
769 			 const struct bt_iso_biginfo *biginfo)
770 {
771 	struct bt_bap_broadcast_sink_cb *listener;
772 	struct bt_bap_broadcast_sink *sink;
773 
774 	sink = broadcast_sink_get_by_pa(sync);
775 	if (sink == NULL) {
776 		/* Not ours */
777 		return;
778 	}
779 
780 	if (sink->big != NULL) {
781 		/* Already synced - ignore */
782 		return;
783 	}
784 
785 	atomic_set_bit(sink->flags,
786 		       BT_BAP_BROADCAST_SINK_FLAG_BIGINFO_RECEIVED);
787 	sink->iso_interval = biginfo->iso_interval;
788 	sink->biginfo_num_bis = biginfo->num_bis;
789 	if (biginfo->encryption != atomic_test_bit(sink->flags,
790 						   BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED)) {
791 		atomic_set_bit_to(sink->flags,
792 				  BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED,
793 				  biginfo->encryption);
794 
795 		if (atomic_test_bit(sink->flags,
796 				    BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID)) {
797 			update_recv_state_encryption(sink);
798 		}
799 	}
800 
801 	sink->codec_qos.framing = biginfo->framing;
802 	sink->codec_qos.phy = biginfo->phy;
803 	sink->codec_qos.sdu = biginfo->max_sdu;
804 	sink->codec_qos.interval = biginfo->sdu_interval;
805 
806 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
807 		if (listener->syncable != NULL) {
808 			listener->syncable(sink, biginfo->encryption);
809 		}
810 	}
811 }
812 
interval_to_sync_timeout(uint16_t interval)813 static uint16_t interval_to_sync_timeout(uint16_t interval)
814 {
815 	uint32_t interval_ms;
816 	uint16_t timeout;
817 
818 	/* Ensure that the following calculation does not overflow silently */
819 	__ASSERT(SYNC_RETRY_COUNT < 10, "SYNC_RETRY_COUNT shall be less than 10");
820 
821 	/* Add retries and convert to unit in 10's of ms */
822 	interval_ms = BT_GAP_PER_ADV_INTERVAL_TO_MS(interval);
823 	timeout = (interval_ms * SYNC_RETRY_COUNT) / 10;
824 
825 	/* Enforce restraints */
826 	timeout = CLAMP(timeout, BT_GAP_PER_ADV_MIN_TIMEOUT,
827 			BT_GAP_PER_ADV_MAX_TIMEOUT);
828 
829 	return timeout;
830 }
831 
sync_broadcast_pa(const struct bt_le_scan_recv_info * info,uint32_t broadcast_id)832 static void sync_broadcast_pa(const struct bt_le_scan_recv_info *info,
833 			      uint32_t broadcast_id)
834 {
835 	struct bt_bap_broadcast_sink_cb *listener;
836 	struct bt_le_per_adv_sync_param param;
837 	struct bt_bap_broadcast_sink *sink;
838 	int err;
839 
840 	sink = broadcast_sink_scanning_get();
841 	/* Should never happen as we set the scanning flag before registering
842 	 * the scanning callbacks
843 	 */
844 	__ASSERT(sink != NULL, "sink is NULL");
845 
846 	/* Unregister the callbacks to prevent broadcast_scan_recv to be called again */
847 	bt_le_scan_cb_unregister(&broadcast_scan_cb);
848 	err = bt_le_scan_stop();
849 	if (err != 0) {
850 		LOG_ERR("Could not stop scan: %d", err);
851 	} else {
852 		atomic_clear_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_SCANNING);
853 	}
854 
855 	bt_addr_le_copy(&param.addr, info->addr);
856 	param.options = 0;
857 	param.sid = info->sid;
858 	param.skip = PA_SYNC_SKIP;
859 	param.timeout = interval_to_sync_timeout(info->interval);
860 	err = bt_le_per_adv_sync_create(&param, &sink->pa_sync);
861 	if (err != 0) {
862 		LOG_ERR("Could not sync to PA: %d", err);
863 		broadcast_sink_cleanup(sink);
864 
865 		SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
866 			if (listener->scan_term != NULL) {
867 				listener->scan_term(err);
868 			}
869 		}
870 	} else {
871 		atomic_set_bit(sink->flags,
872 			       BT_BAP_BROADCAST_SINK_FLAG_SYNCING);
873 		sink->broadcast_id = broadcast_id;
874 	}
875 }
876 
scan_check_and_sync_broadcast(struct bt_data * data,void * user_data)877 static bool scan_check_and_sync_broadcast(struct bt_data *data, void *user_data)
878 {
879 	uint32_t *broadcast_id = user_data;
880 	struct bt_uuid_16 adv_uuid;
881 
882 	if (sys_slist_is_empty(&sink_cbs)) {
883 		/* Terminate early if we do not have any broadcast sink listeners */
884 		return false;
885 	}
886 
887 	if (data->type != BT_DATA_SVC_DATA16) {
888 		return true;
889 	}
890 
891 	if (data->data_len < BT_UUID_SIZE_16 + BT_AUDIO_BROADCAST_ID_SIZE) {
892 		return true;
893 	}
894 
895 	if (!bt_uuid_create(&adv_uuid.uuid, data->data, BT_UUID_SIZE_16)) {
896 		return true;
897 	}
898 
899 	if (bt_uuid_cmp(&adv_uuid.uuid, BT_UUID_BROADCAST_AUDIO)) {
900 		return true;
901 	}
902 
903 	if (broadcast_sink_syncing_get() != NULL) {
904 		/* Already syncing, can maximum sync one */
905 		return true;
906 	}
907 
908 	*broadcast_id = sys_get_le24(data->data + BT_UUID_SIZE_16);
909 
910 	/* Stop parsing */
911 	return false;
912 }
913 
broadcast_scan_recv(const struct bt_le_scan_recv_info * info,struct net_buf_simple * ad)914 static void broadcast_scan_recv(const struct bt_le_scan_recv_info *info,
915 				struct net_buf_simple *ad)
916 {
917 	struct bt_bap_broadcast_sink_cb *listener;
918 	struct net_buf_simple_state state;
919 	uint32_t broadcast_id;
920 
921 	/* We are only interested in non-connectable periodic advertisers */
922 	if ((info->adv_props & BT_GAP_ADV_PROP_CONNECTABLE) ||
923 	     info->interval == 0) {
924 		return;
925 	}
926 
927 	/* As scan_check_and_sync_broadcast modifies the AD data,
928 	 * we store the state before parsing it
929 	 */
930 	net_buf_simple_save(ad, &state);
931 	broadcast_id = INVALID_BROADCAST_ID;
932 	bt_data_parse(ad, scan_check_and_sync_broadcast, (void *)&broadcast_id);
933 	net_buf_simple_restore(ad, &state);
934 
935 	/* We check if `broadcast_id` was modified by `scan_check_and_sync_broadcast`.
936 	 * If it was then that means that we found a broadcast source
937 	 */
938 	if (broadcast_id != INVALID_BROADCAST_ID) {
939 		LOG_DBG("Found broadcast source with address %s and id 0x%06X",
940 			bt_addr_le_str(info->addr), broadcast_id);
941 
942 		if (broadcast_sink_get_by_broadcast_id(broadcast_id) != NULL) {
943 			LOG_DBG("Broadcast sink with broadcast_id 0x%X already exists",
944 				broadcast_id);
945 
946 			return;
947 		}
948 
949 		SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
950 			if (listener->scan_recv != NULL) {
951 				bool sync_pa;
952 
953 
954 				/* As the callback receiver may modify the AD
955 				 * data, we store the state so that we can
956 				 * restore it for each callback
957 				 */
958 				net_buf_simple_save(ad, &state);
959 
960 				sync_pa = listener->scan_recv(info, ad, broadcast_id);
961 
962 				if (sync_pa) {
963 					sync_broadcast_pa(info, broadcast_id);
964 					break;
965 				}
966 
967 				net_buf_simple_restore(ad, &state);
968 			}
969 		}
970 	}
971 }
972 
broadcast_scan_timeout(void)973 static void broadcast_scan_timeout(void)
974 {
975 	struct bt_bap_broadcast_sink_cb *listener;
976 	struct bt_bap_broadcast_sink *sink;
977 
978 	bt_le_scan_cb_unregister(&broadcast_scan_cb);
979 
980 	sink = broadcast_sink_scanning_get();
981 	/* Should never happen as we set the scanning flag before registering
982 	 * the scanning callbacks
983 	 */
984 	__ASSERT(sink != NULL, "sink is NULL");
985 
986 	broadcast_sink_cleanup(sink);
987 
988 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
989 		if (listener->scan_term != NULL) {
990 			listener->scan_term(-ETIME);
991 		}
992 	}
993 }
994 
bt_bap_broadcast_sink_register_cb(struct bt_bap_broadcast_sink_cb * cb)995 int bt_bap_broadcast_sink_register_cb(struct bt_bap_broadcast_sink_cb *cb)
996 {
997 	CHECKIF(cb == NULL) {
998 		LOG_DBG("cb is NULL");
999 		return -EINVAL;
1000 	}
1001 
1002 	sys_slist_append(&sink_cbs, &cb->_node);
1003 
1004 	return 0;
1005 }
1006 
bt_bap_broadcast_sink_scan_start(const struct bt_le_scan_param * param)1007 int bt_bap_broadcast_sink_scan_start(const struct bt_le_scan_param *param)
1008 {
1009 	struct bt_bap_broadcast_sink *sink;
1010 	int err;
1011 
1012 	CHECKIF(param == NULL) {
1013 		LOG_DBG("param is NULL");
1014 		return -EINVAL;
1015 	}
1016 
1017 	CHECKIF(param->timeout != 0) {
1018 		/* This is to avoid having to re-implement the scan timeout
1019 		 * callback as well, and can be modified later if requested
1020 		 */
1021 		LOG_DBG("Scan param shall not have a timeout");
1022 		return -EINVAL;
1023 	}
1024 
1025 	if (sys_slist_is_empty(&sink_cbs)) {
1026 		LOG_WRN("No broadcast sink callbacks registered");
1027 		return -EINVAL;
1028 	}
1029 
1030 	if (broadcast_sink_scanning_get() != NULL) {
1031 		LOG_DBG("Already scanning");
1032 
1033 		return -EALREADY;
1034 	}
1035 
1036 	sink = broadcast_sink_free_get();
1037 	if (sink == NULL) {
1038 		LOG_DBG("No more free broadcast sinks");
1039 		return -ENOMEM;
1040 	}
1041 
1042 	/* TODO: check for scan callback */
1043 	err = bt_le_scan_start(param, NULL);
1044 	if (err == 0) {
1045 		atomic_set_bit(sink->flags,
1046 			       BT_BAP_BROADCAST_SINK_FLAG_INITIALIZED);
1047 		atomic_set_bit(sink->flags,
1048 			       BT_BAP_BROADCAST_SINK_FLAG_SCANNING);
1049 
1050 		broadcast_scan_cb.recv = broadcast_scan_recv;
1051 		broadcast_scan_cb.timeout = broadcast_scan_timeout;
1052 		bt_le_scan_cb_register(&broadcast_scan_cb);
1053 	}
1054 
1055 	return err;
1056 }
1057 
bt_bap_broadcast_sink_scan_stop(void)1058 int bt_bap_broadcast_sink_scan_stop(void)
1059 {
1060 	struct bt_bap_broadcast_sink_cb *listener;
1061 	struct bt_bap_broadcast_sink *sink;
1062 	int err;
1063 
1064 	sink = broadcast_sink_scanning_get();
1065 	if (sink == NULL) {
1066 		LOG_DBG("Not scanning");
1067 
1068 		return -EALREADY;
1069 	}
1070 
1071 	if (sink->pa_sync != NULL) {
1072 		err = bt_le_per_adv_sync_delete(sink->pa_sync);
1073 		if (err != 0) {
1074 			LOG_DBG("Could not delete PA sync: %d", err);
1075 			return err;
1076 		}
1077 	}
1078 
1079 	broadcast_sink_cleanup(sink);
1080 
1081 	err = bt_le_scan_stop();
1082 	if (err == 0) {
1083 		bt_le_scan_cb_unregister(&broadcast_scan_cb);
1084 	}
1085 
1086 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
1087 		if (listener->scan_term != NULL) {
1088 			listener->scan_term(err);
1089 		}
1090 	}
1091 
1092 	return err;
1093 }
1094 
bt_bap_ep_is_broadcast_snk(const struct bt_bap_ep * ep)1095 bool bt_bap_ep_is_broadcast_snk(const struct bt_bap_ep *ep)
1096 {
1097 	for (int i = 0; i < ARRAY_SIZE(broadcast_sink_eps); i++) {
1098 		if (PART_OF_ARRAY(broadcast_sink_eps[i], ep)) {
1099 			return true;
1100 		}
1101 	}
1102 
1103 	return false;
1104 }
1105 
broadcast_sink_ep_init(struct bt_bap_ep * ep)1106 static void broadcast_sink_ep_init(struct bt_bap_ep *ep)
1107 {
1108 	LOG_DBG("ep %p", ep);
1109 
1110 	(void)memset(ep, 0, sizeof(*ep));
1111 	ep->dir = BT_AUDIO_DIR_SINK;
1112 	ep->iso = NULL;
1113 }
1114 
broadcast_sink_new_ep(uint8_t index)1115 static struct bt_bap_ep *broadcast_sink_new_ep(uint8_t index)
1116 {
1117 	for (size_t i = 0; i < ARRAY_SIZE(broadcast_sink_eps[index]); i++) {
1118 		struct bt_bap_ep *ep = &broadcast_sink_eps[index][i];
1119 
1120 		/* If ep->stream is NULL the endpoint is unallocated */
1121 		if (ep->stream == NULL) {
1122 			broadcast_sink_ep_init(ep);
1123 			return ep;
1124 		}
1125 	}
1126 
1127 	return NULL;
1128 }
1129 
bt_bap_broadcast_sink_setup_stream(struct bt_bap_broadcast_sink * sink,struct bt_bap_stream * stream,struct bt_codec * codec)1130 static int bt_bap_broadcast_sink_setup_stream(struct bt_bap_broadcast_sink *sink,
1131 					      struct bt_bap_stream *stream, struct bt_codec *codec)
1132 {
1133 	struct bt_bap_iso *iso;
1134 	struct bt_bap_ep *ep;
1135 
1136 	if (stream->group != NULL) {
1137 		LOG_DBG("Stream %p already in group %p", stream, stream->group);
1138 		return -EALREADY;
1139 	}
1140 
1141 	ep = broadcast_sink_new_ep(sink->index);
1142 	if (ep == NULL) {
1143 		LOG_DBG("Could not allocate new broadcast endpoint");
1144 		return -ENOMEM;
1145 	}
1146 
1147 	iso = bt_bap_iso_new();
1148 	if (iso == NULL) {
1149 		LOG_DBG("Could not allocate iso");
1150 		return -ENOMEM;
1151 	}
1152 
1153 	bt_bap_iso_init(iso, &broadcast_sink_iso_ops);
1154 	bt_bap_iso_bind_ep(iso, ep);
1155 
1156 	bt_audio_codec_qos_to_iso_qos(iso->chan.qos->rx, &sink->codec_qos);
1157 	bt_audio_codec_to_iso_path(iso->chan.qos->rx->path, codec);
1158 
1159 	bt_bap_iso_unref(iso);
1160 
1161 	bt_bap_stream_attach(NULL, stream, ep, codec);
1162 	stream->qos = &sink->codec_qos;
1163 
1164 	return 0;
1165 }
1166 
broadcast_sink_cleanup_streams(struct bt_bap_broadcast_sink * sink)1167 static void broadcast_sink_cleanup_streams(struct bt_bap_broadcast_sink *sink)
1168 {
1169 	struct bt_bap_stream *stream, *next;
1170 
1171 	SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&sink->streams, stream, next, _node) {
1172 		if (stream->ep != NULL) {
1173 			bt_bap_iso_unbind_ep(stream->ep->iso, stream->ep);
1174 			stream->ep->stream = NULL;
1175 			stream->ep = NULL;
1176 		}
1177 
1178 		stream->qos = NULL;
1179 		stream->codec = NULL;
1180 		stream->group = NULL;
1181 
1182 		sys_slist_remove(&sink->streams, NULL, &stream->_node);
1183 	}
1184 
1185 	sink->stream_count = 0;
1186 }
1187 
broadcast_sink_cleanup(struct bt_bap_broadcast_sink * sink)1188 static void broadcast_sink_cleanup(struct bt_bap_broadcast_sink *sink)
1189 {
1190 	if (atomic_test_bit(sink->flags,
1191 			    BT_BAP_BROADCAST_SINK_FLAG_SRC_ID_VALID)) {
1192 		int err;
1193 
1194 		err = bt_bap_scan_delegator_rem_src(sink->bass_src_id);
1195 		if (err != 0) {
1196 			LOG_WRN("Failed to remove Receive State for sink %p: %d",
1197 				sink, err);
1198 		}
1199 	}
1200 
1201 	if (sink->stream_count > 0U) {
1202 		broadcast_sink_cleanup_streams(sink);
1203 	}
1204 
1205 	(void)memset(sink, 0, sizeof(*sink)); /* also clears flags */
1206 }
1207 
codec_from_base_by_index(struct bt_bap_base * base,uint8_t index)1208 static struct bt_codec *codec_from_base_by_index(struct bt_bap_base *base, uint8_t index)
1209 {
1210 	for (size_t i = 0U; i < base->subgroup_count; i++) {
1211 		struct bt_bap_base_subgroup *subgroup = &base->subgroups[i];
1212 
1213 		for (size_t j = 0U; j < subgroup->bis_count; j++) {
1214 			if (subgroup->bis_data[j].index == index) {
1215 				return &subgroup->codec;
1216 			}
1217 		}
1218 	}
1219 
1220 	return NULL;
1221 }
1222 
codec_lookup_id(const struct bt_pacs_cap * cap,void * user_data)1223 static bool codec_lookup_id(const struct bt_pacs_cap *cap, void *user_data)
1224 {
1225 	struct codec_lookup_id_data *data = user_data;
1226 
1227 	if (cap->codec->id == data->id) {
1228 		data->codec = cap->codec;
1229 
1230 		return false;
1231 	}
1232 
1233 	return true;
1234 }
1235 
bt_bap_broadcast_sink_create(struct bt_le_per_adv_sync * pa_sync,uint32_t broadcast_id)1236 int bt_bap_broadcast_sink_create(struct bt_le_per_adv_sync *pa_sync, uint32_t broadcast_id)
1237 {
1238 	const struct bt_bap_scan_delegator_recv_state *recv_state;
1239 	struct bt_bap_broadcast_sink_cb *listener;
1240 	struct bt_bap_broadcast_sink *sink;
1241 
1242 	CHECKIF(pa_sync == NULL) {
1243 		LOG_DBG("pa_sync is NULL");
1244 
1245 		return -EINVAL;
1246 	}
1247 
1248 	CHECKIF(broadcast_id > BT_AUDIO_BROADCAST_ID_MAX) {
1249 		LOG_DBG("Invalid broadcast_id: 0x%X", broadcast_id);
1250 
1251 		return -EINVAL;
1252 	}
1253 
1254 	if (broadcast_sink_get_by_broadcast_id(broadcast_id) != NULL) {
1255 		LOG_DBG("Broadcast sink with broadcast_id 0x%X already exists",
1256 			broadcast_id);
1257 
1258 		return -EALREADY;
1259 	}
1260 
1261 	sink = broadcast_sink_free_get();
1262 	if (sink == NULL) {
1263 		LOG_DBG("No more free broadcast sinks");
1264 
1265 		return -ENOMEM;
1266 	}
1267 
1268 	recv_state = bt_bap_scan_delegator_find_state(find_recv_state_by_pa_sync_cb,
1269 						      (void *)pa_sync);
1270 	if (recv_state == NULL) {
1271 		broadcast_sink_add_src(sink);
1272 	} else {
1273 		/* The PA sync is known by the Scan Delegator */
1274 		if (recv_state->broadcast_id != broadcast_id) {
1275 			LOG_DBG("Broadcast ID mismatch: 0x%X != 0x%X",
1276 				recv_state->broadcast_id, broadcast_id);
1277 
1278 			return -EINVAL;
1279 		}
1280 
1281 		sink->bass_src_id = recv_state->src_id;
1282 	}
1283 
1284 	sink->broadcast_id = broadcast_id;
1285 	sink->pa_sync = pa_sync;
1286 	atomic_set_bit(sink->flags, BT_BAP_BROADCAST_SINK_FLAG_INITIALIZED);
1287 
1288 	SYS_SLIST_FOR_EACH_CONTAINER(&sink_cbs, listener, _node) {
1289 		if (listener->pa_synced != NULL) {
1290 			listener->pa_synced(sink, sink->pa_sync,
1291 					    sink->broadcast_id);
1292 		}
1293 	}
1294 
1295 	return 0;
1296 }
1297 
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])1298 int bt_bap_broadcast_sink_sync(struct bt_bap_broadcast_sink *sink, uint32_t indexes_bitfield,
1299 			       struct bt_bap_stream *streams[], const uint8_t broadcast_code[16])
1300 {
1301 	struct bt_iso_big_sync_param param;
1302 	struct bt_codec *codecs[BROADCAST_SNK_STREAM_CNT] = { NULL };
1303 	uint8_t stream_count;
1304 	int err;
1305 
1306 	CHECKIF(sink == NULL) {
1307 		LOG_DBG("sink is NULL");
1308 		return -EINVAL;
1309 	}
1310 
1311 	CHECKIF(indexes_bitfield == 0) {
1312 		LOG_DBG("indexes_bitfield is 0");
1313 		return -EINVAL;
1314 	}
1315 
1316 	CHECKIF(indexes_bitfield & BIT(0)) {
1317 		LOG_DBG("BIT(0) is not a valid BIS index");
1318 		return -EINVAL;
1319 	}
1320 
1321 	CHECKIF(streams == NULL) {
1322 		LOG_DBG("streams is NULL");
1323 		return -EINVAL;
1324 	}
1325 
1326 	if (sink->pa_sync == NULL) {
1327 		LOG_DBG("Sink is not PA synced");
1328 		return -EINVAL;
1329 	}
1330 
1331 	if (!atomic_test_bit(sink->flags,
1332 			     BT_BAP_BROADCAST_SINK_FLAG_BIGINFO_RECEIVED)) {
1333 		/* TODO: We could store the request to sync and start the sync
1334 		 * once the BIGInfo has been received, and then do the sync
1335 		 * then. This would be similar how LE Create Connection works.
1336 		 */
1337 		LOG_DBG("BIGInfo not received, cannot sync yet");
1338 		return -EAGAIN;
1339 	}
1340 
1341 	if (atomic_test_bit(sink->flags,
1342 			    BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED) &&
1343 	    broadcast_code == NULL) {
1344 		LOG_DBG("Broadcast code required");
1345 
1346 		return -EINVAL;
1347 	}
1348 
1349 	/* Validate that number of bits set is less than number of streams */
1350 	stream_count = 0;
1351 	for (int i = 1; i < BT_ISO_MAX_GROUP_ISO_COUNT; i++) {
1352 		if ((indexes_bitfield & BIT(i)) != 0) {
1353 			struct bt_codec *codec = codec_from_base_by_index(&sink->base, i);
1354 			struct codec_lookup_id_data lookup_data = { };
1355 
1356 			if (codec == NULL) {
1357 				LOG_DBG("Index %d not found in BASE", i);
1358 				return -EINVAL;
1359 			}
1360 
1361 			/* Lookup and assign path_id based on capabilities */
1362 			lookup_data.id = codec->id;
1363 
1364 			bt_pacs_cap_foreach(BT_AUDIO_DIR_SINK, codec_lookup_id,
1365 					    &lookup_data);
1366 			if (lookup_data.codec == NULL) {
1367 				LOG_DBG("Codec with id %u is not supported by our capabilities",
1368 				       codec->id);
1369 
1370 				return -ENOENT;
1371 			}
1372 
1373 			codec->path_id = lookup_data.codec->path_id;
1374 
1375 			codecs[stream_count++] = codec;
1376 
1377 			if (stream_count > BROADCAST_SNK_STREAM_CNT) {
1378 				LOG_DBG("Cannot sync to more than %d streams",
1379 					BROADCAST_SNK_STREAM_CNT);
1380 				return -EINVAL;
1381 			}
1382 		}
1383 	}
1384 
1385 	for (size_t i = 0; i < stream_count; i++) {
1386 		CHECKIF(streams[i] == NULL) {
1387 			LOG_DBG("streams[%zu] is NULL", i);
1388 			return -EINVAL;
1389 		}
1390 	}
1391 
1392 	sink->stream_count = 0U;
1393 	for (size_t i = 0; i < stream_count; i++) {
1394 		struct bt_bap_stream *stream;
1395 		struct bt_codec *codec;
1396 
1397 		stream = streams[i];
1398 		codec = codecs[i];
1399 
1400 		err = bt_bap_broadcast_sink_setup_stream(sink, stream, codec);
1401 		if (err != 0) {
1402 			LOG_DBG("Failed to setup streams[%zu]: %d", i, err);
1403 			broadcast_sink_cleanup_streams(sink);
1404 			return err;
1405 		}
1406 
1407 		sink->bis[i] = bt_bap_stream_iso_chan_get(stream);
1408 		sys_slist_append(&sink->streams, &stream->_node);
1409 		sink->stream_count++;
1410 	}
1411 
1412 	param.bis_channels = sink->bis;
1413 	param.num_bis = sink->stream_count;
1414 	param.bis_bitfield = indexes_bitfield;
1415 	param.mse = 0; /* Let controller decide */
1416 	param.sync_timeout = interval_to_sync_timeout(sink->iso_interval);
1417 	param.encryption = atomic_test_bit(sink->flags,
1418 					   BT_BAP_BROADCAST_SINK_FLAG_BIG_ENCRYPTED);
1419 	if (param.encryption) {
1420 		memcpy(param.bcode, broadcast_code, sizeof(param.bcode));
1421 	} else {
1422 		memset(param.bcode, 0, sizeof(param.bcode));
1423 	}
1424 
1425 	err = bt_iso_big_sync(sink->pa_sync, &param, &sink->big);
1426 	if (err != 0) {
1427 		broadcast_sink_cleanup_streams(sink);
1428 		return err;
1429 	}
1430 
1431 	for (size_t i = 0; i < stream_count; i++) {
1432 		struct bt_bap_ep *ep = streams[i]->ep;
1433 
1434 		ep->broadcast_sink = sink;
1435 		broadcast_sink_set_ep_state(ep, BT_BAP_EP_STATE_QOS_CONFIGURED);
1436 	}
1437 
1438 	return 0;
1439 }
1440 
bt_bap_broadcast_sink_stop(struct bt_bap_broadcast_sink * sink)1441 int bt_bap_broadcast_sink_stop(struct bt_bap_broadcast_sink *sink)
1442 {
1443 	struct bt_bap_stream *stream;
1444 	sys_snode_t *head_node;
1445 	int err;
1446 
1447 	CHECKIF(sink == NULL) {
1448 		LOG_DBG("sink is NULL");
1449 		return -EINVAL;
1450 	}
1451 
1452 	if (sys_slist_is_empty(&sink->streams)) {
1453 		LOG_DBG("Source does not have any streams (already stopped)");
1454 		return -EALREADY;
1455 	}
1456 
1457 	head_node = sys_slist_peek_head(&sink->streams);
1458 	stream = CONTAINER_OF(head_node, struct bt_bap_stream, _node);
1459 
1460 	/* All streams in a broadcast source is in the same state,
1461 	 * so we can just check the first stream
1462 	 */
1463 	if (stream->ep == NULL) {
1464 		LOG_DBG("stream->ep is NULL");
1465 		return -EINVAL;
1466 	}
1467 
1468 	if (stream->ep->status.state != BT_BAP_EP_STATE_STREAMING &&
1469 	    stream->ep->status.state != BT_BAP_EP_STATE_QOS_CONFIGURED) {
1470 		LOG_DBG("Broadcast sink stream %p invalid state: %u", stream,
1471 			stream->ep->status.state);
1472 		return -EBADMSG;
1473 	}
1474 
1475 	err = bt_iso_big_terminate(sink->big);
1476 	if (err) {
1477 		LOG_DBG("Failed to terminate BIG (err %d)", err);
1478 		return err;
1479 	}
1480 
1481 	broadcast_sink_clear_big(sink, BT_HCI_ERR_LOCALHOST_TERM_CONN);
1482 	/* Channel states will be updated in the broadcast_sink_iso_disconnected function */
1483 
1484 	return 0;
1485 }
1486 
bt_bap_broadcast_sink_delete(struct bt_bap_broadcast_sink * sink)1487 int bt_bap_broadcast_sink_delete(struct bt_bap_broadcast_sink *sink)
1488 {
1489 	int err;
1490 
1491 	CHECKIF(sink == NULL) {
1492 		LOG_DBG("sink is NULL");
1493 		return -EINVAL;
1494 	}
1495 
1496 	if (!sys_slist_is_empty(&sink->streams)) {
1497 		struct bt_bap_stream *stream;
1498 		sys_snode_t *head_node;
1499 
1500 		head_node = sys_slist_peek_head(&sink->streams);
1501 		stream = CONTAINER_OF(head_node, struct bt_bap_stream, _node);
1502 
1503 		/* All streams in a broadcast source is in the same state,
1504 		 * so we can just check the first stream
1505 		 */
1506 		if (stream->ep != NULL) {
1507 			LOG_DBG("Sink is not stopped");
1508 			return -EBADMSG;
1509 		}
1510 	}
1511 
1512 	if (sink->pa_sync == NULL) {
1513 		LOG_DBG("Broadcast sink is already deleted");
1514 		return -EALREADY;
1515 	}
1516 
1517 	err = bt_le_per_adv_sync_delete(sink->pa_sync);
1518 	if (err != 0) {
1519 		LOG_DBG("Failed to delete periodic advertising sync (err %d)", err);
1520 		return err;
1521 	}
1522 
1523 	/* Reset the broadcast sink */
1524 	broadcast_sink_cleanup(sink);
1525 
1526 	return 0;
1527 }
1528 
broadcast_sink_init(void)1529 static int broadcast_sink_init(void)
1530 {
1531 	static struct bt_le_per_adv_sync_cb cb = {
1532 		.synced = pa_synced,
1533 		.recv = pa_recv,
1534 		.term = pa_term,
1535 		.biginfo = biginfo_recv
1536 	};
1537 
1538 	bt_le_per_adv_sync_cb_register(&cb);
1539 
1540 	return 0;
1541 }
1542 
1543 SYS_INIT(broadcast_sink_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY);
1544