xref: /btstack/3rd-party/bluedroid/encoder/srce/sbc_encoder.c (revision df25739fc3ea5a0a90f0f5925e6461d653697d2e)
1 /******************************************************************************
2  *
3  *  Copyright (C) 1999-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  contains code for encoder flow and initalization of encoder
22  *
23  ******************************************************************************/
24 
25 #include <string.h>
26 #include "sbc_encoder.h"
27 #include "sbc_enc_func_declare.h"
28 
29 SINT16 EncMaxShiftCounter;
30 
31 /*************************************************************************************************
32  * SBC encoder scramble code
33  * Purpose: to tie the SBC code with BTE/mobile stack code,
34  *          especially for the case when the SBC is ported into a third-party Multimedia chip
35  *
36  * Algorithm:
37  *  init process: all counters reset to 0,
38  *                calculate base_index: (6 + s16NumOfChannels*s16NumOfSubBands/2)
39  *    scramble side:    the init process happens every time SBC_Encoder_Init() is called.
40  *    descramble side:  it would be nice to know if he "init" process has happened.
41  *                      alter the SBC SYNC word 0x9C (1001 1100) to 0x8C (1000 1100).
42  *
43  *  scramble process:
44  *    The CRC byte:
45  *    Every SBC frame has a frame header.
46  *    The 1st byte is the sync word and the following 2 bytes are about the stream format.
47  *    They are supposed to be "constant" within a "song"
48  *    The 4th byte is the CRC byte. The CRC byte is bound to be random.
49  *    Derive 2 items from the CRC byte; one is the "use" bit, the other is the "index".
50  *
51  *    SBC keeps 2 sets of "use" & "index"; derived the current and the previous frame.
52  *
53  *    The "use" bit is any bit in SBC_PRTC_USE_MASK is set.
54  *    If set, SBC uses the "index" from the current frame.
55  *    If not set, SBC uses the "index" from the previous frame or 0.
56  *
57  *    index = (CRC & 0x3) + ((CRC & 0x30) >> 2) // 8 is the max index
58  *
59  *    if(index > 0)
60  *    {
61  *        p = &u8frame[base_index];
62  *        if((index&1)&&(u16PacketLength > (base_index+index*2)))
63  *        {
64  *            // odd index: swap 2 bytes
65  *            tmp = p[index];
66  *            p[index] = p[index*2];
67  *            p[index*2] = tmp;
68  *        }
69  *        else
70  *        {
71  *            // even index: shift by 3
72  *            tmp = (p[index] >> 5) + (p[index] << 3);
73  *            p[index] = tmp;
74  *        }
75  *    }
76  *    //else index is 0. The frame stays unaltered
77  *
78  */
79 
80 #define SBC_PRTC_CRC_IDX        3
81 #define SBC_PRTC_USE_MASK       0x64
82 #define SBC_PRTC_SYNC_MASK      0x10
83 #define SBC_PRTC_CIDX           0
84 #define SBC_PRTC_LIDX           1
85 typedef struct
86 {
87     UINT8   use;
88     UINT8   idx;
89 } tSBC_FR_CB;
90 
91 typedef struct
92 {
93     tSBC_FR_CB      fr[2];
94     UINT8           init;
95     UINT8           index;
96     UINT8           base;
97 } tSBC_PRTC_CB;
98 tSBC_PRTC_CB sbc_prtc_cb;
99 
100 #define SBC_PRTC_IDX(sc) (((sc) & 0x3) + (((sc) & 0x30) >> 2))
101 #define SBC_PRTC_CHK_INIT(ar) {if(sbc_prtc_cb.init == 0){sbc_prtc_cb.init=1; ar[0] &= ~SBC_PRTC_SYNC_MASK;}}
102 #define SBC_PRTC_C2L() {p_last=&sbc_prtc_cb.fr[SBC_PRTC_LIDX]; p_cur=&sbc_prtc_cb.fr[SBC_PRTC_CIDX]; \
103                         p_last->idx = p_cur->idx; p_last->use = p_cur->use;}
104 #define SBC_PRTC_GETC(ar) {p_cur->use = ar[SBC_PRTC_CRC_IDX] & SBC_PRTC_USE_MASK; \
105                            p_cur->idx = SBC_PRTC_IDX(ar[SBC_PRTC_CRC_IDX]);}
106 #define SBC_PRTC_CHK_CRC(ar) {SBC_PRTC_C2L();SBC_PRTC_GETC(ar);sbc_prtc_cb.index = (p_cur->use)?SBC_PRTC_CIDX:SBC_PRTC_LIDX;}
107 #define SBC_PRTC_SCRMB(ar) {idx = sbc_prtc_cb.fr[sbc_prtc_cb.index].idx; \
108     if(idx > 0){if((idx&1)&&(pstrEncParams->u16PacketLength > (sbc_prtc_cb.base+(idx<<1)))) {tmp2=idx<<1; tmp=ar[idx];ar[idx]=ar[tmp2];ar[tmp2]=tmp;} \
109                 else{tmp2=ar[idx]; tmp=(tmp2>>5)+(tmp2<<3);ar[idx]=(UINT8)tmp;}}}
110 
111 #if (SBC_JOINT_STE_INCLUDED == TRUE)
112 SINT32   s32LRDiff[SBC_MAX_NUM_OF_BLOCKS]    = {0};
113 SINT32   s32LRSum[SBC_MAX_NUM_OF_BLOCKS]     = {0};
114 #endif
115 
116 void SBC_Encoder(SBC_ENC_PARAMS *pstrEncParams)
117 {
118     SINT32 s32Ch;                               /* counter for ch*/
119     SINT32 s32Sb;                               /* counter for sub-band*/
120     UINT32 u32Count, maxBit = 0;                          /* loop count*/
121     SINT32 s32MaxValue;                         /* temp variable to store max value */
122 
123     SINT16 *ps16ScfL;
124     SINT32 *SbBuffer;
125     SINT32 s32Blk;                              /* counter for block*/
126     SINT32  s32NumOfBlocks   = pstrEncParams->s16NumOfBlocks;
127 #if (SBC_JOINT_STE_INCLUDED == TRUE)
128     SINT32 s32MaxValue2;
129     UINT32 u32CountSum,u32CountDiff;
130     SINT32 *pSum, *pDiff;
131 #endif
132     UINT8  *pu8;
133     /* BK4BTSTACK_CHANGE START */
134     // tSBC_FR_CB  *p_cur, *p_last;
135     // UINT32       idx, tmp, tmp2;
136     /* BK4BTSTACK_CHANGE STOP */
137     register SINT32  s32NumOfSubBands = pstrEncParams->s16NumOfSubBands;
138 
139     pstrEncParams->pu8NextPacket = pstrEncParams->pu8Packet;
140 
141 #if (SBC_NO_PCM_CPY_OPTION == TRUE)
142     pstrEncParams->ps16NextPcmBuffer = pstrEncParams->ps16PcmBuffer;
143 #else
144     pstrEncParams->ps16NextPcmBuffer  = pstrEncParams->as16PcmBuffer;
145 #endif
146     do
147     {
148         /* SBC ananlysis filter*/
149         if (s32NumOfSubBands == 4)
150             SbcAnalysisFilter4(pstrEncParams);
151         else
152             SbcAnalysisFilter8(pstrEncParams);
153 
154         /* compute the scale factor, and save the max */
155         ps16ScfL = pstrEncParams->as16ScaleFactor;
156         s32Ch=pstrEncParams->s16NumOfChannels*s32NumOfSubBands;
157 
158             pstrEncParams->ps16NextPcmBuffer+=s32Ch*s32NumOfBlocks; /* in case of multible sbc frame to encode update the pcm pointer */
159 
160         for (s32Sb=0; s32Sb<s32Ch; s32Sb++)
161         {
162             SbBuffer=pstrEncParams->s32SbBuffer+s32Sb;
163             s32MaxValue=0;
164             for (s32Blk=s32NumOfBlocks;s32Blk>0;s32Blk--)
165             {
166                 if (s32MaxValue<abs32(*SbBuffer))
167                     s32MaxValue=abs32(*SbBuffer);
168                 SbBuffer+=s32Ch;
169             }
170 
171             u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
172 
173             for ( ; u32Count < 15; u32Count++)
174             {
175                 if (s32MaxValue <= (SINT32)(0x8000 << u32Count))
176                     break;
177             }
178             *ps16ScfL++ = (SINT16)u32Count;
179 
180             if (u32Count > maxBit)
181                 maxBit = u32Count;
182         }
183         /* In case of JS processing,check whether to use JS */
184 #if (SBC_JOINT_STE_INCLUDED == TRUE)
185         if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO)
186         {
187             /* Calculate sum and differance  scale factors for making JS decision   */
188             ps16ScfL = pstrEncParams->as16ScaleFactor ;
189             /* calculate the scale factor of Joint stereo max sum and diff */
190             for (s32Sb = 0; s32Sb < s32NumOfSubBands-1; s32Sb++)
191             {
192                 SbBuffer=pstrEncParams->s32SbBuffer+s32Sb;
193                 s32MaxValue2=0;
194                 s32MaxValue=0;
195                 pSum       = s32LRSum;
196                 pDiff      = s32LRDiff;
197                 for (s32Blk=0;s32Blk<s32NumOfBlocks;s32Blk++)
198                 {
199                     *pSum=(*SbBuffer+*(SbBuffer+s32NumOfSubBands))>>1;
200                     if (abs32(*pSum)>s32MaxValue)
201                         s32MaxValue=abs32(*pSum);
202                     pSum++;
203                     *pDiff=(*SbBuffer-*(SbBuffer+s32NumOfSubBands))>>1;
204                     if (abs32(*pDiff)>s32MaxValue2)
205                         s32MaxValue2=abs32(*pDiff);
206                     pDiff++;
207                     SbBuffer+=s32Ch;
208                 }
209                 u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
210                 for ( ; u32Count < 15; u32Count++)
211                 {
212                     if (s32MaxValue <= (SINT32)(0x8000 << u32Count))
213                         break;
214                 }
215                 u32CountSum=u32Count;
216                 u32Count = (s32MaxValue2 > 0x800000) ? 9 : 0;
217                 for ( ; u32Count < 15; u32Count++)
218                 {
219                     if (s32MaxValue2 <= (SINT32)(0x8000 << u32Count))
220                         break;
221                 }
222                 u32CountDiff=u32Count;
223                 if ( (*ps16ScfL + *(ps16ScfL+s32NumOfSubBands)) > (SINT16)(u32CountSum + u32CountDiff) )
224                 {
225 
226                     if (u32CountSum > maxBit)
227                         maxBit = u32CountSum;
228 
229                     if (u32CountDiff > maxBit)
230                         maxBit = u32CountDiff;
231 
232                     *ps16ScfL = (SINT16)u32CountSum;
233                     *(ps16ScfL+s32NumOfSubBands) = (SINT16)u32CountDiff;
234 
235                     SbBuffer=pstrEncParams->s32SbBuffer+s32Sb;
236                     pSum       = s32LRSum;
237                     pDiff      = s32LRDiff;
238 
239                     for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++)
240                     {
241                         *SbBuffer = *pSum;
242                         *(SbBuffer+s32NumOfSubBands) = *pDiff;
243 
244                         SbBuffer += s32NumOfSubBands<<1;
245                         pSum++;
246                         pDiff++;
247                     }
248 
249                     pstrEncParams->as16Join[s32Sb] = 1;
250                 }
251                 else
252                 {
253                     pstrEncParams->as16Join[s32Sb] = 0;
254                 }
255                 ps16ScfL++;
256             }
257             pstrEncParams->as16Join[s32Sb] = 0;
258         }
259 #endif
260 
261         pstrEncParams->s16MaxBitNeed = (SINT16)maxBit;
262 
263         /* bit allocation */
264         if ((pstrEncParams->s16ChannelMode == SBC_STEREO) || (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO))
265             sbc_enc_bit_alloc_ste(pstrEncParams);
266         else
267             sbc_enc_bit_alloc_mono(pstrEncParams);
268 
269         /* save the beginning of the frame. pu8NextPacket is modified in EncPacking() */
270         pu8 = pstrEncParams->pu8NextPacket;
271         /* Quantize the encoded audio */
272         EncPacking(pstrEncParams);
273 
274 /* BK4BTSTACK_CHANGE START */
275         /* scramble the code */
276         //SBC_PRTC_CHK_INIT(pu8);
277         //SBC_PRTC_CHK_CRC(pu8);
278 #if 0
279         if(pstrEncParams->u16PacketLength > ((sbc_prtc_cb.fr[sbc_prtc_cb.index].idx * 2) + sbc_prtc_cb.base))
280             printf("len: %d, idx: %d\n", pstrEncParams->u16PacketLength, sbc_prtc_cb.fr[sbc_prtc_cb.index].idx);
281         else
282             printf("len: %d, idx: %d!!!!\n", pstrEncParams->u16PacketLength, sbc_prtc_cb.fr[sbc_prtc_cb.index].idx);
283 #endif
284         //SBC_PRTC_SCRMB((&pu8[sbc_prtc_cb.base]));
285 /* BK4BTSTACK_CHANGE STOP */
286 
287     }
288     while(--(pstrEncParams->u8NumPacketToEncode));
289 
290     pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
291 
292 }
293 
294 /****************************************************************************
295 * InitSbcAnalysisFilt - Initalizes the input data to 0
296 *
297 * RETURNS : N/A
298 */
299 void SBC_Encoder_Init(SBC_ENC_PARAMS *pstrEncParams)
300 {
301     UINT16 s16SamplingFreq; /*temp variable to store smpling freq*/
302     SINT16 s16Bitpool;      /*to store bit pool value*/
303     SINT16 s16BitRate;      /*to store bitrate*/
304     SINT16 s16FrameLen;     /*to store frame length*/
305     UINT16 HeaderParams;
306 
307     pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
308 
309     /* Required number of channels */
310     if (pstrEncParams->s16ChannelMode == SBC_MONO)
311         pstrEncParams->s16NumOfChannels = 1;
312     else
313         pstrEncParams->s16NumOfChannels = 2;
314 
315     /* Bit pool calculation */
316     if (pstrEncParams->s16SamplingFreq == SBC_sf16000)
317         s16SamplingFreq = 16000;
318     else if (pstrEncParams->s16SamplingFreq == SBC_sf32000)
319         s16SamplingFreq = 32000;
320     else if (pstrEncParams->s16SamplingFreq == SBC_sf44100)
321         s16SamplingFreq = 44100;
322     else
323         s16SamplingFreq = 48000;
324 
325     if ( (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO)
326         ||  (pstrEncParams->s16ChannelMode == SBC_STEREO) )
327     {
328         s16Bitpool = (SINT16)( (pstrEncParams->u16BitRate *
329             pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq)
330             -( (32 + (4 * pstrEncParams->s16NumOfSubBands *
331             pstrEncParams->s16NumOfChannels)
332             + ( (pstrEncParams->s16ChannelMode - 2) *
333             pstrEncParams->s16NumOfSubBands )   )
334             / pstrEncParams->s16NumOfBlocks) );
335 
336         s16FrameLen = 4 + (4*pstrEncParams->s16NumOfSubBands*
337             pstrEncParams->s16NumOfChannels)/8
338             + ( ((pstrEncParams->s16ChannelMode - 2) *
339             pstrEncParams->s16NumOfSubBands)
340             + (pstrEncParams->s16NumOfBlocks * s16Bitpool) ) / 8;
341 
342         s16BitRate = (8 * s16FrameLen * s16SamplingFreq)
343             / (pstrEncParams->s16NumOfSubBands *
344             pstrEncParams->s16NumOfBlocks * 1000);
345 
346         if (s16BitRate > pstrEncParams->u16BitRate)
347             s16Bitpool--;
348 
349         if(pstrEncParams->s16NumOfSubBands == 8)
350             pstrEncParams->s16BitPool = (s16Bitpool > 255) ? 255 : s16Bitpool;
351         else
352             pstrEncParams->s16BitPool = (s16Bitpool > 128) ? 128 : s16Bitpool;
353     }
354     else
355     {
356         s16Bitpool = (SINT16)( ((pstrEncParams->s16NumOfSubBands *
357             pstrEncParams->u16BitRate * 1000)
358             / (s16SamplingFreq * pstrEncParams->s16NumOfChannels))
359             -( ( (32 / pstrEncParams->s16NumOfChannels) +
360             (4 * pstrEncParams->s16NumOfSubBands) )
361             /   pstrEncParams->s16NumOfBlocks ) );
362 
363         pstrEncParams->s16BitPool = (s16Bitpool >
364             (16 * pstrEncParams->s16NumOfSubBands))
365             ? (16*pstrEncParams->s16NumOfSubBands) : s16Bitpool;
366     }
367 
368     if (pstrEncParams->s16BitPool < 0)
369         pstrEncParams->s16BitPool = 0;
370     /* sampling freq */
371     HeaderParams = ((pstrEncParams->s16SamplingFreq & 3)<< 6);
372 
373     /* number of blocks*/
374     HeaderParams |= (((pstrEncParams->s16NumOfBlocks -4) & 12) << 2);
375 
376     /* channel mode: mono, dual...*/
377     HeaderParams |= ((pstrEncParams->s16ChannelMode & 3)<< 2);
378 
379     /* Loudness or SNR */
380     HeaderParams |= ((pstrEncParams->s16AllocationMethod & 1)<< 1);
381     HeaderParams |= ((pstrEncParams->s16NumOfSubBands >> 3) & 1);  /*4 or 8*/
382     pstrEncParams->FrameHeader=HeaderParams;
383 
384     if (pstrEncParams->s16NumOfSubBands==4)
385     {
386         if (pstrEncParams->s16NumOfChannels==1)
387             EncMaxShiftCounter=((ENC_VX_BUFFER_SIZE-4*10)>>2)<<2;
388         else
389             EncMaxShiftCounter=((ENC_VX_BUFFER_SIZE-4*10*2)>>3)<<2;
390     }
391     else
392     {
393         if (pstrEncParams->s16NumOfChannels==1)
394             EncMaxShiftCounter=((ENC_VX_BUFFER_SIZE-8*10)>>3)<<3;
395         else
396             EncMaxShiftCounter=((ENC_VX_BUFFER_SIZE-8*10*2)>>4)<<3;
397     }
398 
399     // APPL_TRACE_EVENT("SBC_Encoder_Init : bitrate %d, bitpool %d",
400     //         pstrEncParams->u16BitRate, pstrEncParams->s16BitPool);
401 
402     SbcAnalysisInit();
403 
404     memset(&sbc_prtc_cb, 0, sizeof(tSBC_PRTC_CB));
405     sbc_prtc_cb.base = 6 + pstrEncParams->s16NumOfChannels*pstrEncParams->s16NumOfSubBands/2;
406 }
407