xref: /btstack/test/le_audio/le_audio_broadcast_sink.c (revision da8e14c5aa3783b6bb7dd63e71572a901bcf168b)
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 <unistd.h>
52 #include <inttypes.h>
53 #include <fcntl.h>        // open
54 #include <errno.h>
55 
56 #include "ad_parser.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 
73 #ifdef HAVE_POSIX_FILE_IO
74 #include "wav_util.h"
75 #endif
76 
77 // max config
78 #define MAX_NUM_BIS 2
79 #define MAX_SAMPLES_PER_FRAME 480
80 
81 #define DUMP_LEN_LC3_FRAMES 10000
82 
83 // playback
84 #define MAX_NUM_LC3_FRAMES   5
85 #define MAX_BYTES_PER_SAMPLE 4
86 #define PLAYBACK_BUFFER_SIZE (MAX_NUM_LC3_FRAMES * MAX_SAMPLES_PER_FRAME * MAX_BYTES_PER_SAMPLE)
87 
88 // analysis
89 #define PACKET_PREFIX_LEN 10
90 
91 #define ANSI_COLOR_RED     "\x1b[31m"
92 #define ANSI_COLOR_GREEN   "\x1b[32m"
93 #define ANSI_COLOR_YELLOW  "\x1b[33m"
94 #define ANSI_COLOR_BLUE    "\x1b[34m"
95 #define ANSI_COLOR_MAGENTA "\x1b[35m"
96 #define ANSI_COLOR_CYAN    "\x1b[36m"
97 #define ANSI_COLOR_RESET   "\x1b[0m"
98 
99 static void show_usage(void);
100 
101 static const char * filename_lc3 = "le_audio_broadcast_sink.lc3";
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_BIG_SYNC_ESTABLISHED,
109     APP_STREAMING,
110     APP_IDLE
111 } app_state = APP_W4_WORKING;
112 
113 //
114 static btstack_packet_callback_registration_t hci_event_callback_registration;
115 
116 static bool have_base;
117 static bool have_big_info;
118 
119 uint32_t last_samples_report_ms;
120 uint16_t samples_received;
121 uint16_t samples_dropped;
122 uint16_t frames_per_second[MAX_NUM_BIS];
123 
124 // remote info
125 static char remote_name[20];
126 static bd_addr_t remote;
127 static bd_addr_type_t remote_type;
128 static uint8_t remote_sid;
129 static bool count_mode;
130 static bool pts_mode;
131 static bool nrf5340_audio_demo;
132 
133 
134 // broadcast info
135 static const uint8_t    big_handle = 1;
136 static hci_con_handle_t sync_handle;
137 static hci_con_handle_t bis_con_handles[MAX_NUM_BIS];
138 static unsigned int     next_bis_index;
139 
140 // analysis
141 static uint16_t last_packet_sequence[MAX_NUM_BIS];
142 static uint32_t last_packet_time_ms[MAX_NUM_BIS];
143 static uint8_t last_packet_prefix[MAX_NUM_BIS * PACKET_PREFIX_LEN];
144 
145 // BIG Sync
146 static le_audio_big_sync_t        big_sync_storage;
147 static le_audio_big_sync_params_t big_sync_params;
148 
149 // lc3 writer
150 static int dump_file;
151 static uint32_t lc3_frames;
152 
153 // lc3 codec config
154 static uint16_t sampling_frequency_hz;
155 static btstack_lc3_frame_duration_t frame_duration;
156 static uint16_t number_samples_per_frame;
157 static uint16_t octets_per_frame;
158 static uint8_t  num_bis;
159 
160 // lc3 decoder
161 static bool request_lc3plus_decoder = false;
162 static bool use_lc3plus_decoder = false;
163 static const btstack_lc3_decoder_t * lc3_decoder;
164 static int16_t pcm[MAX_NUM_BIS * MAX_SAMPLES_PER_FRAME];
165 
166 static btstack_lc3_decoder_google_t google_decoder_contexts[MAX_NUM_BIS];
167 #ifdef HAVE_LC3PLUS
168 static btstack_lc3plus_fraunhofer_decoder_t fraunhofer_decoder_contexts[MAX_NUM_BIS];
169 #endif
170 static void * decoder_contexts[MAX_NR_BIS];
171 
172 // playback
173 static uint8_t playback_buffer_storage[PLAYBACK_BUFFER_SIZE];
174 static btstack_ring_buffer_t playback_buffer;
175 
176 // PLC state
177 #define PLC_GUARD_MS 1
178 
179 static btstack_timer_source_t next_packet_timer[MAX_NUM_BIS];
180 static uint16_t               cached_iso_sdu_len;
181 static bool                   have_pcm[MAX_NUM_BIS];
182 
183 static void le_audio_broadcast_sink_playback(int16_t * buffer, uint16_t num_samples){
184     // called from lower-layer but guaranteed to be on main thread
185     uint32_t bytes_needed = num_samples * num_bis * 2;
186 
187     static bool underrun = true;
188 
189     log_info("Playback: need %u, have %u", num_samples, btstack_ring_buffer_bytes_available(&playback_buffer) / ( num_bis * 2));
190 
191     if (bytes_needed > btstack_ring_buffer_bytes_available(&playback_buffer)){
192         memset(buffer, 0, bytes_needed);
193         if (underrun == false){
194             log_info("Playback underrun");
195             underrun = true;
196         }
197         return;
198     }
199 
200     if (underrun){
201         underrun = false;
202         log_info("Playback started");
203     }
204     uint32_t bytes_read;
205     btstack_ring_buffer_read(&playback_buffer, (uint8_t *) buffer, bytes_needed, &bytes_read);
206     btstack_assert(bytes_read == bytes_needed);
207 }
208 
209 #ifdef HAVE_POSIX_FILE_IO
210 static void open_lc3_file(void) {
211     // open lc3 file
212     int oflags = O_WRONLY | O_CREAT | O_TRUNC;
213     dump_file = open(filename_lc3, oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
214     if (dump_file < 0) {
215         printf("failed to open file %s, errno = %d\n", filename_lc3, errno);
216         return;
217     }
218 
219     printf("LC3 binary file: %s\n", filename_lc3);
220 
221     // calc bps
222     uint16_t frame_duration_100us = (frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US) ? 75 : 100;
223     uint32_t bits_per_second = (uint32_t) octets_per_frame * num_bis * 8 * 10000 / frame_duration_100us;
224 
225     // write header for floating point implementation
226     uint8_t header[18];
227     little_endian_store_16(header, 0, 0xcc1c);
228     little_endian_store_16(header, 2, sizeof(header));
229     little_endian_store_16(header, 4, sampling_frequency_hz / 100);
230     little_endian_store_16(header, 6, bits_per_second / 100);
231     little_endian_store_16(header, 8, num_bis);
232     little_endian_store_16(header, 10, frame_duration_100us * 10);
233     little_endian_store_16(header, 12, 0);
234     little_endian_store_32(header, 14, DUMP_LEN_LC3_FRAMES * number_samples_per_frame);
235     write(dump_file, header, sizeof(header));
236 }
237 #endif
238 
239 static void setup_lc3_decoder(void){
240     uint8_t channel;
241     for (channel = 0 ; channel < num_bis ; channel++){
242         // pick decoder
243         void * decoder_context = NULL;
244 #ifdef HAVE_LC3PLUS
245         if (use_lc3plus_decoder){
246             decoder_context = &fraunhofer_decoder_contexts[channel];
247             lc3_decoder = btstack_lc3plus_fraunhofer_decoder_init_instance(decoder_context);
248         }
249         else
250 #endif
251         {
252             decoder_context = &google_decoder_contexts[channel];
253             lc3_decoder = btstack_lc3_decoder_google_init_instance(decoder_context);
254         }
255         decoder_contexts[channel] = decoder_context;
256         lc3_decoder->configure(decoder_context, sampling_frequency_hz, frame_duration);
257     }
258     number_samples_per_frame = lc3_decoder->get_number_samples_per_frame(decoder_contexts[0]);
259     btstack_assert(number_samples_per_frame <= MAX_SAMPLES_PER_FRAME);
260 }
261 
262 static void close_files(void){
263 #ifdef HAVE_POSIX_FILE_IO
264     printf("Close files\n");
265     close(dump_file);
266     wav_writer_close();
267 #endif
268 }
269 
270 static void handle_periodic_advertisement(const uint8_t * packet, uint16_t size){
271     // nRF534_audio quirk - no BASE in periodic advertisement
272     if (nrf5340_audio_demo){
273         // hard coded config LC3
274         // default: mono bitrate 96000, 10 ms with USB audio source, 120 octets per frame
275         count_mode = 0;
276         pts_mode   = 0;
277         num_bis    = 1;
278         sampling_frequency_hz = 48000;
279         frame_duration = BTSTACK_LC3_FRAME_DURATION_10000US;
280         octets_per_frame = 120;
281         have_base = true;
282         return;
283     }
284 
285     // periodic advertisement contains the BASE
286     // TODO: BASE might be split across multiple advertisements
287     const uint8_t * adv_data = hci_subevent_le_periodic_advertising_report_get_data(packet);
288     uint16_t adv_size = hci_subevent_le_periodic_advertising_report_get_data_length(packet);
289     uint8_t adv_status = hci_subevent_le_periodic_advertising_report_get_data_status(packet);
290 
291     if (adv_status != 0) {
292         printf("Periodic Advertisement (status %u): ", adv_status);
293         printf_hexdump(adv_data, adv_size);
294         return;
295     }
296 
297     ad_context_t context;
298     for (ad_iterator_init(&context, adv_size, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
299         uint8_t data_type = ad_iterator_get_data_type(&context);
300         // TODO: avoid out-of-bounds read
301         // uint8_t data_size = ad_iterator_get_data_len(&context);
302         const uint8_t * data = ad_iterator_get_data(&context);
303         uint16_t uuid;
304         switch (data_type){
305             case BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID:
306                 uuid = little_endian_read_16(data, 0);
307                 if (uuid == ORG_BLUETOOTH_SERVICE_BASIC_AUDIO_ANNOUNCEMENT_SERVICE){
308                     have_base = true;
309                     // Level 1: Group Level
310                     const uint8_t * base_data = &data[2];
311                     // TODO: avoid out-of-bounds read
312                     // uint16_t base_len = data_size - 2;
313                     printf("BASE:\n");
314                     uint32_t presentation_delay = little_endian_read_24(base_data, 0);
315                     printf("- presentation delay: %"PRIu32" us\n", presentation_delay);
316                     uint8_t num_subgroups = base_data[3];
317                     printf("- num subgroups: %u\n", num_subgroups);
318                     uint8_t i;
319                     uint16_t offset = 4;
320                     for (i=0;i<num_subgroups;i++){
321                         // Level 2: Subgroup Level
322                         num_bis = base_data[offset++];
323                         printf("  - num bis[%u]: %u\n", i, num_bis);
324                         // codec_id: coding format = 0x06, vendor and coded id = 0
325                         offset += 5;
326                         uint8_t codec_specific_configuration_length = base_data[offset++];
327                         const uint8_t * codec_specific_configuration = &base_data[offset];
328                         printf("  - codec specific config[%u]: ", i);
329                         printf_hexdump(codec_specific_configuration, codec_specific_configuration_length);
330                         // parse config to get sampling frequency and frame duration
331                         uint8_t codec_offset = 0;
332                         while ((codec_offset + 1) < codec_specific_configuration_length){
333                             uint8_t ltv_len = codec_specific_configuration[codec_offset++];
334                             uint8_t ltv_type = codec_specific_configuration[codec_offset];
335                             const uint32_t sampling_frequency_map[] = { 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 384000 };
336                             uint8_t sampling_frequency_index;
337                             uint8_t frame_duration_index;
338                             switch (ltv_type){
339                                 case 0x01: // sampling frequency
340                                     sampling_frequency_index = codec_specific_configuration[codec_offset+1];
341                                     // TODO: check range
342                                     sampling_frequency_hz = sampling_frequency_map[sampling_frequency_index - 1];
343                                     printf("    - sampling frequency[%u]: %u\n", i, sampling_frequency_hz);
344                                     break;
345                                 case 0x02: // 0 = 7.5, 1 = 10 ms
346                                     frame_duration_index =  codec_specific_configuration[codec_offset+1];
347                                     frame_duration = (frame_duration_index == 0) ? BTSTACK_LC3_FRAME_DURATION_7500US : BTSTACK_LC3_FRAME_DURATION_10000US;
348                                     printf("    - frame duration[%u]: %s ms\n", i, (frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US) ? "7.5" : "10");
349                                     break;
350                                 case 0x04:  // octets per coding frame
351                                     octets_per_frame = little_endian_read_16(codec_specific_configuration, codec_offset+1);
352                                     printf("    - octets per codec frame[%u]: %u\n", i, octets_per_frame);
353                                     break;
354                                 default:
355                                     break;
356                             }
357                             codec_offset += ltv_len;
358                         }
359                         //
360                         offset += codec_specific_configuration_length;
361                         uint8_t metadata_length = base_data[offset++];
362                         const uint8_t * meta_data = &base_data[offset];
363                         offset += metadata_length;
364                         printf("  - meta data[%u]: ", i);
365                         printf_hexdump(meta_data, metadata_length);
366                         uint8_t k;
367                         for (k=0;k<num_bis;k++){
368                             // Level 3: BIS Level
369                             uint8_t bis_index = base_data[offset++];
370                             printf("    - bis index[%u][%u]: %u\n", i, k, bis_index);
371                             uint8_t codec_specific_configuration_length2 = base_data[offset++];
372                             const uint8_t * codec_specific_configuration2 = &base_data[offset];
373                             printf("    - codec specific config[%u][%u]: ", i, k);
374                             printf_hexdump(codec_specific_configuration2, codec_specific_configuration_length2);
375                             offset += codec_specific_configuration_length2;
376                         }
377                     }
378                 }
379                 break;
380             default:
381                 break;
382         }
383     }
384 }
385 
386 static void handle_big_info(const uint8_t * packet, uint16_t size){
387     printf("BIG Info advertising report\n");
388     sync_handle = hci_subevent_le_biginfo_advertising_report_get_sync_handle(packet);
389     have_big_info = true;
390 }
391 
392 static void enter_create_big_sync(void){
393     // stop scanning
394     gap_stop_scan();
395 
396     // switch to lc3plus if requested and possible
397     use_lc3plus_decoder = request_lc3plus_decoder && (frame_duration == BTSTACK_LC3_FRAME_DURATION_10000US);
398 
399     // init decoder
400     setup_lc3_decoder();
401 
402     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);
403 
404 #ifdef HAVE_POSIX_FILE_IO
405     // create lc3 file
406     open_lc3_file();
407 
408     // create wav file
409     printf("WAV file: %s\n", filename_wav);
410     wav_writer_open(filename_wav, num_bis, sampling_frequency_hz);
411 #endif
412 
413     // init playback buffer
414     btstack_ring_buffer_init(&playback_buffer, playback_buffer_storage, PLAYBACK_BUFFER_SIZE);
415 
416     // start playback
417     // PTS 8.2 sends stereo at half speed for stereo, for now playback at half speed
418     const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
419     if (sink != NULL){
420         uint16_t playback_speed;
421         if ((num_bis > 1) && pts_mode){
422             playback_speed = sampling_frequency_hz / num_bis;
423             printf("PTS workaround: playback at %u hz\n", playback_speed);
424         } else {
425             playback_speed = sampling_frequency_hz;
426         };
427         sink->init(num_bis, sampling_frequency_hz, le_audio_broadcast_sink_playback);
428         sink->start_stream();
429     }
430 
431     big_sync_params.big_handle = big_handle;
432     big_sync_params.sync_handle = sync_handle;
433     big_sync_params.encryption = 0;
434     memset(big_sync_params.broadcast_code, 0, 16);
435     big_sync_params.mse = 0;
436     big_sync_params.big_sync_timeout_10ms = 100;
437     big_sync_params.num_bis = num_bis;
438     uint8_t i;
439     printf("BIG Create Sync for BIS: ");
440     for (i=0;i<num_bis;i++){
441         big_sync_params.bis_indices[i] = i + 1;
442         printf("%u ", big_sync_params.bis_indices[i]);
443     }
444     printf("\n");
445     app_state = APP_W4_BIG_SYNC_ESTABLISHED;
446     gap_big_sync_create(&big_sync_storage, &big_sync_params);
447 }
448 
449 static void start_scanning() {
450     app_state = APP_W4_BROADCAST_ADV;
451     gap_set_scan_params(1, 0x30, 0x30, 0);
452     gap_start_scan();
453     printf("Start scan..\n");
454 }
455 
456 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
457     UNUSED(channel);
458     if (packet_type != HCI_EVENT_PACKET) return;
459     switch (packet[0]) {
460         case BTSTACK_EVENT_STATE:
461             switch(btstack_event_state_get_state(packet)) {
462                 case HCI_STATE_WORKING:
463 #ifdef ENABLE_DEMO_MODE
464                     if (app_state != APP_W4_WORKING) break;
465                     start_scanning();
466 #else
467                     show_usage();
468 #endif
469                     break;
470                 case HCI_STATE_OFF:
471                     printf("Goodbye\n");
472                     exit(0);
473                     break;
474                 default:
475                     break;
476             }
477             break;
478         case GAP_EVENT_EXTENDED_ADVERTISING_REPORT:
479         {
480             if (app_state != APP_W4_BROADCAST_ADV) break;
481 
482             gap_event_extended_advertising_report_get_address(packet, remote);
483             uint8_t adv_size = gap_event_extended_advertising_report_get_data_length(packet);
484             const uint8_t * adv_data = gap_event_extended_advertising_report_get_data(packet);
485 
486             ad_context_t context;
487             bool found = false;
488             remote_name[0] = '\0';
489             uint16_t uuid;
490             for (ad_iterator_init(&context, adv_size, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
491                 uint8_t data_type = ad_iterator_get_data_type(&context);
492                 uint8_t size = ad_iterator_get_data_len(&context);
493                 const uint8_t *data = ad_iterator_get_data(&context);
494                 switch (data_type){
495                     case BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID:
496                         uuid = little_endian_read_16(data, 0);
497                         if (uuid == ORG_BLUETOOTH_SERVICE_BROADCAST_AUDIO_ANNOUNCEMENT_SERVICE){
498                             found = true;
499                         }
500                         break;
501                     case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
502                     case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
503                         size = btstack_min(sizeof(remote_name) - 1, size);
504                         memcpy(remote_name, data, size);
505                         remote_name[size] = 0;
506                         // support for nRF5340 Audio DK
507                         if (strncmp("NRF5340", remote_name, 7) == 0){
508                             nrf5340_audio_demo = true;
509                             found = true;
510                         }
511                         break;
512                     default:
513                         break;
514                 }
515             }
516             if (!found) break;
517             remote_type = gap_event_extended_advertising_report_get_address_type(packet);
518             remote_sid = gap_event_extended_advertising_report_get_advertising_sid(packet);
519             pts_mode = strncmp("PTS-", remote_name, 4) == 0;
520             count_mode = strncmp("COUNT", remote_name, 5) == 0;
521             printf("Remote Broadcast sink found, addr %s, name: '%s' (pts-mode: %u, count: %u)\n", bd_addr_to_str(remote), remote_name, pts_mode, count_mode);
522             // ignore other advertisements
523             gap_whitelist_add(remote_type, remote);
524             gap_set_scan_params(1, 0x30, 0x30, 1);
525             // sync to PA
526             gap_periodic_advertiser_list_clear();
527             gap_periodic_advertiser_list_add(remote_type, remote, remote_sid);
528             app_state = APP_W4_PA_AND_BIG_INFO;
529             printf("Start Periodic Advertising Sync\n");
530             gap_periodic_advertising_create_sync(0x01, remote_sid, remote_type, remote, 0, 1000, 0);
531             break;
532         }
533 
534         case HCI_EVENT_LE_META:
535             switch(hci_event_le_meta_get_subevent_code(packet)) {
536                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
537                     printf("Periodic advertising sync established\n");
538                     break;
539                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_REPORT:
540                     if (have_base) break;
541                     handle_periodic_advertisement(packet, size);
542                     if (have_base & have_big_info){
543                         enter_create_big_sync();
544                     }
545                     break;
546                 case HCI_SUBEVENT_LE_BIGINFO_ADVERTISING_REPORT:
547                     if (have_big_info) break;
548                     handle_big_info(packet, size);
549                     if (have_base & have_big_info){
550                         enter_create_big_sync();
551                     }
552                     break;
553                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
554                     printf("BIG Sync Lost\n");
555                     {
556                         const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
557                         if (sink != NULL) {
558                             sink->stop_stream();
559                             sink->close();
560                         }
561                     }
562                     // start over
563                     start_scanning();
564                     break;
565                 default:
566                     break;
567             }
568             break;
569         case HCI_EVENT_META_GAP:
570             switch (hci_event_gap_meta_get_subevent_code(packet)){
571                 case GAP_SUBEVENT_BIG_SYNC_CREATED: {
572                     printf("BIG Sync created with BIS Connection handles: ");
573                     uint8_t i;
574                     for (i=0;i<num_bis;i++){
575                         bis_con_handles[i] = gap_subevent_big_sync_created_get_bis_con_handles(packet, i);
576                         printf("0x%04x ", bis_con_handles[i]);
577                     }
578                     app_state = APP_STREAMING;
579                     last_samples_report_ms = btstack_run_loop_get_time_ms();
580                     printf("Start streaming\n");
581                     break;
582                 }
583                 default:
584                     break;
585             }
586             break;
587         default:
588             break;
589     }
590 }
591 
592 static void store_samples_in_ringbuffer(void){
593     // check if we have all channels
594     uint8_t bis_channel;
595     for (bis_channel = 0; bis_channel < num_bis ; bis_channel++){
596         if (have_pcm[bis_channel] == false) return;
597     }
598 #ifdef HAVE_POSIX_FILE_IO
599     // write wav samples
600     wav_writer_write_int16(num_bis * number_samples_per_frame, pcm);
601 #endif
602     // store samples in playback buffer
603     uint32_t bytes_to_store = num_bis * number_samples_per_frame * 2;
604     samples_received += number_samples_per_frame;
605     if (btstack_ring_buffer_bytes_free(&playback_buffer) >= bytes_to_store) {
606         btstack_ring_buffer_write(&playback_buffer, (uint8_t *) pcm, bytes_to_store);
607     } else {
608         printf("Samples dropped\n");
609         samples_dropped += number_samples_per_frame;
610     }
611     // reset
612     for (bis_channel = 0; bis_channel < num_bis ; bis_channel++){
613         have_pcm[bis_channel] = false;
614     }
615 }
616 
617 
618 static void plc_timeout(btstack_timer_source_t * timer) {
619 
620     uint8_t bis_channel = (uint8_t) (uintptr_t) btstack_run_loop_get_timer_context(timer);
621     log_info("PLC channel %u", bis_channel);
622 
623     // set timer again
624     uint32_t frame_duration_ms = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 8 : 10;
625     btstack_run_loop_set_timer(&next_packet_timer[bis_channel], frame_duration_ms);
626     btstack_run_loop_set_timer_handler(&next_packet_timer[bis_channel], plc_timeout);
627     btstack_run_loop_add_timer(&next_packet_timer[bis_channel]);
628 
629     // inject packet
630     uint8_t tmp_BEC_detect;
631     uint8_t BFI = 1;
632     (void) lc3_decoder->decode_signed_16(decoder_contexts[bis_channel], NULL, cached_iso_sdu_len, BFI,
633                                          &pcm[bis_channel], num_bis,
634                                          &tmp_BEC_detect);
635     have_pcm[bis_channel] = true;
636     store_samples_in_ringbuffer();
637 }
638 
639 static void iso_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
640 
641     uint16_t header = little_endian_read_16(packet, 0);
642     hci_con_handle_t con_handle = header & 0x0fff;
643     uint8_t pb_flag = (header >> 12) & 3;
644     uint8_t ts_flag = (header >> 14) & 1;
645     uint16_t iso_load_len = little_endian_read_16(packet, 2);
646 
647     uint16_t offset = 4;
648     uint32_t time_stamp = 0;
649     if (ts_flag){
650         uint32_t time_stamp = little_endian_read_32(packet, offset);
651         offset += 4;
652     }
653 
654     uint32_t receive_time_ms = btstack_run_loop_get_time_ms();
655 
656     uint16_t packet_sequence_number = little_endian_read_16(packet, offset);
657     offset += 2;
658 
659     uint16_t header_2 = little_endian_read_16(packet, offset);
660     uint16_t iso_sdu_length = header_2 & 0x3fff;
661     uint8_t packet_status_flag = (uint8_t) (header_2 >> 14);
662     offset += 2;
663 
664     if (iso_sdu_length == 0) return;
665 
666     // infer channel from con handle - only works for up to 2 channels
667     uint8_t bis_channel = (con_handle == bis_con_handles[0]) ? 0 : 1;
668 
669     if (count_mode){
670         // check for missing packet
671         uint16_t last_seq_no = last_packet_sequence[bis_channel];
672         uint32_t now = btstack_run_loop_get_time_ms();
673         bool packet_missed = (last_seq_no != 0) && ((last_seq_no + 1) != packet_sequence_number);
674         if (packet_missed){
675             // print last packet
676             printf("\n");
677             printf("%04x %10"PRIu32" %u ", last_seq_no, last_packet_time_ms[bis_channel], bis_channel);
678             printf_hexdump(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], PACKET_PREFIX_LEN);
679             last_seq_no++;
680 
681             printf(ANSI_COLOR_RED);
682             while (last_seq_no < packet_sequence_number){
683                 printf("%04x            %u MISSING\n", last_seq_no, bis_channel);
684                 last_seq_no++;
685             }
686             printf(ANSI_COLOR_RESET);
687 
688             // print current packet
689             printf("%04x %10"PRIu32" %u ", packet_sequence_number, now, bis_channel);
690             printf_hexdump(&packet[offset], PACKET_PREFIX_LEN);
691         }
692 
693         // cache current packet
694         last_packet_time_ms[bis_channel] = now;
695         last_packet_sequence[bis_channel] = packet_sequence_number;
696         memcpy(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], &packet[offset], PACKET_PREFIX_LEN);
697 
698     } else {
699 
700         if ((packet_sequence_number & 0x7c) == 0) {
701             printf("%04x %10"PRIu32" %u ", packet_sequence_number, btstack_run_loop_get_time_ms(), bis_channel);
702             printf_hexdump(&packet[offset], iso_sdu_length);
703         }
704 
705         if (lc3_frames < DUMP_LEN_LC3_FRAMES) {
706             // store len header only for first bis
707             if (bis_channel == 0) {
708                 uint8_t len_header[2];
709                 little_endian_store_16(len_header, 0, num_bis * iso_sdu_length);
710                 write(dump_file, len_header, 2);
711             }
712 
713             // store single channel codec frame
714             write(dump_file, &packet[offset], iso_sdu_length);
715         }
716 
717         // decode codec frame
718         uint8_t tmp_BEC_detect;
719         uint8_t BFI = 0;
720         (void) lc3_decoder->decode_signed_16(decoder_contexts[bis_channel], &packet[offset], iso_sdu_length, BFI,
721                                    &pcm[bis_channel], num_bis,
722                                    &tmp_BEC_detect);
723         have_pcm[bis_channel] = true;
724         store_samples_in_ringbuffer();
725 
726         lc3_frames++;
727         frames_per_second[bis_channel]++;
728 
729         // PLC
730         cached_iso_sdu_len = iso_sdu_length;
731         uint32_t frame_duration_ms = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 8 : 10;
732         btstack_run_loop_remove_timer(&next_packet_timer[bis_channel]);
733         btstack_run_loop_set_timer(&next_packet_timer[bis_channel], frame_duration_ms + PLC_GUARD_MS);
734         btstack_run_loop_set_timer_context(&next_packet_timer[bis_channel], (void *) (uintptr_t) bis_channel);
735         btstack_run_loop_set_timer_handler(&next_packet_timer[bis_channel], plc_timeout);
736         btstack_run_loop_add_timer(&next_packet_timer[bis_channel]);
737 
738         uint32_t time_ms = btstack_run_loop_get_time_ms();
739         if (btstack_time_delta(time_ms, last_samples_report_ms) >= 1000){
740             last_samples_report_ms = time_ms;
741             printf("LC3 Frames: %4u - ", (int) (lc3_frames / num_bis));
742             uint8_t i;
743             for (i=0;i<num_bis;i++){
744                 printf("%u ", frames_per_second[i]);
745                 frames_per_second[i] = 0;
746             }
747             printf(" frames per second, dropped %u of %u\n", samples_dropped, samples_received);
748             samples_received = 0;
749             samples_dropped  =  0;
750         }
751 
752         if (lc3_frames == DUMP_LEN_LC3_FRAMES){
753             close_files();
754         }
755     }
756 }
757 
758 static void show_usage(void){
759     printf("\n--- LE Audio Broadcast Sink Test Console ---\n");
760     printf("s - start scanning\n");
761 #ifdef HAVE_LC3PLUS
762     printf("q - use LC3plus decoder if 10 ms ISO interval is used\n");
763 #endif
764     printf("x - close files and exit\n");
765     printf("---\n");
766 }
767 
768 static void stdin_process(char c){
769     switch (c){
770         case 's':
771             if (app_state != APP_W4_WORKING) break;
772             start_scanning();
773             break;
774 #ifdef HAVE_LC3PLUS
775         case 'q':
776             request_lc3plus_decoder = true;
777             break;
778 #endif
779         case 'x':
780             close_files();
781             printf("Shutdown...\n");
782             hci_power_control(HCI_POWER_OFF);
783             break;
784         case '\n':
785         case '\r':
786             break;
787         default:
788             show_usage();
789             break;
790 
791     }
792 }
793 
794 int btstack_main(int argc, const char * argv[]);
795 int btstack_main(int argc, const char * argv[]){
796     (void) argv;
797     (void) argc;
798 
799     // register for HCI events
800     hci_event_callback_registration.callback = &packet_handler;
801     hci_add_event_handler(&hci_event_callback_registration);
802 
803     // register for ISO Packet
804     hci_register_iso_packet_handler(&iso_packet_handler);
805 
806     // turn on!
807     hci_power_control(HCI_POWER_ON);
808 
809     btstack_stdin_setup(stdin_process);
810     return 0;
811 }
812