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