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 const 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 = 0, 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_remote_client_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 gap_extended_advertising_setup(&le_advertising_set, &extended_params, &adv_handle); 488 gap_extended_advertising_set_adv_data(adv_handle, sizeof(extended_adv_data), extended_adv_data); 489 gap_extended_advertising_start(adv_handle, 0, 0); 490 } 491 492 static void got_base_and_big_info() { 493 // add source 494 if (standalone_mode) { 495 printf("BASS: add Broadcast Source\n"); 496 // add source 497 uint8_t source_index = 0; 498 broadcast_audio_scan_service_server_add_source(bass_source_new, &source_index); 499 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA); 500 } 501 502 if ((encryption == false) || have_broadcast_code){ 503 enter_create_big_sync(); 504 } else { 505 printf("BASS: request Broadcast Code\n"); 506 bass_sources[0].big_encryption = LE_AUDIO_BIG_ENCRYPTION_BROADCAST_CODE_REQUIRED; 507 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA); 508 app_state = APP_W4_BROADCAST_CODE; 509 } 510 } 511 512 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 513 UNUSED(channel); 514 if (packet_type != HCI_EVENT_PACKET) return; 515 switch (packet[0]) { 516 case BTSTACK_EVENT_STATE: 517 switch(btstack_event_state_get_state(packet)) { 518 case HCI_STATE_WORKING: 519 app_state = APP_IDLE; 520 #ifdef ENABLE_DEMO_MODE 521 start_scanning(); 522 #else 523 show_usage(); 524 #endif 525 break; 526 case HCI_STATE_OFF: 527 printf("Goodbye\n"); 528 exit(0); 529 break; 530 default: 531 break; 532 } 533 break; 534 case GAP_EVENT_EXTENDED_ADVERTISING_REPORT: 535 { 536 if (app_state != APP_W4_BROADCAST_ADV) break; 537 538 gap_event_extended_advertising_report_get_address(packet, remote); 539 uint8_t adv_size = gap_event_extended_advertising_report_get_data_length(packet); 540 const uint8_t * adv_data = gap_event_extended_advertising_report_get_data(packet); 541 542 ad_context_t context; 543 bool found = false; 544 remote_name[0] = '\0'; 545 uint16_t uuid; 546 uint32_t broadcast_id; 547 for (ad_iterator_init(&context, adv_size, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) { 548 uint8_t data_type = ad_iterator_get_data_type(&context); 549 uint8_t size = ad_iterator_get_data_len(&context); 550 const uint8_t *data = ad_iterator_get_data(&context); 551 switch (data_type){ 552 case BLUETOOTH_DATA_TYPE_SERVICE_DATA_16_BIT_UUID: 553 uuid = little_endian_read_16(data, 0); 554 if (uuid == ORG_BLUETOOTH_SERVICE_BROADCAST_AUDIO_ANNOUNCEMENT_SERVICE){ 555 broadcast_id = little_endian_read_24(data, 2); 556 found = true; 557 } 558 break; 559 case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME: 560 case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME: 561 size = btstack_min(sizeof(remote_name) - 1, size); 562 memcpy(remote_name, data, size); 563 remote_name[size] = 0; 564 // support for nRF5340 Audio DK 565 if (strncmp("NRF5340", remote_name, 7) == 0){ 566 nrf5340_audio_demo = true; 567 found = true; 568 } 569 break; 570 default: 571 break; 572 } 573 } 574 if (!found) break; 575 remote_type = gap_event_extended_advertising_report_get_address_type(packet); 576 remote_sid = gap_event_extended_advertising_report_get_advertising_sid(packet); 577 pts_mode = strncmp("PTS-", remote_name, 4) == 0; 578 count_mode = strncmp("COUNT", remote_name, 5) == 0; 579 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); 580 // ignore other advertisements 581 gap_whitelist_add(remote_type, remote); 582 gap_set_scan_params(1, 0x30, 0x30, 1); 583 // sync to PA 584 gap_periodic_advertiser_list_clear(); 585 gap_periodic_advertiser_list_add(remote_type, remote, remote_sid); 586 app_state = APP_W4_PA_AND_BIG_INFO; 587 printf("Start Periodic Advertising Sync\n"); 588 gap_periodic_advertising_create_sync(0x01, remote_sid, remote_type, remote, 0, 1000, 0); 589 590 // setup bass source info 591 bass_source_new.address_type = remote_type; 592 memcpy(bass_source_new.address, remote, 6); 593 bass_source_new.adv_sid = remote_sid; 594 bass_source_new.broadcast_id = broadcast_id; 595 bass_source_new.pa_sync = LE_AUDIO_PA_SYNC_SYNCHRONIZE_TO_PA_PAST_AVAILABLE; 596 bass_source_new.pa_interval = gap_event_extended_advertising_report_get_periodic_advertising_interval(packet); 597 break; 598 } 599 600 case HCI_EVENT_LE_META: 601 switch(hci_event_le_meta_get_subevent_code(packet)) { 602 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED: 603 // PAST implies broadcast source has been added by client 604 printf("Periodic advertising sync transfer received\n"); 605 btstack_run_loop_remove_timer(&broadcast_sink_pa_sync_timer); 606 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA); 607 app_state = APP_W4_PA_AND_BIG_INFO; 608 break; 609 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT: 610 sync_handle = hci_subevent_le_periodic_advertising_sync_establishment_get_sync_handle(packet); 611 printf("Periodic advertising sync with handle 0x%04x established\n", sync_handle); 612 app_state = APP_W4_PA_AND_BIG_INFO; 613 break; 614 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_REPORT: 615 if (app_state != APP_W4_PA_AND_BIG_INFO) break; 616 if (have_base) break; 617 handle_periodic_advertisement(packet, size); 618 if (have_base && have_big_info){ 619 got_base_and_big_info(); 620 } 621 break; 622 case HCI_SUBEVENT_LE_BIGINFO_ADVERTISING_REPORT: 623 if (app_state != APP_W4_PA_AND_BIG_INFO) break; 624 if (have_big_info) break; 625 handle_big_info(packet, size); 626 if (have_base && have_big_info){ 627 got_base_and_big_info(); 628 } 629 break; 630 case HCI_SUBEVENT_LE_BIG_SYNC_LOST: 631 printf("BIG Sync Lost\n"); 632 { 633 const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance(); 634 if (sink != NULL) { 635 sink->stop_stream(); 636 sink->close(); 637 } 638 } 639 // start over 640 if (!standalone_mode) break; 641 start_scanning(); 642 break; 643 default: 644 break; 645 } 646 break; 647 case HCI_EVENT_META_GAP: 648 switch (hci_event_gap_meta_get_subevent_code(packet)){ 649 case GAP_SUBEVENT_BIG_SYNC_CREATED: { 650 printf("BIG Sync created with BIS Connection handles: "); 651 uint8_t i; 652 for (i=0;i<num_bis;i++){ 653 bis_con_handles[i] = gap_subevent_big_sync_created_get_bis_con_handles(packet, i); 654 printf("0x%04x ", bis_con_handles[i]); 655 } 656 printf("\n"); 657 app_state = APP_STREAMING; 658 last_packet_received_big = false; 659 last_samples_report_ms = btstack_run_loop_get_time_ms(); 660 memset(last_packet_sequence, 0, sizeof(last_packet_sequence)); 661 memset(last_packet_received, 0, sizeof(last_packet_received)); 662 memset(pcm, 0, sizeof(pcm)); 663 printf("Start receiving\n"); 664 665 // update BIS Sync state 666 bass_sources[0].data.subgroups[0].bis_sync_state = bis_sync_mask; 667 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA); 668 break; 669 } 670 case GAP_SUBEVENT_BIG_SYNC_STOPPED: 671 printf("BIG Sync stopped, big_handle 0x%02x\n", gap_subevent_big_sync_stopped_get_big_handle(packet)); 672 break; 673 default: 674 break; 675 } 676 break; 677 case SM_EVENT_JUST_WORKS_REQUEST: 678 printf("Just Works requested\n"); 679 sm_just_works_confirm(sm_event_just_works_request_get_handle(packet)); 680 break; 681 default: 682 break; 683 } 684 } 685 686 static void store_samples_in_ringbuffer(void){ 687 // check if we have all channels 688 uint8_t bis_channel; 689 for (bis_channel = 0; bis_channel < num_bis ; bis_channel++){ 690 if (have_pcm[bis_channel] == false) return; 691 } 692 #ifdef HAVE_POSIX_FILE_IO 693 // write wav samples 694 wav_writer_write_int16(num_bis * number_samples_per_frame, pcm); 695 #endif 696 // store samples in playback buffer 697 uint32_t bytes_to_store = num_bis * number_samples_per_frame * 2; 698 samples_received += number_samples_per_frame; 699 if (btstack_ring_buffer_bytes_free(&playback_buffer) >= bytes_to_store) { 700 btstack_ring_buffer_write(&playback_buffer, (uint8_t *) pcm, bytes_to_store); 701 } else { 702 //printf("Samples dropped\n"); 703 samples_dropped += number_samples_per_frame; 704 } 705 // reset 706 for (bis_channel = 0; bis_channel < num_bis ; bis_channel++){ 707 have_pcm[bis_channel] = false; 708 } 709 } 710 711 static void plc_do(uint8_t bis_channel) {// inject packet 712 uint8_t tmp_BEC_detect; 713 uint8_t BFI = 1; 714 (void) lc3_decoder->decode_signed_16(decoder_contexts[bis_channel], NULL, BFI, 715 &pcm[bis_channel], num_bis, 716 &tmp_BEC_detect); 717 718 have_pcm[bis_channel] = true; 719 store_samples_in_ringbuffer(); 720 } 721 722 // 723 // Perform PLC for packets missing in previous intervals 724 // 725 // assumptions: 726 // - packet sequence number is monotonic increasing 727 // - if packet with seq nr x is received, all packets with smaller seq number are either received or missed 728 static void plc_check(uint16_t packet_sequence_number) { 729 while (last_packet_sequence_big != packet_sequence_number){ 730 uint8_t i; 731 for (i=0;i<num_bis;i++){ 732 // deal with first packet missing. inject silent samples, pcm buffer is memset to zero at start 733 if (last_packet_received[i] == false){ 734 printf_plc("- BIS #%u, very first packet missing\n", i); 735 have_pcm[i] = true; 736 store_samples_in_ringbuffer(); 737 738 last_packet_received[i] = true; 739 last_packet_sequence[i] = last_packet_sequence_big; 740 continue; 741 } 742 743 // missing packet if big sequence counter is higher than bis sequence counter 744 if (btstack_time16_delta(last_packet_sequence_big, last_packet_sequence[i]) > 0) { 745 printf_plc("- BIS #%u, PLC for %u\n", i, last_packet_sequence_big); 746 plc_do(i); 747 btstack_assert((last_packet_sequence[i] + 1) == last_packet_sequence_big); 748 last_packet_sequence[i] = last_packet_sequence_big; 749 } 750 } 751 last_packet_sequence_big++; 752 } 753 } 754 755 static void plc_timeout(btstack_timer_source_t * timer) { 756 if (app_state != APP_STREAMING) return; 757 758 // Restart timer. This will loose sync with ISO interval, but if we stop caring if we loose that many packets 759 uint32_t frame_duration_ms = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 8 : 10; 760 btstack_run_loop_set_timer(timer, frame_duration_ms); 761 btstack_run_loop_set_timer_handler(timer, plc_timeout); 762 btstack_run_loop_add_timer(timer); 763 764 // assume no packet received in iso interval 765 plc_check(last_packet_sequence_big + 1); 766 } 767 768 static void iso_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 769 770 if (app_state != APP_STREAMING) return; 771 772 uint16_t header = little_endian_read_16(packet, 0); 773 hci_con_handle_t con_handle = header & 0x0fff; 774 uint8_t pb_flag = (header >> 12) & 3; 775 uint8_t ts_flag = (header >> 14) & 1; 776 uint16_t iso_load_len = little_endian_read_16(packet, 2); 777 778 uint16_t offset = 4; 779 uint32_t time_stamp = 0; 780 if (ts_flag){ 781 uint32_t time_stamp = little_endian_read_32(packet, offset); 782 offset += 4; 783 } 784 785 uint32_t receive_time_ms = btstack_run_loop_get_time_ms(); 786 787 uint16_t packet_sequence_number = little_endian_read_16(packet, offset); 788 offset += 2; 789 790 uint16_t header_2 = little_endian_read_16(packet, offset); 791 uint16_t iso_sdu_length = header_2 & 0x3fff; 792 uint8_t packet_status_flag = (uint8_t) (header_2 >> 14); 793 offset += 2; 794 795 if (iso_sdu_length == 0) return; 796 797 // infer channel from con handle - only works for up to 2 channels 798 uint8_t bis_channel = (con_handle == bis_con_handles[0]) ? 0 : 1; 799 800 if (count_mode){ 801 // check for missing packet 802 uint16_t last_seq_no = last_packet_sequence[bis_channel]; 803 bool packet_missed = (last_seq_no != 0) && ((last_seq_no + 1) != packet_sequence_number); 804 if (packet_missed){ 805 // print last packet 806 printf("\n"); 807 printf("%04x %10"PRIu32" %u ", last_seq_no, last_packet_time_ms[bis_channel], bis_channel); 808 printf_hexdump(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], PACKET_PREFIX_LEN); 809 last_seq_no++; 810 811 printf(ANSI_COLOR_RED); 812 while (last_seq_no < packet_sequence_number){ 813 printf("%04x %u MISSING\n", last_seq_no, bis_channel); 814 last_seq_no++; 815 } 816 printf(ANSI_COLOR_RESET); 817 818 // print current packet 819 printf("%04x %10"PRIu32" %u ", packet_sequence_number, receive_time_ms, bis_channel); 820 printf_hexdump(&packet[offset], PACKET_PREFIX_LEN); 821 } 822 823 // cache current packet 824 memcpy(&last_packet_prefix[num_bis*PACKET_PREFIX_LEN], &packet[offset], PACKET_PREFIX_LEN); 825 826 } else { 827 828 829 if (last_packet_received[bis_channel]) { 830 831 printf_plc("BIS #%u, receive %u\n", bis_channel, packet_sequence_number); 832 833 int16_t packet_sequence_delta = btstack_time16_delta(packet_sequence_number, 834 last_packet_sequence[bis_channel]); 835 if (packet_sequence_delta < 1) { 836 // drop delayed packet that had already been generated by PLC 837 printf_plc("- dropping delayed packet. Current sequence number %u, last received or generated by PLC: %u\n", 838 packet_sequence_number, last_packet_sequence[bis_channel]); 839 return; 840 } 841 // simple check 842 if (packet_sequence_number != last_packet_sequence[bis_channel] + 1) { 843 printf_plc("- BIS #%u, missing %u\n", bis_channel, last_packet_sequence[bis_channel] + 1); 844 } 845 } else { 846 847 printf_plc("BIS %u, first packet seq number %u\n", bis_channel, packet_sequence_number); 848 849 if (!last_packet_received_big) { 850 // track sequence number of very first received packet 851 last_packet_received_big = true; 852 last_packet_sequence_big = packet_sequence_number; 853 } 854 last_packet_received[bis_channel] = true; 855 } 856 857 plc_check(packet_sequence_number); 858 859 // decode codec frame 860 uint8_t tmp_BEC_detect; 861 uint8_t BFI = 0; 862 (void) lc3_decoder->decode_signed_16(decoder_contexts[bis_channel], &packet[offset], BFI, 863 &pcm[bis_channel], num_bis, 864 &tmp_BEC_detect); 865 have_pcm[bis_channel] = true; 866 store_samples_in_ringbuffer(); 867 868 lc3_frames++; 869 frames_per_second[bis_channel]++; 870 871 // PLC 872 cached_iso_sdu_len = iso_sdu_length; 873 uint32_t frame_duration_ms = frame_duration == BTSTACK_LC3_FRAME_DURATION_7500US ? 8 : 10; 874 uint32_t timeout_ms = frame_duration_ms * 5 / 2; 875 btstack_run_loop_remove_timer(&next_packet_timer); 876 btstack_run_loop_set_timer(&next_packet_timer, timeout_ms); 877 btstack_run_loop_set_timer_handler(&next_packet_timer, plc_timeout); 878 btstack_run_loop_add_timer(&next_packet_timer); 879 880 uint32_t time_ms = btstack_run_loop_get_time_ms(); 881 if (btstack_time_delta(time_ms, last_samples_report_ms) >= 1000){ 882 last_samples_report_ms = time_ms; 883 printf("LC3 Frames: %4u - ", (int) (lc3_frames / num_bis)); 884 uint8_t i; 885 for (i=0;i<num_bis;i++){ 886 printf("%u ", frames_per_second[i]); 887 frames_per_second[i] = 0; 888 } 889 printf(" frames per second, dropped %u of %u\n", samples_dropped, samples_received); 890 samples_received = 0; 891 samples_dropped = 0; 892 } 893 } 894 895 last_packet_time_ms[bis_channel] = receive_time_ms; 896 last_packet_sequence[bis_channel] = packet_sequence_number; 897 } 898 899 static void show_usage(void){ 900 printf("\n--- LE Audio Broadcast Sink Test Console ---\n"); 901 printf("s - start scanning\n"); 902 #ifdef HAVE_LC3PLUS 903 printf("q - use LC3plus decoder if 10 ms ISO interval is used\n"); 904 #endif 905 printf("e - set broadcast code to 0x11111111111111111111111111111111\n"); 906 printf("t - terminate BIS streams\n"); 907 printf("x - close files and exit\n"); 908 printf("---\n"); 909 } 910 911 static void stdin_process(char c){ 912 switch (c){ 913 case 's': 914 if (app_state != APP_IDLE) break; 915 standalone_mode = true; 916 start_scanning(); 917 break; 918 case 'e': 919 printf("Set broadcast code to 0x11111111111111111111111111111111\n"); 920 memset(broadcast_code, 0x11, 16); 921 have_broadcast_code = true; 922 break; 923 #ifdef HAVE_LC3PLUS 924 case 'q': 925 printf("Use LC3plus decoder for 10 ms ISO interval...\n"); 926 request_lc3plus_decoder = true; 927 break; 928 #endif 929 case 't': 930 switch (app_state){ 931 case APP_STREAMING: 932 case APP_W4_BIG_SYNC_ESTABLISHED: 933 app_state = APP_IDLE; 934 close_files(); 935 printf("Terminate BIG SYNC\n"); 936 gap_big_sync_terminate(big_handle); 937 break; 938 default: 939 break; 940 } 941 break; 942 case 'x': 943 close_files(); 944 printf("Shutdown...\n"); 945 hci_power_control(HCI_POWER_OFF); 946 break; 947 case '\n': 948 case '\r': 949 break; 950 default: 951 show_usage(); 952 break; 953 954 } 955 } 956 957 static void broadcast_sync_pa_sync_timeout_handler(btstack_timer_source_t * ts){ 958 UNUSED(ts); 959 printf("PAST Timeout -> LE_AUDIO_PA_SYNC_STATE_NO_PAST\n"); 960 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_NO_PAST); 961 } 962 963 static void bass_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 964 UNUSED(packet_type); 965 UNUSED(channel); 966 btstack_assert (packet_type == HCI_EVENT_PACKET); 967 btstack_assert(hci_event_packet_get_type(packet) == HCI_EVENT_GATTSERVICE_META); 968 printf("BASS Event 0x%02x: ", hci_event_gattservice_meta_get_subevent_code(packet)); 969 printf_hexdump(packet, size); 970 switch (hci_event_gattservice_meta_get_subevent_code(packet)){ 971 case GATTSERVICE_SUBEVENT_BASS_SOURCE_ADDED: 972 printf("GATTSERVICE_SUBEVENT_BASS_SOURCE_ADDED, source_id 0x%04x, pa_sync %u\n", 973 gattservice_subevent_bass_source_added_get_source_id(packet), 974 gattservice_subevent_bass_source_added_get_pa_sync(packet)); 975 switch (gattservice_subevent_bass_source_added_get_pa_sync(packet)){ 976 case LE_AUDIO_PA_SYNC_SYNCHRONIZE_TO_PA_PAST_AVAILABLE: 977 printf("LE_AUDIO_PA_SYNC_SYNCHRONIZE_TO_PA_PAST_AVAILABLE -> Request SyncInfo\n"); 978 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCINFO_REQUEST); 979 // start timeout 980 btstack_run_loop_set_timer_handler(&broadcast_sink_pa_sync_timer, broadcast_sync_pa_sync_timeout_handler); 981 btstack_run_loop_set_timer(&broadcast_sink_pa_sync_timer, 10000); // 10 seconds 982 btstack_run_loop_add_timer(&broadcast_sink_pa_sync_timer); 983 break; 984 } 985 break; 986 case GATTSERVICE_SUBEVENT_BASS_SOURCE_MODIFIED: 987 printf("GATTSERVICE_SUBEVENT_BASS_SOURCE_MODIFIED, source_id 0x%04x, pa_sync %u\n", 988 gattservice_subevent_bass_source_added_get_source_id(packet), 989 gattservice_subevent_bass_source_added_get_pa_sync(packet)); 990 // handle 'bis sync == 0' 991 printf("PA Sync %u, bis_sync[0] = %u\n", bass_sources[0].data.pa_sync, bass_sources[0].data.subgroups[0].bis_sync); 992 if (bass_sources[0].data.subgroups[0].bis_sync == 0){ 993 printf("Simulate BIS Sync has stopped\n"); 994 bass_sources[0].data.subgroups[0].bis_sync_state = 0; 995 broadcast_audio_scan_service_server_set_pa_sync_state(0, LE_AUDIO_PA_SYNC_STATE_SYNCHRONIZED_TO_PA); 996 } 997 break; 998 case GATTSERVICE_SUBEVENT_BASS_BROADCAST_CODE: 999 gattservice_subevent_bass_broadcast_code_get_broadcast_code(packet, broadcast_code); 1000 printf("GATTSERVICE_SUBEVENT_BASS_BROADCAST_CODE received: "); 1001 printf_hexdump(broadcast_code, 16); 1002 bass_sources[0].big_encryption = LE_AUDIO_BIG_ENCRYPTION_DECRYPTING; 1003 if (have_base && have_big_info){ 1004 enter_create_big_sync(); 1005 } 1006 break; 1007 default: 1008 break; 1009 } 1010 } 1011 1012 int btstack_main(int argc, const char * argv[]); 1013 int btstack_main(int argc, const char * argv[]){ 1014 (void) argv; 1015 (void) argc; 1016 1017 l2cap_init(); 1018 sm_init(); 1019 1020 // setup ATT server 1021 att_server_init(profile_data, NULL, NULL); 1022 1023 // register for HCI events 1024 hci_event_callback_registration.callback = &packet_handler; 1025 hci_add_event_handler(&hci_event_callback_registration); 1026 1027 // register for ISO Packet 1028 hci_register_iso_packet_handler(&iso_packet_handler); 1029 1030 // register for SM events 1031 sm_event_callback_registration.callback = &packet_handler; 1032 sm_add_event_handler(&sm_event_callback_registration); 1033 1034 // setup BASS Server 1035 broadcast_audio_scan_service_server_init(BASS_NUM_SOURCES, bass_sources, BASS_NUM_CLIENTS, bass_clients); 1036 broadcast_audio_scan_service_server_register_packet_handler(&bass_packet_handler); 1037 1038 // setup advertising and allow to receive periodic advertising sync trasnfers 1039 setup_advertising(); 1040 gap_periodic_advertising_sync_transfer_set_default_parameters(2, 0, 0x2000, 0); 1041 1042 // turn on! 1043 hci_power_control(HCI_POWER_ON); 1044 1045 btstack_stdin_setup(stdin_process); 1046 return 0; 1047 } 1048