xref: /btstack/example/le_audio_demo_util_sink.c (revision 0a06514414279c433835343bc78f6a19bbdfc0ac)
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 
42 #include "le_audio_demo_util_sink.h"
43 
44 #include "btstack_bool.h"
45 #include "btstack_config.h"
46 #include <btstack_debug.h>
47 #include <printf.h>
48 
49 #include "hci.h"
50 #include "btstack_audio.h"
51 #include "btstack_lc3_google.h"
52 #include "btstack_lc3plus_fraunhofer.h"
53 
54 #include "btstack_sample_rate_compensation.h"
55 #include "btstack_resample.h"
56 
57 #include "hxcmod.h"
58 #include "mods/mod.h"
59 
60 #ifdef HAVE_POSIX_FILE_IO
61 #include "wav_util.h"
62 #include "btstack_ring_buffer.h"
63 
64 #endif
65 
66 //#define DEBUG_PLC
67 #ifdef DEBUG_PLC
68 #define printf_plc(...) { \
69     printf(__VA_ARGS__);  \
70     log_info(__VA_ARGS__);\
71 }
72 #else
73 #define printf_plc(...)  (void)(0);
74 #endif
75 
76 #define MAX_CHANNELS 2
77 #define MAX_SAMPLES_PER_FRAME 480
78 #define MAX_LC3_FRAME_BYTES   155
79 
80 // playback
81 #define MAX_NUM_LC3_FRAMES   15
82 #define MAX_BYTES_PER_SAMPLE 4
83 #define PLAYBACK_BUFFER_SIZE (MAX_NUM_LC3_FRAMES * MAX_SAMPLES_PER_FRAME * MAX_CHANNELS * MAX_BYTES_PER_SAMPLE)
84 #define PLAYBACK_START_MS (MAX_NUM_LC3_FRAMES * 20 / 3)
85 
86 #define ANSI_COLOR_RED     "\x1b[31m"
87 #define ANSI_COLOR_GREEN   "\x1b[32m"
88 #define ANSI_COLOR_YELLOW  "\x1b[33m"
89 #define ANSI_COLOR_BLUE    "\x1b[34m"
90 #define ANSI_COLOR_MAGENTA "\x1b[35m"
91 #define ANSI_COLOR_CYAN    "\x1b[36m"
92 #define ANSI_COLOR_RESET   "\x1b[0m"
93 
94 // SINK
95 
96 static const char * le_audio_demo_sink_filename_wav;
97 static btstack_sample_rate_compensation_t sample_rate_compensation;
98 static btstack_resample_t resample_instance;
99 static bool sink_receive_streaming;
100 
101 static int16_t pcm_resample[MAX_CHANNELS * MAX_SAMPLES_PER_FRAME * 2];
102 
103 
104 static btstack_lc3_frame_duration_t le_audio_demo_sink_frame_duration;
105 static hci_iso_type_t               le_audio_demo_sink_type;
106 
107 static uint32_t le_audio_demo_sink_sampling_frequency_hz;
108 static uint16_t le_audio_demo_sink_num_samples_per_frame;
109 static uint8_t  le_audio_demo_sink_num_streams;
110 static uint8_t  le_audio_demo_sink_num_channels_per_stream;
111 static uint8_t  le_audio_demo_sink_num_channels;
112 static uint16_t le_audio_demo_sink_octets_per_frame;
113 static uint16_t le_audio_demo_sink_iso_interval_1250us;
114 static uint8_t  le_audio_demo_sink_flush_timeout;
115 static uint8_t  le_audio_demo_sink_pre_transmission_offset;
116 
117 // playback
118 static uint16_t              playback_start_threshold_bytes;
119 static bool                  playback_active;
120 static uint8_t               playback_buffer_storage[PLAYBACK_BUFFER_SIZE];
121 static btstack_ring_buffer_t playback_buffer;
122 
123 // PLC
124 static bool     stream_last_packet_received[MAX_CHANNELS];
125 static uint16_t stream_last_packet_sequence[MAX_CHANNELS];
126 static uint16_t group_last_packet_sequence;
127 static bool     group_last_packet_received;
128 static uint16_t plc_timeout_initial_ms;
129 static uint16_t plc_timeout_subsequent_ms;
130 
131 static uint32_t le_audio_demo_sink_lc3_frames;
132 static uint32_t samples_received;
133 static uint32_t samples_played;
134 static uint32_t samples_dropped;
135 
136 static btstack_timer_source_t next_packet_timer;
137 
138 // lc3 decoder
139 static bool le_audio_demo_lc3plus_decoder_requested = false;
140 static const btstack_lc3_decoder_t * lc3_decoder;
141 static int16_t pcm[MAX_CHANNELS * MAX_SAMPLES_PER_FRAME];
142 static bool have_pcm[MAX_CHANNELS];
143 
144 static btstack_lc3_decoder_google_t google_decoder_contexts[MAX_CHANNELS];
145 #ifdef HAVE_LC3PLUS
146 static btstack_lc3plus_fraunhofer_decoder_t fraunhofer_decoder_contexts[MAX_CHANNELS];
147 #endif
148 static void * decoder_contexts[MAX_CHANNELS];
149 
150 static void le_audio_connection_sink_playback(int16_t * buffer, uint16_t num_samples){
151     // called from lower-layer but guaranteed to be on main thread
152     log_info("Playback: need %u, have %u", num_samples, btstack_ring_buffer_bytes_available(&playback_buffer) / (le_audio_demo_sink_num_channels * 2));
153 
154     samples_played += num_samples;
155 
156     uint32_t bytes_needed = num_samples * le_audio_demo_sink_num_channels * 2;
157     if (playback_active == false){
158         if (btstack_ring_buffer_bytes_available(&playback_buffer) >= playback_start_threshold_bytes) {
159             log_info("Playback started");
160             playback_active = true;
161         }
162     } else {
163         if (bytes_needed > btstack_ring_buffer_bytes_available(&playback_buffer)) {
164             log_info("Playback underrun");
165             printf("Playback Underrun\n");
166             // empty buffer
167             uint32_t bytes_read;
168             btstack_ring_buffer_read(&playback_buffer, (uint8_t *) buffer, bytes_needed, &bytes_read);
169             playback_active = false;
170         }
171     }
172 
173     if (playback_active){
174         uint32_t bytes_read;
175         btstack_ring_buffer_read(&playback_buffer, (uint8_t *) buffer, bytes_needed, &bytes_read);
176         btstack_assert(bytes_read == bytes_needed);
177     } else {
178         memset(buffer, 0, bytes_needed);
179     }
180 }
181 
182 static void store_samples_in_ringbuffer(void){
183     // check if we have all channels
184     uint8_t channel;
185     for (channel = 0; channel < le_audio_demo_sink_num_channels; channel++){
186         if (have_pcm[channel] == false) return;
187     }
188 #ifdef HAVE_POSIX_FILE_IO
189     // write wav samples
190     wav_writer_write_int16(le_audio_demo_sink_num_channels * le_audio_demo_sink_num_samples_per_frame, pcm);
191 #endif
192     // store samples in playback buffer
193     samples_received += le_audio_demo_sink_num_samples_per_frame;
194     uint32_t resampled_frames = btstack_resample_block(&resample_instance, pcm, le_audio_demo_sink_num_samples_per_frame, pcm_resample);
195     uint32_t bytes_to_store = resampled_frames * le_audio_demo_sink_num_channels * 2;
196 
197     if (btstack_ring_buffer_bytes_free(&playback_buffer) >= bytes_to_store) {
198         btstack_ring_buffer_write(&playback_buffer, (uint8_t *) pcm_resample, bytes_to_store);
199         log_info("Samples in playback buffer %5u", btstack_ring_buffer_bytes_available(&playback_buffer) / (le_audio_demo_sink_num_channels * 2));
200     } else {
201         printf("Samples dropped\n");
202         samples_dropped += le_audio_demo_sink_num_samples_per_frame;
203     }
204     memset(have_pcm, 0, sizeof(have_pcm));
205 }
206 
207 static void plc_do(uint8_t stream_index) {
208     // inject packet
209     uint8_t tmp_BEC_detect;
210     uint8_t BFI = 1;
211     uint8_t i;
212     for (i = 0; i < le_audio_demo_sink_num_channels_per_stream; i++){
213         uint8_t effective_channel = stream_index + i;
214         (void) lc3_decoder->decode_signed_16(decoder_contexts[effective_channel], NULL, BFI,
215                                              &pcm[effective_channel], le_audio_demo_sink_num_channels,
216                                              &tmp_BEC_detect);
217     }
218     // and store in ringbuffer when PCM for all channels is available
219     store_samples_in_ringbuffer();
220 }
221 
222 //
223 // Perform PLC for packets missing in previous intervals
224 //
225 // assumptions:
226 // - packet sequence number is monotonic increasing
227 // - if packet with seq nr x is received, all packets with smaller seq number are either received or missed
228 static void plc_check(uint16_t packet_sequence_number) {
229     while (group_last_packet_sequence != packet_sequence_number){
230         uint8_t i;
231         for (i=0;i<le_audio_demo_sink_num_streams;i++){
232             // deal with first packet missing. inject silent samples, pcm buffer is memset to zero at start
233             if (stream_last_packet_received[i] == false){
234                 printf_plc("- ISO #%u, very first packet missing\n", i);
235                 have_pcm[i] = true;
236                 store_samples_in_ringbuffer();
237 
238                 stream_last_packet_received[i] = true;
239                 stream_last_packet_sequence[i] = group_last_packet_sequence;
240                 continue;
241             }
242 
243             // missing packet if big sequence counter is higher than bis sequence counter
244             if (btstack_time16_delta(group_last_packet_sequence, stream_last_packet_sequence[i]) > 0) {
245                 printf_plc("- ISO #%u, PLC for %u\n", i, group_last_packet_sequence);
246                 plc_do(i);
247                 btstack_assert((stream_last_packet_sequence[i] + 1) == group_last_packet_sequence);
248                 stream_last_packet_sequence[i] = group_last_packet_sequence;
249             }
250         }
251         group_last_packet_sequence++;
252     }
253 }
254 
255 static void plc_timeout(btstack_timer_source_t * timer) {
256     // Restart timer. This will loose sync with ISO interval, but if we stop caring if we loose that many packets
257     btstack_run_loop_set_timer(timer, plc_timeout_subsequent_ms);
258     btstack_run_loop_set_timer_handler(timer, plc_timeout);
259     btstack_run_loop_add_timer(timer);
260 
261     switch (le_audio_demo_sink_type){
262         case HCI_ISO_TYPE_CIS:
263             // assume no packet received in iso interval => FT packets missed
264             printf_plc("PLC: timeout cis, group %u, FT %u", group_last_packet_sequence, le_audio_demo_sink_flush_timeout);
265             plc_check(group_last_packet_sequence + le_audio_demo_sink_flush_timeout);
266             break;
267         case HCI_ISO_TYPE_BIS:
268             // assume PTO not used => 1 packet missed
269             plc_check(group_last_packet_sequence + 1);
270             break;
271         default:
272             btstack_unreachable();
273             break;
274     }
275 }
276 
277 void le_audio_demo_util_sink_init(const char * filename_wav){
278     le_audio_demo_sink_filename_wav = filename_wav;
279 }
280 
281 void le_audio_demo_util_sink_enable_lc3plus(bool enable){
282     le_audio_demo_lc3plus_decoder_requested = enable;
283 }
284 
285 static void setup_lc3_decoder(bool use_lc3plus_decoder){
286     uint8_t channel;
287     for (channel = 0 ; channel < le_audio_demo_sink_num_channels ; channel++){
288         // pick decoder
289         void * decoder_context = NULL;
290 #ifdef HAVE_LC3PLUS
291         if (use_lc3plus_decoder){
292             decoder_context = &fraunhofer_decoder_contexts[channel];
293             lc3_decoder = btstack_lc3plus_fraunhofer_decoder_init_instance(decoder_context);
294         }
295         else
296 #endif
297         {
298             decoder_context = &google_decoder_contexts[channel];
299             lc3_decoder = btstack_lc3_decoder_google_init_instance(decoder_context);
300         }
301         decoder_contexts[channel] = decoder_context;
302         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);
303     }
304     btstack_assert(le_audio_demo_sink_num_samples_per_frame <= MAX_SAMPLES_PER_FRAME);
305 }
306 
307 void le_audio_demo_util_sink_configure_general(uint8_t num_streams, uint8_t num_channels_per_stream,
308                                                uint32_t sampling_frequency_hz,
309                                                btstack_lc3_frame_duration_t frame_duration, uint16_t octets_per_frame,
310                                                uint32_t iso_interval_1250us) {
311     le_audio_demo_sink_sampling_frequency_hz = sampling_frequency_hz;
312     le_audio_demo_sink_frame_duration = frame_duration;
313     le_audio_demo_sink_octets_per_frame = octets_per_frame;
314     le_audio_demo_sink_iso_interval_1250us = iso_interval_1250us;
315     le_audio_demo_sink_num_streams = num_streams;
316     le_audio_demo_sink_num_channels_per_stream = num_channels_per_stream;
317 
318     sink_receive_streaming = false;
319 
320     le_audio_demo_sink_num_channels = le_audio_demo_sink_num_streams * le_audio_demo_sink_num_channels_per_stream;
321     btstack_assert((le_audio_demo_sink_num_channels == 1) || (le_audio_demo_sink_num_channels == 2));
322 
323     le_audio_demo_sink_lc3_frames = 0;
324 
325     group_last_packet_received = false;
326     uint8_t i;
327     for (i=0;i<MAX_CHANNELS;i++){
328         stream_last_packet_received[i] = false;
329         have_pcm[i] = false;
330     }
331 
332     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);
333 
334     // switch to lc3plus if requested and possible
335     bool use_lc3plus_decoder = le_audio_demo_lc3plus_decoder_requested && (frame_duration == BTSTACK_LC3_FRAME_DURATION_10000US);
336 
337     // init decoder
338     setup_lc3_decoder(use_lc3plus_decoder);
339 
340     printf("Configure: %u streams, %u channels per stream, sampling rate %u, samples per frame %u, lc3plus %u\n",
341            num_streams, num_channels_per_stream, sampling_frequency_hz, le_audio_demo_sink_num_samples_per_frame, use_lc3plus_decoder);
342 
343 #ifdef HAVE_POSIX_FILE_IO
344     // create wav file
345     printf("WAV file: %s\n", le_audio_demo_sink_filename_wav);
346     wav_writer_open(le_audio_demo_sink_filename_wav, le_audio_demo_sink_num_channels, le_audio_demo_sink_sampling_frequency_hz);
347 #endif
348 
349     // init playback buffer
350     btstack_ring_buffer_init(&playback_buffer, playback_buffer_storage, PLAYBACK_BUFFER_SIZE);
351 
352     // calc start threshold in bytes for PLAYBACK_START_MS
353     playback_start_threshold_bytes = (sampling_frequency_hz / 1000 * PLAYBACK_START_MS) * le_audio_demo_sink_num_channels * 2;
354 
355     // start playback
356     const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
357     if (sink != NULL){
358         btstack_sample_rate_compensation_reset( &sample_rate_compensation, btstack_run_loop_get_time_ms() );
359         btstack_resample_init(&resample_instance, le_audio_demo_sink_num_channels_per_stream);
360         sink->init(le_audio_demo_sink_num_channels, le_audio_demo_sink_sampling_frequency_hz, le_audio_connection_sink_playback);
361         sink->start_stream();
362     }
363 }
364 
365 void le_audio_demo_util_sink_configure_unicast(uint8_t num_streams, uint8_t num_channels_per_stream, uint32_t sampling_frequency_hz,
366                                                btstack_lc3_frame_duration_t frame_duration, uint16_t octets_per_frame,
367                                                uint32_t iso_interval_1250us, uint8_t flush_timeout){
368     le_audio_demo_sink_type = HCI_ISO_TYPE_CIS;
369     le_audio_demo_sink_flush_timeout = flush_timeout;
370 
371     // set playback start: FT * ISO Interval + max(10 ms, 1/2 ISO Interval)
372     uint16_t playback_start_ms = flush_timeout * (iso_interval_1250us * 5 / 4) + btstack_max(10, iso_interval_1250us * 5 / 8);
373     uint16_t playback_start_samples = sampling_frequency_hz / 1000 * playback_start_ms;
374     playback_start_threshold_bytes = playback_start_samples * num_streams * num_channels_per_stream * 2;
375     printf("Playback: start %u ms (%u samples, %u bytes)\n", playback_start_ms, playback_start_samples, playback_start_threshold_bytes);
376 
377     // set subsequent plc timeout: FT * ISO Interval
378     plc_timeout_subsequent_ms = flush_timeout * iso_interval_1250us * 5 / 4;
379 
380     // set initial plc timeout:FT * ISO Interval + 4 ms
381     plc_timeout_initial_ms = plc_timeout_subsequent_ms + 4;
382 
383     printf("PLC: initial timeout    %u ms\n", plc_timeout_initial_ms);
384     printf("PLC: subsequent timeout %u ms\n", plc_timeout_subsequent_ms);
385 
386     le_audio_demo_util_sink_configure_general(num_streams, num_channels_per_stream, sampling_frequency_hz,
387                                               frame_duration, octets_per_frame, iso_interval_1250us);
388 }
389 
390 void le_audio_demo_util_sink_configure_broadcast(uint8_t num_streams, uint8_t num_channels_per_stream, uint32_t sampling_frequency_hz,
391                                                btstack_lc3_frame_duration_t frame_duration, uint16_t octets_per_frame,
392                                                uint32_t iso_interval_1250us, uint8_t pre_transmission_offset) {
393     le_audio_demo_sink_type = HCI_ISO_TYPE_BIS;
394     le_audio_demo_sink_pre_transmission_offset = pre_transmission_offset;
395 
396     // set playback start: ISO Interval + 10 ms
397     uint16_t playback_start_ms = (iso_interval_1250us * 5 / 4) + 10;
398     uint16_t playback_start_samples = sampling_frequency_hz / 1000 * playback_start_ms;
399     playback_start_threshold_bytes = playback_start_samples * num_streams * num_channels_per_stream * 2;
400     printf("Playback: start %u ms (%u samples, %u bytes)\n", playback_start_ms, playback_start_samples, playback_start_threshold_bytes);
401 
402     // set subsequent plc timeout: ISO Interval
403     plc_timeout_subsequent_ms = iso_interval_1250us * 5 / 4;
404 
405     // set initial plc timeout: ISO Interval + 4 ms
406     plc_timeout_initial_ms = plc_timeout_subsequent_ms + 4;
407 
408     printf("PLC: initial timeout    %u ms\n", plc_timeout_initial_ms);
409     printf("PLC: subsequent timeout %u ms\n", plc_timeout_subsequent_ms);
410 
411     le_audio_demo_util_sink_configure_unicast(num_streams, num_channels_per_stream, sampling_frequency_hz, frame_duration,
412                                               octets_per_frame, iso_interval_1250us, pre_transmission_offset);
413 }
414 
415 void le_audio_demo_util_sink_receive(uint8_t stream_index, uint8_t *packet, uint16_t size) {
416     uint16_t header = little_endian_read_16(packet, 0);
417     hci_con_handle_t con_handle = header & 0x0fff;
418     uint8_t pb_flag = (header >> 12) & 3;
419     uint8_t ts_flag = (header >> 14) & 1;
420     uint16_t iso_load_len = little_endian_read_16(packet, 2);
421 
422     uint16_t offset = 4;
423     uint32_t time_stamp = 0;
424     if (ts_flag){
425         time_stamp = little_endian_read_32(packet, offset);
426         offset += 4;
427     }
428 
429     uint32_t receive_time_ms = btstack_run_loop_get_time_ms();
430 
431     uint16_t packet_sequence_number = little_endian_read_16(packet, offset);
432     offset += 2;
433 
434     uint16_t header_2 = little_endian_read_16(packet, offset);
435     uint16_t iso_sdu_length = header_2 & 0x3fff;
436     uint8_t packet_status_flag = (uint8_t) (header_2 >> 14);
437     offset += 2;
438 
439     // avoid warning for (yet) unused fields
440     UNUSED(con_handle);
441     UNUSED(pb_flag);
442     UNUSED(iso_load_len);
443     UNUSED(packet_status_flag);
444 
445     // start with first packet on first stream
446     if (group_last_packet_received == false){
447         if (stream_index != 0){
448             printf("Ignore first packet for second stream\n");
449             return;
450         }
451         group_last_packet_received = true;
452         group_last_packet_sequence = packet_sequence_number;
453     }
454 
455     if (stream_last_packet_received[stream_index]) {
456         printf_plc("ISO #%u, receive %u\n", stream_index, packet_sequence_number);
457 
458         int16_t packet_sequence_delta = btstack_time16_delta(packet_sequence_number,
459                                                              stream_last_packet_sequence[stream_index]);
460         if (packet_sequence_delta < 1) {
461             // drop delayed packet that had already been generated by PLC
462             printf_plc("- dropping delayed packet. Current sequence number %u, last received or generated by PLC: %u\n",
463                        packet_sequence_number, stream_last_packet_sequence[stream_index]);
464             return;
465         }
466         // simple check
467         if (packet_sequence_number != stream_last_packet_sequence[stream_index] + 1) {
468             printf_plc("- ISO #%u, missing %u\n", stream_index, stream_last_packet_sequence[stream_index] + 1);
469         }
470     } else {
471         printf_plc("ISO %u, first packet seq number %u\n", stream_index, packet_sequence_number);
472         stream_last_packet_received[stream_index] = true;
473     }
474 
475     plc_check(packet_sequence_number);
476 
477     // either empty packets or num channels * num octets
478     if ((iso_sdu_length != 0) && (iso_sdu_length != le_audio_demo_sink_num_channels_per_stream * le_audio_demo_sink_octets_per_frame)) {
479         printf("ISO Length %u != %u * %u\n", iso_sdu_length, le_audio_demo_sink_num_channels_per_stream, le_audio_demo_sink_octets_per_frame);
480         log_info("ISO Length %u != %u * %u", iso_sdu_length, le_audio_demo_sink_num_channels_per_stream, le_audio_demo_sink_octets_per_frame);
481         return;
482     }
483 
484     const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
485     if( (sink != NULL) && (iso_sdu_length>0)) {
486         if( !sink_receive_streaming && playback_active ) {
487             btstack_sample_rate_compensation_init( &sample_rate_compensation, receive_time_ms,
488                     le_audio_demo_sink_sampling_frequency_hz, FLOAT_TO_Q15(1.f) );
489             sink_receive_streaming = true;
490         }
491         if( sink_receive_streaming ) {
492             uint32_t resampling_factor = btstack_sample_rate_compensation_update( &sample_rate_compensation, receive_time_ms,
493                     le_audio_demo_sink_num_samples_per_frame, sink->get_samplerate() );
494             btstack_resample_set_factor(&resample_instance, resampling_factor);
495         }
496     }
497 
498 
499     if (iso_sdu_length == 0) {
500         // empty packet -> generate silence
501         memset(pcm, 0, sizeof(pcm));
502         uint8_t i;
503         for (i = 0 ; i < le_audio_demo_sink_num_channels_per_stream ; i++) {
504             have_pcm[stream_index + i] = true;
505         }
506     } else {
507         // regular packet -> decode codec frame
508         uint8_t i;
509         for (i = 0 ; i < le_audio_demo_sink_num_channels_per_stream ; i++){
510             uint8_t tmp_BEC_detect;
511             uint8_t BFI = 0;
512             uint8_t effective_channel = stream_index + i;
513             (void) lc3_decoder->decode_signed_16(decoder_contexts[effective_channel], &packet[offset], BFI,
514                                                  &pcm[effective_channel], le_audio_demo_sink_num_channels,
515                                                  &tmp_BEC_detect);
516             offset += le_audio_demo_sink_octets_per_frame;
517             have_pcm[stream_index + i] = true;
518         }
519     }
520 
521     store_samples_in_ringbuffer();
522 
523     le_audio_demo_sink_lc3_frames++;
524 
525     // PLC
526     btstack_run_loop_remove_timer(&next_packet_timer);
527     btstack_run_loop_set_timer(&next_packet_timer, plc_timeout_initial_ms);
528     btstack_run_loop_set_timer_handler(&next_packet_timer, plc_timeout);
529     btstack_run_loop_add_timer(&next_packet_timer);
530 
531     if (samples_received >= le_audio_demo_sink_sampling_frequency_hz){
532         printf("LC3 Frames: %4u - samples received %5u, played %5u, dropped %5u\n", le_audio_demo_sink_lc3_frames, samples_received, samples_played, samples_dropped);
533         samples_received = 0;
534         samples_dropped  =  0;
535         samples_played = 0;
536     }
537 
538     stream_last_packet_sequence[stream_index] = packet_sequence_number;
539 }
540 
541 /**
542  * @brief Close sink: close wav file, stop playback
543  */
544 void le_audio_demo_util_sink_close(void){
545 #ifdef HAVE_POSIX_FILE_IO
546     printf("Close WAV file\n");
547     wav_writer_close();
548 #endif
549     // stop playback
550     const btstack_audio_sink_t * sink = btstack_audio_sink_get_instance();
551     if (sink != NULL){
552         sink->stop_stream();
553     }
554     sink_receive_streaming = false;
555     // stop timer
556     btstack_run_loop_remove_timer(&next_packet_timer);
557 }
558