xref: /btstack/src/classic/btstack_sbc_decoder_bluedroid.c (revision c37cd8f3d1350b92a2f66c31b2a5fcd75f8c91a4)
1 /*
2  * Copyright (C) 2014 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__ "btstack_sbc_decoder_bluedroid.c"
39 
40 // *****************************************************************************
41 //
42 // SBC decoder based on Bluedroid library
43 //
44 // *****************************************************************************
45 
46 #include "btstack_config.h"
47 
48 #include <stdint.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 
53 #include "btstack_sbc.h"
54 #include "btstack_sbc_plc.h"
55 
56 #include "oi_codec_sbc.h"
57 #include "oi_assert.h"
58 #include "btstack.h"
59 
60 #define mSBC_SYNCWORD 0xad
61 #define SBC_SYNCWORD 0x9c
62 #define SBC_MAX_CHANNELS 2
63 // #define LOG_FRAME_STATUS
64 
65 #define DECODER_DATA_SIZE (SBC_MAX_CHANNELS*SBC_MAX_BLOCKS*SBC_MAX_BANDS * 4 + SBC_CODEC_MIN_FILTER_BUFFERS*SBC_MAX_BANDS*SBC_MAX_CHANNELS * 2)
66 
67 typedef struct {
68     OI_UINT32 bytes_in_frame_buffer;
69     OI_CODEC_SBC_DECODER_CONTEXT decoder_context;
70 
71     uint8_t frame_buffer[SBC_MAX_FRAME_LEN];
72     int16_t pcm_plc_data[SBC_MAX_CHANNELS * SBC_MAX_BANDS * SBC_MAX_BLOCKS];
73     int16_t pcm_data[SBC_MAX_CHANNELS * SBC_MAX_BANDS * SBC_MAX_BLOCKS];
74     uint32_t pcm_bytes;
75     OI_UINT32 decoder_data[(DECODER_DATA_SIZE+3)/4];
76     int h2_sequence_nr;
77     int search_new_sync_word;
78     int sync_word_found;
79     int first_good_frame_found;
80 } bludroid_decoder_state_t;
81 
82 static btstack_sbc_decoder_state_t * sbc_decoder_state_singleton = NULL;
83 static bludroid_decoder_state_t bd_decoder_state;
84 
85 // Testing only - START
86 static int plc_enabled = 1;
87 static int corrupt_frame_period = -1;
88 // Testing - STOP
89 
90 void btstack_sbc_decoder_test_disable_plc(void){
91     plc_enabled = 0;
92 }
93 
94 void btstack_sbc_decoder_test_simulate_corrupt_frames(int period){
95     corrupt_frame_period = period;
96 }
97 
98 static int find_sequence_of_zeros(const OI_BYTE *frame_data, OI_UINT32 frame_bytes, int seq_length){
99     int zero_seq_count = 0;
100     unsigned int i;
101     for (i=0; i<frame_bytes; i++){
102         if (frame_data[i] == 0) {
103             zero_seq_count++;
104             if (zero_seq_count >= seq_length) return zero_seq_count;
105         } else {
106             zero_seq_count = 0;
107         }
108     }
109     return 0;
110 }
111 
112 static int find_h2_syncword(const OI_BYTE *frame_data, OI_UINT32 frame_bytes){
113     int syncword = mSBC_SYNCWORD;
114     uint8_t h2_first_byte = 0;
115     uint8_t h2_second_byte = 0;
116 
117     unsigned int i;
118     for (i=0; i<frame_bytes; i++){
119         if (frame_data[i] == syncword) {
120             break;
121         }
122         h2_first_byte = h2_second_byte;
123         h2_second_byte = frame_data[i];
124     }
125     if (h2_first_byte != 1) return -1;
126 
127     // check if upper nibble of second byte is 0x08
128     uint8_t ln = h2_second_byte & 0x0F;
129     if (ln != 8) return -1;
130 
131     // check that bits 0+2 == bits 1+3
132     uint8_t hn = h2_second_byte >> 4;
133     if  ( ((hn>>1) & 0x05) != (hn & 0x05) ) return -1;
134 
135     return ((hn & 0x04) >> 1) | (hn & 0x01);
136 }
137 
138 int btstack_sbc_decoder_num_samples_per_frame(btstack_sbc_decoder_state_t * state){
139     bludroid_decoder_state_t * decoder_state = (bludroid_decoder_state_t *) state->decoder_state;
140     return decoder_state->decoder_context.common.frameInfo.nrof_blocks * decoder_state->decoder_context.common.frameInfo.nrof_subbands;
141 }
142 
143 int btstack_sbc_decoder_num_channels(btstack_sbc_decoder_state_t * state){
144     bludroid_decoder_state_t * decoder_state = (bludroid_decoder_state_t *) state->decoder_state;
145     return decoder_state->decoder_context.common.frameInfo.nrof_channels;
146 }
147 
148 int btstack_sbc_decoder_sample_rate(btstack_sbc_decoder_state_t * state){
149     bludroid_decoder_state_t * decoder_state = (bludroid_decoder_state_t *) state->decoder_state;
150     return decoder_state->decoder_context.common.frameInfo.frequency;
151 }
152 
153 #ifdef OI_DEBUG
154 void OI_AssertFail(const char* file, int line, const char* reason){
155     log_error("AssertFail file %s, line %d, reason %s", file, line, reason);
156 }
157 #endif
158 
159 void btstack_sbc_decoder_init(btstack_sbc_decoder_state_t * state, btstack_sbc_mode_t mode, void (*callback)(int16_t * data, int num_samples, int num_channels, int sample_rate, void * context), void * context){
160     if (sbc_decoder_state_singleton && sbc_decoder_state_singleton != state ){
161         log_error("SBC decoder: different sbc decoder state is allready registered");
162     }
163     OI_STATUS status = OI_STATUS_SUCCESS;
164     switch (mode){
165         case SBC_MODE_STANDARD:
166             // note: we always request stereo output, even for mono input
167             status = OI_CODEC_SBC_DecoderReset(&(bd_decoder_state.decoder_context), bd_decoder_state.decoder_data, sizeof(bd_decoder_state.decoder_data), 2, 2, FALSE);
168             break;
169         case SBC_MODE_mSBC:
170             status = OI_CODEC_mSBC_DecoderReset(&(bd_decoder_state.decoder_context), bd_decoder_state.decoder_data, sizeof(bd_decoder_state.decoder_data));
171             break;
172         default:
173             break;
174     }
175 
176     if (status != OI_STATUS_SUCCESS){
177         log_error("SBC decoder: error during reset %d\n", status);
178     }
179 
180     sbc_decoder_state_singleton = state;
181 
182     bd_decoder_state.bytes_in_frame_buffer = 0;
183     bd_decoder_state.pcm_bytes = sizeof(bd_decoder_state.pcm_data);
184     bd_decoder_state.h2_sequence_nr = -1;
185     bd_decoder_state.sync_word_found = 0;
186     bd_decoder_state.search_new_sync_word = 0;
187     if (mode == SBC_MODE_mSBC){
188         bd_decoder_state.search_new_sync_word = 1;
189     }
190     bd_decoder_state.first_good_frame_found = 0;
191 
192     memset(state, 0, sizeof(btstack_sbc_decoder_state_t));
193     state->handle_pcm_data = callback;
194     state->mode = mode;
195     state->context = context;
196     state->decoder_state = &bd_decoder_state;
197     btstack_sbc_plc_init(&state->plc_state);
198 }
199 
200 static void append_received_sbc_data(bludroid_decoder_state_t * state, uint8_t * buffer, int size){
201     int numFreeBytes = sizeof(state->frame_buffer) - state->bytes_in_frame_buffer;
202 
203     if (size > numFreeBytes){
204         log_error("SBC data: more bytes read %u than free bytes in buffer %u", size, numFreeBytes);
205     }
206 
207     memcpy(state->frame_buffer + state->bytes_in_frame_buffer, buffer, size);
208     state->bytes_in_frame_buffer += size;
209 }
210 
211 
212 static void btstack_sbc_decoder_process_sbc_data(btstack_sbc_decoder_state_t * state, int packet_status_flag, uint8_t * buffer, int size){
213     bludroid_decoder_state_t * decoder_state = (bludroid_decoder_state_t*)state->decoder_state;
214     int input_bytes_to_process = size;
215 
216     while (input_bytes_to_process){
217         int bytes_free_in_buffer = SBC_MAX_FRAME_LEN - decoder_state->bytes_in_frame_buffer;
218         int bytes_to_append = btstack_min(input_bytes_to_process, bytes_free_in_buffer);
219         if (!bytes_to_append) break;
220         append_received_sbc_data(decoder_state, buffer, bytes_to_append);
221         buffer           += bytes_to_append;
222         input_bytes_to_process -= bytes_to_append;
223 
224         uint16_t bytes_in_buffer_before = decoder_state->bytes_in_frame_buffer;
225         uint16_t bytes_processed = 0;
226         const OI_BYTE *frame_data = decoder_state->frame_buffer;
227 
228         static int frame_count = 0;
229         while (1){
230             if (corrupt_frame_period > 0){
231                frame_count++;
232 
233                 if (frame_count % corrupt_frame_period == 0){
234                     *(uint8_t*)&frame_data[5] = 0;
235                     frame_count = 0;
236                 }
237             }
238 
239             OI_STATUS status = OI_STATUS_SUCCESS;
240             int bad_frame = 0;
241             int zero_seq_found = 0;
242 
243             if (decoder_state->first_good_frame_found){
244                 zero_seq_found = find_sequence_of_zeros(frame_data, decoder_state->bytes_in_frame_buffer, 20);
245                 bad_frame = zero_seq_found || packet_status_flag;
246             }
247 
248             if (bad_frame){
249                 status = OI_CODEC_SBC_CHECKSUM_MISMATCH;
250                 decoder_state->bytes_in_frame_buffer = 0;
251             } else {
252                 memset(decoder_state->pcm_plc_data, 0x55, SBC_MAX_CHANNELS * SBC_MAX_BANDS * SBC_MAX_BLOCKS * 2);
253                 status = OI_CODEC_SBC_DecodeFrame(&(decoder_state->decoder_context),
254                                                     &frame_data,
255                                                     &(decoder_state->bytes_in_frame_buffer),
256                                                     decoder_state->pcm_plc_data,
257                                                     &(decoder_state->pcm_bytes));
258             }
259 
260             bytes_processed = bytes_in_buffer_before - decoder_state->bytes_in_frame_buffer;
261             switch(status){
262                 case OI_STATUS_SUCCESS:
263                     decoder_state->first_good_frame_found = 1;
264 
265                     if (state->mode == SBC_MODE_mSBC){
266                         decoder_state->search_new_sync_word = 1;
267                         decoder_state->sync_word_found = 0;
268                     }
269 
270                     state->handle_pcm_data(decoder_state->pcm_plc_data,
271                                         btstack_sbc_decoder_num_samples_per_frame(state),
272                                         btstack_sbc_decoder_num_channels(state),
273                                         btstack_sbc_decoder_sample_rate(state), state->context);
274                     state->good_frames_nr++;
275                     continue;
276                 case OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA:
277                 case OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA:
278                     // printf("    NOT_ENOUGH_DATA\n");
279                     if (decoder_state->sync_word_found){
280                         decoder_state->search_new_sync_word = 0;
281                     }
282                     break;
283                 case OI_CODEC_SBC_NO_SYNCWORD:
284                 case OI_CODEC_SBC_CHECKSUM_MISMATCH:
285                     // printf("NO_SYNCWORD or CHECKSUM_MISMATCH\n");
286                     decoder_state->bytes_in_frame_buffer = 0;
287                     if (!decoder_state->first_good_frame_found) break;
288 
289                     if (zero_seq_found){
290                         state->zero_frames_nr++;
291                     } else {
292                         state->bad_frames_nr++;
293                     }
294                     if (!plc_enabled) break;
295                     break;
296                 default:
297                     log_info("Frame decode error: %d", status);
298                     break;
299             }
300 
301             memmove(decoder_state->frame_buffer, decoder_state->frame_buffer + bytes_processed, decoder_state->bytes_in_frame_buffer);
302             if ((status != OI_STATUS_SUCCESS) || (decoder_state->bytes_in_frame_buffer == 0)) break;
303 
304         }
305     }
306 }
307 
308 
309 static void btstack_sbc_decoder_process_msbc_data(btstack_sbc_decoder_state_t * state, int packet_status_flag, uint8_t * buffer, int size){
310 
311     bludroid_decoder_state_t * decoder_state = (bludroid_decoder_state_t*)state->decoder_state;
312     int input_bytes_to_process = size;
313     unsigned int msbc_frame_size = 57;
314 
315     // printf("<<-- enter -->>\n");
316     // printf("Process data: in buffer %u, new %u\n", decoder_state->bytes_in_frame_buffer, size);
317 
318     while (input_bytes_to_process > 0){
319 
320         int bytes_missing_for_complete_msbc_frame = msbc_frame_size - decoder_state->bytes_in_frame_buffer;
321         int bytes_to_append = btstack_min(input_bytes_to_process, bytes_missing_for_complete_msbc_frame);
322 
323         append_received_sbc_data(decoder_state, buffer, bytes_to_append);
324         // printf("Append %u bytes, now %u in buffer \n", bytes_to_append, decoder_state->bytes_in_frame_buffer);
325         buffer           += bytes_to_append;
326         input_bytes_to_process -= bytes_to_append;
327 
328         if (decoder_state->bytes_in_frame_buffer < msbc_frame_size){
329             // printf("not enough data %d > %d\n", msbc_frame_size, decoder_state->bytes_in_frame_buffer);
330             if (input_bytes_to_process){
331                 log_error("SHOULD NOT HAPPEN... not enough bytes, but bytes left to process");
332             }
333             break;
334         }
335 
336         uint16_t bytes_in_buffer_before = decoder_state->bytes_in_frame_buffer;
337         uint16_t bytes_processed = 0;
338         const OI_BYTE *frame_data = decoder_state->frame_buffer;
339 
340         static int frame_count = 0;
341         if (corrupt_frame_period > 0){
342            frame_count++;
343 
344             if (frame_count % corrupt_frame_period == 0){
345                 *(uint8_t*)&frame_data[5] = 0;
346                 frame_count = 0;
347             }
348         }
349 
350         OI_STATUS status = OI_STATUS_SUCCESS;
351         int bad_frame = 0;
352         int zero_seq_found = 0;
353 
354         if (decoder_state->first_good_frame_found){
355             zero_seq_found = find_sequence_of_zeros(frame_data, decoder_state->bytes_in_frame_buffer, 20);
356             bad_frame = zero_seq_found || packet_status_flag;
357         }
358 
359         if (bad_frame){
360             status = OI_CODEC_SBC_CHECKSUM_MISMATCH;
361             decoder_state->bytes_in_frame_buffer = 0;
362         } else {
363             if (decoder_state->search_new_sync_word && !decoder_state->sync_word_found){
364                 int h2_syncword = find_h2_syncword(frame_data, decoder_state->bytes_in_frame_buffer);
365 
366                 if (h2_syncword != -1){
367                     decoder_state->sync_word_found = 1;
368                     decoder_state->h2_sequence_nr = h2_syncword;
369                 }
370             }
371             status = OI_CODEC_SBC_DecodeFrame(&(decoder_state->decoder_context),
372                                                 &frame_data,
373                                                 &(decoder_state->bytes_in_frame_buffer),
374                                                 decoder_state->pcm_plc_data,
375                                                 &(decoder_state->pcm_bytes));
376         }
377 
378         bytes_processed = bytes_in_buffer_before - decoder_state->bytes_in_frame_buffer;
379         OI_UINT32 bytes_in_frame_buffer = msbc_frame_size;
380 
381         switch(status){
382             case 0:
383                 decoder_state->first_good_frame_found = 1;
384 
385                 if (state->mode == SBC_MODE_mSBC){
386                     decoder_state->search_new_sync_word = 1;
387                     decoder_state->sync_word_found = 0;
388                 }
389 
390                 btstack_sbc_plc_good_frame(&state->plc_state, decoder_state->pcm_plc_data, decoder_state->pcm_data);
391                 state->handle_pcm_data(decoder_state->pcm_data,
392                                     btstack_sbc_decoder_num_samples_per_frame(state),
393                                     btstack_sbc_decoder_num_channels(state),
394                                     btstack_sbc_decoder_sample_rate(state), state->context);
395                 state->good_frames_nr++;
396                 continue;
397             case OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA:
398             case OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA:
399                 // printf("    NOT_ENOUGH_DATA\n");
400                 if (decoder_state->sync_word_found){
401                     decoder_state->search_new_sync_word = 0;
402                 }
403                 break;
404             case OI_CODEC_SBC_NO_SYNCWORD:
405             case OI_CODEC_SBC_CHECKSUM_MISMATCH:
406                 // printf("NO_SYNCWORD or CHECKSUM_MISMATCH\n");
407                 decoder_state->bytes_in_frame_buffer = 0;
408                 if (!decoder_state->first_good_frame_found) break;
409 
410                 if (state->mode == SBC_MODE_mSBC){
411                     if (!decoder_state->sync_word_found){
412                         decoder_state->h2_sequence_nr = (decoder_state->h2_sequence_nr + 1)%4;
413                     }
414                     decoder_state->search_new_sync_word = 1;
415                     decoder_state->sync_word_found = 0;
416                 }
417 
418                 if (zero_seq_found){
419                     state->zero_frames_nr++;
420                 } else {
421                     state->bad_frames_nr++;
422                 }
423 
424 #ifdef LOG_FRAME_STATUS
425                 if (zero_seq_found){
426                     printf("%d : ZERO FRAME\n", decoder_state->h2_sequence_nr);
427                 } else {
428                     printf("%d : BAD FRAME\n", decoder_state->h2_sequence_nr);
429                 }
430                 if (decoder_state->h2_sequence_nr == 3) printf("\n");
431 #endif
432                 if (!plc_enabled) break;
433 
434                 frame_data = btstack_sbc_plc_zero_signal_frame();
435 
436                 status = OI_CODEC_SBC_DecodeFrame(&(decoder_state->decoder_context),
437                                                     &frame_data,
438                                                     &bytes_in_frame_buffer,
439                                                     decoder_state->pcm_plc_data,
440                                                     &(decoder_state->pcm_bytes));
441 
442                 if (status != 0) {
443                     log_error("SBC decoder: error %d\n", status);
444                 }
445                 btstack_sbc_plc_bad_frame(&state->plc_state, decoder_state->pcm_plc_data, decoder_state->pcm_data);
446                 state->handle_pcm_data(decoder_state->pcm_data,
447                                     btstack_sbc_decoder_num_samples_per_frame(state),
448                                     btstack_sbc_decoder_num_channels(state),
449                                     btstack_sbc_decoder_sample_rate(state), state->context);
450 
451 
452                 break;
453             default:
454                 log_info("Frame decode error: %d", status);
455                 break;
456         }
457 
458         memmove(decoder_state->frame_buffer, decoder_state->frame_buffer + bytes_processed, decoder_state->bytes_in_frame_buffer);
459     }
460 }
461 
462 void btstack_sbc_decoder_process_data(btstack_sbc_decoder_state_t * state, int packet_status_flag, uint8_t * buffer, int size){
463     if (state->mode == SBC_MODE_mSBC){
464         btstack_sbc_decoder_process_msbc_data(state, packet_status_flag, buffer, size);
465     } else {
466         btstack_sbc_decoder_process_sbc_data(state, packet_status_flag, buffer, size);
467     }
468 }
469