xref: /btstack/example/le_audio_demo_util_sink.c (revision 47f34e0cffc2da3ae0dfdf6cba95f7f9d992eb2f)
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_DEBUGx
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     // mark current packet as handled
454     e->data = NULL;
455     if( me->have_pcm != ((1<<(le_audio_demo_sink_num_streams*le_audio_demo_sink_num_channels_per_stream))-1) ) {
456         return;
457     }
458 
459     int16_t *data_in = pcm;
460     int16_t *data_out = pcm_resample;
461 #ifdef HAVE_POSIX_FILE_IO
462     // write wav samples
463     wav_writer_write_int16(le_audio_demo_sink_num_channels * le_audio_demo_sink_num_samples_per_frame, data_in);
464 #endif
465 
466     // count for samplerate compensation
467     me->received_samples += le_audio_demo_sink_num_samples_per_frame;
468 
469     // store samples in playback buffer
470     samples_received += le_audio_demo_sink_num_samples_per_frame;
471     uint32_t resampled_frames = btstack_resample_block(&resample_instance, data_in, le_audio_demo_sink_num_samples_per_frame, data_out);
472     uint32_t bytes_to_store = resampled_frames * le_audio_demo_sink_num_channels * 2;
473 
474     if (btstack_ring_buffer_bytes_free(&playback_buffer) >= bytes_to_store) {
475         btstack_ring_buffer_write(&playback_buffer, (uint8_t *)data_out, bytes_to_store);
476         log_info("Samples in playback buffer %5u", btstack_ring_buffer_bytes_available(&playback_buffer) / (le_audio_demo_sink_num_channels * 2));
477     } else {
478         printf("Samples dropped\n");
479         samples_dropped += le_audio_demo_sink_num_samples_per_frame;
480     }
481     me->have_pcm = 0;
482 }
483 
484 static btstack_fsm_state_t audio_processing_decode( audio_processing_t * const me, btstack_fsm_event_t const * const e ) {
485     audio_fsm_debug("%s - %s\n", __FUNCTION__, sigToString[e->sig]);
486     btstack_fsm_state_t status;
487     switch(e->sig) {
488         case BTSTACK_FSM_ENTRY_SIG: {
489             btstack_assert( (le_audio_demo_sink_num_streams*le_audio_demo_sink_num_channels_per_stream) < (sizeof(me->have_pcm)*8));
490             status = BTSTACK_FSM_HANDLED_STATUS;
491             break;
492         }
493         case BTSTACK_FSM_EXIT_SIG: {
494             const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
495             if( sink == NULL ) {
496 
497                 status = BTSTACK_FSM_HANDLED_STATUS;
498                 break;
499             }
500             uint32_t resampling_factor = btstack_sample_rate_compensation_update( &sample_rate_compensation, me->receive_time_ms,
501                                                                                   me->received_samples, sink->get_samplerate() );
502             btstack_resample_set_factor(&resample_instance, resampling_factor);
503             me->received_samples = 0;
504 
505             status = BTSTACK_FSM_HANDLED_STATUS;
506             break;
507         }
508         case DATA_SIG: {
509             data_event_t *data_event = (data_event_t*)e;
510             uint8_t *data_in = data_event->data;
511             int16_t *data_out = pcm;
512             uint16_t offset = 0;
513             uint8_t BFI = 0;
514             if (data_event->size != le_audio_demo_sink_num_channels_per_stream * le_audio_demo_sink_octets_per_frame) {
515                 // incorrect size. we assume that we received this packet on time but cannot decode it, so we use PLC
516                 BFI = 1;
517                 printf("predict audio\n");
518             }
519             uint8_t i;
520             for (i = 0 ; i < le_audio_demo_sink_num_channels_per_stream ; i++){
521                 uint8_t tmp_BEC_detect;
522                 uint8_t effective_channel = (data_event->stream * le_audio_demo_sink_num_channels_per_stream) + i;
523                 (void) lc3_decoder->decode_signed_16(decoder_contexts[effective_channel], &data_in[offset], BFI,
524                                                      &data_out[effective_channel], le_audio_demo_sink_num_channels,
525                                                      &tmp_BEC_detect);
526                 offset += le_audio_demo_sink_octets_per_frame;
527                 audio_fsm_debug("effective_channel: %d\n", effective_channel );
528                 if( (me->have_pcm & (1<<effective_channel)) ) {
529                     audio_fsm_debug("de-syncroniced, resync\n");
530                     status = TRAN(audio_processing_waiting);
531                     break;
532                 }
533                 me->have_pcm |= (1<<effective_channel);
534             }
535             audio_processing_resample( me, data_event );
536             status = TRAN(audio_processing_streaming);
537             break;
538         }
539         default: {
540             status = BTSTACK_FSM_IGNORED_STATUS;
541             break;
542         }
543     }
544     return status;
545 }
546 
547 static btstack_fsm_state_t audio_processing_streaming( audio_processing_t * const me, btstack_fsm_event_t const * const e ) {
548     audio_fsm_debug("%s - %s\n", __FUNCTION__, sigToString[e->sig]);
549 
550     btstack_fsm_state_t status;
551     switch(e->sig) {
552         case BTSTACK_FSM_ENTRY_SIG: {
553             status = BTSTACK_FSM_HANDLED_STATUS;
554             break;
555         }
556         case BTSTACK_FSM_EXIT_SIG: {
557             me->last_receive_time_ms = me->receive_time_ms;
558             status = BTSTACK_FSM_HANDLED_STATUS;
559             break;
560         }
561         case TIME_SIG: {
562             time_event_t *time = (time_event_t*)e;
563             printf("time: %d - %d %d\n", time->time_ms, me->last_receive_time_ms, time->time_ms-me->last_receive_time_ms );
564             // we were last called ages ago, so just start waiting again
565             if( btstack_time_delta( time->time_ms, me->last_receive_time_ms ) > 100) {
566                 status = TRAN(audio_processing_waiting);
567                 break;
568             }
569             status = BTSTACK_FSM_HANDLED_STATUS;
570             break;
571         }
572         case DATA_SIG: {
573             data_event_t *data_event = (data_event_t*)e;
574             me->receive_time_ms = data_event->receive_time_ms;
575 
576             // done processing this data
577             if( data_event->data == NULL ) {
578                 status = BTSTACK_FSM_HANDLED_STATUS;
579                 break;
580             }
581 
582             if( btstack_time_delta( data_event->receive_time_ms, me->last_receive_time_ms ) > 100) {
583                 status = TRAN(audio_processing_waiting);
584                 break;
585             }
586 
587             if( me->zero_frames > 10 ) {
588                 status = TRAN(audio_processing_waiting);
589                 break;
590             }
591 
592             // track consecutive audio frames without data
593             if( data_event->size == 0 ) {
594                 me->zero_frames++;
595             } else {
596                 me->zero_frames = 0;
597             }
598 
599             // will decode and/or predict missing data
600             status = TRAN(audio_processing_decode);
601             break;
602         }
603         default: {
604             status = BTSTACK_FSM_IGNORED_STATUS;
605             break;
606         }
607     }
608     return status;
609 }
610 
611 static void audio_processing_constructor( audio_processing_t *me) {
612     btstack_fsm_constructor(&me->super, (btstack_fsm_state_handler_t)&audio_processing_initial);
613     btstack_fsm_init(&me->super, NULL);
614 }
615 
616 static void audio_processing_task( audio_processing_t *me, btstack_fsm_event_t const *e ) {
617     btstack_fsm_dispatch_until(&me->super, e);
618 }
619 
620 static bool audio_processing_is_streaming( audio_processing_t *me ) {
621     btstack_fsm_t *fsm = &me->super;
622     time_event_t const time_event = { TIME_SIG, btstack_run_loop_get_time_ms() };
623     audio_processing_task( me, &time_event.super );
624     return fsm->state == (btstack_fsm_state_handler_t)&audio_processing_streaming;
625 }
626 
627 void le_audio_demo_util_sink_receive(uint8_t stream_index, uint8_t *packet, uint16_t size) {
628     if (le_audio_demo_util_sink_state != LE_AUDIO_SINK_CONFIGURED) return;
629 
630     uint16_t header = little_endian_read_16(packet, 0);
631     hci_con_handle_t con_handle = header & 0x0fff;
632     uint8_t pb_flag = (header >> 12) & 3;
633     uint8_t ts_flag = (header >> 14) & 1;
634     uint16_t iso_load_len = little_endian_read_16(packet, 2);
635 
636     uint16_t offset = 4;
637     uint32_t time_stamp = 0;
638     if (ts_flag){
639         time_stamp = little_endian_read_32(packet, offset);
640         offset += 4;
641     }
642 
643     uint32_t receive_time_ms = btstack_run_loop_get_time_ms();
644 
645     uint16_t packet_sequence_number = little_endian_read_16(packet, offset);
646     offset += 2;
647 
648     uint16_t header_2 = little_endian_read_16(packet, offset);
649     uint16_t iso_sdu_length = header_2 & 0x3fff;
650     uint8_t packet_status_flag = (uint8_t) (header_2 >> 14);
651     offset += 2;
652 
653     // avoid warning for (yet) unused fields
654     UNUSED(con_handle);
655     UNUSED(pb_flag);
656     UNUSED(iso_load_len);
657     UNUSED(packet_status_flag);
658     UNUSED(time_stamp);
659 
660     data_event_t const data_event = {
661             .super.sig = DATA_SIG,
662             .sequence_number = packet_sequence_number,
663             .stream = stream_index,
664             .data = &packet[offset],
665             .size = iso_sdu_length,
666             .receive_time_ms = receive_time_ms,
667     };
668 
669     audio_fsm_debug("new data\n stream_index: %d\n", stream_index);
670     audio_processing_task( &audio_processing, &data_event.super );
671 
672     le_audio_demo_sink_lc3_frames++;
673 
674     if (samples_received >= 10 * le_audio_demo_sink_sampling_frequency_hz){
675         printf("LC3 Frames: %4u - samples received %5u, played %5u, dropped %5u\n", le_audio_demo_sink_lc3_frames, samples_received, samples_played, samples_dropped);
676         samples_received = 0;
677         samples_dropped  =  0;
678         samples_played = 0;
679     }
680 }
681 
682 void le_audio_demo_util_sink_init(const char * filename_wav){
683     le_audio_demo_sink_filename_wav = filename_wav;
684     le_audio_demo_util_sink_state = LE_AUDIO_SINK_INIT;
685     audio_processing_constructor( &audio_processing );
686 }
687 
688 /**
689  * @brief Close sink: close wav file, stop playback
690  */
691 void le_audio_demo_util_sink_close(void){
692 #ifdef HAVE_POSIX_FILE_IO
693     printf("Close WAV file\n");
694     wav_writer_close();
695 #endif
696     // stop playback
697     const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
698     if (sink != NULL){
699         sink->stop_stream();
700     }
701     le_audio_demo_util_sink_state = LE_AUDIO_SINK_INIT;
702     sink_receive_streaming = false;
703     // stop timer
704     btstack_run_loop_remove_timer(&next_packet_timer);
705 }
706