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