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