xref: /btstack/test/le_audio/le_audio_broadcast_sink.c (revision c518ce542f4804ef73024eb6e87a1f249a027c59)
1 /*
2  * Copyright (C) 2022 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "le_audio_broadcast_sink.c"
39 
40 /*
41  * LE Audio Broadcast Sink
42  */
43 
44 
45 #include "btstack_config.h"
46 
47 #include <stdint.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <inttypes.h>
52 
53 #include "ad_parser.h"
54 #include "ble/gatt-service/broadcast_audio_scan_service_server.h"
55 #include "ble/att_server.h"
56 #include "ble/sm.h"
57 #include "bluetooth_data_types.h"
58 #include "bluetooth_gatt.h"
59 #include "btstack_debug.h"
60 #include "btstack_audio.h"
61 #include "btstack_event.h"
62 #include "btstack_run_loop.h"
63 #include "btstack_ring_buffer.h"
64 #include "btstack_stdin.h"
65 #include "btstack_util.h"
66 #include "gap.h"
67 #include "hci.h"
68 #include "hci_cmd.h"
69 #include "btstack_lc3.h"
70 #include "btstack_lc3_google.h"
71 #include "btstack_lc3plus_fraunhofer.h"
72 #include "l2cap.h"
73 #include "le-audio/le_audio_base_parser.h"
74 
75 #include "le_audio_broadcast_sink.h"
76 
77 #ifdef HAVE_POSIX_FILE_IO
78 #include "wav_util.h"
79 #endif
80 
81 // max config
82 #define MAX_NUM_BIS 2
83 #define MAX_SAMPLES_PER_FRAME 480
84 
85 // playback
86 #define MAX_NUM_LC3_FRAMES   5
87 #define MAX_BYTES_PER_SAMPLE 4
88 #define PLAYBACK_BUFFER_SIZE (MAX_NUM_LC3_FRAMES * MAX_SAMPLES_PER_FRAME * MAX_BYTES_PER_SAMPLE)
89 
90 // analysis
91 #define PACKET_PREFIX_LEN 10
92 
93 #define ANSI_COLOR_RED     "\x1b[31m"
94 #define ANSI_COLOR_GREEN   "\x1b[32m"
95 #define ANSI_COLOR_YELLOW  "\x1b[33m"
96 #define ANSI_COLOR_BLUE    "\x1b[34m"
97 #define ANSI_COLOR_MAGENTA "\x1b[35m"
98 #define ANSI_COLOR_CYAN    "\x1b[36m"
99 #define ANSI_COLOR_RESET   "\x1b[0m"
100 
101 static void show_usage(void);
102 
103 static const char * filename_wav = "le_audio_broadcast_sink.wav";
104 
105 static enum {
106     APP_W4_WORKING,
107     APP_W4_BROADCAST_ADV,
108     APP_W4_PA_AND_BIG_INFO,
109     APP_W4_BROADCAST_CODE,
110     APP_W4_BIG_SYNC_ESTABLISHED,
111     APP_STREAMING,
112     APP_IDLE
113 } app_state = APP_W4_WORKING;
114 
115 static const uint8_t adv_sid = 0;
116 static le_advertising_set_t le_advertising_set;
117 static uint8_t adv_handle = 0;
118 
119 static const le_extended_advertising_parameters_t extended_params = {
120         .advertising_event_properties = 1,  // connectable
121         .primary_advertising_interval_min = 0x4b0, // 750 ms
122         .primary_advertising_interval_max = 0x4b0, // 750 ms
123         .primary_advertising_channel_map = 7,
124         .own_address_type = 0,
125         .peer_address_type = 0,
126         .peer_address =  { 0 },
127         .advertising_filter_policy = 0,
128         .advertising_tx_power = 10, // 10 dBm
129         .primary_advertising_phy = 1, // LE 1M PHY
130         .secondary_advertising_max_skip = 0,
131         .secondary_advertising_phy = 1, // LE 1M PHY
132         .advertising_sid = adv_sid,
133         .scan_request_notification_enable = 0,
134 };
135 
136 static const uint8_t extended_adv_data[] = {
137         // 16 bit service data, ORG_BLUETOOTH_SERVICE_BROADCAST_AUDIO_SCAN_SERVICE,
138         3, BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID,
139             ORG_BLUETOOTH_SERVICE_BROADCAST_AUDIO_SCAN_SERVICE & 0xff, ORG_BLUETOOTH_SERVICE_BROADCAST_AUDIO_SCAN_SERVICE >> 8,
140        // name
141         5, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'S', 'i', 'n', 'k'
142 };
143 
144 #define BASS_NUM_CLIENTS 1
145 #define BASS_NUM_SOURCES 1
146 static bass_source_data_t   bass_source_new;
147 static bass_server_source_t bass_sources[BASS_NUM_SOURCES];
148 static bass_remote_client_t bass_clients[BASS_NUM_CLIENTS];
149 
150 //
151 static btstack_packet_callback_registration_t hci_event_callback_registration;
152 static btstack_packet_callback_registration_t sm_event_callback_registration;
153 
154 static bool have_base;
155 static bool have_big_info;
156 static bool have_past;
157 static bool have_broadcast_code;
158 static bool standalone_mode;
159 static uint32_t bis_sync_mask;
160 
161 uint32_t last_samples_report_ms;
162 uint16_t samples_received;
163 uint16_t samples_dropped;
164 uint16_t frames_per_second[MAX_NUM_BIS];
165 
166 // remote info
167 static char remote_name[20];
168 static bd_addr_t remote;
169 static bd_addr_type_t remote_type;
170 static uint8_t remote_sid;
171 static bool count_mode;
172 static bool pts_mode;
173 static bool nrf5340_audio_demo;
174 
175 
176 // broadcast info
177 static const uint8_t    big_handle = 1;
178 static hci_con_handle_t sync_handle;
179 static hci_con_handle_t bis_con_handles[MAX_NUM_BIS];
180 static unsigned int     next_bis_index;
181 static uint8_t          encryption;
182 static uint8_t          broadcast_code[16];
183 
184 static btstack_timer_source_t broadcast_sink_pa_sync_timer;
185 
186 // analysis
187 static bool     last_packet_received_big;
188 static uint16_t last_packet_sequence_big;
189 static bool     last_packet_received[MAX_NUM_BIS];
190 static uint16_t last_packet_sequence[MAX_NUM_BIS];
191 static uint32_t last_packet_time_ms[MAX_NUM_BIS];
192 static uint8_t  last_packet_prefix[MAX_NUM_BIS * PACKET_PREFIX_LEN];
193 
194 // BIG Sync
195 static le_audio_big_sync_t        big_sync_storage;
196 static le_audio_big_sync_params_t big_sync_params;
197 
198 // lc3 writer
199 static uint32_t lc3_frames;
200 
201 // lc3 codec config
202 static uint16_t sampling_frequency_hz;
203 static btstack_lc3_frame_duration_t frame_duration;
204 static uint16_t number_samples_per_frame;
205 static uint16_t octets_per_frame;
206 static uint8_t  num_bis;
207 
208 // lc3 decoder
209 static bool request_lc3plus_decoder = false;
210 static bool use_lc3plus_decoder = false;
211 static const btstack_lc3_decoder_t * lc3_decoder;
212 static int16_t pcm[MAX_NUM_BIS * MAX_SAMPLES_PER_FRAME];
213 
214 static btstack_lc3_decoder_google_t google_decoder_contexts[MAX_NUM_BIS];
215 #ifdef HAVE_LC3PLUS
216 static btstack_lc3plus_fraunhofer_decoder_t fraunhofer_decoder_contexts[MAX_NUM_BIS];
217 #endif
218 static void * decoder_contexts[MAX_NR_BIS];
219 
220 // playback
221 static uint8_t playback_buffer_storage[PLAYBACK_BUFFER_SIZE];
222 static btstack_ring_buffer_t playback_buffer;
223 
224 static btstack_timer_source_t next_packet_timer;
225 static uint16_t               cached_iso_sdu_len;
226 static bool                   have_pcm[MAX_NUM_BIS];
227 
228 static void le_audio_broadcast_sink_playback(int16_t * buffer, uint16_t num_samples){
229     // called from lower-layer but guaranteed to be on main thread
230     uint32_t bytes_needed = num_samples * num_bis * 2;
231 
232     static bool underrun = true;
233 
234     log_info("Playback: need %u, have %u", num_samples, btstack_ring_buffer_bytes_available(&playback_buffer) / ( num_bis * 2));
235 
236     if (bytes_needed > btstack_ring_buffer_bytes_available(&playback_buffer)){
237         memset(buffer, 0, bytes_needed);
238         if (underrun == false){
239             log_info("Playback underrun");
240             underrun = true;
241         }
242         return;
243     }
244 
245     if (underrun){
246         underrun = false;
247         log_info("Playback started");
248     }
249     uint32_t bytes_read;
250     btstack_ring_buffer_read(&playback_buffer, (uint8_t *) buffer, bytes_needed, &bytes_read);
251     btstack_assert(bytes_read == bytes_needed);
252 }
253 
254 static void setup_lc3_decoder(void){
255     uint8_t channel;
256     for (channel = 0 ; channel < num_bis ; channel++){
257         // pick decoder
258         void * decoder_context = NULL;
259 #ifdef HAVE_LC3PLUS
260         if (use_lc3plus_decoder){
261             decoder_context = &fraunhofer_decoder_contexts[channel];
262             lc3_decoder = btstack_lc3plus_fraunhofer_decoder_init_instance(decoder_context);
263         }
264         else
265 #endif
266         {
267             decoder_context = &google_decoder_contexts[channel];
268             lc3_decoder = btstack_lc3_decoder_google_init_instance(decoder_context);
269         }
270         decoder_contexts[channel] = decoder_context;
271         lc3_decoder->configure(decoder_context, sampling_frequency_hz, frame_duration, octets_per_frame);
272     }
273     number_samples_per_frame = btstack_lc3_samples_per_frame(sampling_frequency_hz, frame_duration);
274     btstack_assert(number_samples_per_frame <= MAX_SAMPLES_PER_FRAME);
275 }
276 
277 static void close_files(void){
278 #ifdef HAVE_POSIX_FILE_IO
279     printf("Close files\n");
280     wav_writer_close();
281 #endif
282     const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
283     if (sink != NULL){
284         sink->stop_stream();
285         sink->close();
286     }
287 }
288 
289 static void handle_periodic_advertisement(const uint8_t * packet, uint16_t size){
290     // nRF534_audio quirk - no BASE in periodic advertisement
291     if (nrf5340_audio_demo){
292         // hard coded config LC3
293         // default: mono bitrate 96000, 10 ms with USB audio source, 120 octets per frame
294         count_mode = 0;
295         pts_mode   = 0;
296         num_bis    = 1;
297         sampling_frequency_hz = 48000;
298         frame_duration = BTSTACK_LC3_FRAME_DURATION_10000US;
299         octets_per_frame = 120;
300         have_base = true;
301         return;
302     }
303 
304     // periodic advertisement contains the BASE
305     // TODO: BASE might be split across multiple advertisements
306     const uint8_t * adv_data = hci_subevent_le_periodic_advertising_report_get_data(packet);
307     uint16_t adv_size = hci_subevent_le_periodic_advertising_report_get_data_length(packet);
308     uint8_t adv_status = hci_subevent_le_periodic_advertising_report_get_data_status(packet);
309 
310     if (adv_status != 0) {
311         printf("Periodic Advertisement (status %u): ", adv_status);
312         printf_hexdump(adv_data, adv_size);
313         return;
314     }
315 
316     le_audio_base_parser_t parser;
317     bool ok = le_audio_base_parser_init(&parser, adv_data, adv_size);
318     if (ok == false){
319         return;
320     }
321     have_base = true;
322 
323     printf("BASE:\n");
324     uint32_t presentation_delay = le_audio_base_parser_get_presentation_delay(&parser);
325     printf("- presentation delay: %"PRIu32" us\n", presentation_delay);
326     uint8_t num_subgroups = le_audio_base_parser_get_num_subgroups(&parser);
327     // Cache in new source struct
328     bass_source_new.subgroups_num = num_subgroups;
329     printf("- num subgroups: %u\n", num_subgroups);
330     uint8_t i;
331     for (i=0;i<num_subgroups;i++){
332         // Level 2: Subgroup Level
333         num_bis = le_audio_base_parser_subgroup_get_num_bis(&parser);
334         printf("  - num bis[%u]: %u\n", i, num_bis);
335         uint8_t codec_specific_configuration_length = le_audio_base_parser_bis_get_codec_specific_configuration_length(&parser);
336         const uint8_t * codec_specific_configuration = le_audio_base_parser_subgroup_get_codec_specific_configuration(&parser);
337         printf("  - codec specific config[%u]: ", i);
338         printf_hexdump(codec_specific_configuration, codec_specific_configuration_length);
339         // parse config to get sampling frequency and frame duration
340         uint8_t codec_offset = 0;
341         while ((codec_offset + 1) < codec_specific_configuration_length){
342             uint8_t ltv_len = codec_specific_configuration[codec_offset++];
343             uint8_t ltv_type = codec_specific_configuration[codec_offset];
344             const uint32_t sampling_frequency_map[] = { 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 384000 };
345             uint8_t sampling_frequency_index;
346             uint8_t frame_duration_index;
347             switch (ltv_type){
348                 case 0x01: // sampling frequency
349                     sampling_frequency_index = codec_specific_configuration[codec_offset+1];
350                     // TODO: check range
351                     sampling_frequency_hz = sampling_frequency_map[sampling_frequency_index - 1];
352                     printf("    - sampling frequency[%u]: %u\n", i, sampling_frequency_hz);
353                     break;
354                 case 0x02: // 0 = 7.5, 1 = 10 ms
355                     frame_duration_index =  codec_specific_configuration[codec_offset+1];
356                     frame_duration = (frame_duration_index == 0) ? BTSTACK_LC3_FRAME_DURATION_7500US : BTSTACK_LC3_FRAME_DURATION_10000US;
357                     printf("    - frame duration[%u]: %s ms\n", i, (frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US) ? "7.5" : "10");
358                     break;
359                 case 0x04:  // octets per coding frame
360                     octets_per_frame = little_endian_read_16(codec_specific_configuration, codec_offset+1);
361                     printf("    - octets per codec frame[%u]: %u\n", i, octets_per_frame);
362                     break;
363                 default:
364                     break;
365             }
366             codec_offset += ltv_len;
367         }
368         uint8_t metadata_length = le_audio_base_parser_subgroup_get_metadata_length(&parser);
369         const uint8_t * meta_data = le_audio_base_subgroup_parser_get_metadata(&parser);
370         printf("  - meta data[%u]: ", i);
371         printf_hexdump(meta_data, metadata_length);
372         uint8_t k;
373         for (k=0;k<num_bis;k++){
374             // Level 3: BIS Level
375             uint8_t bis_index =  le_audio_base_parser_bis_get_index(&parser);
376             if ((bis_index == 0) || (bis_index > 30)){
377                 continue;
378             }
379 
380             // collect bis sync mask
381             bis_sync_mask |=  1 << (bis_index - 1);
382 
383             bass_source_new.subgroups[i].metadata_length = 0;
384             memset(&bass_source_new.subgroups[i].metadata, 0, sizeof(le_audio_metadata_t));
385 
386             printf("    - bis index[%u][%u]: %u\n", i, k, bis_index);
387             codec_specific_configuration_length = le_audio_base_parser_bis_get_codec_specific_configuration_length(&parser);
388             codec_specific_configuration = le_audio_base_bis_parser_get_codec_specific_configuration(&parser);
389             printf("    - codec specific config[%u][%u]: ", i, k);
390             printf_hexdump(codec_specific_configuration, codec_specific_configuration_length);
391             // parse next BIS
392             le_audio_base_parser_bis_next(&parser);
393         }
394 
395         // parse next subgroup
396         le_audio_base_parser_subgroup_next(&parser);
397     }
398 }
399 
400 static void handle_big_info(const uint8_t * packet, uint16_t size){
401     printf("BIG Info advertising report\n");
402     sync_handle = hci_subevent_le_biginfo_advertising_report_get_sync_handle(packet);
403     encryption = hci_subevent_le_biginfo_advertising_report_get_encryption(packet);
404     if (encryption) {
405         printf("Stream is encrypted\n");
406     }
407     have_big_info = true;
408 }
409 
410 static void enter_create_big_sync(void){
411     // stop scanning
412     gap_stop_scan();
413 
414     // switch to lc3plus if requested and possible
415     use_lc3plus_decoder = request_lc3plus_decoder && (frame_duration == BTSTACK_LC3_FRAME_DURATION_10000US);
416 
417     // init decoder
418     setup_lc3_decoder();
419 
420     printf("Configure: %u channels, sampling rate %u, samples per frame %u, lc3plus %u\n", num_bis, sampling_frequency_hz, number_samples_per_frame, use_lc3plus_decoder);
421 
422 #ifdef HAVE_POSIX_FILE_IO
423     // create wav file
424     printf("WAV file: %s\n", filename_wav);
425     wav_writer_open(filename_wav, num_bis, sampling_frequency_hz);
426 #endif
427 
428     // init playback buffer
429     btstack_ring_buffer_init(&playback_buffer, playback_buffer_storage, PLAYBACK_BUFFER_SIZE);
430 
431     // start playback
432     // PTS 8.2 sends stereo at half speed for stereo, for now playback at half speed
433     const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
434     if (sink != NULL){
435         uint16_t playback_speed;
436         if ((num_bis > 1) && pts_mode){
437             playback_speed = sampling_frequency_hz / num_bis;
438             printf("PTS workaround: playback at %u hz\n", playback_speed);
439         } else {
440             playback_speed = sampling_frequency_hz;
441         };
442         sink->init(num_bis, sampling_frequency_hz, le_audio_broadcast_sink_playback);
443         sink->start_stream();
444     }
445 
446     big_sync_params.big_handle = big_handle;
447     big_sync_params.sync_handle = sync_handle;
448     big_sync_params.encryption = encryption;
449     if (encryption) {
450         memcpy(big_sync_params.broadcast_code, &broadcast_code[0], 16);
451     } else {
452         memset(big_sync_params.broadcast_code, 0, 16);
453     }
454     big_sync_params.mse = 0;
455     big_sync_params.big_sync_timeout_10ms = 100;
456     big_sync_params.num_bis = num_bis;
457     uint8_t i;
458     printf("BIG Create Sync for BIS: ");
459     for (i=0;i<num_bis;i++){
460         big_sync_params.bis_indices[i] = i + 1;
461         printf("%u ", big_sync_params.bis_indices[i]);
462     }
463     printf("\n");
464     app_state = APP_W4_BIG_SYNC_ESTABLISHED;
465     gap_big_sync_create(&big_sync_storage, &big_sync_params);
466 }
467 
468 static void start_scanning() {
469     app_state = APP_W4_BROADCAST_ADV;
470     have_base = false;
471     have_big_info = false;
472     gap_set_scan_params(1, 0x30, 0x30, 0);
473     gap_start_scan();
474     printf("Start scan..\n");
475 }
476 
477 static void setup_advertising() {
478     gap_extended_advertising_setup(&le_advertising_set, &extended_params, &adv_handle);
479     gap_extended_advertising_set_adv_data(adv_handle, sizeof(extended_adv_data), extended_adv_data);
480     gap_extended_advertising_start(adv_handle, 0, 0);
481 }
482 
483 static void got_base_and_big_info() {
484     // add source
485     if (standalone_mode) {
486         printf("BASS: add Broadcast Source\n");
487         // add source
488         uint8_t source_index = 0;
489         broadcast_audio_scan_service_server_add_source(bass_source_new, &source_index);
490         broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA);
491     }
492 
493     if ((encryption == false) || have_broadcast_code){
494         enter_create_big_sync();
495     } else {
496         printf("BASS: request Broadcast Code\n");
497         bass_sources[0].big_encryption = LE_AUDIO_BIG_ENCRYPTION_BROADCAST_CODE_REQUIRED;
498         broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA);
499         app_state = APP_W4_BROADCAST_CODE;
500     }
501 }
502 
503 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
504     UNUSED(channel);
505     if (packet_type != HCI_EVENT_PACKET) return;
506     switch (packet[0]) {
507         case BTSTACK_EVENT_STATE:
508             switch(btstack_event_state_get_state(packet)) {
509                 case HCI_STATE_WORKING:
510                     app_state = APP_IDLE;
511 #ifdef ENABLE_DEMO_MODE
512                     start_scanning();
513 #else
514                     show_usage();
515 #endif
516                     break;
517                 case HCI_STATE_OFF:
518                     printf("Goodbye\n");
519                     exit(0);
520                     break;
521                 default:
522                     break;
523             }
524             break;
525         case GAP_EVENT_EXTENDED_ADVERTISING_REPORT:
526         {
527             if (app_state != APP_W4_BROADCAST_ADV) break;
528 
529             gap_event_extended_advertising_report_get_address(packet, remote);
530             uint8_t adv_size = gap_event_extended_advertising_report_get_data_length(packet);
531             const uint8_t * adv_data = gap_event_extended_advertising_report_get_data(packet);
532 
533             ad_context_t context;
534             bool found = false;
535             remote_name[0] = '\0';
536             uint16_t uuid;
537             uint32_t broadcast_id;
538             for (ad_iterator_init(&context, adv_size, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
539                 uint8_t data_type = ad_iterator_get_data_type(&context);
540                 uint8_t size = ad_iterator_get_data_len(&context);
541                 const uint8_t *data = ad_iterator_get_data(&context);
542                 switch (data_type){
543                     case BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID:
544                         uuid = little_endian_read_16(data, 0);
545                         if (uuid == ORG_BLUETOOTH_SERVICE_BROADCAST_AUDIO_ANNOUNCEMENT_SERVICE){
546                             broadcast_id = little_endian_read_24(data, 2);
547                             found = true;
548                         }
549                         break;
550                     case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
551                     case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
552                         size = btstack_min(sizeof(remote_name) - 1, size);
553                         memcpy(remote_name, data, size);
554                         remote_name[size] = 0;
555                         // support for nRF5340 Audio DK
556                         if (strncmp("NRF5340", remote_name, 7) == 0){
557                             nrf5340_audio_demo = true;
558                             found = true;
559                         }
560                         break;
561                     default:
562                         break;
563                 }
564             }
565             if (!found) break;
566             remote_type = gap_event_extended_advertising_report_get_address_type(packet);
567             remote_sid = gap_event_extended_advertising_report_get_advertising_sid(packet);
568             pts_mode = strncmp("PTS-", remote_name, 4) == 0;
569             count_mode = strncmp("COUNT", remote_name, 5) == 0;
570             printf("Broadcast sink found, addr %s, name: '%s' (pts-mode: %u, count: %u), Broadcast_ID 0%06x\n", bd_addr_to_str(remote), remote_name, pts_mode, count_mode, broadcast_id);
571             // ignore other advertisements
572             gap_whitelist_add(remote_type, remote);
573             gap_set_scan_params(1, 0x30, 0x30, 1);
574             // sync to PA
575             gap_periodic_advertiser_list_clear();
576             gap_periodic_advertiser_list_add(remote_type, remote, remote_sid);
577             app_state = APP_W4_PA_AND_BIG_INFO;
578             printf("Start Periodic Advertising Sync\n");
579             gap_periodic_advertising_create_sync(0x01, remote_sid, remote_type, remote, 0, 1000, 0);
580 
581             // setup bass source info
582             bass_source_new.address_type = remote_type;
583             memcpy(bass_source_new.address, remote, 6);
584             bass_source_new.adv_sid = remote_sid;
585             bass_source_new.broadcast_id = broadcast_id;
586             bass_source_new.pa_sync = LE_AUDIO_PA_SYNC_SYNCHRONIZE_TO_PA_PAST_AVAILABLE;
587             bass_source_new.pa_interval = gap_event_extended_advertising_report_get_periodic_advertising_interval(packet);
588             break;
589         }
590 
591         case HCI_EVENT_LE_META:
592             switch(hci_event_le_meta_get_subevent_code(packet)) {
593                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED:
594                     // PAST implies broadcast source has been added by client
595                     printf("Periodic advertising sync transfer received\n");
596                     btstack_run_loop_remove_timer(&broadcast_sink_pa_sync_timer);
597                     broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA);
598                     app_state = APP_W4_PA_AND_BIG_INFO;
599                     break;
600                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
601                     sync_handle = hci_subevent_le_periodic_advertising_sync_establishment_get_sync_handle(packet);
602                     printf("Periodic advertising sync with handle 0x%04x established\n", sync_handle);
603                     app_state = APP_W4_PA_AND_BIG_INFO;
604                     break;
605                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_REPORT:
606                     if (app_state != APP_W4_PA_AND_BIG_INFO) break;
607                     if (have_base) break;
608                     handle_periodic_advertisement(packet, size);
609                     if (have_base && have_big_info){
610                         got_base_and_big_info();
611                     }
612                     break;
613                 case HCI_SUBEVENT_LE_BIGINFO_ADVERTISING_REPORT:
614                     if (app_state != APP_W4_PA_AND_BIG_INFO) break;
615                     if (have_big_info) break;
616                     handle_big_info(packet, size);
617                     if (have_base && have_big_info){
618                         got_base_and_big_info();
619                     }
620                     break;
621                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
622                     printf("BIG Sync Lost\n");
623                     {
624                         const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
625                         if (sink != NULL) {
626                             sink->stop_stream();
627                             sink->close();
628                         }
629                     }
630                     // start over
631                     if (!standalone_mode) break;
632                     start_scanning();
633                     break;
634                 default:
635                     break;
636             }
637             break;
638         case HCI_EVENT_META_GAP:
639             switch (hci_event_gap_meta_get_subevent_code(packet)){
640                 case GAP_SUBEVENT_BIG_SYNC_CREATED: {
641                     printf("BIG Sync created with BIS Connection handles: ");
642                     uint8_t i;
643                     for (i=0;i<num_bis;i++){
644                         bis_con_handles[i] = gap_subevent_big_sync_created_get_bis_con_handles(packet, i);
645                         printf("0x%04x ", bis_con_handles[i]);
646                     }
647                     printf("\n");
648                     app_state = APP_STREAMING;
649                     last_packet_received_big = false;
650                     last_samples_report_ms = btstack_run_loop_get_time_ms();
651                     memset(last_packet_sequence, 0, sizeof(last_packet_sequence));
652                     memset(last_packet_received, 0, sizeof(last_packet_received));
653                     memset(pcm, 0, sizeof(pcm));
654                     printf("Start receiving\n");
655 
656                     // update BIS Sync state
657                     bass_sources[0].data.subgroups[0].bis_sync_state = bis_sync_mask;
658                     broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA);
659                     break;
660                 }
661                 case GAP_SUBEVENT_BIG_SYNC_STOPPED:
662                     printf("BIG Sync stopped, big_handle 0x%02x\n", gap_subevent_big_sync_stopped_get_big_handle(packet));
663                     break;
664                 default:
665                     break;
666             }
667             break;
668         case SM_EVENT_JUST_WORKS_REQUEST:
669             printf("Just Works requested\n");
670             sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
671             break;
672         default:
673             break;
674     }
675 }
676 
677 static void store_samples_in_ringbuffer(void){
678     // check if we have all channels
679     uint8_t bis_channel;
680     for (bis_channel = 0; bis_channel < num_bis ; bis_channel++){
681         if (have_pcm[bis_channel] == false) return;
682     }
683 #ifdef HAVE_POSIX_FILE_IO
684     // write wav samples
685     wav_writer_write_int16(num_bis * number_samples_per_frame, pcm);
686 #endif
687     // store samples in playback buffer
688     uint32_t bytes_to_store = num_bis * number_samples_per_frame * 2;
689     samples_received += number_samples_per_frame;
690     if (btstack_ring_buffer_bytes_free(&playback_buffer) >= bytes_to_store) {
691         btstack_ring_buffer_write(&playback_buffer, (uint8_t *) pcm, bytes_to_store);
692     } else {
693         printf("Samples dropped\n");
694         samples_dropped += number_samples_per_frame;
695     }
696     // reset
697     for (bis_channel = 0; bis_channel < num_bis ; bis_channel++){
698         have_pcm[bis_channel] = false;
699     }
700 }
701 
702 static void plc_do(uint8_t bis_channel) {// inject packet
703     uint8_t tmp_BEC_detect;
704     uint8_t BFI = 1;
705     (void) lc3_decoder->decode_signed_16(decoder_contexts[bis_channel], NULL, BFI,
706                                          &pcm[bis_channel], num_bis,
707                                          &tmp_BEC_detect);
708 
709     printf("PLC channel %u - packet sequence %u\n", bis_channel,  last_packet_sequence[bis_channel]);
710 
711     have_pcm[bis_channel] = true;
712     store_samples_in_ringbuffer();
713 }
714 
715 static void plc_missing(uint16_t packet_sequence_number) {
716     while (btstack_time16_delta(packet_sequence_number, last_packet_sequence_big) > 1){
717         uint8_t i;
718         for (i=0;i<num_bis;i++){
719             // deal with first packet missing. inject silent samples, pcm buffer is memset to zero at start
720             if (last_packet_received[i] == false){
721                 printf("PLC Missing: very first packet BIS %u missing\n", i);
722                 have_pcm[i] = true;
723                 store_samples_in_ringbuffer();
724 
725                 last_packet_received[i] = true;
726                 last_packet_sequence[i] = last_packet_sequence_big;
727                 continue;
728             }
729 
730             // missing packet if big sequence counter is higher than bis sequence counter
731             if (btstack_time16_delta(last_packet_sequence_big, last_packet_sequence[i]) > 0) {
732                 plc_do(i);
733                 last_packet_sequence[i] = last_packet_sequence_big;
734             }
735         }
736         last_packet_sequence_big++;
737     }
738 }
739 
740 static void plc_timeout(btstack_timer_source_t * timer) {
741     if (app_state != APP_STREAMING) return;
742 
743     // Restart timer. This will loose sync with ISO interval, but if we stop caring if we loose that many packets
744     uint32_t frame_duration_ms = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 8 : 10;
745     btstack_run_loop_set_timer(timer, frame_duration_ms);
746     btstack_run_loop_set_timer_handler(timer, plc_timeout);
747     btstack_run_loop_add_timer(timer);
748 
749     // assume no packet received in iso interval
750     plc_missing(last_packet_sequence_big + 1);
751 }
752 
753 static void iso_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
754 
755     if (app_state != APP_STREAMING) return;
756 
757     uint16_t header = little_endian_read_16(packet, 0);
758     hci_con_handle_t con_handle = header & 0x0fff;
759     uint8_t pb_flag = (header >> 12) & 3;
760     uint8_t ts_flag = (header >> 14) & 1;
761     uint16_t iso_load_len = little_endian_read_16(packet, 2);
762 
763     uint16_t offset = 4;
764     uint32_t time_stamp = 0;
765     if (ts_flag){
766         uint32_t time_stamp = little_endian_read_32(packet, offset);
767         offset += 4;
768     }
769 
770     uint32_t receive_time_ms = btstack_run_loop_get_time_ms();
771 
772     uint16_t packet_sequence_number = little_endian_read_16(packet, offset);
773     offset += 2;
774 
775     uint16_t header_2 = little_endian_read_16(packet, offset);
776     uint16_t iso_sdu_length = header_2 & 0x3fff;
777     uint8_t packet_status_flag = (uint8_t) (header_2 >> 14);
778     offset += 2;
779 
780     if (iso_sdu_length == 0) return;
781 
782     // infer channel from con handle - only works for up to 2 channels
783     uint8_t bis_channel = (con_handle == bis_con_handles[0]) ? 0 : 1;
784 
785     if (count_mode){
786         // check for missing packet
787         uint16_t last_seq_no = last_packet_sequence[bis_channel];
788         bool packet_missed = (last_seq_no != 0) && ((last_seq_no + 1) != packet_sequence_number);
789         if (packet_missed){
790             // print last packet
791             printf("\n");
792             printf("%04x %10"PRIu32" %u ", last_seq_no, last_packet_time_ms[bis_channel], bis_channel);
793             printf_hexdump(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], PACKET_PREFIX_LEN);
794             last_seq_no++;
795 
796             printf(ANSI_COLOR_RED);
797             while (last_seq_no < packet_sequence_number){
798                 printf("%04x            %u MISSING\n", last_seq_no, bis_channel);
799                 last_seq_no++;
800             }
801             printf(ANSI_COLOR_RESET);
802 
803             // print current packet
804             printf("%04x %10"PRIu32" %u ", packet_sequence_number, receive_time_ms, bis_channel);
805             printf_hexdump(&packet[offset], PACKET_PREFIX_LEN);
806         }
807 
808         // cache current packet
809         memcpy(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], &packet[offset], PACKET_PREFIX_LEN);
810 
811     } else {
812 
813         if (last_packet_received[bis_channel]) {
814             int16_t packet_sequence_delta = btstack_time16_delta(packet_sequence_number,
815                                                                  last_packet_sequence[bis_channel]);
816             if (packet_sequence_delta < 1) {
817                 // drop delayed packet that had already been generated by PLC
818                 printf("Dropping delayed packet. Current sequence number %u, last received or generated by PLC: %u\n",
819                        packet_sequence_number, last_packet_sequence[bis_channel]);
820                 return;
821             }
822         } else {
823             if (!last_packet_received_big) {
824                 // track sequence number of very first received packet
825                 last_packet_received_big = true;
826                 last_packet_sequence_big = packet_sequence_number;
827             }
828             printf("BIS %u, first packet seq number %u\n", bis_channel, packet_sequence_number);
829             last_packet_received[bis_channel] = true;
830         }
831 
832         // assert no channel is more than one packet behind
833         plc_missing(packet_sequence_number);
834 
835         // decode codec frame
836         uint8_t tmp_BEC_detect;
837         uint8_t BFI = 0;
838         (void) lc3_decoder->decode_signed_16(decoder_contexts[bis_channel], &packet[offset], BFI,
839                                    &pcm[bis_channel], num_bis,
840                                    &tmp_BEC_detect);
841         have_pcm[bis_channel] = true;
842         store_samples_in_ringbuffer();
843 
844         lc3_frames++;
845         frames_per_second[bis_channel]++;
846 
847         // PLC
848         cached_iso_sdu_len = iso_sdu_length;
849         uint32_t frame_duration_ms = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 8 : 10;
850         uint32_t timeout_ms = frame_duration_ms * 5 / 2;
851         btstack_run_loop_remove_timer(&next_packet_timer);
852         btstack_run_loop_set_timer(&next_packet_timer, timeout_ms);
853         btstack_run_loop_set_timer_handler(&next_packet_timer, plc_timeout);
854         btstack_run_loop_add_timer(&next_packet_timer);
855 
856         uint32_t time_ms = btstack_run_loop_get_time_ms();
857         if (btstack_time_delta(time_ms, last_samples_report_ms) >= 1000){
858             last_samples_report_ms = time_ms;
859             printf("LC3 Frames: %4u - ", (int) (lc3_frames / num_bis));
860             uint8_t i;
861             for (i=0;i<num_bis;i++){
862                 printf("%u ", frames_per_second[i]);
863                 frames_per_second[i] = 0;
864             }
865             printf(" frames per second, dropped %u of %u\n", samples_dropped, samples_received);
866             samples_received = 0;
867             samples_dropped  =  0;
868         }
869     }
870 
871     last_packet_time_ms[bis_channel]  = receive_time_ms;
872     last_packet_sequence[bis_channel] = packet_sequence_number;
873 }
874 
875 static void show_usage(void){
876     printf("\n--- LE Audio Broadcast Sink Test Console ---\n");
877     printf("s - start scanning\n");
878 #ifdef HAVE_LC3PLUS
879     printf("q - use LC3plus decoder if 10 ms ISO interval is used\n");
880 #endif
881     printf("e - set broadcast code to 0x11111111111111111111111111111111\n");
882     printf("t - terminate BIS streams\n");
883     printf("x - close files and exit\n");
884     printf("---\n");
885 }
886 
887 static void stdin_process(char c){
888     switch (c){
889         case 's':
890             if (app_state != APP_IDLE) break;
891             standalone_mode = true;
892             start_scanning();
893             break;
894         case 'e':
895             printf("Set broadcast code to 0x11111111111111111111111111111111\n");
896             memset(broadcast_code, 0x11, 16);
897             have_broadcast_code = true;
898             break;
899 #ifdef HAVE_LC3PLUS
900         case 'q':
901             printf("Use LC3plus decoder for 10 ms ISO interval...\n");
902             request_lc3plus_decoder = true;
903             break;
904 #endif
905         case 't':
906             switch (app_state){
907                 case APP_STREAMING:
908                 case APP_W4_BIG_SYNC_ESTABLISHED:
909                     app_state = APP_IDLE;
910                     close_files();
911                     printf("Terminate BIG SYNC\n");
912                     gap_big_sync_terminate(big_handle);
913                     break;
914                 default:
915                     break;
916             }
917             break;
918         case 'x':
919             close_files();
920             printf("Shutdown...\n");
921             hci_power_control(HCI_POWER_OFF);
922             break;
923         case '\n':
924         case '\r':
925             break;
926         default:
927             show_usage();
928             break;
929 
930     }
931 }
932 
933 static void broadcast_sync_pa_sync_timeout_handler(btstack_timer_source_t * ts){
934     UNUSED(ts);
935     printf("PAST Timeout -> LE_AUDIO_PA_SYNC_STATE_NO_PAST\n");
936     broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_NO_PAST);
937 }
938 
939 static void bass_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
940     UNUSED(packet_type);
941     UNUSED(channel);
942     btstack_assert (packet_type == HCI_EVENT_PACKET);
943     btstack_assert(hci_event_packet_get_type(packet) == HCI_EVENT_GATTSERVICE_META);
944     printf("BASS Event 0x%02x: ", hci_event_gattservice_meta_get_subevent_code(packet));
945     printf_hexdump(packet, size);
946     switch (hci_event_gattservice_meta_get_subevent_code(packet)){
947         case GATTSERVICE_SUBEVENT_BASS_SOURCE_ADDED:
948             printf("GATTSERVICE_SUBEVENT_BASS_SOURCE_ADDED, source_id 0x%04x, pa_sync %u\n",
949                    gattservice_subevent_bass_source_added_get_source_id(packet),
950                    gattservice_subevent_bass_source_added_get_pa_sync(packet));
951             switch (gattservice_subevent_bass_source_added_get_pa_sync(packet)){
952                 case LE_AUDIO_PA_SYNC_SYNCHRONIZE_TO_PA_PAST_AVAILABLE:
953                     printf("LE_AUDIO_PA_SYNC_SYNCHRONIZE_TO_PA_PAST_AVAILABLE -> Request SyncInfo\n");
954                     broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCINFO_REQUEST);
955                     // start timeout
956                     btstack_run_loop_set_timer_handler(&broadcast_sink_pa_sync_timer, broadcast_sync_pa_sync_timeout_handler);
957                     btstack_run_loop_set_timer(&broadcast_sink_pa_sync_timer, 10000);   // 10 seconds
958                     btstack_run_loop_add_timer(&broadcast_sink_pa_sync_timer);
959                     break;
960             }
961             break;
962         case GATTSERVICE_SUBEVENT_BASS_SOURCE_MODIFIED:
963             printf("GATTSERVICE_SUBEVENT_BASS_SOURCE_MODIFIED, source_id 0x%04x, pa_sync %u\n",
964                    gattservice_subevent_bass_source_added_get_source_id(packet),
965                    gattservice_subevent_bass_source_added_get_pa_sync(packet));
966             // handle 'bis sync == 0'
967             printf("PA Sync %u, bis_sync[0] = %u\n", bass_sources[0].data.pa_sync, bass_sources[0].data.subgroups[0].bis_sync);
968             if (bass_sources[0].data.subgroups[0].bis_sync == 0){
969                 printf("Simulate BIS Sync has stopped\n");
970                 bass_sources[0].data.subgroups[0].bis_sync_state = 0;
971                 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA);
972             }
973             break;
974         case GATTSERVICE_SUBEVENT_BASS_BROADCAST_CODE:
975             gattservice_subevent_bass_broadcast_code_get_broadcast_code(packet, broadcast_code);
976             printf("GATTSERVICE_SUBEVENT_BASS_BROADCAST_CODE received: ");
977             printf_hexdump(broadcast_code, 16);
978             bass_sources[0].big_encryption = LE_AUDIO_BIG_ENCRYPTION_DECRYPTING;
979             if (have_base && have_big_info){
980                 enter_create_big_sync();
981             }
982             break;
983         default:
984             break;
985     }
986 }
987 
988 int btstack_main(int argc, const char * argv[]);
989 int btstack_main(int argc, const char * argv[]){
990     (void) argv;
991     (void) argc;
992 
993     l2cap_init();
994     sm_init();
995 
996     // setup ATT server
997     att_server_init(profile_data, NULL, NULL);
998 
999     // register for HCI events
1000     hci_event_callback_registration.callback = &packet_handler;
1001     hci_add_event_handler(&hci_event_callback_registration);
1002 
1003     // register for ISO Packet
1004     hci_register_iso_packet_handler(&iso_packet_handler);
1005 
1006     // register for SM events
1007     sm_event_callback_registration.callback = &packet_handler;
1008     sm_add_event_handler(&sm_event_callback_registration);
1009 
1010     // setup BASS Server
1011     broadcast_audio_scan_service_server_init(BASS_NUM_SOURCES, bass_sources, BASS_NUM_CLIENTS, bass_clients);
1012     broadcast_audio_scan_service_server_register_packet_handler(&bass_packet_handler);
1013 
1014     // setup advertising and allow to receive periodic advertising sync trasnfers
1015     setup_advertising();
1016     gap_periodic_advertising_sync_transfer_set_default_parameters(2, 0, 0x2000, 0);
1017 
1018     // turn on!
1019     hci_power_control(HCI_POWER_ON);
1020 
1021     btstack_stdin_setup(stdin_process);
1022     return 0;
1023 }
1024