1 /*
2  * Copyright (c) 2022-2024 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <string.h>
11 
12 #include <zephyr/autoconf.h>
13 #include <zephyr/bluetooth/audio/audio.h>
14 #include <zephyr/bluetooth/audio/bap.h>
15 #include <zephyr/bluetooth/audio/bap_lc3_preset.h>
16 #include <zephyr/bluetooth/bluetooth.h>
17 #include <zephyr/bluetooth/byteorder.h>
18 #include <zephyr/bluetooth/gap.h>
19 #include <zephyr/bluetooth/iso.h>
20 #include <zephyr/bluetooth/uuid.h>
21 #include <zephyr/device.h>
22 #include <zephyr/devicetree.h>
23 #include <zephyr/kernel.h>
24 #include <zephyr/net_buf.h>
25 #include <zephyr/sys/printk.h>
26 #include <zephyr/sys/util.h>
27 #include <zephyr/sys_clock.h>
28 #include <zephyr/toolchain.h>
29 
30 BUILD_ASSERT(strlen(CONFIG_BROADCAST_CODE) <= BT_ISO_BROADCAST_CODE_SIZE, "Invalid broadcast code");
31 
32 /* Zephyr Controller works best while Extended Advertising interval to be a multiple
33  * of the ISO Interval minus 10 ms (max. advertising random delay). This is
34  * required to place the AUX_ADV_IND PDUs in a non-overlapping interval with the
35  * Broadcast ISO radio events.
36  *
37  * I.e. for a 7.5 ms ISO interval use 90 ms minus 10 ms ==> 80 ms advertising
38  * interval.
39  * And, for 10 ms ISO interval, can use 90 ms minus 10 ms ==> 80 ms advertising
40  * interval.
41  */
42 #define BT_LE_EXT_ADV_CUSTOM                                                                       \
43 	BT_LE_ADV_PARAM(BT_LE_ADV_OPT_EXT_ADV, BT_GAP_MS_TO_ADV_INTERVAL(80),                      \
44 			BT_GAP_MS_TO_ADV_INTERVAL(80), NULL)
45 
46 /* When BROADCAST_ENQUEUE_COUNT > 1 we can enqueue enough buffers to ensure that
47  * the controller is never idle
48  */
49 #define BROADCAST_ENQUEUE_COUNT 3U
50 #define TOTAL_BUF_NEEDED        (BROADCAST_ENQUEUE_COUNT * CONFIG_BT_BAP_BROADCAST_SRC_STREAM_COUNT)
51 
52 BUILD_ASSERT(CONFIG_BT_ISO_TX_BUF_COUNT >= TOTAL_BUF_NEEDED,
53 	     "CONFIG_BT_ISO_TX_BUF_COUNT should be at least "
54 	     "BROADCAST_ENQUEUE_COUNT * CONFIG_BT_BAP_BROADCAST_SRC_STREAM_COUNT");
55 
56 #if defined(CONFIG_BAP_BROADCAST_16_2_1)
57 
58 static struct bt_bap_lc3_preset preset_active = BT_BAP_LC3_BROADCAST_PRESET_16_2_1(
59 	BT_AUDIO_LOCATION_FRONT_LEFT | BT_AUDIO_LOCATION_FRONT_RIGHT,
60 	BT_AUDIO_CONTEXT_TYPE_UNSPECIFIED);
61 
62 #define BROADCAST_SAMPLE_RATE 16000
63 
64 #elif defined(CONFIG_BAP_BROADCAST_24_2_1)
65 
66 static struct bt_bap_lc3_preset preset_active = BT_BAP_LC3_BROADCAST_PRESET_24_2_1(
67 	BT_AUDIO_LOCATION_FRONT_LEFT | BT_AUDIO_LOCATION_FRONT_RIGHT,
68 	BT_AUDIO_CONTEXT_TYPE_UNSPECIFIED);
69 
70 #define BROADCAST_SAMPLE_RATE 24000
71 
72 #endif
73 
74 #if defined(CONFIG_BAP_BROADCAST_16_2_1)
75 #define MAX_SAMPLE_RATE 16000
76 #elif defined(CONFIG_BAP_BROADCAST_24_2_1)
77 #define MAX_SAMPLE_RATE 24000
78 #endif
79 #define MAX_FRAME_DURATION_US 10000
80 #define MAX_NUM_SAMPLES       ((MAX_FRAME_DURATION_US * MAX_SAMPLE_RATE) / USEC_PER_SEC)
81 
82 #if defined(CONFIG_LIBLC3)
83 #include "lc3.h"
84 
85 #if defined(CONFIG_USB_DEVICE_AUDIO)
86 #include <zephyr/usb/usb_device.h>
87 #include <zephyr/usb/class/usb_audio.h>
88 #include <zephyr/sys/ring_buffer.h>
89 
90 /* USB Audio Data is downsampled from 48kHz to match broadcast preset when receiving data */
91 #define USB_SAMPLE_RATE       48000
92 #define USB_DOWNSAMPLE_RATE   BROADCAST_SAMPLE_RATE
93 #define USB_FRAME_DURATION_US 1000
94 #define USB_NUM_SAMPLES       ((USB_FRAME_DURATION_US * USB_DOWNSAMPLE_RATE) / USEC_PER_SEC)
95 #define USB_BYTES_PER_SAMPLE  2
96 #define USB_CHANNELS          2
97 
98 #define RING_BUF_USB_FRAMES  20
99 #define AUDIO_RING_BUF_BYTES (USB_NUM_SAMPLES * USB_BYTES_PER_SAMPLE * RING_BUF_USB_FRAMES)
100 #else /* !defined(CONFIG_USB_DEVICE_AUDIO) */
101 
102 #include <math.h>
103 
104 #define AUDIO_VOLUME            (INT16_MAX - 3000) /* codec does clipping above INT16_MAX - 3000 */
105 #define AUDIO_TONE_FREQUENCY_HZ 400
106 
107 /**
108  * Use the math lib to generate a sine-wave using 16 bit samples into a buffer.
109  *
110  * @param buf Destination buffer
111  * @param length_us Length of the buffer in microseconds
112  * @param frequency_hz frequency in Hz
113  * @param sample_rate_hz sample-rate in Hz.
114  */
fill_audio_buf_sin(int16_t * buf,int length_us,int frequency_hz,int sample_rate_hz)115 static void fill_audio_buf_sin(int16_t *buf, int length_us, int frequency_hz, int sample_rate_hz)
116 {
117 	const int sine_period_samples = sample_rate_hz / frequency_hz;
118 	const unsigned int num_samples = (length_us * sample_rate_hz) / USEC_PER_SEC;
119 	const float step = 2 * 3.1415f / sine_period_samples;
120 
121 	for (unsigned int i = 0; i < num_samples; i++) {
122 		const float sample = sinf(i * step);
123 
124 		buf[i] = (int16_t)(AUDIO_VOLUME * sample);
125 	}
126 }
127 #endif /* defined(CONFIG_USB_DEVICE_AUDIO) */
128 #endif /* defined(CONFIG_LIBLC3) */
129 
130 static struct broadcast_source_stream {
131 	struct bt_bap_stream stream;
132 	uint16_t seq_num;
133 	size_t sent_cnt;
134 #if defined(CONFIG_LIBLC3)
135 	lc3_encoder_t lc3_encoder;
136 #if defined(CONFIG_BAP_BROADCAST_16_2_1)
137 	lc3_encoder_mem_16k_t lc3_encoder_mem;
138 #elif defined(CONFIG_BAP_BROADCAST_24_2_1)
139 	lc3_encoder_mem_48k_t lc3_encoder_mem;
140 #endif
141 #if defined(CONFIG_USB_DEVICE_AUDIO)
142 	struct ring_buf audio_ring_buf;
143 	uint8_t _ring_buffer_memory[AUDIO_RING_BUF_BYTES];
144 #endif /* defined(CONFIG_USB_DEVICE_AUDIO) */
145 #endif /* defined(CONFIG_LIBLC3) */
146 } streams[CONFIG_BT_BAP_BROADCAST_SRC_STREAM_COUNT];
147 static struct bt_bap_broadcast_source *broadcast_source;
148 
149 NET_BUF_POOL_FIXED_DEFINE(tx_pool, TOTAL_BUF_NEEDED, BT_ISO_SDU_BUF_SIZE(CONFIG_BT_ISO_TX_MTU),
150 			  CONFIG_BT_CONN_TX_USER_DATA_SIZE, NULL);
151 
152 static int16_t send_pcm_data[MAX_NUM_SAMPLES];
153 static uint16_t seq_num;
154 static bool stopping;
155 
156 static K_SEM_DEFINE(sem_started, 0U, 1U);
157 static K_SEM_DEFINE(sem_stopped, 0U, 1U);
158 
159 #define BROADCAST_SOURCE_LIFETIME 120U /* seconds */
160 
161 #if defined(CONFIG_LIBLC3)
162 static int freq_hz;
163 static int frame_duration_us;
164 static int frames_per_sdu;
165 static int octets_per_frame;
166 
167 static K_SEM_DEFINE(lc3_encoder_sem, 0U, TOTAL_BUF_NEEDED);
168 #endif
169 
send_data(struct broadcast_source_stream * source_stream)170 static void send_data(struct broadcast_source_stream *source_stream)
171 {
172 	struct bt_bap_stream *stream = &source_stream->stream;
173 	struct net_buf *buf;
174 	int ret;
175 
176 	if (stopping) {
177 		return;
178 	}
179 
180 	buf = net_buf_alloc(&tx_pool, K_FOREVER);
181 	if (buf == NULL) {
182 		printk("Could not allocate buffer when sending on %p\n", stream);
183 		return;
184 	}
185 
186 	net_buf_reserve(buf, BT_ISO_CHAN_SEND_RESERVE);
187 #if defined(CONFIG_LIBLC3)
188 	uint8_t lc3_encoded_buffer[preset_active.qos.sdu];
189 
190 	if (source_stream->lc3_encoder == NULL) {
191 		printk("LC3 encoder not setup, cannot encode data.\n");
192 		net_buf_unref(buf);
193 		return;
194 	}
195 
196 #if defined(CONFIG_USB_DEVICE_AUDIO)
197 	uint32_t size = ring_buf_get(&source_stream->audio_ring_buf, (uint8_t *)send_pcm_data,
198 				     sizeof(send_pcm_data));
199 
200 	if (size < sizeof(send_pcm_data)) {
201 		const size_t padding_size = sizeof(send_pcm_data) - size;
202 
203 		printk("Not enough bytes ready, padding %d!\n", padding_size);
204 		memset(&((uint8_t *)send_pcm_data)[size], 0, padding_size);
205 	}
206 #endif
207 
208 	ret = lc3_encode(source_stream->lc3_encoder, LC3_PCM_FORMAT_S16, send_pcm_data, 1,
209 			 octets_per_frame, lc3_encoded_buffer);
210 	if (ret == -1) {
211 		printk("LC3 encoder failed - wrong parameters?: %d", ret);
212 		net_buf_unref(buf);
213 		return;
214 	}
215 
216 	net_buf_add_mem(buf, lc3_encoded_buffer, preset_active.qos.sdu);
217 #else
218 	net_buf_add_mem(buf, send_pcm_data, preset_active.qos.sdu);
219 #endif /* defined(CONFIG_LIBLC3) */
220 
221 	ret = bt_bap_stream_send(stream, buf, source_stream->seq_num++);
222 	if (ret < 0) {
223 		/* This will end broadcasting on this stream. */
224 		printk("Unable to broadcast data on %p: %d\n", stream, ret);
225 		net_buf_unref(buf);
226 		return;
227 	}
228 
229 	source_stream->sent_cnt++;
230 	if ((source_stream->sent_cnt % 1000U) == 0U) {
231 		printk("Stream %p: Sent %u total ISO packets\n", stream, source_stream->sent_cnt);
232 	}
233 }
234 
235 #if defined(CONFIG_LIBLC3)
init_lc3_thread(void * arg1,void * arg2,void * arg3)236 static void init_lc3_thread(void *arg1, void *arg2, void *arg3)
237 {
238 	const struct bt_audio_codec_cfg *codec_cfg = &preset_active.codec_cfg;
239 	int ret;
240 
241 	ret = bt_audio_codec_cfg_get_freq(codec_cfg);
242 	if (ret > 0) {
243 		freq_hz = bt_audio_codec_cfg_freq_to_freq_hz(ret);
244 	} else {
245 		return;
246 	}
247 
248 	ret = bt_audio_codec_cfg_get_frame_dur(codec_cfg);
249 	if (ret > 0) {
250 		frame_duration_us = bt_audio_codec_cfg_frame_dur_to_frame_dur_us(ret);
251 	} else {
252 		printk("Error: Frame duration not set, cannot start codec.");
253 		return;
254 	}
255 
256 	octets_per_frame = bt_audio_codec_cfg_get_octets_per_frame(codec_cfg);
257 	frames_per_sdu = bt_audio_codec_cfg_get_frame_blocks_per_sdu(codec_cfg, true);
258 
259 	if (freq_hz < 0) {
260 		printk("Error: Codec frequency not set, cannot start codec.");
261 		return;
262 	}
263 
264 	if (frame_duration_us < 0) {
265 		printk("Error: Frame duration not set, cannot start codec.");
266 		return;
267 	}
268 
269 	if (octets_per_frame < 0) {
270 		printk("Error: Octets per frame not set, cannot start codec.");
271 		return;
272 	}
273 
274 #if !defined(CONFIG_USB_DEVICE_AUDIO)
275 	/* If USB is not used as a sound source, generate a sine wave */
276 	fill_audio_buf_sin(send_pcm_data, frame_duration_us, AUDIO_TONE_FREQUENCY_HZ, freq_hz);
277 #endif
278 
279 	/* Create the encoder instance. This shall complete before stream_started() is called. */
280 	for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
281 		printk("Initializing lc3 encoder for stream %zu\n", i);
282 		streams[i].lc3_encoder = lc3_setup_encoder(frame_duration_us, freq_hz, 0,
283 							   &streams[i].lc3_encoder_mem);
284 
285 		if (streams[i].lc3_encoder == NULL) {
286 			printk("ERROR: Failed to setup LC3 encoder - wrong parameters?\n");
287 		}
288 	}
289 
290 	while (true) {
291 		for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
292 			k_sem_take(&lc3_encoder_sem, K_FOREVER);
293 		}
294 		for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
295 			send_data(&streams[i]);
296 		}
297 	}
298 }
299 
300 #define LC3_ENCODER_STACK_SIZE 4 * 4096
301 #define LC3_ENCODER_PRIORITY   5
302 
303 K_THREAD_DEFINE(encoder, LC3_ENCODER_STACK_SIZE, init_lc3_thread, NULL, NULL, NULL,
304 		LC3_ENCODER_PRIORITY, 0, -1);
305 
306 #if defined(CONFIG_USB_DEVICE_AUDIO)
data_received(const struct device * dev,struct net_buf * buffer,size_t size)307 static void data_received(const struct device *dev, struct net_buf *buffer, size_t size)
308 {
309 	static int count;
310 	int16_t *pcm;
311 	int nsamples, ratio;
312 	int16_t usb_pcm_data[USB_CHANNELS][USB_NUM_SAMPLES];
313 
314 	if (!buffer) {
315 		return;
316 	}
317 
318 	if (!size) {
319 		net_buf_unref(buffer);
320 		return;
321 	}
322 
323 	pcm = (int16_t *)net_buf_pull_mem(buffer, size);
324 
325 	/* 'size' is in bytes, containing 1ms, 48kHz, stereo, 2 bytes per sample.
326 	 * Take left channel and do a simple downsample to 16kHz/24Khz
327 	 * matching the broadcast preset.
328 	 */
329 
330 	ratio = USB_SAMPLE_RATE / USB_DOWNSAMPLE_RATE;
331 	nsamples = size / (sizeof(int16_t) * USB_CHANNELS * ratio);
332 	for (size_t i = 0, j = 0; i < nsamples; i++, j += USB_CHANNELS * ratio) {
333 		usb_pcm_data[0][i] = pcm[j];
334 		usb_pcm_data[1][i] = pcm[j + 1];
335 	}
336 
337 	for (size_t i = 0U; i < MIN(ARRAY_SIZE(streams), 2); i++) {
338 		const uint32_t size_put =
339 			ring_buf_put(&(streams[i].audio_ring_buf), (uint8_t *)(usb_pcm_data[i]),
340 				     nsamples * USB_BYTES_PER_SAMPLE);
341 		if (size_put < nsamples * USB_BYTES_PER_SAMPLE) {
342 			printk("Not enough room for samples in %s buffer: %u < %u, total capacity: "
343 			       "%u\n",
344 			       i == 0 ? "left" : "right", size_put, nsamples * USB_BYTES_PER_SAMPLE,
345 			       ring_buf_capacity_get(&(streams[i].audio_ring_buf)));
346 		}
347 	}
348 
349 	count++;
350 	if ((count % 1000) == 0) {
351 		printk("USB Data received (count = %d)\n", count);
352 	}
353 
354 	net_buf_unref(buffer);
355 }
356 
357 static const struct usb_audio_ops ops = {.data_received_cb = data_received};
358 #endif /* defined(CONFIG_USB_DEVICE_AUDIO) */
359 #endif /* defined(CONFIG_LIBLC3) */
360 
stream_started_cb(struct bt_bap_stream * stream)361 static void stream_started_cb(struct bt_bap_stream *stream)
362 {
363 	struct broadcast_source_stream *source_stream =
364 		CONTAINER_OF(stream, struct broadcast_source_stream, stream);
365 
366 	source_stream->seq_num = 0U;
367 	source_stream->sent_cnt = 0U;
368 }
369 
stream_sent_cb(struct bt_bap_stream * stream)370 static void stream_sent_cb(struct bt_bap_stream *stream)
371 {
372 #if defined(CONFIG_LIBLC3)
373 	k_sem_give(&lc3_encoder_sem);
374 #else
375 	/* If no LC3 encoder is used, just send mock data directly */
376 	struct broadcast_source_stream *source_stream =
377 		CONTAINER_OF(stream, struct broadcast_source_stream, stream);
378 
379 	send_data(source_stream);
380 #endif
381 }
382 
383 static struct bt_bap_stream_ops stream_ops = {
384 	.started = stream_started_cb,
385 	.sent = stream_sent_cb,
386 };
387 
setup_broadcast_source(struct bt_bap_broadcast_source ** source)388 static int setup_broadcast_source(struct bt_bap_broadcast_source **source)
389 {
390 	struct bt_bap_broadcast_source_stream_param
391 		stream_params[CONFIG_BT_BAP_BROADCAST_SRC_STREAM_COUNT];
392 	struct bt_bap_broadcast_source_subgroup_param
393 		subgroup_param[CONFIG_BT_BAP_BROADCAST_SRC_SUBGROUP_COUNT];
394 	struct bt_bap_broadcast_source_param create_param = {0};
395 	const size_t streams_per_subgroup = ARRAY_SIZE(stream_params) / ARRAY_SIZE(subgroup_param);
396 	uint8_t left[] = {BT_AUDIO_CODEC_DATA(BT_AUDIO_CODEC_CFG_CHAN_ALLOC,
397 					      BT_BYTES_LIST_LE32(BT_AUDIO_LOCATION_FRONT_LEFT))};
398 	uint8_t right[] = {BT_AUDIO_CODEC_DATA(BT_AUDIO_CODEC_CFG_CHAN_ALLOC,
399 					       BT_BYTES_LIST_LE32(BT_AUDIO_LOCATION_FRONT_RIGHT))};
400 	int err;
401 
402 	for (size_t i = 0U; i < ARRAY_SIZE(subgroup_param); i++) {
403 		subgroup_param[i].params_count = streams_per_subgroup;
404 		subgroup_param[i].params = stream_params + i * streams_per_subgroup;
405 		subgroup_param[i].codec_cfg = &preset_active.codec_cfg;
406 	}
407 
408 	for (size_t j = 0U; j < ARRAY_SIZE(stream_params); j++) {
409 		stream_params[j].stream = &streams[j].stream;
410 		stream_params[j].data = j == 0 ? left : right;
411 		stream_params[j].data_len = j == 0 ? sizeof(left) : sizeof(right);
412 		bt_bap_stream_cb_register(stream_params[j].stream, &stream_ops);
413 	}
414 
415 	create_param.params_count = ARRAY_SIZE(subgroup_param);
416 	create_param.params = subgroup_param;
417 	create_param.qos = &preset_active.qos;
418 	create_param.encryption = strlen(CONFIG_BROADCAST_CODE) > 0;
419 	create_param.packing = BT_ISO_PACKING_SEQUENTIAL;
420 
421 	if (create_param.encryption) {
422 		memcpy(create_param.broadcast_code, CONFIG_BROADCAST_CODE,
423 		       strlen(CONFIG_BROADCAST_CODE));
424 	}
425 
426 	printk("Creating broadcast source with %zu subgroups with %zu streams\n",
427 	       ARRAY_SIZE(subgroup_param), ARRAY_SIZE(subgroup_param) * streams_per_subgroup);
428 
429 	err = bt_bap_broadcast_source_create(&create_param, source);
430 	if (err != 0) {
431 		printk("Unable to create broadcast source: %d\n", err);
432 		return err;
433 	}
434 
435 	return 0;
436 }
437 
source_started_cb(struct bt_bap_broadcast_source * source)438 static void source_started_cb(struct bt_bap_broadcast_source *source)
439 {
440 	printk("Broadcast source %p started\n", source);
441 	k_sem_give(&sem_started);
442 }
443 
source_stopped_cb(struct bt_bap_broadcast_source * source,uint8_t reason)444 static void source_stopped_cb(struct bt_bap_broadcast_source *source, uint8_t reason)
445 {
446 	printk("Broadcast source %p stopped with reason 0x%02X\n", source, reason);
447 	k_sem_give(&sem_stopped);
448 }
449 
main(void)450 int main(void)
451 {
452 	static struct bt_bap_broadcast_source_cb broadcast_source_cb = {
453 		.started = source_started_cb,
454 		.stopped = source_stopped_cb,
455 	};
456 	struct bt_le_ext_adv *adv;
457 	int err;
458 
459 	err = bt_enable(NULL);
460 	if (err) {
461 		printk("Bluetooth init failed (err %d)\n", err);
462 		return 0;
463 	}
464 	printk("Bluetooth initialized\n");
465 
466 	err = bt_bap_broadcast_source_register_cb(&broadcast_source_cb);
467 	if (err != 0) {
468 		printk("Failed to register broadcast source callbacks (err %d)\n", err);
469 		return 0;
470 	}
471 
472 	for (size_t i = 0U; i < ARRAY_SIZE(send_pcm_data); i++) {
473 		/* Initialize mock data */
474 		send_pcm_data[i] = i;
475 	}
476 
477 #if defined(CONFIG_LIBLC3)
478 #if defined(CONFIG_USB_DEVICE_AUDIO)
479 	const struct device *hs_dev;
480 
481 	hs_dev = DEVICE_DT_GET(DT_NODELABEL(hs_0));
482 
483 	if (!device_is_ready(hs_dev)) {
484 		printk("Device USB Headset is not ready\n");
485 		return 0;
486 	}
487 
488 	printk("Found USB Headset Device\n");
489 
490 	(void)memset(streams, 0, sizeof(streams));
491 
492 	for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
493 		ring_buf_init(&(streams[i].audio_ring_buf), sizeof(streams[i]._ring_buffer_memory),
494 			      streams[i]._ring_buffer_memory);
495 		printk("Initialized ring buf %zu: capacity: %u\n", i,
496 		       ring_buf_capacity_get(&(streams[i].audio_ring_buf)));
497 	}
498 
499 	usb_audio_register(hs_dev, &ops);
500 
501 	err = usb_enable(NULL);
502 	if (err && err != -EALREADY) {
503 		printk("Failed to enable USB (%d)", err);
504 		return 0;
505 	}
506 
507 #endif /* defined(CONFIG_USB_DEVICE_AUDIO) */
508 	k_thread_start(encoder);
509 #endif /* defined(CONFIG_LIBLC3) */
510 
511 	while (true) {
512 		/* Broadcast Audio Streaming Endpoint advertising data */
513 		NET_BUF_SIMPLE_DEFINE(ad_buf, BT_UUID_SIZE_16 + BT_AUDIO_BROADCAST_ID_SIZE);
514 		NET_BUF_SIMPLE_DEFINE(base_buf, 128);
515 		struct bt_data ext_ad[2];
516 		struct bt_data per_ad;
517 		uint32_t broadcast_id;
518 
519 		/* Create a connectable advertising set */
520 		err = bt_le_ext_adv_create(BT_LE_EXT_ADV_CUSTOM, NULL, &adv);
521 		if (err != 0) {
522 			printk("Unable to create extended advertising set: %d\n", err);
523 			return 0;
524 		}
525 
526 		/* Set periodic advertising parameters */
527 		err = bt_le_per_adv_set_param(adv, BT_LE_PER_ADV_DEFAULT);
528 		if (err) {
529 			printk("Failed to set periodic advertising parameters (err %d)\n", err);
530 			return 0;
531 		}
532 
533 		printk("Creating broadcast source\n");
534 		err = setup_broadcast_source(&broadcast_source);
535 		if (err != 0) {
536 			printk("Unable to setup broadcast source: %d\n", err);
537 			return 0;
538 		}
539 
540 #if defined(CONFIG_STATIC_BROADCAST_ID)
541 		broadcast_id = CONFIG_BROADCAST_ID;
542 #else
543 		err = bt_rand(&broadcast_id, BT_AUDIO_BROADCAST_ID_SIZE);
544 		if (err) {
545 			printk("Unable to generate broadcast ID: %d\n", err);
546 			return err;
547 		}
548 #endif /* CONFIG_STATIC_BROADCAST_ID */
549 
550 		/* Setup extended advertising data */
551 		net_buf_simple_add_le16(&ad_buf, BT_UUID_BROADCAST_AUDIO_VAL);
552 		net_buf_simple_add_le24(&ad_buf, broadcast_id);
553 		ext_ad[0].type = BT_DATA_SVC_DATA16;
554 		ext_ad[0].data_len = ad_buf.len;
555 		ext_ad[0].data = ad_buf.data;
556 		ext_ad[1] = (struct bt_data)BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME,
557 						    sizeof(CONFIG_BT_DEVICE_NAME) - 1);
558 		err = bt_le_ext_adv_set_data(adv, ext_ad, 2, NULL, 0);
559 		if (err != 0) {
560 			printk("Failed to set extended advertising data: %d\n", err);
561 			return 0;
562 		}
563 
564 		/* Setup periodic advertising data */
565 		err = bt_bap_broadcast_source_get_base(broadcast_source, &base_buf);
566 		if (err != 0) {
567 			printk("Failed to get encoded BASE: %d\n", err);
568 			return 0;
569 		}
570 
571 		per_ad.type = BT_DATA_SVC_DATA16;
572 		per_ad.data_len = base_buf.len;
573 		per_ad.data = base_buf.data;
574 		err = bt_le_per_adv_set_data(adv, &per_ad, 1);
575 		if (err != 0) {
576 			printk("Failed to set periodic advertising data: %d\n", err);
577 			return 0;
578 		}
579 
580 		/* Start extended advertising */
581 		err = bt_le_ext_adv_start(adv, BT_LE_EXT_ADV_START_DEFAULT);
582 		if (err) {
583 			printk("Failed to start extended advertising: %d\n", err);
584 			return 0;
585 		}
586 
587 		/* Enable Periodic Advertising */
588 		err = bt_le_per_adv_start(adv);
589 		if (err) {
590 			printk("Failed to enable periodic advertising: %d\n", err);
591 			return 0;
592 		}
593 
594 		printk("Starting broadcast source\n");
595 		stopping = false;
596 		err = bt_bap_broadcast_source_start(broadcast_source, adv);
597 		if (err != 0) {
598 			printk("Unable to start broadcast source: %d\n", err);
599 			return 0;
600 		}
601 
602 		/* Wait for broadcast source to be started */
603 		k_sem_take(&sem_started, K_FOREVER);
604 		printk("Broadcast source started\n");
605 
606 		/* Initialize sending */
607 		for (size_t i = 0U; i < ARRAY_SIZE(streams); i++) {
608 			for (unsigned int j = 0U; j < BROADCAST_ENQUEUE_COUNT; j++) {
609 				stream_sent_cb(&streams[i].stream);
610 			}
611 		}
612 
613 #if defined(CONFIG_LIBLC3) && defined(CONFIG_USB_DEVICE_AUDIO)
614 		/* Never stop streaming when using USB Audio as input */
615 		k_sleep(K_FOREVER);
616 #endif /* defined(CONFIG_LIBLC3) && defined(CONFIG_USB_DEVICE_AUDIO) */
617 		printk("Waiting %u seconds before stopped\n", BROADCAST_SOURCE_LIFETIME);
618 		k_sleep(K_SECONDS(BROADCAST_SOURCE_LIFETIME));
619 		printk("Stopping broadcast source\n");
620 		stopping = true;
621 		err = bt_bap_broadcast_source_stop(broadcast_source);
622 		if (err != 0) {
623 			printk("Unable to stop broadcast source: %d\n", err);
624 			return 0;
625 		}
626 
627 		/* Wait for broadcast source to be stopped */
628 		k_sem_take(&sem_stopped, K_FOREVER);
629 		printk("Broadcast source stopped\n");
630 
631 		printk("Deleting broadcast source\n");
632 		err = bt_bap_broadcast_source_delete(broadcast_source);
633 		if (err != 0) {
634 			printk("Unable to delete broadcast source: %d\n", err);
635 			return 0;
636 		}
637 		printk("Broadcast source deleted\n");
638 		broadcast_source = NULL;
639 		seq_num = 0;
640 
641 		err = bt_le_per_adv_stop(adv);
642 		if (err) {
643 			printk("Failed to stop periodic advertising (err %d)\n", err);
644 			return 0;
645 		}
646 
647 		err = bt_le_ext_adv_stop(adv);
648 		if (err) {
649 			printk("Failed to stop extended advertising (err %d)\n", err);
650 			return 0;
651 		}
652 
653 		err = bt_le_ext_adv_delete(adv);
654 		if (err) {
655 			printk("Failed to delete extended advertising (err %d)\n", err);
656 			return 0;
657 		}
658 	}
659 	return 0;
660 }
661