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