1 /*
2  * Copyright (c) 2021-2023 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdint.h>
11 #include <string.h>
12 
13 #include <zephyr/autoconf.h>
14 #include <zephyr/autoconf.h>
15 #include <zephyr/bluetooth/addr.h>
16 #include <zephyr/bluetooth/audio/audio.h>
17 #include <zephyr/bluetooth/audio/bap.h>
18 #include <zephyr/bluetooth/audio/bap_lc3_preset.h>
19 #include <zephyr/bluetooth/audio/lc3.h>
20 #include <zephyr/bluetooth/audio/pacs.h>
21 #include <zephyr/bluetooth/bluetooth.h>
22 #include <zephyr/bluetooth/gap.h>
23 #include <zephyr/bluetooth/iso.h>
24 #include <zephyr/bluetooth/uuid.h>
25 #include <zephyr/kernel.h>
26 #include <zephyr/net/buf.h>
27 #include <zephyr/sys/byteorder.h>
28 #include <zephyr/sys/printk.h>
29 #include <zephyr/sys/util.h>
30 #include <zephyr/sys/util_macro.h>
31 #include <zephyr/toolchain.h>
32 
33 #include "bap_common.h"
34 #include "bstests.h"
35 #include "common.h"
36 
37 #if defined(CONFIG_BT_BAP_BROADCAST_SINK)
38 extern enum bst_result_t bst_result;
39 
40 CREATE_FLAG(flag_broadcaster_found);
41 CREATE_FLAG(flag_base_received);
42 CREATE_FLAG(flag_base_metadata_updated);
43 CREATE_FLAG(flag_pa_synced);
44 CREATE_FLAG(flag_syncable);
45 CREATE_FLAG(flag_pa_sync_lost);
46 CREATE_FLAG(flag_received);
47 CREATE_FLAG(flag_pa_request);
48 CREATE_FLAG(flag_bis_sync_requested);
49 
50 static struct bt_bap_broadcast_sink *g_sink;
51 static struct bt_le_scan_recv_info broadcaster_info;
52 static bt_addr_le_t broadcaster_addr;
53 static struct bt_le_per_adv_sync *pa_sync;
54 static uint32_t broadcaster_broadcast_id;
55 static struct audio_test_stream broadcast_sink_streams[CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT];
56 static struct bt_bap_stream *streams[ARRAY_SIZE(broadcast_sink_streams)];
57 static uint32_t requested_bis_sync;
58 static struct bt_le_ext_adv *ext_adv;
59 static const struct bt_bap_scan_delegator_recv_state *req_recv_state;
60 
61 #define SUPPORTED_CHAN_COUNTS          BT_AUDIO_CODEC_CAP_CHAN_COUNT_SUPPORT(1, 2)
62 #define SUPPORTED_MIN_OCTETS_PER_FRAME 30
63 #define SUPPORTED_MAX_OCTETS_PER_FRAME 155
64 #define SUPPORTED_MAX_FRAMES_PER_SDU   1
65 
66 /* We support 1 or 2 channels, so the maximum SDU size we support will be 2 times the maximum frame
67  * size per frame we support
68  */
69 #define SUPPORTED_MAX_SDU_SIZE (2 * SUPPORTED_MAX_FRAMES_PER_SDU * SUPPORTED_MAX_OCTETS_PER_FRAME)
70 
71 BUILD_ASSERT(CONFIG_BT_ISO_RX_MTU >= SUPPORTED_MAX_SDU_SIZE);
72 
73 #define SUPPORTED_CONTEXTS (BT_AUDIO_CONTEXT_TYPE_CONVERSATIONAL | BT_AUDIO_CONTEXT_TYPE_MEDIA)
74 
75 static const struct bt_audio_codec_cap codec_cap = BT_AUDIO_CODEC_CAP_LC3(
76 	BT_AUDIO_CODEC_CAP_FREQ_ANY, BT_AUDIO_CODEC_CAP_DURATION_ANY, SUPPORTED_CHAN_COUNTS,
77 	SUPPORTED_MIN_OCTETS_PER_FRAME, SUPPORTED_MAX_OCTETS_PER_FRAME,
78 	SUPPORTED_MAX_FRAMES_PER_SDU, SUPPORTED_CONTEXTS);
79 
80 static K_SEM_DEFINE(sem_started, 0U, ARRAY_SIZE(streams));
81 static K_SEM_DEFINE(sem_stopped, 0U, ARRAY_SIZE(streams));
82 
83 /* Create a mask for the maximum BIS we can sync to using the number of streams
84  * we have. We add an additional 1 since the bis indexes start from 1 and not
85  * 0.
86  */
87 static const uint32_t bis_index_mask = BIT_MASK(ARRAY_SIZE(streams) + 1U);
88 static uint32_t bis_index_bitfield;
89 
valid_base_subgroup(const struct bt_bap_base_subgroup * subgroup)90 static bool valid_base_subgroup(const struct bt_bap_base_subgroup *subgroup)
91 {
92 	struct bt_audio_codec_cfg codec_cfg = {0};
93 	enum bt_audio_location chan_allocation;
94 	uint8_t frames_blocks_per_sdu;
95 	size_t min_sdu_size_required;
96 	uint16_t octets_per_frame;
97 	uint8_t chan_cnt;
98 	int ret;
99 
100 	ret = bt_bap_base_subgroup_codec_to_codec_cfg(subgroup, &codec_cfg);
101 	if (ret < 0) {
102 		printk("Could not get subgroup codec_cfg: %d\n", ret);
103 
104 		return false;
105 	}
106 
107 	ret = bt_audio_codec_cfg_get_freq(&codec_cfg);
108 	if (ret >= 0) {
109 		const int freq = bt_audio_codec_cfg_freq_to_freq_hz(ret);
110 
111 		if (freq < 0) {
112 			printk("Invalid subgroup frequency value: %d (%d)\n", ret, freq);
113 
114 			return false;
115 		}
116 	} else {
117 		printk("Could not get subgroup frequency: %d\n", ret);
118 
119 		return false;
120 	}
121 
122 	ret = bt_audio_codec_cfg_get_frame_dur(&codec_cfg);
123 	if (ret >= 0) {
124 		const int frame_duration_us = bt_audio_codec_cfg_frame_dur_to_frame_dur_us(ret);
125 
126 		if (frame_duration_us < 0) {
127 			printk("Invalid subgroup frame duration value: %d (%d)\n", ret,
128 			       frame_duration_us);
129 
130 			return false;
131 		}
132 	} else {
133 		printk("Could not get subgroup frame duration: %d\n", ret);
134 
135 		return false;
136 	}
137 
138 	ret = bt_audio_codec_cfg_get_chan_allocation(&codec_cfg, &chan_allocation, false);
139 	if (ret == 0) {
140 		chan_cnt = bt_audio_get_chan_count(chan_allocation);
141 	} else {
142 		printk("Could not get subgroup channel allocation: %d\n", ret);
143 		/* Channel allocation is an optional field, and omitting it implicitly means mono */
144 		chan_cnt = 1U;
145 	}
146 
147 	if (chan_cnt == 0 || (BIT(chan_cnt - 1) & SUPPORTED_CHAN_COUNTS) == 0) {
148 		printk("Unsupported channel count: %u\n", chan_cnt);
149 
150 		return false;
151 	}
152 
153 	ret = bt_audio_codec_cfg_get_octets_per_frame(&codec_cfg);
154 	if (ret > 0) {
155 		octets_per_frame = (uint16_t)ret;
156 	} else {
157 		printk("Could not get subgroup octets per frame: %d\n", ret);
158 
159 		return false;
160 	}
161 
162 	if (!IN_RANGE(octets_per_frame, SUPPORTED_MIN_OCTETS_PER_FRAME,
163 		      SUPPORTED_MAX_OCTETS_PER_FRAME)) {
164 		printk("Unsupported octets per frame: %u\n", octets_per_frame);
165 
166 		return false;
167 	}
168 
169 	ret = bt_audio_codec_cfg_get_frame_blocks_per_sdu(&codec_cfg, false);
170 	if (ret > 0) {
171 		frames_blocks_per_sdu = (uint8_t)ret;
172 	} else {
173 		printk("Could not get subgroup octets per frame: %d\n", ret);
174 		/* Frame blocks per SDU is optional and is implicitly 1 */
175 		frames_blocks_per_sdu = 1U;
176 	}
177 
178 	/* An SDU can consist of X frame blocks, each with Y frames (one per channel) of size Z in
179 	 * them. The minimum SDU size required for this is X * Y * Z.
180 	 */
181 	min_sdu_size_required = chan_cnt * octets_per_frame * frames_blocks_per_sdu;
182 	if (min_sdu_size_required > SUPPORTED_MAX_SDU_SIZE) {
183 		printk("With %zu channels and %u octets per frame and %u frames per block, SDUs "
184 		       "shall be at minimum %zu, we only support %d\n",
185 		       chan_cnt, octets_per_frame, frames_blocks_per_sdu, min_sdu_size_required,
186 		       SUPPORTED_MAX_SDU_SIZE);
187 
188 		return false;
189 	}
190 
191 	return true;
192 }
193 
base_subgroup_cb(const struct bt_bap_base_subgroup * subgroup,void * user_data)194 static bool base_subgroup_cb(const struct bt_bap_base_subgroup *subgroup, void *user_data)
195 {
196 	static uint8_t metadata[CONFIG_BT_AUDIO_CODEC_CFG_MAX_METADATA_SIZE];
197 	static size_t metadata_size;
198 	uint8_t *meta;
199 	int ret;
200 
201 	ret = bt_bap_base_get_subgroup_codec_meta(subgroup, &meta);
202 	if (ret < 0) {
203 		FAIL("Could not get subgroup meta: %d\n", ret);
204 		return false;
205 	}
206 
207 	if (TEST_FLAG(flag_base_received) &&
208 	    ((size_t)ret != metadata_size || memcmp(meta, metadata, metadata_size) != 0)) {
209 		printk("Metadata updated\n");
210 		SET_FLAG(flag_base_metadata_updated);
211 	}
212 
213 	metadata_size = (size_t)ret;
214 	(void)memcpy(metadata, meta, metadata_size);
215 
216 	if (!valid_base_subgroup(subgroup)) {
217 		printk("Invalid or unsupported subgroup\n");
218 		return false;
219 	}
220 
221 	return true;
222 }
223 
base_recv_cb(struct bt_bap_broadcast_sink * sink,const struct bt_bap_base * base,size_t base_size)224 static void base_recv_cb(struct bt_bap_broadcast_sink *sink, const struct bt_bap_base *base,
225 			 size_t base_size)
226 {
227 	uint32_t base_bis_index_bitfield = 0U;
228 	int ret;
229 
230 	printk("Received BASE with %d subgroups from broadcast sink %p\n",
231 	       bt_bap_base_get_subgroup_count(base), sink);
232 
233 	ret = bt_bap_base_foreach_subgroup(base, base_subgroup_cb, NULL);
234 	if (ret != 0) {
235 		FAIL("Failed to parse subgroups: %d\n", ret);
236 		return;
237 	}
238 
239 	ret = bt_bap_base_get_bis_indexes(base, &base_bis_index_bitfield);
240 	if (ret != 0) {
241 		FAIL("Failed to BIS indexes: %d\n", ret);
242 		return;
243 	}
244 
245 	bis_index_bitfield = base_bis_index_bitfield & bis_index_mask;
246 
247 	SET_FLAG(flag_base_received);
248 }
249 
syncable_cb(struct bt_bap_broadcast_sink * sink,const struct bt_iso_biginfo * biginfo)250 static void syncable_cb(struct bt_bap_broadcast_sink *sink, const struct bt_iso_biginfo *biginfo)
251 {
252 	printk("Broadcast sink %p syncable with%s encryption\n",
253 	       sink, biginfo->encryption ? "" : "out");
254 	SET_FLAG(flag_syncable);
255 }
256 
257 static struct bt_bap_broadcast_sink_cb broadcast_sink_cbs = {
258 	.base_recv = base_recv_cb,
259 	.syncable = syncable_cb,
260 };
261 
scan_check_and_sync_broadcast(struct bt_data * data,void * user_data)262 static bool scan_check_and_sync_broadcast(struct bt_data *data, void *user_data)
263 {
264 	const struct bt_le_scan_recv_info *info = user_data;
265 	char le_addr[BT_ADDR_LE_STR_LEN];
266 	struct bt_uuid_16 adv_uuid;
267 	uint32_t broadcast_id;
268 
269 	if (TEST_FLAG(flag_broadcaster_found)) {
270 		/* no-op*/
271 		return false;
272 	}
273 
274 	if (data->type != BT_DATA_SVC_DATA16) {
275 		return true;
276 	}
277 
278 	if (data->data_len < BT_UUID_SIZE_16 + BT_AUDIO_BROADCAST_ID_SIZE) {
279 		return true;
280 	}
281 
282 	if (!bt_uuid_create(&adv_uuid.uuid, data->data, BT_UUID_SIZE_16)) {
283 		return true;
284 	}
285 
286 	if (bt_uuid_cmp(&adv_uuid.uuid, BT_UUID_BROADCAST_AUDIO)) {
287 		return true;
288 	}
289 
290 	broadcast_id = sys_get_le24(data->data + BT_UUID_SIZE_16);
291 
292 	bt_addr_le_to_str(info->addr, le_addr, sizeof(le_addr));
293 
294 	printk("Found broadcaster with ID 0x%06X and addr %s and sid 0x%02X\n", broadcast_id,
295 	       le_addr, info->sid);
296 
297 	SET_FLAG(flag_broadcaster_found);
298 
299 	/* Store info for PA sync parameters */
300 	memcpy(&broadcaster_info, info, sizeof(broadcaster_info));
301 	bt_addr_le_copy(&broadcaster_addr, info->addr);
302 	broadcaster_broadcast_id = broadcast_id;
303 
304 	/* Stop parsing */
305 	return false;
306 }
307 
broadcast_scan_recv(const struct bt_le_scan_recv_info * info,struct net_buf_simple * ad)308 static void broadcast_scan_recv(const struct bt_le_scan_recv_info *info, struct net_buf_simple *ad)
309 {
310 	if (info->interval != 0U) {
311 		bt_data_parse(ad, scan_check_and_sync_broadcast, (void *)info);
312 	}
313 }
314 
315 static struct bt_le_scan_cb bap_scan_cb = {
316 	.recv = broadcast_scan_recv,
317 };
318 
bap_pa_sync_synced_cb(struct bt_le_per_adv_sync * sync,struct bt_le_per_adv_sync_synced_info * info)319 static void bap_pa_sync_synced_cb(struct bt_le_per_adv_sync *sync,
320 				  struct bt_le_per_adv_sync_synced_info *info)
321 {
322 	if (sync == pa_sync) {
323 		printk("PA sync %p synced for broadcast sink with broadcast ID 0x%06X\n", sync,
324 		       broadcaster_broadcast_id);
325 
326 		SET_FLAG(flag_pa_synced);
327 	}
328 }
329 
bap_pa_sync_terminated_cb(struct bt_le_per_adv_sync * sync,const struct bt_le_per_adv_sync_term_info * info)330 static void bap_pa_sync_terminated_cb(struct bt_le_per_adv_sync *sync,
331 				      const struct bt_le_per_adv_sync_term_info *info)
332 {
333 	if (sync == pa_sync) {
334 		printk("PA sync %p lost with reason %u\n", sync, info->reason);
335 		pa_sync = NULL;
336 
337 		SET_FLAG(flag_pa_sync_lost);
338 	}
339 }
340 
341 static struct bt_le_per_adv_sync_cb bap_pa_sync_cb = {
342 	.synced = bap_pa_sync_synced_cb,
343 	.term = bap_pa_sync_terminated_cb,
344 };
345 
346 static struct bt_pacs_cap cap = {
347 	.codec_cap = &codec_cap,
348 };
349 
pa_sync_req_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state,bool past_avail,uint16_t pa_interval)350 static int pa_sync_req_cb(struct bt_conn *conn,
351 			  const struct bt_bap_scan_delegator_recv_state *recv_state,
352 			  bool past_avail, uint16_t pa_interval)
353 {
354 	if (recv_state->pa_sync_state == BT_BAP_PA_STATE_SYNCED ||
355 	    recv_state->pa_sync_state == BT_BAP_PA_STATE_INFO_REQ) {
356 		/* Already syncing */
357 		/* TODO: Terminate existing sync and then sync to new?*/
358 		return -EALREADY;
359 	}
360 
361 	req_recv_state = recv_state;
362 
363 	SET_FLAG(flag_pa_request);
364 
365 	return 0;
366 }
367 
pa_sync_term_req_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state)368 static int pa_sync_term_req_cb(struct bt_conn *conn,
369 			       const struct bt_bap_scan_delegator_recv_state *recv_state)
370 {
371 	if (pa_sync == NULL || recv_state->pa_sync_state == BT_BAP_PA_STATE_NOT_SYNCED) {
372 		return -EALREADY;
373 	}
374 
375 	req_recv_state = recv_state;
376 
377 	UNSET_FLAG(flag_pa_request);
378 
379 	return 0;
380 }
381 
bis_sync_req_cb(struct bt_conn * conn,const struct bt_bap_scan_delegator_recv_state * recv_state,const uint32_t bis_sync_req[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS])382 static int bis_sync_req_cb(struct bt_conn *conn,
383 			   const struct bt_bap_scan_delegator_recv_state *recv_state,
384 			   const uint32_t bis_sync_req[CONFIG_BT_BAP_BASS_MAX_SUBGROUPS])
385 {
386 	printk("BIS sync request received for %p: 0x%08x\n", recv_state, bis_sync_req[0]);
387 	/* We only care about a single subgroup in this test */
388 	requested_bis_sync = bis_sync_req[0];
389 	broadcaster_broadcast_id = recv_state->broadcast_id;
390 	if (bis_sync_req[0] != 0) {
391 		SET_FLAG(flag_bis_sync_requested);
392 	} else {
393 		UNSET_FLAG(flag_bis_sync_requested);
394 	}
395 
396 	return 0;
397 }
398 
399 static struct bt_bap_scan_delegator_cb scan_delegator_cbs = {
400 	.pa_sync_req = pa_sync_req_cb,
401 	.pa_sync_term_req = pa_sync_term_req_cb,
402 	.bis_sync_req = bis_sync_req_cb,
403 };
404 
validate_stream_codec_cfg(const struct bt_bap_stream * stream)405 static void validate_stream_codec_cfg(const struct bt_bap_stream *stream)
406 {
407 	struct bt_audio_codec_cfg *codec_cfg = stream->codec_cfg;
408 	enum bt_audio_location chan_allocation;
409 	uint8_t frames_blocks_per_sdu;
410 	size_t min_sdu_size_required;
411 	uint16_t octets_per_frame;
412 	uint8_t chan_cnt;
413 	int ret;
414 
415 	ret = bt_audio_codec_cfg_get_freq(codec_cfg);
416 	if (ret >= 0) {
417 		const int freq = bt_audio_codec_cfg_freq_to_freq_hz(ret);
418 
419 		if (freq < 0) {
420 			FAIL("Invalid frequency value: %d (%d)\n", ret, freq);
421 
422 			return;
423 		}
424 	} else {
425 		FAIL("Could not get frequency: %d\n", ret);
426 
427 		return;
428 	}
429 
430 	ret = bt_audio_codec_cfg_get_frame_dur(codec_cfg);
431 	if (ret >= 0) {
432 		const int frame_duration_us = bt_audio_codec_cfg_frame_dur_to_frame_dur_us(ret);
433 
434 		if (frame_duration_us < 0) {
435 			FAIL("Invalid frame duration value: %d (%d)\n", ret, frame_duration_us);
436 
437 			return;
438 		}
439 	} else {
440 		FAIL("Could not get frame duration: %d\n", ret);
441 
442 		return;
443 	}
444 
445 	/* The broadcast source sets the channel allocation in the BIS to
446 	 * BT_AUDIO_LOCATION_FRONT_LEFT
447 	 */
448 	ret = bt_audio_codec_cfg_get_chan_allocation(codec_cfg, &chan_allocation, false);
449 	if (ret == 0) {
450 		if (chan_allocation != BT_AUDIO_LOCATION_FRONT_CENTER) {
451 			FAIL("Unexpected channel allocation: 0x%08X", chan_allocation);
452 
453 			return;
454 		}
455 
456 		chan_cnt = bt_audio_get_chan_count(chan_allocation);
457 	} else {
458 		FAIL("Could not get subgroup channel allocation: %d\n", ret);
459 
460 		return;
461 	}
462 
463 	if (chan_cnt == 0 || (BIT(chan_cnt - 1) & SUPPORTED_CHAN_COUNTS) == 0) {
464 		FAIL("Unsupported channel count: %u\n", chan_cnt);
465 
466 		return;
467 	}
468 
469 	ret = bt_audio_codec_cfg_get_octets_per_frame(codec_cfg);
470 	if (ret > 0) {
471 		octets_per_frame = (uint16_t)ret;
472 	} else {
473 		FAIL("Could not get subgroup octets per frame: %d\n", ret);
474 
475 		return;
476 	}
477 
478 	if (!IN_RANGE(octets_per_frame, SUPPORTED_MIN_OCTETS_PER_FRAME,
479 		      SUPPORTED_MAX_OCTETS_PER_FRAME)) {
480 		FAIL("Unsupported octets per frame: %u\n", octets_per_frame);
481 
482 		return;
483 	}
484 
485 	ret = bt_audio_codec_cfg_get_frame_blocks_per_sdu(codec_cfg, false);
486 	if (ret > 0) {
487 		frames_blocks_per_sdu = (uint8_t)ret;
488 	} else {
489 		printk("Could not get octets per frame: %d\n", ret);
490 		/* Frame blocks per SDU is optional and is implicitly 1 */
491 		frames_blocks_per_sdu = 1U;
492 	}
493 
494 	/* An SDU can consist of X frame blocks, each with Y frames (one per channel) of size Z in
495 	 * them. The minimum SDU size required for this is X * Y * Z.
496 	 */
497 	min_sdu_size_required = chan_cnt * octets_per_frame * frames_blocks_per_sdu;
498 	if (min_sdu_size_required > stream->qos->sdu) {
499 		FAIL("With %zu channels and %u octets per frame and %u frames per block, SDUs "
500 		     "shall be at minimum %zu, but the stream has been configured for %u\n",
501 		     chan_cnt, octets_per_frame, frames_blocks_per_sdu, min_sdu_size_required,
502 		     stream->qos->sdu);
503 
504 		return;
505 	}
506 }
507 
started_cb(struct bt_bap_stream * stream)508 static void started_cb(struct bt_bap_stream *stream)
509 {
510 	struct bt_bap_ep_info info;
511 	int err;
512 
513 	err = bt_bap_ep_get_info(stream->ep, &info);
514 	if (err != 0) {
515 		FAIL("Failed to get EP info: %d\n", err);
516 		return;
517 	}
518 
519 	if (info.state != BT_BAP_EP_STATE_STREAMING) {
520 		FAIL("Unexpected EP state: %d\n", info.state);
521 		return;
522 	}
523 
524 	if (info.dir != BT_AUDIO_DIR_SINK) {
525 		FAIL("Unexpected info.dir: %d\n", info.dir);
526 		return;
527 	}
528 
529 	if (info.can_send) {
530 		FAIL("info.can_send is true\n");
531 		return;
532 	}
533 
534 	if (!info.can_recv) {
535 		FAIL("info.can_recv is false\n");
536 		return;
537 	}
538 
539 	if (info.paired_ep != NULL) {
540 		FAIL("Unexpected info.paired_ep: %p\n", info.paired_ep);
541 		return;
542 	}
543 
544 	printk("Stream %p started\n", stream);
545 	k_sem_give(&sem_started);
546 
547 	validate_stream_codec_cfg(stream);
548 }
549 
stopped_cb(struct bt_bap_stream * stream,uint8_t reason)550 static void stopped_cb(struct bt_bap_stream *stream, uint8_t reason)
551 {
552 	printk("Stream %p stopped with reason 0x%02X\n", stream, reason);
553 	k_sem_give(&sem_stopped);
554 }
555 
recv_cb(struct bt_bap_stream * stream,const struct bt_iso_recv_info * info,struct net_buf * buf)556 static void recv_cb(struct bt_bap_stream *stream,
557 		    const struct bt_iso_recv_info *info,
558 		    struct net_buf *buf)
559 {
560 	struct audio_test_stream *test_stream = audio_test_stream_from_bap_stream(stream);
561 
562 	if ((test_stream->rx_cnt % 100U) == 0U) {
563 		printk("[%zu]: Incoming audio on stream %p len %u and ts %u\n", test_stream->rx_cnt,
564 		       stream, buf->len, info->ts);
565 	}
566 
567 	if (test_stream->rx_cnt > 0U && info->ts == test_stream->last_info.ts) {
568 		FAIL("Duplicated timestamp received: %u\n", test_stream->last_info.ts);
569 		return;
570 	}
571 
572 	if (test_stream->rx_cnt > 0U && info->seq_num == test_stream->last_info.seq_num) {
573 		FAIL("Duplicated PSN received: %u\n", test_stream->last_info.seq_num);
574 		return;
575 	}
576 
577 	if (info->flags & BT_ISO_FLAGS_ERROR) {
578 		/* Fail the test if we have not received what we expected */
579 		if (!TEST_FLAG(flag_received)) {
580 			FAIL("ISO receive error\n");
581 		}
582 
583 		return;
584 	}
585 
586 	if (info->flags & BT_ISO_FLAGS_LOST) {
587 		FAIL("ISO receive lost\n");
588 		return;
589 	}
590 
591 	if (memcmp(buf->data, mock_iso_data, buf->len) == 0) {
592 		test_stream->rx_cnt++;
593 
594 		if (test_stream->rx_cnt >= MIN_SEND_COUNT) {
595 			/* We set the flag is just one stream has received the expected */
596 			SET_FLAG(flag_received);
597 		}
598 	} else {
599 		FAIL("Unexpected data received\n");
600 	}
601 }
602 
603 static struct bt_bap_stream_ops stream_ops = {
604 	.started = started_cb,
605 	.stopped = stopped_cb,
606 	.recv = recv_cb
607 };
608 
init(void)609 static int init(void)
610 {
611 	int err;
612 
613 	err = bt_enable(NULL);
614 	if (err) {
615 		FAIL("Bluetooth enable failed (err %d)\n", err);
616 		return err;
617 	}
618 
619 	printk("Bluetooth initialized\n");
620 
621 	err = bt_pacs_cap_register(BT_AUDIO_DIR_SINK, &cap);
622 	if (err) {
623 		FAIL("Capability register failed (err %d)\n", err);
624 		return err;
625 	}
626 
627 	/* Test invalid input */
628 	err = bt_bap_broadcast_sink_register_cb(NULL);
629 	if (err == 0) {
630 		FAIL("bt_bap_broadcast_sink_register_cb did not fail with NULL cb\n");
631 		return err;
632 	}
633 
634 	err = bt_bap_broadcast_sink_register_cb(&broadcast_sink_cbs);
635 	if (err != 0) {
636 		FAIL("Sink callback register failed (err %d)\n", err);
637 		return err;
638 	}
639 
640 	bt_bap_scan_delegator_register_cb(&scan_delegator_cbs);
641 	bt_le_per_adv_sync_cb_register(&bap_pa_sync_cb);
642 	bt_le_scan_cb_register(&bap_scan_cb);
643 
644 	UNSET_FLAG(flag_broadcaster_found);
645 	UNSET_FLAG(flag_base_received);
646 	UNSET_FLAG(flag_pa_synced);
647 
648 	for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
649 		streams[i] = bap_stream_from_audio_test_stream(&broadcast_sink_streams[i]);
650 		bt_bap_stream_cb_register(streams[i], &stream_ops);
651 	}
652 
653 	return 0;
654 }
655 
interval_to_sync_timeout(uint16_t pa_interval)656 static uint16_t interval_to_sync_timeout(uint16_t pa_interval)
657 {
658 	uint16_t pa_timeout;
659 
660 	if (pa_interval == BT_BAP_PA_INTERVAL_UNKNOWN) {
661 		/* Use maximum value to maximize chance of success */
662 		pa_timeout = BT_GAP_PER_ADV_MAX_TIMEOUT;
663 	} else {
664 		uint32_t interval_ms;
665 		uint32_t timeout;
666 
667 		/* Add retries and convert to unit in 10's of ms */
668 		interval_ms = BT_GAP_PER_ADV_INTERVAL_TO_MS(pa_interval);
669 		timeout = (interval_ms * PA_SYNC_INTERVAL_TO_TIMEOUT_RATIO) / 10;
670 
671 		/* Enforce restraints */
672 		pa_timeout = CLAMP(timeout, BT_GAP_PER_ADV_MIN_TIMEOUT, BT_GAP_PER_ADV_MAX_TIMEOUT);
673 	}
674 
675 	return pa_timeout;
676 }
677 
pa_sync_create(void)678 static int pa_sync_create(void)
679 {
680 	struct bt_le_per_adv_sync_param create_params = {0};
681 
682 	bt_addr_le_copy(&create_params.addr, &broadcaster_addr);
683 	create_params.options = BT_LE_PER_ADV_SYNC_OPT_FILTER_DUPLICATE;
684 	create_params.sid = broadcaster_info.sid;
685 	create_params.skip = PA_SYNC_SKIP;
686 	create_params.timeout = interval_to_sync_timeout(broadcaster_info.interval);
687 
688 	return bt_le_per_adv_sync_create(&create_params, &pa_sync);
689 }
test_pa_sync_delete(void)690 static void test_pa_sync_delete(void)
691 {
692 	int err;
693 
694 	err = bt_le_per_adv_sync_delete(pa_sync);
695 	if (err != 0) {
696 		FAIL("Unable to stop sink: %d", err);
697 		return;
698 	}
699 
700 	pa_sync = NULL;
701 }
702 
test_scan_and_pa_sync(void)703 static void test_scan_and_pa_sync(void)
704 {
705 	int err;
706 
707 	printk("Scanning for broadcast sources\n");
708 	err = bt_le_scan_start(BT_LE_SCAN_ACTIVE, NULL);
709 	if (err != 0) {
710 		FAIL("Unable to start scan for broadcast sources: %d", err);
711 		return;
712 	}
713 
714 	WAIT_FOR_FLAG(flag_broadcaster_found);
715 
716 	printk("Broadcast source found, stopping scan\n");
717 	err = bt_le_scan_stop();
718 	if (err != 0) {
719 		FAIL("bt_le_scan_stop failed with %d\n", err);
720 		return;
721 	}
722 
723 	printk("Scan stopped, attempting to PA sync to the broadcaster with id 0x%06X\n",
724 	       broadcaster_broadcast_id);
725 	err = pa_sync_create();
726 	if (err != 0) {
727 		FAIL("Could not create Broadcast PA sync: %d\n", err);
728 		return;
729 	}
730 
731 	printk("Waiting for PA sync\n");
732 	WAIT_FOR_FLAG(flag_pa_synced);
733 }
734 
test_broadcast_sink_create(void)735 static void test_broadcast_sink_create(void)
736 {
737 	int err;
738 
739 	printk("Creating the broadcast sink\n");
740 	err = bt_bap_broadcast_sink_create(pa_sync, broadcaster_broadcast_id, &g_sink);
741 	if (err != 0) {
742 		FAIL("Unable to create the sink: %d\n", err);
743 		return;
744 	}
745 }
746 
test_broadcast_sink_create_inval(void)747 static void test_broadcast_sink_create_inval(void)
748 {
749 	int err;
750 
751 	err = bt_bap_broadcast_sink_create(NULL, broadcaster_broadcast_id, &g_sink);
752 	if (err == 0) {
753 		FAIL("bt_bap_broadcast_sink_create did not fail with NULL sink\n");
754 		return;
755 	}
756 
757 	err = bt_bap_broadcast_sink_create(pa_sync, INVALID_BROADCAST_ID, &g_sink);
758 	if (err == 0) {
759 		FAIL("bt_bap_broadcast_sink_create did not fail with invalid broadcast ID\n");
760 		return;
761 	}
762 
763 	err = bt_bap_broadcast_sink_create(pa_sync, broadcaster_broadcast_id, NULL);
764 	if (err == 0) {
765 		FAIL("bt_bap_broadcast_sink_create did not fail with NULL sink\n");
766 		return;
767 	}
768 }
769 
test_broadcast_sync(bool encryption)770 static void test_broadcast_sync(bool encryption)
771 {
772 	int err;
773 
774 	printk("Syncing the sink\n");
775 	err = bt_bap_broadcast_sink_sync(g_sink, bis_index_bitfield, streams,
776 					 encryption ? BROADCAST_CODE : NULL);
777 	if (err != 0) {
778 		FAIL("Unable to sync the sink: %d\n", err);
779 		return;
780 	}
781 
782 	/* Wait for all to be started */
783 	printk("Waiting for streams to be started\n");
784 	for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
785 		k_sem_take(&sem_started, K_FOREVER);
786 	}
787 }
788 
test_broadcast_sync_inval(void)789 static void test_broadcast_sync_inval(void)
790 {
791 	struct bt_bap_stream *tmp_streams[ARRAY_SIZE(streams) + 1] = {0};
792 	uint32_t bis_index;
793 	int err;
794 
795 	err = bt_bap_broadcast_sink_sync(NULL, bis_index_bitfield, streams, NULL);
796 	if (err == 0) {
797 		FAIL("bt_bap_broadcast_sink_sync did not fail with NULL sink\n");
798 		return;
799 	}
800 
801 	bis_index = 0;
802 	err = bt_bap_broadcast_sink_sync(g_sink, bis_index, streams, NULL);
803 	if (err == 0) {
804 		FAIL("bt_bap_broadcast_sink_sync did not fail with invalid BIS indexes: 0x%08X\n",
805 		     bis_index);
806 		return;
807 	}
808 
809 	bis_index = BT_ISO_BIS_INDEX_BIT(BT_ISO_BIS_INDEX_MAX + 1);
810 	err = bt_bap_broadcast_sink_sync(g_sink, bis_index, streams, NULL);
811 	if (err == 0) {
812 		FAIL("bt_bap_broadcast_sink_sync did not fail with invalid BIS indexes: 0x%08X\n",
813 		     bis_index);
814 		return;
815 	}
816 
817 	err = bt_bap_broadcast_sink_sync(g_sink, bis_index, NULL, NULL);
818 	if (err == 0) {
819 		FAIL("bt_bap_broadcast_sink_sync did not fail with NULL streams\n");
820 		return;
821 	}
822 
823 	memcpy(tmp_streams, streams, sizeof(streams));
824 	bis_index = 0U;
825 	for (size_t i = 0U; i < ARRAY_SIZE(tmp_streams); i++) {
826 		bis_index |= BT_ISO_BIS_INDEX_BIT(i);
827 	}
828 
829 	err = bt_bap_broadcast_sink_sync(g_sink, bis_index, tmp_streams, NULL);
830 	if (err == 0) {
831 		FAIL("bt_bap_broadcast_sink_sync did not fail with NULL streams[%zu]\n",
832 		     ARRAY_SIZE(tmp_streams) - 1);
833 		return;
834 	}
835 
836 	bis_index = 0U;
837 	for (size_t i = 0U; i < CONFIG_BT_BAP_BROADCAST_SNK_STREAM_COUNT + 1; i++) {
838 		bis_index |= BT_ISO_BIS_INDEX_BIT(i);
839 	}
840 
841 	err = bt_bap_broadcast_sink_sync(g_sink, bis_index, tmp_streams, NULL);
842 	if (err == 0) {
843 		FAIL("bt_bap_broadcast_sink_sync did not fail with invalid BIS indexes: 0x%08X\n",
844 		     bis_index);
845 		return;
846 	}
847 }
848 
test_broadcast_stop(void)849 static void test_broadcast_stop(void)
850 {
851 	int err;
852 
853 	err = bt_bap_broadcast_sink_stop(g_sink);
854 	if (err != 0) {
855 		FAIL("Unable to stop sink: %d", err);
856 		return;
857 	}
858 
859 	printk("Waiting for streams to be stopped\n");
860 	for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
861 		k_sem_take(&sem_stopped, K_FOREVER);
862 	}
863 }
864 
test_broadcast_stop_inval(void)865 static void test_broadcast_stop_inval(void)
866 {
867 	int err;
868 
869 	err = bt_bap_broadcast_sink_stop(NULL);
870 	if (err == 0) {
871 		FAIL("bt_bap_broadcast_sink_stop did not fail with NULL sink\n");
872 		return;
873 	}
874 }
875 
test_broadcast_delete(void)876 static void test_broadcast_delete(void)
877 {
878 	int err;
879 
880 	err = bt_bap_broadcast_sink_delete(g_sink);
881 	if (err != 0) {
882 		FAIL("Unable to stop sink: %d", err);
883 		return;
884 	}
885 
886 	/* No "sync lost" event is generated when we initialized the disconnect */
887 	g_sink = NULL;
888 }
889 
test_broadcast_delete_inval(void)890 static void test_broadcast_delete_inval(void)
891 {
892 	int err;
893 
894 	err = bt_bap_broadcast_sink_delete(NULL);
895 	if (err == 0) {
896 		FAIL("bt_bap_broadcast_sink_delete did not fail with NULL sink\n");
897 		return;
898 	}
899 }
900 
test_start_adv(void)901 static void test_start_adv(void)
902 {
903 	const struct bt_data ad[] = {
904 		BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
905 		BT_DATA_BYTES(BT_DATA_UUID16_ALL, BT_UUID_16_ENCODE(BT_UUID_BASS_VAL),
906 			      BT_UUID_16_ENCODE(BT_UUID_PACS_VAL)),
907 		BT_DATA_BYTES(BT_DATA_SVC_DATA16, BT_UUID_16_ENCODE(BT_UUID_BASS_VAL)),
908 	};
909 	int err;
910 
911 	/* Create a connectable advertising set */
912 	err = bt_le_ext_adv_create(BT_LE_EXT_ADV_CONN, NULL, &ext_adv);
913 	if (err != 0) {
914 		FAIL("Failed to create advertising set (err %d)\n", err);
915 
916 		return;
917 	}
918 
919 	err = bt_le_ext_adv_set_data(ext_adv, ad, ARRAY_SIZE(ad), NULL, 0);
920 	if (err != 0) {
921 		FAIL("Failed to set advertising data (err %d)\n", err);
922 
923 		return;
924 	}
925 
926 	err = bt_le_ext_adv_start(ext_adv, BT_LE_EXT_ADV_START_DEFAULT);
927 	if (err != 0) {
928 		FAIL("Failed to start advertising set (err %d)\n", err);
929 
930 		return;
931 	}
932 }
933 
test_common(void)934 static void test_common(void)
935 {
936 	int err;
937 
938 	err = init();
939 	if (err) {
940 		FAIL("Init failed (err %d)\n", err);
941 		return;
942 	}
943 
944 	test_scan_and_pa_sync();
945 
946 	test_broadcast_sink_create_inval();
947 	test_broadcast_sink_create();
948 
949 	printk("Broadcast source PA synced, waiting for BASE\n");
950 	WAIT_FOR_FLAG(flag_base_received);
951 	printk("BASE received\n");
952 
953 	printk("Waiting for BIG syncable\n");
954 	WAIT_FOR_FLAG(flag_syncable);
955 
956 	test_broadcast_sync_inval();
957 	test_broadcast_sync(false);
958 
959 	printk("Waiting for data\n");
960 	WAIT_FOR_FLAG(flag_received);
961 	backchannel_sync_send_all(); /* let other devices know we have received what we wanted */
962 
963 	/* Ensure that we also see the metadata update */
964 	printk("Waiting for metadata update\n");
965 	WAIT_FOR_FLAG(flag_base_metadata_updated)
966 
967 	backchannel_sync_send_all(); /* let other devices know we have received what we wanted */
968 }
969 
test_main(void)970 static void test_main(void)
971 {
972 	test_common();
973 
974 	backchannel_sync_send_all(); /* let the broadcast source know it can stop */
975 
976 	/* The order of PA sync lost and BIG Sync lost is irrelevant
977 	 * and depend on timeout parameters. We just wait for PA first, but
978 	 * either way will work.
979 	 */
980 	printk("Waiting for PA disconnected\n");
981 	WAIT_FOR_FLAG(flag_pa_sync_lost);
982 
983 	printk("Waiting for streams to be stopped\n");
984 	for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
985 		k_sem_take(&sem_stopped, K_FOREVER);
986 	}
987 
988 	PASS("Broadcast sink passed\n");
989 }
990 
test_sink_disconnect(void)991 static void test_sink_disconnect(void)
992 {
993 	test_common();
994 
995 	test_broadcast_stop_inval();
996 	test_broadcast_stop();
997 
998 	/* Retry sync*/
999 	test_broadcast_sync(false);
1000 	test_broadcast_stop();
1001 
1002 	test_broadcast_delete_inval();
1003 	test_broadcast_delete();
1004 
1005 	backchannel_sync_send_all(); /* let the broadcast source know it can stop */
1006 
1007 	PASS("Broadcast sink disconnect passed\n");
1008 }
1009 
test_sink_encrypted(void)1010 static void test_sink_encrypted(void)
1011 {
1012 	int err;
1013 
1014 	err = init();
1015 	if (err) {
1016 		FAIL("Init failed (err %d)\n", err);
1017 		return;
1018 	}
1019 
1020 	test_scan_and_pa_sync();
1021 
1022 	test_broadcast_sink_create();
1023 
1024 	printk("Broadcast source PA synced, waiting for BASE\n");
1025 	WAIT_FOR_FLAG(flag_base_received);
1026 	printk("BASE received\n");
1027 
1028 	printk("Waiting for BIG syncable\n");
1029 	WAIT_FOR_FLAG(flag_syncable);
1030 
1031 	test_broadcast_sync(true);
1032 
1033 	printk("Waiting for data\n");
1034 	WAIT_FOR_FLAG(flag_received);
1035 
1036 	backchannel_sync_send_all(); /* let other devices know we have received data */
1037 
1038 	backchannel_sync_send_all(); /* let the broadcast source know it can stop */
1039 
1040 	/* The order of PA sync lost and BIG Sync lost is irrelevant
1041 	 * and depend on timeout parameters. We just wait for PA first, but
1042 	 * either way will work.
1043 	 */
1044 	printk("Waiting for PA disconnected\n");
1045 	WAIT_FOR_FLAG(flag_pa_sync_lost);
1046 
1047 	printk("Waiting for streams to be stopped\n");
1048 	for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
1049 		k_sem_take(&sem_stopped, K_FOREVER);
1050 	}
1051 
1052 	PASS("Broadcast sink passed\n");
1053 }
1054 
broadcast_sink_with_assistant(void)1055 static void broadcast_sink_with_assistant(void)
1056 {
1057 	int err;
1058 
1059 	err = init();
1060 	if (err) {
1061 		FAIL("Init failed (err %d)\n", err);
1062 		return;
1063 	}
1064 
1065 	test_start_adv();
1066 	WAIT_FOR_FLAG(flag_connected);
1067 
1068 	printk("Waiting for PA sync request\n");
1069 	WAIT_FOR_FLAG(flag_pa_request);
1070 
1071 	test_scan_and_pa_sync();
1072 	test_broadcast_sink_create();
1073 
1074 	printk("Broadcast source PA synced, waiting for BASE\n");
1075 	WAIT_FOR_FLAG(flag_base_received);
1076 	printk("BASE received\n");
1077 
1078 	printk("Waiting for BIG syncable\n");
1079 	WAIT_FOR_FLAG(flag_syncable);
1080 
1081 	printk("Waiting for BIG sync request\n");
1082 	WAIT_FOR_FLAG(flag_bis_sync_requested);
1083 	test_broadcast_sync(false);
1084 
1085 	printk("Waiting for data\n");
1086 	WAIT_FOR_FLAG(flag_received);
1087 	backchannel_sync_send_all(); /* let other devices know we have received what we wanted */
1088 
1089 	/* Ensure that we also see the metadata update */
1090 	printk("Waiting for metadata update\n");
1091 	WAIT_FOR_FLAG(flag_base_metadata_updated)
1092 	backchannel_sync_send_all(); /* let other devices know we have received what we wanted */
1093 
1094 	printk("Waiting for BIG sync terminate request\n");
1095 	WAIT_FOR_UNSET_FLAG(flag_bis_sync_requested);
1096 	test_broadcast_stop();
1097 
1098 	printk("Waiting for PA sync terminate request\n");
1099 	WAIT_FOR_UNSET_FLAG(flag_pa_request);
1100 	test_pa_sync_delete();
1101 	test_broadcast_delete();
1102 
1103 	backchannel_sync_send_all(); /* let the broadcast source know it can stop */
1104 
1105 	PASS("Broadcast sink with assistant passed\n");
1106 }
1107 
1108 static const struct bst_test_instance test_broadcast_sink[] = {
1109 	{
1110 		.test_id = "broadcast_sink",
1111 		.test_pre_init_f = test_init,
1112 		.test_tick_f = test_tick,
1113 		.test_main_f = test_main,
1114 	},
1115 	{
1116 		.test_id = "broadcast_sink_disconnect",
1117 		.test_pre_init_f = test_init,
1118 		.test_tick_f = test_tick,
1119 		.test_main_f = test_sink_disconnect,
1120 	},
1121 	{
1122 		.test_id = "broadcast_sink_encrypted",
1123 		.test_pre_init_f = test_init,
1124 		.test_tick_f = test_tick,
1125 		.test_main_f = test_sink_encrypted,
1126 	},
1127 	{
1128 		.test_id = "broadcast_sink_with_assistant",
1129 		.test_pre_init_f = test_init,
1130 		.test_tick_f = test_tick,
1131 		.test_main_f = broadcast_sink_with_assistant,
1132 	},
1133 	BSTEST_END_MARKER,
1134 };
1135 
test_broadcast_sink_install(struct bst_test_list * tests)1136 struct bst_test_list *test_broadcast_sink_install(struct bst_test_list *tests)
1137 {
1138 	return bst_add_tests(tests, test_broadcast_sink);
1139 }
1140 
1141 #else /* !CONFIG_BT_BAP_BROADCAST_SINK */
1142 
test_broadcast_sink_install(struct bst_test_list * tests)1143 struct bst_test_list *test_broadcast_sink_install(struct bst_test_list *tests)
1144 {
1145 	return tests;
1146 }
1147 
1148 #endif /* CONFIG_BT_BAP_BROADCAST_SINK */
1149