1 /******************************************************************************
2  *
3  *  Copyright 2014 The Android Open Source Project
4  *  Copyright 2006 Open Interface North America, Inc. All rights reserved.
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 /*******************************************************************************
21   $Revision: #1 $
22  ******************************************************************************/
23 
24 /** @file
25 @ingroup codec_internal
26 */
27 
28 /**@addtogroup codec_internal */
29 /**@{*/
30 
31 #include "oi_bitstream.h"
32 #include "oi_codec_sbc_private.h"
33 
34 #define SPECIALIZE_READ_SAMPLES_JOINT
35 
36 #if __has_attribute(fallthrough)
37 #define __fallthrough __attribute__((__fallthrough__))
38 #else
39 #define __fallthrough
40 #endif
41 
42 /**
43  * Scans through a buffer looking for a codec syncword. If the decoder has been
44  * set for enhanced operation using OI_CODEC_SBC_DecoderReset(), it will search
45  * for both a standard and an enhanced syncword.
46  */
FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT * context,const OI_BYTE ** frameData,uint32_t * frameBytes)47 PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT* context,
48                                const OI_BYTE** frameData,
49                                uint32_t* frameBytes) {
50   if (*frameBytes == 0) {
51     return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
52   }
53 
54   if (context->mSbcEnabled) {
55     while (*frameBytes && **frameData != OI_SBC_MSBC_SYNCWORD) {
56       (*frameBytes)--;
57       (*frameData)++;
58     }
59     if (*frameBytes == 0) {
60       return OI_CODEC_SBC_NO_SYNCWORD;
61     }
62     return OI_OK;
63   }
64 
65 #ifdef SBC_ENHANCED
66   OI_BYTE search1 = OI_SBC_SYNCWORD;
67   OI_BYTE search2 = OI_SBC_ENHANCED_SYNCWORD;
68 #endif  // SBC_ENHANCED
69 
70 #ifdef SBC_ENHANCED
71   if (context->limitFrameFormat && context->enhancedEnabled) {
72     /* If the context is restricted, only search for specified SYNCWORD */
73     search1 = search2;
74   } else if (context->enhancedEnabled == FALSE) {
75     /* If enhanced is not enabled, only search for classic SBC SYNCWORD*/
76     search2 = search1;
77   }
78   while (*frameBytes && (**frameData != search1) && (**frameData != search2)) {
79     (*frameBytes)--;
80     (*frameData)++;
81   }
82   if (*frameBytes) {
83     /* Syncword found, *frameData points to it, and *frameBytes correctly
84      * reflects the number of bytes available to read, including the
85      * syncword. */
86     context->common.frameInfo.enhanced =
87         (**frameData == OI_SBC_ENHANCED_SYNCWORD);
88     return OI_OK;
89   } else {
90     /* No syncword was found anywhere in the provided input data.
91      * *frameData points past the end of the original input, and
92      * *frameBytes is 0. */
93     return OI_CODEC_SBC_NO_SYNCWORD;
94   }
95 #else   // SBC_ENHANCED
96   while (*frameBytes && (**frameData != OI_SBC_SYNCWORD)) {
97     (*frameBytes)--;
98     (*frameData)++;
99   }
100   if (*frameBytes) {
101     /* Syncword found, *frameData points to it, and *frameBytes correctly
102      * reflects the number of bytes available to read, including the
103      * syncword. */
104     context->common.frameInfo.enhanced = FALSE;
105     return OI_OK;
106   } else {
107     /* No syncword was found anywhere in the provided input data.
108      * *frameData points past the end of the original input, and
109      * *frameBytes is 0. */
110     return OI_CODEC_SBC_NO_SYNCWORD;
111   }
112 #endif  // SBC_ENHANCED
113 }
114 
DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT * context,const OI_BYTE * bodyData,int16_t * pcmData,uint32_t * pcmBytes,OI_BOOL allowPartial)115 static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT* context,
116                             const OI_BYTE* bodyData, int16_t* pcmData,
117                             uint32_t* pcmBytes, OI_BOOL allowPartial) {
118   OI_BITSTREAM bs;
119   OI_UINT frameSamples = context->common.frameInfo.nrof_blocks *
120                          context->common.frameInfo.nrof_subbands;
121   OI_UINT decode_block_count;
122 
123   /*
124    * Based on the header data, make sure that there is enough room to write the
125    * output samples.
126    */
127   if (*pcmBytes <
128           (sizeof(int16_t) * frameSamples * context->common.pcmStride) &&
129       !allowPartial) {
130     /* If we're not allowing partial decodes, we need room for the entire
131      * codec frame */
132     TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA"));
133     return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
134   } else if (*pcmBytes < sizeof(int16_t) *
135                              context->common.frameInfo.nrof_subbands *
136                              context->common.pcmStride) {
137     /* Even if we're allowing partials, we can still only decode on a frame
138      * boundary */
139     return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
140   }
141 
142   if (context->bufferedBlocks == 0) {
143     TRACE(("Reading scalefactors"));
144     OI_SBC_ReadScalefactors(&context->common, bodyData, &bs);
145 
146     TRACE(("Computing bit allocation"));
147     OI_SBC_ComputeBitAllocation(&context->common);
148 
149     TRACE(("Reading samples"));
150     if (context->common.frameInfo.mode == SBC_JOINT_STEREO) {
151       OI_SBC_ReadSamplesJoint(context, &bs);
152     } else {
153       OI_SBC_ReadSamples(context, &bs);
154     }
155 
156     context->bufferedBlocks = context->common.frameInfo.nrof_blocks;
157   }
158 
159   if (allowPartial) {
160     decode_block_count = *pcmBytes / sizeof(int16_t) /
161                          context->common.pcmStride /
162                          context->common.frameInfo.nrof_subbands;
163 
164     if (decode_block_count > context->bufferedBlocks) {
165       decode_block_count = context->bufferedBlocks;
166     }
167 
168   } else {
169     decode_block_count = context->common.frameInfo.nrof_blocks;
170   }
171 
172   TRACE(("Synthesizing frame"));
173   {
174     OI_UINT start_block =
175         context->common.frameInfo.nrof_blocks - context->bufferedBlocks;
176     OI_SBC_SynthFrame(context, pcmData, start_block, decode_block_count);
177   }
178 
179   OI_ASSERT(context->bufferedBlocks >= decode_block_count);
180   context->bufferedBlocks -= decode_block_count;
181 
182   frameSamples = decode_block_count * context->common.frameInfo.nrof_subbands;
183 
184   /*
185    * When decoding mono into a stride-2 array, copy pcm data to second channel
186    */
187   if (context->common.frameInfo.nrof_channels == 1 &&
188       context->common.pcmStride == 2) {
189     OI_UINT i;
190     for (i = 0; i < frameSamples; ++i) {
191       pcmData[2 * i + 1] = pcmData[2 * i];
192     }
193   }
194 
195   /*
196    * Return number of pcm bytes generated by the decode operation.
197    */
198   *pcmBytes = frameSamples * sizeof(int16_t) * context->common.pcmStride;
199   if (context->bufferedBlocks > 0) {
200     return OI_CODEC_SBC_PARTIAL_DECODE;
201   } else {
202     return OI_OK;
203   }
204 }
205 
internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT * context,uint8_t bitpool,const OI_BYTE ** frameData,uint32_t * frameBytes,int16_t * pcmData,uint32_t * pcmBytes)206 PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context,
207                                      uint8_t bitpool, const OI_BYTE** frameData,
208                                      uint32_t* frameBytes, int16_t* pcmData,
209                                      uint32_t* pcmBytes) {
210   OI_STATUS status;
211   OI_UINT bodyLen;
212 
213   TRACE(("+OI_CODEC_SBC_DecodeRaw"));
214 
215   if (context->bufferedBlocks == 0) {
216     /*
217      * The bitallocator needs to know the bitpool value.
218      */
219     context->common.frameInfo.bitpool = bitpool;
220     /*
221      * Compute the frame length and check we have enough frame data to proceed
222      */
223     bodyLen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo) -
224               SBC_HEADER_LEN;
225     if (*frameBytes < bodyLen) {
226       TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
227       return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
228     }
229   } else {
230     bodyLen = 0;
231   }
232   /*
233    * Decode the SBC data. Pass TRUE to DecodeBody to allow partial decoding of
234    * tones.
235    */
236   status = DecodeBody(context, *frameData, pcmData, pcmBytes, TRUE);
237   if (OI_SUCCESS(status) || status == OI_CODEC_SBC_PARTIAL_DECODE) {
238     *frameData += bodyLen;
239     *frameBytes -= bodyLen;
240   }
241   TRACE(("-OI_CODEC_SBC_DecodeRaw: %d", status));
242   return status;
243 }
244 
OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT * context,uint32_t * decoderData,uint32_t decoderDataBytes,uint8_t maxChannels,uint8_t pcmStride,OI_BOOL enhanced)245 OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context,
246                                     uint32_t* decoderData,
247                                     uint32_t decoderDataBytes,
248                                     uint8_t maxChannels, uint8_t pcmStride,
249                                     OI_BOOL enhanced) {
250   return internal_DecoderReset(context, decoderData, decoderDataBytes,
251                                maxChannels, pcmStride, enhanced);
252 }
253 
OI_CODEC_SBC_DecoderConfigureMSbc(OI_CODEC_SBC_DECODER_CONTEXT * context)254 OI_STATUS OI_CODEC_SBC_DecoderConfigureMSbc(
255     OI_CODEC_SBC_DECODER_CONTEXT* context) {
256   context->mSbcEnabled = TRUE;
257   context->common.frameInfo.enhanced = FALSE;
258   context->common.frameInfo.freqIndex = SBC_FREQ_16000;
259   context->common.frameInfo.mode = SBC_MONO;
260   context->common.frameInfo.subbands = SBC_SUBBANDS_8;
261   context->common.frameInfo.blocks = SBC_BLOCKS_15;
262   context->common.frameInfo.alloc = SBC_LOUDNESS;
263   context->common.frameInfo.bitpool = 26;
264 
265   OI_SBC_ExpandFrameFields(&context->common.frameInfo);
266 
267   return OI_OK;
268 }
269 
OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT * context,const OI_BYTE ** frameData,uint32_t * frameBytes,int16_t * pcmData,uint32_t * pcmBytes)270 OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context,
271                                    const OI_BYTE** frameData,
272                                    uint32_t* frameBytes, int16_t* pcmData,
273                                    uint32_t* pcmBytes) {
274   OI_STATUS status;
275   OI_UINT framelen;
276   uint8_t crc;
277 
278   TRACE(("+OI_CODEC_SBC_DecodeFrame"));
279 
280   TRACE(("Finding syncword"));
281   status = FindSyncword(context, frameData, frameBytes);
282   if (!OI_SUCCESS(status)) {
283     return status;
284   }
285 
286   /* Make sure enough data remains to read the header. */
287   if (*frameBytes < SBC_HEADER_LEN) {
288     TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA"));
289     return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
290   }
291 
292   if (context->mSbcEnabled) {
293     /*
294      * There is no parameter embedded in mSBC's header as the parameters are
295      * fixed unlike the general SBC. We only need the packet's crc for mSBC.
296      */
297     context->common.frameInfo.crc = (*frameData)[3];
298   } else {
299     TRACE(("Reading Header"));
300     OI_SBC_ReadHeader(&context->common, *frameData);
301   }
302   /*
303    * Some implementations load the decoder into RAM and use overlays for 4 vs 8
304    * subbands. We need
305    * to ensure that the SBC parameters for this frame are compatible with the
306    * restrictions imposed
307    * by the loaded overlays.
308    */
309   if (context->limitFrameFormat &&
310       (context->common.frameInfo.subbands != context->restrictSubbands)) {
311     ERROR(("SBC parameters incompatible with loaded overlay"));
312     return OI_STATUS_INVALID_PARAMETERS;
313   }
314 
315   if (context->common.frameInfo.nrof_channels > context->common.maxChannels) {
316     ERROR(
317         ("SBC parameters incompatible with number of channels specified during "
318          "reset"));
319     return OI_STATUS_INVALID_PARAMETERS;
320   }
321 
322   if (context->common.pcmStride < 1 || context->common.pcmStride > 2) {
323     ERROR(("PCM stride not set correctly during reset"));
324     return OI_STATUS_INVALID_PARAMETERS;
325   }
326 
327   /*
328    * At this point a header has been read. However, it's possible that we found
329    * a false syncword,
330    * so the header data might be invalid. Make sure we have enough bytes to read
331    * in the
332    * CRC-protected header, but don't require we have the whole frame. That way,
333    * if it turns out
334    * that we're acting on bogus header data, we don't stall the decoding process
335    * by waiting for
336    * data that we don't actually need.
337    */
338   framelen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo);
339   if (*frameBytes < framelen) {
340     TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
341     return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
342   }
343 
344   TRACE(("Calculating checksum"));
345 
346   crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
347   if (crc != context->common.frameInfo.crc) {
348     TRACE(("CRC Mismatch:  calc=%02x read=%02x\n", crc,
349            context->common.frameInfo.crc));
350     TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_CHECKSUM_MISMATCH"));
351     return OI_CODEC_SBC_CHECKSUM_MISMATCH;
352   }
353 
354   /*
355    * Make sure the bitpool values are sane.
356    */
357   if ((context->common.frameInfo.bitpool < SBC_MIN_BITPOOL) &&
358       !context->common.frameInfo.enhanced) {
359     ERROR(("Bitpool too small: %d (must be >= 2)",
360            context->common.frameInfo.bitpool));
361     return OI_STATUS_INVALID_PARAMETERS;
362   }
363   if (context->common.frameInfo.bitpool >
364       OI_SBC_MaxBitpool(&context->common.frameInfo)) {
365     ERROR(("Bitpool too large: %d (must be <= %ld)",
366            context->common.frameInfo.bitpool,
367            OI_SBC_MaxBitpool(&context->common.frameInfo)));
368     return OI_STATUS_INVALID_PARAMETERS;
369   }
370 
371   /*
372    * Now decode the SBC data. Partial decode is not yet implemented for an SBC
373    * stream, so pass FALSE to decode body to have it enforce the old rule that
374    * you have to decode a whole packet at a time.
375    */
376   status = DecodeBody(context, *frameData + SBC_HEADER_LEN, pcmData, pcmBytes,
377                       FALSE);
378   if (OI_SUCCESS(status)) {
379     *frameData += framelen;
380     *frameBytes -= framelen;
381   }
382   TRACE(("-OI_CODEC_SBC_DecodeFrame: %d", status));
383 
384   /* mSBC is designed with 8 bits of zeros at the end for padding. */
385   if (context->mSbcEnabled) {
386     *frameBytes -= 1;
387   }
388 
389   return status;
390 }
391 
OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT * context,const OI_BYTE ** frameData,uint32_t * frameBytes)392 OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT* context,
393                                  const OI_BYTE** frameData,
394                                  uint32_t* frameBytes) {
395   OI_STATUS status;
396   OI_UINT framelen;
397   OI_UINT headerlen;
398   uint8_t crc;
399 
400   status = FindSyncword(context, frameData, frameBytes);
401   if (!OI_SUCCESS(status)) {
402     return status;
403   }
404   if (*frameBytes < SBC_HEADER_LEN) {
405     return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
406   }
407   OI_SBC_ReadHeader(&context->common, *frameData);
408   framelen =
409       OI_SBC_CalculateFrameAndHeaderlen(&context->common.frameInfo, &headerlen);
410   if (*frameBytes < headerlen) {
411     return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
412   }
413   crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
414   if (crc != context->common.frameInfo.crc) {
415     return OI_CODEC_SBC_CHECKSUM_MISMATCH;
416   }
417   if (*frameBytes < framelen) {
418     return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
419   }
420   context->bufferedBlocks = 0;
421   *frameData += framelen;
422   *frameBytes -= framelen;
423   return OI_OK;
424 }
425 
OI_CODEC_SBC_FrameCount(OI_BYTE * frameData,uint32_t frameBytes)426 uint8_t OI_CODEC_SBC_FrameCount(OI_BYTE* frameData, uint32_t frameBytes) {
427   uint8_t mode;
428   uint8_t blocks;
429   uint8_t subbands;
430   uint8_t frameCount = 0;
431   OI_UINT frameLen;
432 
433   while (frameBytes) {
434     while (frameBytes && ((frameData[0] & 0xFE) != 0x9C)) {
435       frameData++;
436       frameBytes--;
437     }
438 
439     if (frameBytes < SBC_HEADER_LEN) {
440       return frameCount;
441     }
442 
443     /* Extract and translate required fields from Header */
444     subbands = mode = blocks = frameData[1];
445     ;
446     mode = (mode & (BIT3 | BIT2)) >> 2;
447     blocks = block_values[(blocks & (BIT5 | BIT4)) >> 4];
448     subbands = band_values[(subbands & BIT0)];
449 
450     /* Inline logic to avoid corrupting context */
451     frameLen = blocks * frameData[2];
452     switch (mode) {
453       case SBC_JOINT_STEREO:
454         frameLen += subbands + (8 * subbands);
455         break;
456 
457       case SBC_DUAL_CHANNEL:
458         frameLen *= 2;
459         __fallthrough;
460 
461       default:
462         if (mode == SBC_MONO) {
463           frameLen += 4 * subbands;
464         } else {
465           frameLen += 8 * subbands;
466         }
467     }
468 
469     frameCount++;
470     frameLen = SBC_HEADER_LEN + (frameLen + 7) / 8;
471     if (frameBytes > frameLen) {
472       frameBytes -= frameLen;
473       frameData += frameLen;
474     } else {
475       frameBytes = 0;
476     }
477   }
478   return frameCount;
479 }
480 
481 /** Read quantized subband samples from the input bitstream and expand them. */
482 
483 #ifdef SPECIALIZE_READ_SAMPLES_JOINT
484 
OI_SBC_ReadSamplesJoint4(OI_CODEC_SBC_DECODER_CONTEXT * context,OI_BITSTREAM * global_bs)485 PRIVATE void OI_SBC_ReadSamplesJoint4(OI_CODEC_SBC_DECODER_CONTEXT* context,
486                                       OI_BITSTREAM* global_bs) {
487 #define NROF_SUBBANDS 4
488 #include "readsamplesjoint.inc"
489 #undef NROF_SUBBANDS
490 }
491 
OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_DECODER_CONTEXT * context,OI_BITSTREAM * global_bs)492 PRIVATE void OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_DECODER_CONTEXT* context,
493                                       OI_BITSTREAM* global_bs) {
494 #define NROF_SUBBANDS 8
495 #include "readsamplesjoint.inc"
496 #undef NROF_SUBBANDS
497 }
498 
499 typedef void (*READ_SAMPLES)(OI_CODEC_SBC_DECODER_CONTEXT* context,
500                              OI_BITSTREAM* global_bs);
501 
502 static const READ_SAMPLES SpecializedReadSamples[] = {OI_SBC_ReadSamplesJoint4,
503                                                       OI_SBC_ReadSamplesJoint8};
504 
505 #endif /* SPECIALIZE_READ_SAMPLES_JOINT */
506 
OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT * context,OI_BITSTREAM * global_bs)507 PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT* context,
508                                      OI_BITSTREAM* global_bs) {
509   OI_CODEC_SBC_COMMON_CONTEXT* common = &context->common;
510   OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
511 #ifdef SPECIALIZE_READ_SAMPLES_JOINT
512   OI_ASSERT((nrof_subbands >> 3u) <= 1u);
513   SpecializedReadSamples[nrof_subbands >> 3](context, global_bs);
514 #else
515 
516 #define NROF_SUBBANDS nrof_subbands
517 #include "readsamplesjoint.inc"
518 #undef NROF_SUBBANDS
519 #endif /* SPECIALIZE_READ_SAMPLES_JOINT */
520 }
521 
522 /**@}*/
523