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