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