1 /* 2 * Copyright (C) {copyright_year} 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 BLUEKITCHEN 24 * GMBH 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_demo_util_sink.c" 39 40 #include <stdio.h> 41 #include <inttypes.h> 42 43 #include "le_audio_demo_util_sink.h" 44 45 #include "btstack_bool.h" 46 #include "btstack_config.h" 47 #include <btstack_debug.h> 48 #include <stdio.h> 49 50 #include "hci.h" 51 #include "btstack_audio.h" 52 #include "btstack_lc3_google.h" 53 #include "btstack_lc3plus_fraunhofer.h" 54 55 #include "btstack_sample_rate_compensation.h" 56 #include "btstack_resample.h" 57 #include "btstack_fsm.h" 58 59 #include "hxcmod.h" 60 #include "mods/mod.h" 61 62 #include "btstack_ring_buffer.h" 63 #ifdef HAVE_POSIX_FILE_IO 64 #include "wav_util.h" 65 #endif 66 67 #define MAX_CHANNELS 2 68 #define MAX_SAMPLES_PER_FRAME 480 69 #define MAX_LC3_FRAME_BYTES 155 70 71 // playback 72 #define MAX_NUM_LC3_FRAMES (15*2) 73 #define MAX_BYTES_PER_SAMPLE 4 74 #define PLAYBACK_BUFFER_SIZE (MAX_NUM_LC3_FRAMES * MAX_SAMPLES_PER_FRAME * MAX_CHANNELS * MAX_BYTES_PER_SAMPLE) 75 #define PLAYBACK_START_MS (MAX_NUM_LC3_FRAMES * 20 / 3) 76 77 // analysis 78 #define PACKET_PREFIX_LEN 10 79 80 #define ANSI_COLOR_RED "\x1b[31m" 81 #define ANSI_COLOR_GREEN "\x1b[32m" 82 #define ANSI_COLOR_YELLOW "\x1b[33m" 83 #define ANSI_COLOR_BLUE "\x1b[34m" 84 #define ANSI_COLOR_MAGENTA "\x1b[35m" 85 #define ANSI_COLOR_CYAN "\x1b[36m" 86 #define ANSI_COLOR_RESET "\x1b[0m" 87 88 // statistics 89 static uint16_t last_packet_sequence[MAX_CHANNELS]; 90 static uint32_t last_packet_time_ms[MAX_CHANNELS]; 91 static uint8_t last_packet_prefix[MAX_CHANNELS * PACKET_PREFIX_LEN]; 92 93 // SINK 94 95 static enum { 96 LE_AUDIO_SINK_IDLE, 97 LE_AUDIO_SINK_INIT, 98 LE_AUDIO_SINK_CONFIGURED, 99 } le_audio_demo_util_sink_state = LE_AUDIO_SINK_IDLE; 100 101 static const char * le_audio_demo_sink_filename_wav; 102 static btstack_sample_rate_compensation_t sample_rate_compensation; 103 static uint32_t le_audio_demo_sink_received_samples; 104 static btstack_resample_t resample_instance; 105 static bool sink_receive_streaming; 106 107 static int16_t pcm_resample[MAX_CHANNELS * MAX_SAMPLES_PER_FRAME * 2]; 108 109 110 static btstack_lc3_frame_duration_t le_audio_demo_sink_frame_duration; 111 static hci_iso_type_t le_audio_demo_sink_type; 112 113 static uint32_t le_audio_demo_sink_sampling_frequency_hz; 114 static uint16_t le_audio_demo_sink_num_samples_per_frame; 115 static uint8_t le_audio_demo_sink_num_streams; 116 static uint8_t le_audio_demo_sink_num_channels_per_stream; 117 static uint8_t le_audio_demo_sink_num_channels; 118 static uint16_t le_audio_demo_sink_octets_per_frame; 119 static uint16_t le_audio_demo_sink_iso_interval_1250us; 120 static uint8_t le_audio_demo_sink_flush_timeout; 121 static uint8_t le_audio_demo_sink_pre_transmission_offset; 122 123 // playback 124 static uint16_t playback_start_threshold_bytes; 125 static bool playback_active; 126 static uint8_t playback_buffer_storage[PLAYBACK_BUFFER_SIZE]; 127 static btstack_ring_buffer_t playback_buffer; 128 129 // PLC 130 static uint32_t le_audio_demo_sink_lc3_frames; 131 static uint32_t samples_received; 132 static uint32_t samples_played; 133 static uint32_t samples_dropped; 134 135 // Audio FSM 136 #define TRAN( target ) btstack_fsm_transit( &me->super, (btstack_fsm_state_handler_t)target ) 137 138 typedef struct { 139 btstack_fsm_t super; 140 uint32_t receive_time_ms; 141 uint32_t last_receive_time_ms; 142 uint32_t zero_frames; 143 uint32_t have_pcm; 144 uint32_t received_samples; 145 } audio_processing_t; 146 147 typedef struct { 148 btstack_fsm_event_t super; 149 uint16_t sequence_number; 150 uint16_t size; 151 uint32_t receive_time_ms; 152 uint8_t *data; 153 uint8_t stream; 154 } data_event_t; 155 156 typedef struct { 157 btstack_fsm_event_t super; 158 uint32_t time_ms; 159 } time_event_t; 160 161 audio_processing_t audio_processing; 162 163 enum EventSignals { 164 DATA_SIG = BTSTACK_FSM_USER_SIG, 165 TIME_SIG 166 }; 167 168 #define AUDIO_FSM_DEBUG 169 #ifdef AUDIO_FSM_DEBUG 170 #define ENUM_TO_TEXT(sig) [sig] = #sig 171 #define audio_fsm_debug(format, ...) \ 172 printf( format __VA_OPT__(,) __VA_ARGS__) 173 174 const char * const sigToString[] = { 175 ENUM_TO_TEXT(BTSTACK_FSM_INIT_SIG), 176 ENUM_TO_TEXT(BTSTACK_FSM_ENTRY_SIG), 177 ENUM_TO_TEXT(BTSTACK_FSM_EXIT_SIG), 178 ENUM_TO_TEXT(DATA_SIG), 179 ENUM_TO_TEXT(TIME_SIG), 180 }; 181 #else 182 #define audio_fsm_debug(...) 183 #endif 184 185 static btstack_fsm_state_t audio_processing_initial( audio_processing_t * const me, btstack_fsm_event_t const * const e ); 186 static btstack_fsm_state_t audio_processing_waiting( audio_processing_t * const me, btstack_fsm_event_t const * const e ); 187 static btstack_fsm_state_t audio_processing_streaming( audio_processing_t * const me, btstack_fsm_event_t const * const e ); 188 static bool audio_processing_is_streaming( audio_processing_t * const me ); 189 190 static btstack_timer_source_t next_packet_timer; 191 192 // lc3 decoder 193 static bool le_audio_demo_lc3plus_decoder_requested = false; 194 static const btstack_lc3_decoder_t * lc3_decoder; 195 static int16_t pcm[MAX_CHANNELS * MAX_SAMPLES_PER_FRAME]; 196 197 static btstack_lc3_decoder_google_t google_decoder_contexts[MAX_CHANNELS]; 198 #ifdef HAVE_LC3PLUS 199 static btstack_lc3plus_fraunhofer_decoder_t fraunhofer_decoder_contexts[MAX_CHANNELS]; 200 #endif 201 static void * decoder_contexts[MAX_CHANNELS]; 202 203 static void le_audio_connection_sink_playback(int16_t * buffer, uint16_t num_samples){ 204 // called from lower-layer but guaranteed to be on main thread 205 log_info("Playback: need %u, have %u", num_samples, btstack_ring_buffer_bytes_available(&playback_buffer) / (le_audio_demo_sink_num_channels * 2)); 206 207 samples_played += num_samples; 208 209 uint32_t bytes_needed = num_samples * le_audio_demo_sink_num_channels * 2; 210 if (playback_active == false){ 211 if (btstack_ring_buffer_bytes_available(&playback_buffer) >= playback_start_threshold_bytes) { 212 log_info("Playback started"); 213 printf("Playback started\n"); 214 playback_active = true; 215 } 216 } else { 217 if (bytes_needed > btstack_ring_buffer_bytes_available(&playback_buffer)) { 218 if( audio_processing_is_streaming( &audio_processing ) ) { 219 log_info("Playback underrun"); 220 printf("Playback Underrun\n"); 221 } else { 222 log_info("Playback stopped"); 223 printf("Playback stopped\n"); 224 } 225 // empty buffer 226 uint32_t bytes_read; 227 btstack_ring_buffer_read(&playback_buffer, (uint8_t *) buffer, bytes_needed, &bytes_read); 228 playback_active = false; 229 } 230 } 231 232 if (playback_active){ 233 uint32_t bytes_read; 234 btstack_ring_buffer_read(&playback_buffer, (uint8_t *) buffer, bytes_needed, &bytes_read); 235 btstack_assert(bytes_read == bytes_needed); 236 } else { 237 memset(buffer, 0, bytes_needed); 238 } 239 } 240 241 void le_audio_demo_util_sink_enable_lc3plus(bool enable){ 242 le_audio_demo_lc3plus_decoder_requested = enable; 243 } 244 245 static void setup_lc3_decoder(bool use_lc3plus_decoder){ 246 uint8_t channel; 247 for (channel = 0 ; channel < le_audio_demo_sink_num_channels ; channel++){ 248 // pick decoder 249 void * decoder_context = NULL; 250 #ifdef HAVE_LC3PLUS 251 if (use_lc3plus_decoder){ 252 decoder_context = &fraunhofer_decoder_contexts[channel]; 253 lc3_decoder = btstack_lc3plus_fraunhofer_decoder_init_instance(decoder_context); 254 } 255 else 256 #endif 257 { 258 decoder_context = &google_decoder_contexts[channel]; 259 lc3_decoder = btstack_lc3_decoder_google_init_instance(decoder_context); 260 } 261 decoder_contexts[channel] = decoder_context; 262 lc3_decoder->configure(decoder_context, le_audio_demo_sink_sampling_frequency_hz, le_audio_demo_sink_frame_duration, le_audio_demo_sink_octets_per_frame); 263 } 264 btstack_assert(le_audio_demo_sink_num_samples_per_frame <= MAX_SAMPLES_PER_FRAME); 265 } 266 267 void le_audio_demo_util_sink_configure_general(uint8_t num_streams, uint8_t num_channels_per_stream, 268 uint32_t sampling_frequency_hz, 269 btstack_lc3_frame_duration_t frame_duration, uint16_t octets_per_frame, 270 uint32_t iso_interval_1250us) { 271 le_audio_demo_sink_sampling_frequency_hz = sampling_frequency_hz; 272 le_audio_demo_sink_frame_duration = frame_duration; 273 le_audio_demo_sink_octets_per_frame = octets_per_frame; 274 le_audio_demo_sink_iso_interval_1250us = iso_interval_1250us; 275 le_audio_demo_sink_num_streams = num_streams; 276 le_audio_demo_sink_num_channels_per_stream = num_channels_per_stream; 277 278 sink_receive_streaming = false; 279 le_audio_demo_util_sink_state = LE_AUDIO_SINK_CONFIGURED; 280 281 le_audio_demo_sink_num_channels = le_audio_demo_sink_num_streams * le_audio_demo_sink_num_channels_per_stream; 282 btstack_assert((le_audio_demo_sink_num_channels == 1) || (le_audio_demo_sink_num_channels == 2)); 283 284 le_audio_demo_sink_lc3_frames = 0; 285 286 le_audio_demo_sink_num_samples_per_frame = btstack_lc3_samples_per_frame(le_audio_demo_sink_sampling_frequency_hz, le_audio_demo_sink_frame_duration); 287 288 // switch to lc3plus if requested and possible 289 bool use_lc3plus_decoder = le_audio_demo_lc3plus_decoder_requested && (frame_duration == BTSTACK_LC3_FRAME_DURATION_10000US); 290 291 // init decoder 292 setup_lc3_decoder(use_lc3plus_decoder); 293 294 printf("Configure: %u streams, %u channels per stream, sampling rate %u, samples per frame %u, lc3plus %u\n", 295 num_streams, num_channels_per_stream, sampling_frequency_hz, le_audio_demo_sink_num_samples_per_frame, use_lc3plus_decoder); 296 297 #ifdef HAVE_POSIX_FILE_IO 298 // create wav file 299 printf("WAV file: %s\n", le_audio_demo_sink_filename_wav); 300 wav_writer_open(le_audio_demo_sink_filename_wav, le_audio_demo_sink_num_channels, le_audio_demo_sink_sampling_frequency_hz); 301 #endif 302 303 // init playback buffer 304 btstack_ring_buffer_init(&playback_buffer, playback_buffer_storage, PLAYBACK_BUFFER_SIZE); 305 306 // calc start threshold in bytes for PLAYBACK_START_MS 307 playback_start_threshold_bytes = (sampling_frequency_hz / 1000 * PLAYBACK_START_MS) * le_audio_demo_sink_num_channels * 2; 308 309 // sample rate compensation 310 le_audio_demo_sink_received_samples = 0; 311 312 // start playback 313 const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance(); 314 if (sink != NULL){ 315 btstack_sample_rate_compensation_reset( &sample_rate_compensation, btstack_run_loop_get_time_ms() ); 316 btstack_resample_init(&resample_instance, le_audio_demo_sink_num_channels); 317 sink->init(le_audio_demo_sink_num_channels, le_audio_demo_sink_sampling_frequency_hz, le_audio_connection_sink_playback); 318 sink->start_stream(); 319 } 320 } 321 322 void le_audio_demo_util_sink_configure_unicast(uint8_t num_streams, uint8_t num_channels_per_stream, uint32_t sampling_frequency_hz, 323 btstack_lc3_frame_duration_t frame_duration, uint16_t octets_per_frame, 324 uint32_t iso_interval_1250us, uint8_t flush_timeout){ 325 le_audio_demo_sink_type = HCI_ISO_TYPE_CIS; 326 le_audio_demo_sink_flush_timeout = flush_timeout; 327 328 // set playback start: FT * ISO Interval + max(10 ms, 1/2 ISO Interval) 329 uint16_t playback_start_ms = flush_timeout * (iso_interval_1250us * 5 / 4) + btstack_max(10, iso_interval_1250us * 5 / 8); 330 uint16_t playback_start_samples = sampling_frequency_hz / 1000 * playback_start_ms; 331 playback_start_threshold_bytes = playback_start_samples * num_streams * num_channels_per_stream * 2; 332 printf("Playback: start %u ms (%u samples, %u bytes)\n", playback_start_ms, playback_start_samples, playback_start_threshold_bytes); 333 334 le_audio_demo_util_sink_configure_general(num_streams, num_channels_per_stream, sampling_frequency_hz, 335 frame_duration, octets_per_frame, iso_interval_1250us); 336 } 337 338 void le_audio_demo_util_sink_configure_broadcast(uint8_t num_streams, uint8_t num_channels_per_stream, uint32_t sampling_frequency_hz, 339 btstack_lc3_frame_duration_t frame_duration, uint16_t octets_per_frame, 340 uint32_t iso_interval_1250us, uint8_t pre_transmission_offset) { 341 le_audio_demo_sink_type = HCI_ISO_TYPE_BIS; 342 le_audio_demo_sink_pre_transmission_offset = pre_transmission_offset; 343 344 // set playback start: ISO Interval + 10 ms 345 uint16_t playback_start_ms = (iso_interval_1250us * 5 / 4) + 10; 346 uint16_t playback_start_samples = sampling_frequency_hz / 1000 * playback_start_ms; 347 playback_start_threshold_bytes = playback_start_samples * num_streams * num_channels_per_stream * 2; 348 printf("Playback: start %u ms (%u samples, %u bytes)\n", playback_start_ms, playback_start_samples, playback_start_threshold_bytes); 349 350 le_audio_demo_util_sink_configure_general(num_streams, num_channels_per_stream, sampling_frequency_hz, frame_duration, octets_per_frame, iso_interval_1250us); 351 } 352 353 void le_audio_demo_util_sink_count(uint8_t stream_index, uint8_t *packet, uint16_t size) { 354 // check for missing packet 355 uint16_t header = little_endian_read_16(packet, 0); 356 uint8_t ts_flag = (header >> 14) & 1; 357 358 uint16_t offset = 4; 359 uint32_t time_stamp = 0; 360 if (ts_flag){ 361 time_stamp = little_endian_read_32(packet, offset); 362 offset += 4; 363 } 364 (void)time_stamp; 365 uint32_t receive_time_ms = btstack_run_loop_get_time_ms(); 366 367 uint16_t packet_sequence_number = little_endian_read_16(packet, offset); 368 offset += 4; 369 370 uint16_t last_seq_no = last_packet_sequence[stream_index]; 371 bool packet_missed = (last_seq_no != 0) && ((last_seq_no + 1) != packet_sequence_number); 372 if (packet_missed){ 373 // print last packet 374 printf("\n"); 375 printf("%04x %10"PRIu32" %u ", last_seq_no, last_packet_time_ms[stream_index], stream_index); 376 printf_hexdump(&last_packet_prefix[le_audio_demo_sink_num_streams*PACKET_PREFIX_LEN], PACKET_PREFIX_LEN); 377 last_seq_no++; 378 379 printf(ANSI_COLOR_RED); 380 while (last_seq_no < packet_sequence_number){ 381 printf("%04x %u MISSING\n", last_seq_no, stream_index); 382 last_seq_no++; 383 } 384 printf(ANSI_COLOR_RESET); 385 386 // print current packet 387 printf("%04x %10"PRIu32" %u ", packet_sequence_number, receive_time_ms, stream_index); 388 printf_hexdump(&packet[offset], PACKET_PREFIX_LEN); 389 } 390 391 // cache current packet 392 memcpy(&last_packet_prefix[le_audio_demo_sink_num_streams*PACKET_PREFIX_LEN], &packet[offset], PACKET_PREFIX_LEN); 393 } 394 395 static btstack_fsm_state_t audio_processing_initial( audio_processing_t * const me, btstack_fsm_event_t const * const e ) { 396 audio_fsm_debug("%s\n", __FUNCTION__ ); 397 return TRAN(audio_processing_waiting); 398 } 399 400 static btstack_fsm_state_t audio_processing_waiting( audio_processing_t * const me, btstack_fsm_event_t const * const e ) { 401 audio_fsm_debug("%s - %s\n", __FUNCTION__, sigToString[e->sig]); 402 btstack_fsm_state_t status; 403 switch(e->sig) { 404 case BTSTACK_FSM_ENTRY_SIG: { 405 status = BTSTACK_FSM_HANDLED_STATUS; 406 break; 407 } 408 case BTSTACK_FSM_EXIT_SIG: { 409 btstack_ring_buffer_init(&playback_buffer, playback_buffer_storage, PLAYBACK_BUFFER_SIZE); 410 411 btstack_sample_rate_compensation_init(&sample_rate_compensation, me->last_receive_time_ms, 412 le_audio_demo_sink_sampling_frequency_hz, FLOAT_TO_Q15(1.f)); 413 me->zero_frames = 0; 414 me->received_samples = 0; 415 btstack_resample_init( &resample_instance, le_audio_demo_sink_num_channels ); 416 me->have_pcm = 0; 417 status = BTSTACK_FSM_HANDLED_STATUS; 418 break; 419 } 420 case DATA_SIG: { 421 data_event_t *data_event = (data_event_t*)e; 422 // nothing to do here 423 if( data_event->data == NULL ) { 424 status = BTSTACK_FSM_IGNORED_STATUS; 425 break; 426 } 427 428 // ignore empty data at start 429 if( data_event->size == 0 ) { 430 status = BTSTACK_FSM_IGNORED_STATUS; 431 break; 432 } 433 434 // always start at first stream 435 if( data_event->stream > 0 ) { 436 status = BTSTACK_FSM_IGNORED_STATUS; 437 break; 438 } 439 440 me->last_receive_time_ms = data_event->receive_time_ms; 441 status = TRAN(audio_processing_streaming); 442 break; 443 } 444 default: { 445 status = BTSTACK_FSM_IGNORED_STATUS; 446 break; 447 } 448 } 449 return status; 450 } 451 452 static void audio_processing_resample( audio_processing_t * const me, data_event_t *e ) { 453 if( me->have_pcm != ((1<<(le_audio_demo_sink_num_streams*le_audio_demo_sink_num_channels_per_stream))-1) ) { 454 return; 455 } 456 457 int16_t *data_in = pcm; 458 int16_t *data_out = pcm_resample; 459 #ifdef HAVE_POSIX_FILE_IO 460 // write wav samples 461 wav_writer_write_int16(le_audio_demo_sink_num_channels * le_audio_demo_sink_num_samples_per_frame, data_in); 462 #endif 463 464 // count for samplerate compensation 465 me->received_samples += le_audio_demo_sink_num_samples_per_frame; 466 467 // store samples in playback buffer 468 samples_received += le_audio_demo_sink_num_samples_per_frame; 469 uint32_t resampled_frames = btstack_resample_block(&resample_instance, data_in, le_audio_demo_sink_num_samples_per_frame, data_out); 470 uint32_t bytes_to_store = resampled_frames * le_audio_demo_sink_num_channels * 2; 471 472 if (btstack_ring_buffer_bytes_free(&playback_buffer) >= bytes_to_store) { 473 btstack_ring_buffer_write(&playback_buffer, (uint8_t *)data_out, bytes_to_store); 474 log_info("Samples in playback buffer %5u", btstack_ring_buffer_bytes_available(&playback_buffer) / (le_audio_demo_sink_num_channels * 2)); 475 } else { 476 printf("Samples dropped\n"); 477 samples_dropped += le_audio_demo_sink_num_samples_per_frame; 478 } 479 e->data = NULL; 480 me->have_pcm = 0; 481 } 482 483 static btstack_fsm_state_t audio_processing_decode( audio_processing_t * const me, btstack_fsm_event_t const * const e ) { 484 audio_fsm_debug("%s - %s\n", __FUNCTION__, sigToString[e->sig]); 485 btstack_fsm_state_t status; 486 switch(e->sig) { 487 case BTSTACK_FSM_ENTRY_SIG: { 488 btstack_assert( (le_audio_demo_sink_num_streams*le_audio_demo_sink_num_channels_per_stream) < (sizeof(me->have_pcm)*8)); 489 status = BTSTACK_FSM_HANDLED_STATUS; 490 break; 491 } 492 case BTSTACK_FSM_EXIT_SIG: { 493 const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance(); 494 if( sink == NULL ) { 495 496 status = BTSTACK_FSM_HANDLED_STATUS; 497 break; 498 } 499 uint32_t resampling_factor = btstack_sample_rate_compensation_update( &sample_rate_compensation, me->receive_time_ms, 500 me->received_samples, sink->get_samplerate() ); 501 btstack_resample_set_factor(&resample_instance, resampling_factor); 502 me->received_samples = 0; 503 504 status = BTSTACK_FSM_HANDLED_STATUS; 505 break; 506 } 507 case DATA_SIG: { 508 data_event_t *data_event = (data_event_t*)e; 509 uint8_t *data_in = data_event->data; 510 int16_t *data_out = pcm; 511 uint16_t offset = 0; 512 uint8_t BFI = 0; 513 if (data_event->size != le_audio_demo_sink_num_channels_per_stream * le_audio_demo_sink_octets_per_frame) { 514 // incorrect size. we assume that we received this packet on time but cannot decode it, so we use PLC 515 BFI = 1; 516 printf("predict audio\n"); 517 } 518 uint8_t i; 519 for (i = 0 ; i < le_audio_demo_sink_num_channels_per_stream ; i++){ 520 uint8_t tmp_BEC_detect; 521 uint8_t effective_channel = (data_event->stream * le_audio_demo_sink_num_channels_per_stream) + i; 522 (void) lc3_decoder->decode_signed_16(decoder_contexts[effective_channel], &data_in[offset], BFI, 523 &data_out[effective_channel], le_audio_demo_sink_num_channels, 524 &tmp_BEC_detect); 525 offset += le_audio_demo_sink_octets_per_frame; 526 btstack_assert( !(me->have_pcm & (1<<effective_channel)) ); 527 me->have_pcm |= (1<<effective_channel); 528 } 529 audio_processing_resample( me, data_event ); 530 status = TRAN(audio_processing_streaming); 531 break; 532 } 533 default: { 534 status = BTSTACK_FSM_IGNORED_STATUS; 535 break; 536 } 537 } 538 return status; 539 } 540 541 static btstack_fsm_state_t audio_processing_streaming( audio_processing_t * const me, btstack_fsm_event_t const * const e ) { 542 audio_fsm_debug("%s - %s\n", __FUNCTION__, sigToString[e->sig]); 543 544 btstack_fsm_state_t status; 545 switch(e->sig) { 546 case BTSTACK_FSM_ENTRY_SIG: { 547 status = BTSTACK_FSM_HANDLED_STATUS; 548 break; 549 } 550 case BTSTACK_FSM_EXIT_SIG: { 551 me->last_receive_time_ms = me->receive_time_ms; 552 status = BTSTACK_FSM_HANDLED_STATUS; 553 break; 554 } 555 case TIME_SIG: { 556 time_event_t *time = (time_event_t*)e; 557 printf("time: %d - %d %d\n", time->time_ms, me->last_receive_time_ms, time->time_ms-me->last_receive_time_ms ); 558 // we were last called ages ago, so just start waiting again 559 if( btstack_time_delta( time->time_ms, me->last_receive_time_ms ) > 100) { 560 status = TRAN(audio_processing_waiting); 561 break; 562 } 563 status = BTSTACK_FSM_HANDLED_STATUS; 564 break; 565 } 566 case DATA_SIG: { 567 data_event_t *data_event = (data_event_t*)e; 568 me->receive_time_ms = data_event->receive_time_ms; 569 570 // done processing this data 571 if( data_event->data == NULL ) { 572 status = BTSTACK_FSM_HANDLED_STATUS; 573 break; 574 } 575 576 if( btstack_time_delta( data_event->receive_time_ms, me->last_receive_time_ms ) > 100) { 577 status = TRAN(audio_processing_waiting); 578 break; 579 } 580 581 if( me->zero_frames > 10 ) { 582 status = TRAN(audio_processing_waiting); 583 break; 584 } 585 586 // track consecutive audio frames without data 587 if( data_event->size == 0 ) { 588 me->zero_frames++; 589 } else { 590 me->zero_frames = 0; 591 } 592 593 // will decode and/or predict missing data 594 status = TRAN(audio_processing_decode); 595 break; 596 } 597 default: { 598 status = BTSTACK_FSM_IGNORED_STATUS; 599 break; 600 } 601 } 602 return status; 603 } 604 605 static void audio_processing_constructor( audio_processing_t *me) { 606 btstack_fsm_constructor(&me->super, (btstack_fsm_state_handler_t)&audio_processing_initial); 607 btstack_fsm_init(&me->super, NULL); 608 } 609 610 static void audio_processing_task( audio_processing_t *me, btstack_fsm_event_t const *e ) { 611 btstack_fsm_dispatch_until(&me->super, e); 612 } 613 614 static bool audio_processing_is_streaming( audio_processing_t *me ) { 615 btstack_fsm_t *fsm = &me->super; 616 time_event_t const time_event = { TIME_SIG, btstack_run_loop_get_time_ms() }; 617 audio_processing_task( me, &time_event.super ); 618 return fsm->state == (btstack_fsm_state_handler_t)&audio_processing_streaming; 619 } 620 621 void le_audio_demo_util_sink_receive(uint8_t stream_index, uint8_t *packet, uint16_t size) { 622 if (le_audio_demo_util_sink_state != LE_AUDIO_SINK_CONFIGURED) return; 623 624 uint16_t header = little_endian_read_16(packet, 0); 625 hci_con_handle_t con_handle = header & 0x0fff; 626 uint8_t pb_flag = (header >> 12) & 3; 627 uint8_t ts_flag = (header >> 14) & 1; 628 uint16_t iso_load_len = little_endian_read_16(packet, 2); 629 630 uint16_t offset = 4; 631 uint32_t time_stamp = 0; 632 if (ts_flag){ 633 time_stamp = little_endian_read_32(packet, offset); 634 offset += 4; 635 } 636 637 uint32_t receive_time_ms = btstack_run_loop_get_time_ms(); 638 639 uint16_t packet_sequence_number = little_endian_read_16(packet, offset); 640 offset += 2; 641 642 uint16_t header_2 = little_endian_read_16(packet, offset); 643 uint16_t iso_sdu_length = header_2 & 0x3fff; 644 uint8_t packet_status_flag = (uint8_t) (header_2 >> 14); 645 offset += 2; 646 647 // avoid warning for (yet) unused fields 648 UNUSED(con_handle); 649 UNUSED(pb_flag); 650 UNUSED(iso_load_len); 651 UNUSED(packet_status_flag); 652 UNUSED(time_stamp); 653 654 data_event_t const data_event = { 655 .super.sig = DATA_SIG, 656 .sequence_number = packet_sequence_number, 657 .stream = stream_index, 658 .data = &packet[offset], 659 .size = iso_sdu_length, 660 .receive_time_ms = receive_time_ms, 661 }; 662 audio_fsm_debug("new data\n"); 663 audio_processing_task( &audio_processing, &data_event.super ); 664 665 le_audio_demo_sink_lc3_frames++; 666 667 if (samples_received >= le_audio_demo_sink_sampling_frequency_hz){ 668 printf("LC3 Frames: %4u - samples received %5u, played %5u, dropped %5u\n", le_audio_demo_sink_lc3_frames, samples_received, samples_played, samples_dropped); 669 samples_received = 0; 670 samples_dropped = 0; 671 samples_played = 0; 672 } 673 } 674 675 void le_audio_demo_util_sink_init(const char * filename_wav){ 676 le_audio_demo_sink_filename_wav = filename_wav; 677 le_audio_demo_util_sink_state = LE_AUDIO_SINK_INIT; 678 audio_processing_constructor( &audio_processing ); 679 } 680 681 /** 682 * @brief Close sink: close wav file, stop playback 683 */ 684 void le_audio_demo_util_sink_close(void){ 685 #ifdef HAVE_POSIX_FILE_IO 686 printf("Close WAV file\n"); 687 wav_writer_close(); 688 #endif 689 // stop playback 690 const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance(); 691 if (sink != NULL){ 692 sink->stop_stream(); 693 } 694 le_audio_demo_util_sink_state = LE_AUDIO_SINK_INIT; 695 sink_receive_streaming = false; 696 // stop timer 697 btstack_run_loop_remove_timer(&next_packet_timer); 698 } 699