1 /******************************************************************************
2  *
3  *  Copyright (C) 2014 The Android Open Source Project
4  *  Copyright 2003 - 2004 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 /**
25 @file
26 
27 The functions in this file relate to the allocation of available bits to
28 subbands within the SBC/eSBC frame, along with support functions for computing
29 frame length and bitrate.
30 
31 @ingroup codec_internal
32 */
33 
34 /**
35 @addtogroup codec_internal
36 @{
37 */
38 
39 #include "common/bt_target.h"
40 #include "oi_utils.h"
41 #include <oi_codec_sbc_private.h>
42 
43 #if (defined(SBC_DEC_INCLUDED) && SBC_DEC_INCLUDED == TRUE)
44 
OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO * frame)45 OI_UINT32 OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO *frame)
46 {
47     switch (frame->mode) {
48     case SBC_MONO:
49     case SBC_DUAL_CHANNEL:
50         return 16 * frame->nrof_subbands;
51     case SBC_STEREO:
52     case SBC_JOINT_STEREO:
53         return 32 * frame->nrof_subbands;
54     }
55 
56     ERROR(("Invalid frame mode %d", frame->mode));
57     OI_ASSERT(FALSE);
58     return 0; /* Should never be reached */
59 }
60 
61 
internal_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO * frame)62 PRIVATE OI_UINT16 internal_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame)
63 {
64     OI_UINT16 nbits = frame->nrof_blocks * frame->bitpool;
65     OI_UINT16 nrof_subbands = frame->nrof_subbands;
66     OI_UINT16 result = nbits;
67 
68     if (frame->mode == SBC_JOINT_STEREO) {
69         result += nrof_subbands + (8 * nrof_subbands);
70     } else {
71         if (frame->mode == SBC_DUAL_CHANNEL) {
72             result += nbits;
73         }
74         if (frame->mode == SBC_MONO) {
75             result += 4 * nrof_subbands;
76         } else {
77             result += 8 * nrof_subbands;
78         }
79     }
80     return SBC_HEADER_LEN + (result + 7) / 8;
81 }
82 
83 
internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO * frame)84 PRIVATE OI_UINT32 internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame)
85 {
86     OI_UINT blocksbands;
87     blocksbands = frame->nrof_subbands * frame->nrof_blocks;
88 
89     return DIVIDE(8 * internal_CalculateFramelen(frame) * frame->frequency, blocksbands);
90 }
91 
92 
OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO * frame,OI_UINT * headerLen_)93 INLINE OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *frame, OI_UINT *headerLen_)
94 {
95     OI_UINT headerLen = SBC_HEADER_LEN + frame->nrof_subbands * frame->nrof_channels / 2;
96 
97     if (frame->mode == SBC_JOINT_STEREO) {
98         headerLen++;
99     }
100 
101     *headerLen_ = headerLen;
102     return internal_CalculateFramelen(frame);
103 }
104 
105 
106 #define MIN(x, y)  ((x) < (y) ? (x) : (y))
107 
108 
109 /*
110  * Computes the bit need for each sample and as also returns a counts of bit needs that are greater
111  * than one. This count is used in the first phase of bit allocation.
112  *
113  * We also compute a preferred bitpool value that this is the minimum bitpool needed to guarantee
114  * lossless representation of the audio data. The preferred bitpool may be larger than the bits
115  * actually required but the only input we have are the scale factors. For example, it takes 2 bits
116  * to represent values in the range -1 .. +1 but the scale factor is 0. To guarantee lossless
117  * representation we add 2 to each scale factor and sum them to come up with the preferred bitpool.
118  * This is not ideal because 0 requires 0 bits but we currently have no way of knowing this.
119  *
120  * @param bitneed       Array to return bitneeds for each subband
121  *
122  * @param ch            Channel 0 or 1
123  *
124  * @param preferredBitpool  Returns the number of reserved bits
125  *
126  * @return              The SBC bit need
127  *
128  */
computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT * common,OI_UINT8 * bitneeds,OI_UINT ch,OI_UINT * preferredBitpool)129 OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common,
130                        OI_UINT8 *bitneeds,
131                        OI_UINT ch,
132                        OI_UINT *preferredBitpool)
133 {
134     static const OI_INT8 offset4[4][4] = {
135         { -1, 0, 0, 0 },
136         { -2, 0, 0, 1 },
137         { -2, 0, 0, 1 },
138         { -2, 0, 0, 1 }
139     };
140 
141     static const OI_INT8 offset8[4][8] = {
142         { -2, 0, 0, 0, 0, 0, 0, 1 },
143         { -3, 0, 0, 0, 0, 0, 1, 2 },
144         { -4, 0, 0, 0, 0, 0, 1, 2 },
145         { -4, 0, 0, 0, 0, 0, 1, 2 }
146     };
147 
148     const OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
149     OI_UINT sb;
150     OI_INT8 *scale_factor = &common->scale_factor[ch ? nrof_subbands : 0];
151     OI_UINT bitcount = 0;
152     OI_UINT8 maxBits = 0;
153     OI_UINT8 prefBits = 0;
154 
155     if (common->frameInfo.alloc == SBC_SNR) {
156         for (sb = 0; sb < nrof_subbands; sb++) {
157             OI_INT bits = scale_factor[sb];
158             if (bits > maxBits) {
159                 maxBits = bits;
160             }
161             if ((bitneeds[sb] = bits) > 1) {
162                 bitcount += bits;
163             }
164             prefBits += 2 + bits;
165         }
166     } else {
167         const OI_INT8 *offset;
168         if (nrof_subbands == 4) {
169             offset = offset4[common->frameInfo.freqIndex];
170         } else {
171             offset = offset8[common->frameInfo.freqIndex];
172         }
173         for (sb = 0; sb < nrof_subbands; sb++) {
174             OI_INT bits = scale_factor[sb];
175             if (bits > maxBits) {
176                 maxBits = bits;
177             }
178             prefBits += 2 + bits;
179             if (bits) {
180                 bits -= offset[sb];
181                 if (bits > 0) {
182                     bits /= 2;
183                 }
184                 bits += 5;
185             }
186             if ((bitneeds[sb] = bits) > 1) {
187                 bitcount += bits;
188             }
189         }
190     }
191     common->maxBitneed = OI_MAX(maxBits, common->maxBitneed);
192     *preferredBitpool += prefBits;
193     return bitcount;
194 }
195 
196 
197 /*
198  * Explanation of the adjustToFitBitpool inner loop.
199  *
200  * The inner loop computes the effect of adjusting the bit allocation up or
201  * down. Allocations must be 0 or in the range 2..16. This is accomplished by
202  * the following code:
203  *
204  *           for (s = bands - 1; s >= 0; --s) {
205  *              OI_INT bits = bitadjust + bitneeds[s];
206  *              bits = bits < 2 ? 0 : bits;
207  *              bits = bits > 16 ? 16 : bits;
208  *              count += bits;
209  *          }
210  *
211  * This loop can be optimized to perform 4 operations at a time as follows:
212  *
213  * Adjustment is computed as a 7 bit signed value and added to the bitneed.
214  *
215  * Negative allocations are zeroed by masking. (n & 0x40) >> 6 puts the
216  * sign bit into bit 0, adding this to 0x7F give us a mask of 0x80
217  * for -ve values and 0x7F for +ve values.
218  *
219  * n &= 0x7F + (n & 0x40) >> 6)
220  *
221  * Allocations greater than 16 are truncated to 16. Adjusted allocations are in
222  * the range 0..31 so we know that bit 4 indicates values >= 16. We use this bit
223  * to create a mask that zeroes bits 0 .. 3 if bit 4 is set.
224  *
225  * n &= (15 + (n >> 4))
226  *
227  * Allocations of 1 are disallowed. Add and shift creates a mask that
228  * eliminates the illegal value
229  *
230  * n &= ((n + 14) >> 4) | 0x1E
231  *
232  * These operations can be performed in 8 bits without overflowing so we can
233  * operate on 4 values at once.
234  */
235 
236 
237 /*
238  * Encoder/Decoder
239  *
240  * Computes adjustment +/- of bitneeds to fill bitpool and returns overall
241  * adjustment and excess bits.
242  *
243  * @param bitpool   The bitpool we have to work within
244  *
245  * @param bitneeds  An array of bit needs (more acturately allocation prioritities) for each
246  *                  subband across all blocks in the SBC frame
247  *
248  * @param subbands  The number of subbands over which the adkustment is calculated. For mono and
249  *                  dual mode this is 4 or 8, for stereo or joint stereo this is 8 or 16.
250  *
251  * @param bitcount  A starting point for the adjustment
252  *
253  * @param excess    Returns the excess bits after the adjustment
254  *
255  * @return   The adjustment.
256  */
adjustToFitBitpool(const OI_UINT bitpool,OI_UINT32 * bitneeds,const OI_UINT subbands,OI_UINT bitcount,OI_UINT * excess)257 OI_INT adjustToFitBitpool(const OI_UINT bitpool,
258                           OI_UINT32 *bitneeds,
259                           const OI_UINT subbands,
260                           OI_UINT bitcount,
261                           OI_UINT *excess)
262 {
263     OI_INT maxBitadjust = 0;
264     OI_INT bitadjust = (bitcount > bitpool) ? -8 : 8;
265     OI_INT chop = 8;
266 
267     /*
268      * This is essentially a binary search for the optimal adjustment value.
269      */
270     while ((bitcount != bitpool) && chop) {
271         OI_UINT32 total = 0;
272         OI_UINT count;
273         OI_UINT32 adjust4;
274         OI_INT i;
275 
276         adjust4 = bitadjust & 0x7F;
277         adjust4 |= (adjust4 << 8);
278         adjust4 |= (adjust4 << 16);
279 
280         for (i = (subbands / 4 - 1); i >= 0; --i) {
281             OI_UINT32 mask;
282             OI_UINT32 n = bitneeds[i] + adjust4;
283             mask = 0x7F7F7F7F + ((n & 0x40404040) >> 6);
284             n &= mask;
285             mask = 0x0F0F0F0F + ((n & 0x10101010) >> 4);
286             n &= mask;
287             mask = (((n + 0x0E0E0E0E) >> 4) | 0x1E1E1E1E);
288             n &= mask;
289             total += n;
290         }
291 
292         count = (total & 0xFFFF) + (total >> 16);
293         count = (count & 0xFF) + (count >> 8);
294 
295         chop >>= 1;
296         if (count > bitpool) {
297             bitadjust -= chop;
298         } else {
299             maxBitadjust = bitadjust;
300             bitcount = count;
301             bitadjust += chop;
302         }
303     }
304 
305     *excess = bitpool - bitcount;
306 
307     return maxBitadjust;
308 }
309 
310 
311 /*
312  * The bit allocator trys to avoid single bit allocations except as a last resort. So in the case
313  * where a bitneed of 1 was passed over during the adsjustment phase 2 bits are now allocated.
314  */
allocAdjustedBits(OI_UINT8 * dest,OI_INT bits,OI_INT excess)315 INLINE OI_INT allocAdjustedBits(OI_UINT8 *dest,
316                                 OI_INT bits,
317                                 OI_INT excess)
318 {
319     if (bits < 16) {
320         if (bits > 1) {
321             if (excess) {
322                 ++bits;
323                 --excess;
324             }
325         } else if ((bits == 1) && (excess > 1)) {
326             bits = 2;
327             excess -= 2;
328         } else {
329             bits  = 0;
330         }
331     } else {
332         bits = 16;
333     }
334     *dest = (OI_UINT8)bits;
335     return excess;
336 }
337 
338 
339 /*
340  * Excess bits not allocated by allocaAdjustedBits are allocated round-robin.
341  */
allocExcessBits(OI_UINT8 * dest,OI_INT excess)342 INLINE OI_INT allocExcessBits(OI_UINT8 *dest,
343                               OI_INT excess)
344 {
345     if (*dest < 16) {
346         *dest += 1;
347         return excess - 1;
348     } else {
349         return excess;
350     }
351 }
352 
oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT * common,BITNEED_UNION1 * bitneeds,OI_UINT ch,OI_UINT bitcount)353 void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common,
354                              BITNEED_UNION1 *bitneeds,
355                              OI_UINT ch,
356                              OI_UINT bitcount)
357 {
358     const OI_UINT8 nrof_subbands = common->frameInfo.nrof_subbands;
359     OI_UINT excess;
360     OI_UINT sb;
361     OI_INT bitadjust;
362     OI_UINT8 RESTRICT *allocBits;
363 
364 
365     {
366         OI_UINT ex;
367         bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds->uint32, nrof_subbands, bitcount, &ex);
368         /* We want the compiler to put excess into a register */
369         excess = ex;
370     }
371 
372     /*
373      * Allocate adjusted bits
374      */
375     allocBits = &common->bits.uint8[ch ? nrof_subbands : 0];
376 
377     sb = 0;
378     while (sb < nrof_subbands) {
379         excess = allocAdjustedBits(&allocBits[sb], bitneeds->uint8[sb] + bitadjust, excess);
380         ++sb;
381     }
382     sb = 0;
383     while (excess) {
384         excess = allocExcessBits(&allocBits[sb], excess);
385         ++sb;
386     }
387 }
388 
389 
monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT * common)390 void monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
391 {
392     BITNEED_UNION1 bitneeds;
393     OI_UINT bitcount;
394     OI_UINT bitpoolPreference = 0;
395 
396     bitcount = computeBitneed(common, bitneeds.uint8, 0, &bitpoolPreference);
397 
398     oneChannelBitAllocation(common, &bitneeds, 0, bitcount);
399 }
400 
401 /**
402 @}
403 */
404 
405 #endif /* #if (defined(SBC_DEC_INCLUDED) && SBC_DEC_INCLUDED == TRUE) */
406