1 /*
2  *  TwoLAME: an optimized MPEG Audio Layer Two encoder
3  *
4  *  Copyright (C) 2001-2004 Michael Cheng
5  *  Copyright (C) 2004-2018 The TwoLAME Project
6  *
7  *  This library is free software; you can redistribute it and/or
8  *  modify it under the terms of the GNU Lesser General Public
9  *  License as published by the Free Software Foundation; either
10  *  version 2.1 of the License, or (at your option) any later version.
11  *
12  *  This library is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *  Lesser General Public License for more details.
16  *
17  *  You should have received a copy of the GNU Lesser General Public
18  *  License along with this library; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 
23 
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <math.h>
27 
28 #include "twolame.h"
29 #include "common.h"
30 #include "bitbuffer.h"
31 #include "availbits.h"
32 #include "encode.h"
33 #include "util.h"
34 
35 #include "bitbuffer_inline.h"
36 
37 
38 static const FLOAT multiple[64] = {
39     2.00000000000000, 1.58740105196820, 1.25992104989487,
40     1.00000000000000, 0.79370052598410, 0.62996052494744, 0.50000000000000,
41     0.39685026299205, 0.31498026247372, 0.25000000000000, 0.19842513149602,
42     0.15749013123686, 0.12500000000000, 0.09921256574801, 0.07874506561843,
43     0.06250000000000, 0.04960628287401, 0.03937253280921, 0.03125000000000,
44     0.02480314143700, 0.01968626640461, 0.01562500000000, 0.01240157071850,
45     0.00984313320230, 0.00781250000000, 0.00620078535925, 0.00492156660115,
46     0.00390625000000, 0.00310039267963, 0.00246078330058, 0.00195312500000,
47     0.00155019633981, 0.00123039165029, 0.00097656250000, 0.00077509816991,
48     0.00061519582514, 0.00048828125000, 0.00038754908495, 0.00030759791257,
49     0.00024414062500, 0.00019377454248, 0.00015379895629, 0.00012207031250,
50     0.00009688727124, 0.00007689947814, 0.00006103515625, 0.00004844363562,
51     0.00003844973907, 0.00003051757813, 0.00002422181781, 0.00001922486954,
52     0.00001525878906, 0.00001211090890, 0.00000961243477, 0.00000762939453,
53     0.00000605545445, 0.00000480621738, 0.00000381469727, 0.00000302772723,
54     0.00000240310869, 0.00000190734863, 0.00000151386361, 0.00000120155435,
55     1E-20
56 };
57 
58 /* MFC May03
59    Gosh. I should really document this mess.
60    This is a compact data format for all the info that is
61    in the bit allocation tables in the mpeg standards.
62 
63    All the allocation tables are here. There is just multiple
64    redirections to find the number that you want.
65 
66    I might have to reduce the number of index tables to make the code
67    more readable.
68 */
69 
70 
71 #define NUMTABLES 5
72 
73 /* There are really only 9 distinct lines in the allocation tables
74    each member of this table is an index into */
75 /* step_index[linenumber][index] */
76 static const int step_index[9][16] = {
77     /* 0 */ {0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
78     /* 1 */ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17},
79     /* 2 */ {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0},
80     /* 3 */ {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
81     /* 4 */ {0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
82     /* 5 */ {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0},
83     /* From ISO13818 Table B.1 */
84     /* 6 */ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
85     /* 7 */ {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0},
86     /* 8 */ {0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
87 };
88 
89 static const int nbal[9] = { 4, 4, 3, 2, 4, 3, 4, 3, 2 };
90 
91 
92 /* 0, 1, 2, 3, 4,  5,  6,  7,  8,    9,     10,   11,     12,   13,     14,   15,      16,     17 */
93 /* The number of steps allowed */
94 static const int steps[18] =
95 { 0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535 };
96 /* The power of 2 just under the steps value */
97 static const int steps2n[18] =
98 { 0, 2, 4, 4, 8, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 };
99 /* The bits per codeword from TableB.4 */
100 static const int bits[18] = { 0, 5, 7, 3, 10, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
101 
102 /* Samples per codeword Table B.4 Page 53 */
103 //static int group[18] = {0, 3, 3, 1, 3,  1,  1,  1,  1,   1,   1,    1,    1,    1,    1,    1,     1,     1};
104 static const int group[18] = { 0, 1, 1, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
105 
106 /* nbal */
107 
108 /* The sblimits of the 5 allocation tables
109    4 tables for MPEG-1
110    1 table for MPEG-2 LSF */
111 static const int table_sblimit[5] = { 27, 30, 8, 12, 30 };
112 
113 /* Each table contains a list of allowable quantization steps.
114    There are only 9 distinct lists of steps.
115    This table gives the index of which of the 9 lists is being used
116    A "-1" entry means that it is above the sblimit for this table */
117 static const int line[5][SBLIMIT] = {
118     /* 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
119        31 */
120     {   0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, -1, -1, -1,
121         -1, -1
122     },
123     {   0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, -1,
124         -1
125     },
126     {   4, 4, 5, 5, 5, 5, 5, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
127         -1, -1, -1, -1, -1, -1
128     },
129     {   4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
130         -1, -1, -1, -1, -1
131     },
132     /* LSF Table */
133     {6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}
134 };
135 
136 /* This is ISO11172 Table B.1 */
137 static const FLOAT scalefactor[64] = {  /* Equation for nth element = 2 / (cuberoot(2) ^ n) */
138     2.00000000000000, 1.58740105196820, 1.25992104989487,
139     1.00000000000000, 0.79370052598410, 0.62996052494744, 0.50000000000000,
140     0.39685026299205, 0.31498026247372, 0.25000000000000, 0.19842513149602,
141     0.15749013123686, 0.12500000000000, 0.09921256574801, 0.07874506561843,
142     0.06250000000000, 0.04960628287401, 0.03937253280921, 0.03125000000000,
143     0.02480314143700, 0.01968626640461, 0.01562500000000, 0.01240157071850,
144     0.00984313320230, 0.00781250000000, 0.00620078535925, 0.00492156660115,
145     0.00390625000000, 0.00310039267963, 0.00246078330058, 0.00195312500000,
146     0.00155019633981, 0.00123039165029, 0.00097656250000, 0.00077509816991,
147     0.00061519582514, 0.00048828125000, 0.00038754908495, 0.00030759791257,
148     0.00024414062500, 0.00019377454248, 0.00015379895629, 0.00012207031250,
149     0.00009688727124, 0.00007689947814, 0.00006103515625, 0.00004844363562,
150     0.00003844973907, 0.00003051757813, 0.00002422181781, 0.00001922486954,
151     0.00001525878906, 0.00001211090890, 0.00000961243477, 0.00000762939453,
152     0.00000605545445, 0.00000480621738, 0.00000381469727, 0.00000302772723,
153     0.00000240310869, 0.00000190734863, 0.00000151386361, 0.00000120155435,
154     1E-20
155 };
156 
157 /* ISO11172 Table C.5 Layer II Signal to Noise Raios
158    MFC FIX find a reference for these in terms of bits->SNR value
159    Index into table is the steps index
160    index   steps    SNR
161        0       0    0.00
162        1       3    7.00
163        2       5   11.00
164        3       7   16.00
165        4       9   20.84
166   etc
167 */
168 static const FLOAT SNR[18] = {
169     0.00, 7.00, 11.00, 16.00, 20.84, 25.28, 31.59, 37.75, 43.84,
170     49.89, 55.93, 61.96, 67.98, 74.01, 80.03, 86.05, 92.01, 98.01
171 };
172 
173 
174 
get_js_bound(int m_ext)175 static int get_js_bound(int m_ext)
176 {
177     static const int jsb_table[4] = { 4, 8, 12, 16 };
178 
179     if (m_ext < 0 || m_ext > 3) {
180         fprintf(stderr, "get_js_bound() bad modext (%d)\n", m_ext);
181         return -1;
182     }
183     return (jsb_table[m_ext]);
184 }
185 
186 
twolame_encode_init(twolame_options * glopts)187 int twolame_encode_init(twolame_options * glopts)
188 {
189     frame_header *header = &glopts->header;
190     int br_per_ch, sfrq;
191 
192     br_per_ch = glopts->bitrate / glopts->num_channels_out;
193     sfrq = (int) (glopts->samplerate_out / 1000.0);
194 
195     /* decision rules refer to per-channel bitrates (kbits/sec/chan) */
196     if (header->version == TWOLAME_MPEG1) { /* MPEG-1 */
197         if (glopts->freeformat) {
198             glopts->tablenum = (sfrq == 48) ? 0 : 1;
199         } else {
200             if ((sfrq == 48 && br_per_ch >= 56)
201                     || (br_per_ch >= 56 && br_per_ch <= 80))
202                 glopts->tablenum = 0;
203             else if (sfrq != 48 && br_per_ch >= 96)
204                 glopts->tablenum = 1;
205             else if (sfrq != 32 && br_per_ch <= 48)
206                 glopts->tablenum = 2;
207             else
208                 glopts->tablenum = 3;
209         }
210     } else {                    /* MPEG-2 LSF */
211         glopts->tablenum = 4;
212     }
213 
214     // glopts->sblimit = pick_table ( glopts );
215     /* MFC FIX this up */
216     glopts->sblimit = table_sblimit[glopts->tablenum];
217     // fprintf(stderr,"twolame_encode_init: using tablenum %i with sblimit %i\n",glopts->tablenum,
218     // glopts->sblimit);
219 
220     if (glopts->mode == TWOLAME_JOINT_STEREO)
221         glopts->jsbound = get_js_bound(header->mode_ext);
222     else
223         glopts->jsbound = glopts->sblimit;
224     /* alloc, tab_num set in pick_table */
225 
226 
227 #define DUMPTABLESx
228 #ifdef DUMPTABLES
229     {
230         int tablenumber, j, sblimit, sb;
231         fprintf(stderr, "Tables B.21,b,c,d from ISO11172 and the LSF table from ISO13818\n");
232         for (tablenumber = 0; tablenumber < NUMTABLES; tablenumber++) {
233             /* Print Table Header */
234             fprintf(stderr, "Tablenum %i\n", tablenumber);
235             fprintf(stderr, "sb nbal ");
236             for (j = 0; j < 16; j++)
237                 fprintf(stderr, "%6i ", j);
238             fprintf(stderr, "\n");
239             fprintf(stderr,
240                     "-----------------------------------------------------------------------------------------------------------------------\n");
241 
242             sblimit = table_sblimit[tablenumber];
243             for (sb = 0; sb < SBLIMIT; sb++) {
244                 int thisline = line[tablenumber][sb];
245                 fprintf(stderr, "%2i %4i ", sb, nbal[thisline]);
246                 if (nbal[thisline] != 0) {
247                     for (j = 0; j < (1 << nbal[thisline]); j++)
248                         fprintf(stderr, "%6i ", steps[step_index[thisline][j]]);
249                 }
250                 fprintf(stderr, "\n");
251             }
252             fprintf(stderr, "\n");
253         }
254     }
255 #endif
256 
257     // Success
258     return 0;
259 }
260 
261 
262 
263 /*
264    scale_factor_calc
265    pick_scale
266    if JOINTSTEREO
267          combine_LR
268          scale_factor_calc
269    use psy model to determine SMR
270    transmission pattern
271    main_bit_allocation
272    if (error protection)
273          calc CRC
274    encode_info
275    if (error_protection)
276          encode_CRC
277    encode_bit_alloc
278    encode_scale
279    subband_quantization
280    sample_encoding
281 */
282 
twolame_scalefactor_calc(FLOAT sb_sample[][3][SCALE_BLOCK][SBLIMIT],unsigned int sf_index[][3][SBLIMIT],int nch,int sblimit)283 void twolame_scalefactor_calc(FLOAT sb_sample[][3][SCALE_BLOCK][SBLIMIT],
284                               unsigned int sf_index[][3][SBLIMIT], int nch, int sblimit)
285 {
286     /* Optimized to use binary search instead of linear scan through the scalefactor table;
287        guarantees to find scalefactor in only 5 jumps/comparisons and not in {0 (lin. best) to 63
288        (lin. worst)}. Scalefactors for subbands > sblimit are no longer computed. Uses a single
289        sblimit-loop. Patrick De Smet Oct 1999. */
290     int ch, gr;
291     /* Using '--' loops to avoid possible "cmp value + bne/beq" compiler */
292     /* inefficiencies. Below loops should compile to "bne/beq" only code */
293     for (ch = nch; ch--;)
294         for (gr = 3; gr--;) {
295             int sb;
296             for (sb = sblimit; sb--;) {
297                 int j;
298                 unsigned int l;
299                 register FLOAT temp;
300                 unsigned int scale_fac;
301                 /* Determination of max. over each set of 12 subband samples: */
302                 /* PDS TODO: maybe this could/should ??!! be integrated into */
303                 /* the subband filtering routines? */
304                 register FLOAT cur_max = fabs(sb_sample[ch][gr][SCALE_BLOCK - 1][sb]);
305                 for (j = SCALE_BLOCK - 1; j--;) {
306                     if ((temp = fabs(sb_sample[ch][gr][j][sb])) > cur_max)
307                         cur_max = temp;
308                 }
309                 /* PDS: binary search in the scalefactor table: */
310                 /* This is the real speed up: */
311                 for (l = 16, scale_fac = 32; l; l >>= 1) {
312                     if (cur_max <= scalefactor[scale_fac])
313                         scale_fac += l;
314                     else
315                         scale_fac -= l;
316                 }
317                 if (cur_max > scalefactor[scale_fac])
318                     scale_fac--;
319                 sf_index[ch][gr][sb] = scale_fac;
320                 /* There is a direct way of working out the index, if the maximum value is known
321                    but since it involves a log it isn't really speedy. Items in the scalefactor[]
322                    table are calculated by: the n'th entry = 2 / (cuberoot(2) ^ n) And so using a
323                    bit of maths you get: index = (int)(log(2.0/cur_max) / LNCUBEROOTTWO);
324                    fprintf(stderr,"cur_max %.14lf scalefactorindex %i multiple %.14lf\n",cur_max,
325                    scale_fac, scalefactor[scale_fac]); */
326             }
327         }
328 }
329 
330 
331 /* Combine L&R channels into a mono joint stereo channel */
twolame_combine_lr(FLOAT sb_sample[2][3][SCALE_BLOCK][SBLIMIT],FLOAT joint_sample[3][SCALE_BLOCK][SBLIMIT],int sblimit)332 void twolame_combine_lr(FLOAT sb_sample[2][3][SCALE_BLOCK][SBLIMIT],
333                         FLOAT joint_sample[3][SCALE_BLOCK][SBLIMIT], int sblimit)
334 {
335     int sb, sample, gr;
336 
337     for (sb = 0; sb < sblimit; ++sb)
338         for (sample = 0; sample < SCALE_BLOCK; ++sample)
339             for (gr = 0; gr < 3; ++gr)
340                 joint_sample[gr][sample][sb] =
341                     .5 * (sb_sample[0][gr][sample][sb] + sb_sample[1][gr][sample][sb]);
342 }
343 
344 /* PURPOSE:For each subband, puts the smallest scalefactor of the 3
345    associated with a frame into #max_sc#.  This is used
346    used by Psychoacoustic Model I.
347    Someone in dist10 source code's history, somebody wrote the following:
348    "(I would recommend changin max_sc to min_sc)"
349 
350    In psy model 1, the *maximum* out of the scale picked here and
351    the maximum SPL within each subband is selected. So I'd think that
352    a maximum here makes heaps of sense.
353 
354    MFC FIX: Feb 2003 - is this only needed for psy model 1?
355 */
twolame_find_sf_max(twolame_options * glopts,unsigned int sf_index[2][3][SBLIMIT],FLOAT sf_max[2][SBLIMIT])356 void twolame_find_sf_max(twolame_options * glopts,
357                          unsigned int sf_index[2][3][SBLIMIT], FLOAT sf_max[2][SBLIMIT])
358 {
359     unsigned int sb, gr, ch;
360     unsigned int lowest_sf_index;
361     unsigned int nch = glopts->num_channels_out;
362     unsigned int sblimit = glopts->sblimit;
363 
364     for (ch = 0; ch < nch; ch++)
365         for (sb = 0; sb < sblimit; sb++) {
366             for (gr = 1, lowest_sf_index = sf_index[ch][0][sb]; gr < 3; gr++)
367                 if (lowest_sf_index > sf_index[ch][gr][sb])
368                     lowest_sf_index = sf_index[ch][gr][sb];
369             sf_max[ch][sb] = multiple[lowest_sf_index];
370         }
371     for (sb = sblimit; sb < SBLIMIT; sb++)
372         sf_max[0][sb] = sf_max[1][sb] = 1E-20;
373 }
374 
375 /*    sf_transmission_pattern
376     PURPOSE:For a given subband, determines whether to send 1, 2, or
377     all 3 of the scalefactors, and fills in the scalefactor
378     select information accordingly
379 
380     This is From ISO11172 Sect C.1.5.2.5 "coding of scalefactors"
381     and
382     Table C.4 "LayerII Scalefactors Transmission Pattern"
383 */
twolame_sf_transmission_pattern(twolame_options * glopts,unsigned int sf_index[2][3][SBLIMIT],unsigned int sf_selectinfo[2][SBLIMIT])384 void twolame_sf_transmission_pattern(twolame_options * glopts,
385                                      unsigned int sf_index[2][3][SBLIMIT],
386                                      unsigned int sf_selectinfo[2][SBLIMIT])
387 {
388     int nch = glopts->num_channels_out;
389     int sblimit = glopts->sblimit;
390     int dscf[2];
391     int class[2], i, j, k;
392     static const int pattern[5][5] = {
393         {0x123, 0x122, 0x122, 0x133, 0x123},
394         {0x113, 0x111, 0x111, 0x444, 0x113},
395         {0x111, 0x111, 0x111, 0x333, 0x113},
396         {0x222, 0x222, 0x222, 0x333, 0x123},
397         {0x123, 0x122, 0x122, 0x133, 0x123}
398     };
399 
400     for (k = 0; k < nch; k++)
401         for (i = 0; i < sblimit; i++) {
402             dscf[0] = (sf_index[k][0][i] - sf_index[k][1][i]);
403             dscf[1] = (sf_index[k][1][i] - sf_index[k][2][i]);
404             for (j = 0; j < 2; j++) {
405                 if (dscf[j] <= -3)
406                     class[j] = 0;
407                 else if (dscf[j] > -3 && dscf[j] < 0)
408                     class[j] = 1;
409                 else if (dscf[j] == 0)
410                     class[j] = 2;
411                 else if (dscf[j] > 0 && dscf[j] < 3)
412                     class[j] = 3;
413                 else
414                     class[j] = 4;
415             }
416             switch (pattern[class[0]][class[1]]) {
417             case 0x123:
418                 sf_selectinfo[k][i] = 0;
419                 break;
420             case 0x122:
421                 sf_selectinfo[k][i] = 3;
422                 sf_index[k][2][i] = sf_index[k][1][i];
423                 break;
424             case 0x133:
425                 sf_selectinfo[k][i] = 3;
426                 sf_index[k][1][i] = sf_index[k][2][i];
427                 break;
428             case 0x113:
429                 sf_selectinfo[k][i] = 1;
430                 sf_index[k][1][i] = sf_index[k][0][i];
431                 break;
432             case 0x111:
433                 sf_selectinfo[k][i] = 2;
434                 sf_index[k][1][i] = sf_index[k][2][i] = sf_index[k][0][i];
435                 break;
436             case 0x222:
437                 sf_selectinfo[k][i] = 2;
438                 sf_index[k][0][i] = sf_index[k][2][i] = sf_index[k][1][i];
439                 break;
440             case 0x333:
441                 sf_selectinfo[k][i] = 2;
442                 sf_index[k][0][i] = sf_index[k][1][i] = sf_index[k][2][i];
443                 break;
444             case 0x444:
445                 sf_selectinfo[k][i] = 2;
446                 if (sf_index[k][0][i] > sf_index[k][2][i])
447                     sf_index[k][0][i] = sf_index[k][2][i];
448                 sf_index[k][1][i] = sf_index[k][2][i] = sf_index[k][0][i];
449                 break;
450             }
451         }
452 }
453 
twolame_write_header(twolame_options * glopts,bit_stream * bs)454 void twolame_write_header(twolame_options * glopts, bit_stream * bs)
455 {
456     frame_header *header = &glopts->header;
457 
458     buffer_putbits(bs, 0xfff, 12);  /* syncword 12 bits */
459     buffer_put1bit(bs, header->version);    /* ID 1 bit */
460     buffer_putbits(bs, 4 - header->lay, 2); /* layer 2 bits */
461     buffer_put1bit(bs, !header->error_protection);  /* bit set => no err prot */
462     buffer_putbits(bs, header->bitrate_index, 4);
463     buffer_putbits(bs, header->samplerate_idx, 2);
464     buffer_put1bit(bs, header->padding);
465     buffer_put1bit(bs, header->private_extension);    /* private extension bit */
466     buffer_putbits(bs, header->mode, 2);
467     buffer_putbits(bs, header->mode_ext, 2);
468     buffer_put1bit(bs, header->copyright);
469     buffer_put1bit(bs, header->original);
470     buffer_putbits(bs, header->emphasis, 2);
471 }
472 
473 /*************************************************************************
474  encode_bit_alloc (Layer II)
475 
476  PURPOSE: Writes bit allocation information onto bitstream
477 
478  4,3,2, or 0 bits depending on the quantization table used.
479 
480 ************************************************************************/
twolame_write_bit_alloc(twolame_options * glopts,unsigned int bit_alloc[2][SBLIMIT],bit_stream * bs)481 void twolame_write_bit_alloc(twolame_options * glopts, unsigned int bit_alloc[2][SBLIMIT], bit_stream * bs)
482 {
483     int nch = glopts->num_channels_out;
484     int sblimit = glopts->sblimit;
485     int jsbound = glopts->jsbound;
486     int sb, ch;
487 
488     for (sb = 0; sb < sblimit; sb++) {
489         for (ch = 0; ch < ((sb < jsbound) ? nch : 1); ch++) {
490             buffer_putbits(bs, bit_alloc[ch][sb], nbal[line[glopts->tablenum][sb]]);
491             glopts->num_crc_bits += nbal[line[glopts->tablenum][sb]];
492         }
493     }
494 }
495 
496 /************************************************************************
497  write_scalefactors
498 
499  PURPOSE:The encoded scalar factor information is arranged and
500  queued into the output fifo to be transmitted.
501 
502  The three scale factors associated with
503  a given subband and channel are transmitted in accordance
504  with the scfsi, which is transmitted first.
505 
506 ************************************************************************/
507 
twolame_write_scalefactors(twolame_options * glopts,unsigned int bit_alloc[2][SBLIMIT],unsigned int sf_selectinfo[2][SBLIMIT],unsigned int sf_index[2][3][SBLIMIT],bit_stream * bs)508 void twolame_write_scalefactors(twolame_options * glopts,
509                                 unsigned int bit_alloc[2][SBLIMIT],
510                                 unsigned int sf_selectinfo[2][SBLIMIT],
511                                 unsigned int sf_index[2][3][SBLIMIT], bit_stream * bs)
512 {
513     int nch = glopts->num_channels_out;
514     int sblimit = glopts->sblimit;
515     int sb, gr, ch;
516 
517     /* Write out the scalefactor selection information */
518     for (sb = 0; sb < sblimit; sb++)
519         for (ch = 0; ch < nch; ch++)
520             if (bit_alloc[ch][sb]) {
521                 buffer_putbits(bs, sf_selectinfo[ch][sb], 2);
522                 glopts->num_crc_bits += 2;
523             }
524 
525     /* Write out the scalefactors */
526     for (sb = 0; sb < sblimit; sb++)
527         for (ch = 0; ch < nch; ch++)
528             if (bit_alloc[ch][sb])  // above jsbound, bit_alloc[0][i] == ba[1][i]
529             {
530                 switch (sf_selectinfo[ch][sb]) {
531                 case 0:
532                     for (gr = 0; gr < 3; gr++)
533                         buffer_putbits(bs, sf_index[ch][gr][sb], 6);
534                     break;
535                 case 1:
536                 case 3:
537                     buffer_putbits(bs, sf_index[ch][0][sb], 6);
538                     buffer_putbits(bs, sf_index[ch][2][sb], 6);
539                     break;
540                 case 2:
541                     buffer_putbits(bs, sf_index[ch][0][sb], 6);
542                     break;
543                 }
544             }
545 }
546 
547 
548 /* ISO11172 Table C.6 Layer II quantization co-efficients */
549 static const FLOAT a[18] = {
550     0,
551     0.750000000, 0.625000000, 0.875000000, 0.562500000, 0.937500000,
552     0.968750000, 0.984375000, 0.992187500, 0.996093750, 0.998046875,
553     0.999023438, 0.999511719, 0.999755859, 0.999877930, 0.999938965,
554     0.999969482, 0.999984741
555 };
556 
557 static const FLOAT b[18] = {
558     0,
559     -0.250000000, -0.375000000, -0.125000000, -0.437500000, -0.062500000,
560     -0.031250000, -0.015625000, -0.007812500, -0.003906250, -0.001953125,
561     -0.000976563, -0.000488281, -0.000244141, -0.000122070, -0.000061035,
562     -0.000030518, -0.000015259
563 };
564 
565 /************************************************************************
566    subband_quantization (Layer II)
567 
568  PURPOSE:Quantizes subband samples to appropriate number of bits
569 
570  SEMANTICS:     Subband samples are divided by their scalefactors, which
571  makes the quantization more efficient. The scaled samples are
572  quantized by the function a*x+b, where a and b are functions of
573  the number of quantization levels. The result is then truncated
574  to the appropriate number of bits and the MSB is inverted.
575 
576  Note that for fractional 2's complement, inverting the MSB for a
577  negative number x is equivalent to adding 1 to it.
578 
579 ************************************************************************/
twolame_subband_quantization(twolame_options * glopts,unsigned int sf_index[2][3][SBLIMIT],FLOAT sb_samples[2][3][SCALE_BLOCK][SBLIMIT],unsigned int j_scale[3][SBLIMIT],FLOAT j_samps[3][SCALE_BLOCK][SBLIMIT],unsigned int bit_alloc[2][SBLIMIT],unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT])580 void twolame_subband_quantization(twolame_options * glopts,
581                                   unsigned int sf_index[2][3][SBLIMIT],
582                                   FLOAT sb_samples[2][3][SCALE_BLOCK][SBLIMIT],
583                                   unsigned int j_scale[3][SBLIMIT],
584                                   FLOAT j_samps[3][SCALE_BLOCK][SBLIMIT],
585                                   unsigned int bit_alloc[2][SBLIMIT],
586                                   unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT])
587 {
588     int sb, j, ch, gr, qnt_coeff_index, sig;
589     int nch = glopts->num_channels_out;
590     int sblimit = glopts->sblimit;
591     int jsbound = glopts->jsbound;
592     FLOAT d;
593 
594     for (gr = 0; gr < 3; gr++)
595         for (j = 0; j < SCALE_BLOCK; j++)
596             for (sb = 0; sb < sblimit; sb++)
597                 for (ch = 0; ch < ((sb < jsbound) ? nch : 1); ch++)
598 
599                     if (bit_alloc[ch][sb]) {
600                         /* scale and quantize FLOATing point sample */
601                         if (nch == 2 && sb >= jsbound)  /* use j-stereo samples */
602                             d = j_samps[gr][j][sb] / scalefactor[j_scale[gr][sb]];
603                         else
604                             d = sb_samples[ch][gr][j][sb] / scalefactor[sf_index[ch][gr][sb]];
605 
606                         /* Check that the wrong scale factor hasn't been chosen - which would
607                            result in a scaled sample being > 1.0 This error shouldn't ever happen
608                            *unless* something went wrong in scalefactor calc
609 
610                            if (mod (d) > 1.0) fprintf (stderr, "Not scaled properly %d %d %d %d\n",
611                            ch, gr, j, sb); */
612 
613                         {
614                             /* 'index' indicates which "step line" we are using */
615                             int index = line[glopts->tablenum][sb];
616 
617                             /* Find the "step index" within that line */
618                             qnt_coeff_index = step_index[index][bit_alloc[ch][sb]];
619                         }
620                         d = d * a[qnt_coeff_index] + b[qnt_coeff_index];
621 
622                         /* extract MSB N-1 bits from the FLOATing point sample */
623                         if (d >= 0)
624                             sig = 1;
625                         else {
626                             sig = 0;
627                             d += 1.0;
628                         }
629 
630                         sbband[ch][gr][j][sb] =
631                             (unsigned int) (d * (FLOAT) steps2n[qnt_coeff_index]);
632                         /* tag the inverted sign bit to sbband at position N */
633                         /* The bit inversion is a must for grouping with 3,5,9 steps so it is done
634                            for all subbands */
635                         if (sig)
636                             sbband[ch][gr][j][sb] |= steps2n[qnt_coeff_index];
637                     }
638 
639     /* Set everything above the sblimit to 0 */
640     for (ch = 0; ch < nch; ch++)
641         for (gr = 0; gr < 3; gr++)
642             for (sb = 0; sb < SCALE_BLOCK; sb++)
643                 for (j = sblimit; j < SBLIMIT; j++)
644                     sbband[ch][gr][sb][j] = 0;
645 }
646 
647 /************************************************************************
648     sample_encoding
649 
650  PURPOSE:Put one frame of subband samples on to the bitstream
651 
652  SEMANTICS:     The number of bits allocated per sample is read from
653  the bit allocation information #bit_alloc#.  Layer 2
654  supports writing grouped samples for quantization steps
655  that are not a power of 2.
656 
657 ***********************************************************************/
twolame_write_samples(twolame_options * glopts,unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT],unsigned int bit_alloc[2][SBLIMIT],bit_stream * bs)658 void twolame_write_samples(twolame_options * glopts,
659                            unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT],
660                            unsigned int bit_alloc[2][SBLIMIT], bit_stream * bs)
661 {
662     unsigned int nch = glopts->num_channels_out;
663     unsigned int sblimit = glopts->sblimit;
664     unsigned int jsbound = glopts->jsbound;
665     unsigned int sb, j, ch, gr, x, y;
666     unsigned int temp;
667 
668     for (gr = 0; gr < 3; gr++)
669         for (j = 0; j < SCALE_BLOCK; j += 3)
670             for (sb = 0; sb < sblimit; sb++)
671                 for (ch = 0; ch < ((sb < jsbound) ? nch : 1); ch++) {
672                     if (bit_alloc[ch][sb]) {
673                         int thisline = line[glopts->tablenum][sb];
674                         int thisstep_index = step_index[thisline][bit_alloc[ch][sb]];
675 
676                         /* Check how many samples per codeword */
677                         if (group[thisstep_index] == 3) {
678                             /* Going to send 1 sample per codeword -> 3 samples */
679                             for (x = 0; x < 3; x++) {
680                                 buffer_putbits(bs, sbband[ch][gr][j + x][sb], bits[thisstep_index]);
681                             }
682 
683                         } else {
684                             /* ISO11172 Sec C.1.5.2.8 If steps=3, 5 or 9, then three consecutive
685                                samples are coded as one codeword i.e. only one value (V) is
686                                transmitted for this triplet. If the 3 subband samples are x,y,z
687                                then V = (steps*steps)*z + steps*y +x */
688                             y = steps[thisstep_index];
689                             temp =
690                                 sbband[ch][gr][j][sb] + sbband[ch][gr][j + 1][sb] * y +
691                                 sbband[ch][gr][j + 2][sb] * y * y;
692                             buffer_putbits(bs, temp, bits[thisstep_index]);
693                         }
694                     }
695                 }
696 }
697 
698 
699 /************************************************************************
700 *
701 * bits_for_nonoise (Layer II)
702 *
703 * PURPOSE:Returns the number of bits required to produce a
704 * mask-to-noise ratio better or equal to the noise/no_noise threshold.
705 *
706 * SEMANTICS:
707 * bbal = # bits needed for encoding bit allocation
708 * bsel = # bits needed for encoding scalefactor select information
709 * banc = # bits needed for ancillary data (header info included)
710 *
711 * For each subband and channel, will add bits until one of the
712 * following occurs:
713 * - Hit maximum number of bits we can allocate for that subband
714 * - MNR is better than or equal to the minimum masking level
715 *    (NOISY_MIN_MNR)
716 * Then the bits required for scalefactors, scfsi, bit allocation,
717 * and the subband samples are tallied (#req_bits#) and returned.
718 *
719 * (NOISY_MIN_MNR) is the smallest MNR a subband can have before it is
720 * counted as 'noisy' by the logic which chooses the number of JS
721 * subbands.
722 *
723 * Joint stereo is supported.
724 *
725 ************************************************************************/
726 
twolame_bits_for_nonoise(twolame_options * glopts,FLOAT SMR[2][SBLIMIT],unsigned int scfsi[2][SBLIMIT],FLOAT min_mnr,unsigned int bit_alloc[2][SBLIMIT])727 int twolame_bits_for_nonoise(twolame_options * glopts,
728                              FLOAT SMR[2][SBLIMIT],
729                              unsigned int scfsi[2][SBLIMIT], FLOAT min_mnr,
730                              unsigned int bit_alloc[2][SBLIMIT])
731 {
732     frame_header *header = &glopts->header;
733     int sb, ch, ba;
734     int nch = glopts->num_channels_out;
735     int sblimit = glopts->sblimit;
736     int jsbound = glopts->jsbound;
737     int req_bits = 0, bbal = 0, berr = 0, banc = 32;
738     int maxAlloc, sel_bits, sc_bits, smp_bits;
739     static const int sfsPerScfsi[] = { 3, 2, 1, 2 };    /* lookup # sfs per scfsi */
740 
741     /* MFC Feb 2003 This works out the basic number of bits just to get a valid (but empty) frame.
742        This needs to be done for every frame, since a joint_stereo frame will change the number of
743        basic bits (depending on the sblimit in the particular js mode that's been selected */
744 
745     /* Make sure there's room for the error protection bits */
746     if (header->error_protection)
747         berr = 16;
748     else
749         berr = 0;
750 
751     /* Count the number of bits required to encode the quantization index for both channels in each
752        subband. If we're above the jsbound, then pretend we only have one channel */
753     for (sb = 0; sb < jsbound; ++sb)
754         bbal += nch * nbal[line[glopts->tablenum][sb]]; // (*alloc)[sb][0].bits;
755 
756     for (sb = jsbound; sb < sblimit; ++sb)
757         bbal += nbal[line[glopts->tablenum][sb]];   // (*alloc)[sb][0].bits;
758     req_bits = banc + bbal + berr;
759 
760     for (sb = 0; sb < sblimit; ++sb)
761         for (ch = 0; ch < ((sb < jsbound) ? nch : 1); ++ch) {
762             int thisline = line[glopts->tablenum][sb];
763 
764             /* How many possible steps are there to choose from ? */
765             maxAlloc = (1 << nbal[line[glopts->tablenum][sb]]) - 1; // (*alloc)[sb][0].bits) - 1;
766             sel_bits = sc_bits = smp_bits = 0;
767             /* Keep choosing the next number of steps (and hence our SNR value) until we have the
768                required MNR value */
769             for (ba = 0; ba < maxAlloc - 1; ++ba) {
770                 int thisstep_index = step_index[thisline][ba];
771                 if ((SNR[thisstep_index] - SMR[ch][sb]) >= min_mnr)
772                     break;      /* we found enough bits */
773             }
774             if (nch == 2 && sb >= jsbound)  /* check other JS channel */
775                 for (; ba < maxAlloc - 1; ++ba) {
776                     int thisstep_index = step_index[thisline][ba];
777                     if ((SNR[thisstep_index] - SMR[1 - ch][sb]) >= min_mnr)
778                         break;
779                 }
780             if (ba > 0) {
781                 // smp_bits = SCALE_BLOCK * ((*alloc)[sb][ba].group * (*alloc)[sb][ba].bits);
782                 int thisstep_index = step_index[thisline][ba];
783                 smp_bits = SCALE_BLOCK * group[thisstep_index] * bits[thisstep_index];
784                 /* scale factor bits required for subband */
785                 sel_bits = 2;
786                 sc_bits = 6 * sfsPerScfsi[scfsi[ch][sb]];
787                 if (nch == 2 && sb >= jsbound) {
788                     /* each new js sb has L+R scfsis */
789                     sel_bits += 2;
790                     sc_bits += 6 * sfsPerScfsi[scfsi[1 - ch][sb]];
791                 }
792                 req_bits += smp_bits + sel_bits + sc_bits;
793             }
794             bit_alloc[ch][sb] = ba;
795         }
796     return req_bits;
797 }
798 
799 
800 /* must be called before calling main_bit_allocation */
twolame_init_bit_allocation(twolame_options * glopts)801 int twolame_init_bit_allocation(twolame_options * glopts)
802 {
803     frame_header *header = &glopts->header;
804     int nch = glopts->num_channels_out;
805     int brindex;
806 
807 
808     /* these are the tables which specify the limits within which the VBR can vary You can't vary
809        outside these ranges, otherwise a new alloc table would have to be loaded in the middle of
810        encoding. This VBR hack is dodgy - the standard says that LayerII decoders don't have to
811        support a variable bitrate, but Layer3 decoders must do so. Hence, it is unlikely that a
812        compliant layer2 decoder would be written to dynmically change allocation tables. *BUT* a
813        layer3 encoder might handle it by default, meaning we could switch tables mid-encode and
814        enjoy a wider range of bitrates for the VBR encoding. None of this needs to be done for LSF,
815        since there is only *one* possible alloc table in LSF MFC Feb 2003 */
816 
817     static const int vbrlimits[2][3][2] = {
818         /* MONO */
819         {   /* 44 */ {6, 10},
820             /* 48 */ {3, 10},
821             /* 32 */ {6, 10}
822         },
823         /* STEREO */
824         {   /* 44 */ {10, 14},
825             /* 48 */ {7, 14},
826             /* 32 */ {10, 14}
827         }
828     };
829 
830 
831     for (brindex = 0; brindex < 15; brindex++)
832         glopts->bitrateindextobits[brindex] = 0;
833 
834     if (header->version == TWOLAME_MPEG2) {
835         /* LSF: so can use any bitrate index from 1->15 */
836         glopts->lower_index = 1;
837         glopts->upper_index = 14;
838     } else {
839         int sfreq = header->samplerate_idx;
840         glopts->lower_index = vbrlimits[nch - 1][sfreq][0];
841         glopts->upper_index = vbrlimits[nch - 1][sfreq][1];
842     }
843 
844     if (glopts->vbr_upper_index > 0) {
845         /* User is requesting a specific upperbitrate */
846         if ((glopts->vbr_upper_index < glopts->lower_index) ||
847                 (glopts->vbr_upper_index > glopts->upper_index)) {
848             fprintf(stderr, "Can't satisfy upper bitrate index constraint. out of bounds. %i\n",
849                     glopts->vbr_upper_index);
850             return -2;
851         } else
852             glopts->upper_index = glopts->vbr_upper_index;
853     }
854     /* when vbr is requested, check glopts->bitrate and fix it eventually */
855     if (glopts->vbr) {
856         /* the specified bitrate will be used as a lower bound when valid */
857         if (glopts->bitrate < twolame_index_bitrate((int)glopts->version, glopts->lower_index))
858             glopts->bitrate = twolame_index_bitrate((int)glopts->version, glopts->lower_index);
859         else
860             glopts->lower_index = twolame_get_bitrate_index(glopts->bitrate, glopts->version);
861     }
862 
863 
864     /* set up a conversion table for bitrateindex->bits for this version/sampl freq This will be
865        used to find the best bitrate to cope with the number of bits that are needed (as determined
866        by vbr_bits_for_nonoise) */
867     for (brindex = glopts->lower_index; brindex <= glopts->upper_index; brindex++) {
868         glopts->bitrateindextobits[brindex] =
869             (int) (1152.0 / (glopts->samplerate_out / 1000.0) * (FLOAT) twolame_index_bitrate((int)glopts->version, brindex));
870     }
871 
872     return 0;
873 }
874 
875 
876 /************************************************************************
877 *
878 * main_bit_allocation  (Layer II)
879 *
880 * PURPOSE:For joint stereo mode, determines which of the 4 joint
881 * stereo modes is needed.  Then calls *_a_bit_allocation(), which
882 * allocates bits for each of the subbands until there are no more bits
883 * left, or the MNR is at the noise/no_noise threshold.
884 *
885 * SEMANTICS:
886 *
887 * For joint stereo mode, joint stereo is changed to stereo if
888 * there are enough bits to encode stereo at or better than the
889 * no-noise threshold (NOISY_MIN_MNR).  Otherwise, the system
890 * iteratively allocates less bits by using joint stereo until one
891 * of the following occurs:
892 * - there are no more noisy subbands (MNR >= NOISY_MIN_MNR)
893 * - mode_ext has been reduced to 0, which means that all but the
894 *    lowest 4 subbands have been converted from stereo to joint
895 *    stereo, and no more subbands may be converted
896 *
897 *      This function calls *_bits_for_nonoise() and *_a_bit_allocation().
898 *
899 ************************************************************************/
twolame_main_bit_allocation(twolame_options * glopts,FLOAT SMR[2][SBLIMIT],unsigned int scfsi[2][SBLIMIT],unsigned int bit_alloc[2][SBLIMIT],int * adb)900 void twolame_main_bit_allocation(twolame_options * glopts,
901                                  FLOAT SMR[2][SBLIMIT],
902                                  unsigned int scfsi[2][SBLIMIT],
903                                  unsigned int bit_alloc[2][SBLIMIT], int *adb)
904 {
905     frame_header *header = &glopts->header;
906     int mode = glopts->mode;
907     int mode_ext;
908     int rq_db;                  /* av_db = *adb; Not Used MFC Nov 99 */
909     int guessindex = 0;
910 
911 
912     if (mode == TWOLAME_JOINT_STEREO) {
913         header->mode = TWOLAME_STEREO;
914         header->mode_ext = 0;
915         glopts->jsbound = glopts->sblimit;
916         if ((rq_db = twolame_bits_for_nonoise(glopts, SMR, scfsi, 0, bit_alloc)) > *adb) {
917             header->mode = TWOLAME_JOINT_STEREO;
918             mode_ext = 4;       /* 3 is least severe reduction */
919             do {
920                 --mode_ext;
921                 glopts->jsbound = get_js_bound(mode_ext);
922                 rq_db = twolame_bits_for_nonoise(glopts, SMR, scfsi, 0, bit_alloc);
923             }
924             while ((rq_db > *adb) && (mode_ext > 0));
925             header->mode_ext = mode_ext;
926         }                       /* well we either eliminated noisy sbs or mode_ext == 0 */
927     }
928 
929     /* decide on which bit allocation method to use */
930     if (glopts->vbr == FALSE) {
931         /* Just do the old bit allocation method */
932         twolame_a_bit_allocation(glopts, SMR, scfsi, bit_alloc, adb);
933     } else {
934         /* do the VBR bit allocation method */
935         {
936             int brindex;
937 
938             /* Work out how many bits are needed for there to be no noise (ie all MNR > VBRLEVEL) */
939             int req = twolame_bits_for_nonoise(glopts, SMR, scfsi, glopts->vbrlevel, bit_alloc);
940 
941             /* Look up this value in the bitrateindextobits table to find what bitrate we should
942                use for this frame */
943             for (brindex = glopts->lower_index; brindex <= glopts->upper_index; brindex++) {
944                 if (glopts->bitrateindextobits[brindex] > req) {
945                     /* this method always *overestimates* the bits that are needed i.e. it will
946                        usually guess right but when it's wrong it'll guess a higher bitrate than
947                        actually required. e.g. on "messages from earth" track 6, the guess was
948                        wrong on 75/36341 frames. each time it guessed higher. MFC Feb 2003 */
949                     guessindex = brindex;
950                     break;
951                 }
952             }
953             /* Just for sanity */
954             if (brindex == glopts->upper_index+1)
955                 guessindex = glopts->upper_index;
956         }
957 
958         header->bitrate_index = guessindex;
959         glopts->bitrate = twolame_index_bitrate((int)glopts->version, guessindex);
960         *adb = twolame_available_bits(glopts);
961 
962         /* update the statistics */
963         glopts->vbrstats[header->bitrate_index]++;
964 
965         if (glopts->verbosity > 3) {
966             /* print out the VBR stats every 1000th frame */
967             int i;
968             if ((glopts->vbr_frame_count++ % 1000) == 0) {
969                 for (i = 1; i < 15; i++)
970                     fprintf(stderr, "%4i ", glopts->vbrstats[i]);
971                 fprintf(stderr, "\n");
972             }
973 
974             /* Print out *every* frames bitrateindex, bits required, and bits available at this
975                bitrate */
976             if (glopts->verbosity > 5)
977                 fprintf(stderr,
978                         "> bitrate index %2i has %i bits available to encode the %i bits\n",
979                         header->bitrate_index, *adb,
980                         twolame_bits_for_nonoise(glopts, SMR, scfsi, glopts->vbrlevel, bit_alloc));
981 
982         }
983 
984         twolame_vbr_bit_allocation(glopts, SMR, scfsi, bit_alloc, adb);
985     }
986 }
987 
vbr_maxmnr(FLOAT mnr[2][SBLIMIT],char used[2][SBLIMIT],int sblimit,int nch,int * min_sb,int * min_ch,FLOAT vbrlevel)988 static void vbr_maxmnr(FLOAT mnr[2][SBLIMIT], char used[2][SBLIMIT], int sblimit,
989                        int nch, int *min_sb, int *min_ch, FLOAT vbrlevel)
990 {
991     int sb, ch;
992     FLOAT small;
993 
994     small = 999999.0;
995     *min_sb = -1;
996     *min_ch = -1;
997 
998 #define NEWBITx
999 #ifdef NEWBIT
1000     /* Keep going until all subbands have reached the MNR level that we specified */
1001     for (ch = 0; ch < nch; ch++)
1002         for (sb = 0; sb < sblimit; sb++)
1003             if (mnr[ch][sb] < vbrlevel) {
1004                 *min_sb = sb;
1005                 *min_ch = ch;
1006                 // fprintf(stderr,".");
1007                 // fflush(stderr);
1008                 return;
1009             }
1010 #endif
1011 
1012     /* Then start adding bits to whichever is the min MNR */
1013     for (ch = 0; ch < nch; ++ch)
1014         for (sb = 0; sb < sblimit; sb++)
1015             if (used[ch][sb] != 2 && small > mnr[ch][sb]) {
1016                 small = mnr[ch][sb];
1017                 *min_sb = sb;
1018                 *min_ch = ch;
1019             }
1020     // fprintf(stderr,"Min sb: %i\n",*min_sb);
1021 }
1022 
1023 
1024 
1025 
1026 /********************
1027 MFC Feb 2003
1028 vbr_bit_allocation is different to the normal a_bit_allocation in that
1029 it is known beforehand that there are definitely enough bits to do what we
1030 have to - i.e. a bitrate was specificially chosen in main_bit_allocation so
1031 that we have enough bits to encode what we have to.
1032 This function should take that into account and just greedily assign
1033 the bits, rather than fussing over the minimum MNR subband - we know
1034 each subband gets its required bits, why quibble?
1035 This function doesn't chew much CPU, so I haven't made any attempt
1036 to do this yet.
1037 *********************/
twolame_vbr_bit_allocation(twolame_options * glopts,FLOAT SMR[2][SBLIMIT],unsigned int scfsi[2][SBLIMIT],unsigned int bit_alloc[2][SBLIMIT],int * adb)1038 int twolame_vbr_bit_allocation(twolame_options * glopts,
1039                                FLOAT SMR[2][SBLIMIT],
1040                                unsigned int scfsi[2][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], int *adb)
1041 {
1042     int sb, min_ch, min_sb, oth_ch, ch, increment, scale, seli, ba;
1043     int bspl, bscf, bsel, ad, bbal = 0;
1044     frame_header *header = &glopts->header;
1045     FLOAT mnr[2][SBLIMIT];
1046     char used[2][SBLIMIT];
1047     int nch = glopts->num_channels_out;
1048     int sblimit = glopts->sblimit;
1049     int jsbound = glopts->jsbound;
1050     int banc, berr;
1051     static const int sfsPerScfsi[] = { 3, 2, 1, 2 };    /* lookup # sfs per scfsi */
1052     int thisstep_index;
1053 
1054     if (header->error_protection) {
1055         berr = 16;              /* added 92-08-11 shn */
1056         banc = 32;
1057     } else {
1058         berr = 0;
1059         banc = 32;
1060     }
1061 
1062 
1063     /* No need to worry about jsbound here as JS is disabled for VBR mode */
1064     for (sb = 0; sb < sblimit; sb++)
1065         bbal += nch * nbal[line[glopts->tablenum][sb]];
1066     *adb -= bbal + berr + banc;
1067     ad = *adb;
1068 
1069     for (sb = 0; sb < sblimit; sb++)
1070         for (ch = 0; ch < nch; ch++) {
1071             mnr[ch][sb] = SNR[0] - SMR[ch][sb];
1072             bit_alloc[ch][sb] = 0;
1073             used[ch][sb] = 0;
1074         }
1075     bspl = bscf = bsel = 0;
1076 
1077     do {
1078         /* locate the subband with minimum SMR */
1079         vbr_maxmnr(mnr, used, sblimit, nch, &min_sb, &min_ch, glopts->vbrlevel);
1080 
1081         if (min_sb > -1) {      /* there was something to find */
1082             int thisline = line[glopts->tablenum][min_sb];
1083             {
1084                 /* find increase in bit allocation in subband [min] */
1085                 int nextstep_index = step_index[thisline][bit_alloc[min_ch][min_sb] + 1];
1086                 increment = SCALE_BLOCK * group[nextstep_index] * bits[nextstep_index];
1087             }
1088             if (used[min_ch][min_sb]) {
1089                 /* If we've already increased the limit on this ch/sb, then subtract the last thing
1090                    that we added */
1091                 thisstep_index = step_index[thisline][bit_alloc[min_ch][min_sb]];
1092                 increment -= SCALE_BLOCK * group[thisstep_index] * bits[thisstep_index];
1093             }
1094 
1095             /* scale factor bits required for subband [min] */
1096             oth_ch = 1 - min_ch;    /* above js bound, need both chans */
1097             if (used[min_ch][min_sb]) {
1098                 scale = seli = 0;
1099             } else {            /* this channel had no bits or scfs before */
1100                 seli = 2;
1101                 scale = 6 * sfsPerScfsi[scfsi[min_ch][min_sb]];
1102                 if (nch == 2 && min_sb >= jsbound) {
1103                     /* each new js sb has L+R scfsis */
1104                     seli += 2;
1105                     scale += 6 * sfsPerScfsi[scfsi[oth_ch][min_sb]];
1106                 }
1107             }
1108 
1109             /* check to see enough bits were available for */
1110             /* increasing resolution in the minimum band */
1111             if (ad >= bspl + bscf + bsel + seli + scale + increment) {
1112                 /* Then there are enough bits to have another go at allocating */
1113                 ba = ++bit_alloc[min_ch][min_sb];   /* next up alloc */
1114                 bspl += increment;  /* bits for subband sample */
1115                 bscf += scale;  /* bits for scale factor */
1116                 bsel += seli;   /* bits for scfsi code */
1117                 used[min_ch][min_sb] = 1;   /* subband has bits */
1118                 thisstep_index = step_index[thisline][ba];
1119                 mnr[min_ch][min_sb] = SNR[thisstep_index] - SMR[min_ch][min_sb];
1120                 /* Check if this min_sb subband has been fully allocated max bits */
1121                 if (ba >= (1 << nbal[line[glopts->tablenum][min_sb]]) - 1)  // (*alloc)[min_sb][0].bits)
1122                     //
1123                     // - 1)
1124                     used[min_ch][min_sb] = 2;   /* don't let this sb get any more bits */
1125             } else {
1126                 used[min_ch][min_sb] = 2;   /* can't increase this alloc */
1127             }
1128         }
1129     }
1130     while (min_sb > -1);        /* until could find no channel */
1131 
1132     /* Calculate the number of bits left */
1133     ad -= bspl + bscf + bsel;
1134     *adb = ad;
1135     for (ch = 0; ch < nch; ch++)
1136         for (sb = sblimit; sb < SBLIMIT; sb++)
1137             bit_alloc[ch][sb] = 0;
1138 
1139     return 0;
1140 }
1141 
1142 
1143 
maxmnr(FLOAT mnr[2][SBLIMIT],char used[2][SBLIMIT],int sblimit,int nch,int * min_sb,int * min_ch)1144 static void maxmnr(FLOAT mnr[2][SBLIMIT], char used[2][SBLIMIT], int sblimit,
1145                    int nch, int *min_sb, int *min_ch)
1146 {
1147     int sb, ch;
1148     FLOAT small;
1149 
1150     small = 999999.0;
1151     *min_sb = -1;
1152     *min_ch = -1;
1153     for (ch = 0; ch < nch; ++ch)
1154         for (sb = 0; sb < sblimit; sb++)
1155             if (used[ch][sb] != 2 && small > mnr[ch][sb]) {
1156                 small = mnr[ch][sb];
1157                 *min_sb = sb;
1158                 *min_ch = ch;
1159             }
1160 }
1161 
1162 
1163 
1164 
1165 
1166 /************************************************************************
1167 *
1168 * a_bit_allocation (Layer II)
1169 *
1170 * PURPOSE:Adds bits to the subbands with the lowest mask-to-noise
1171 * ratios, until the maximum number of bits for the subband has
1172 * been allocated.
1173 *
1174 * SEMANTICS:
1175 * 1. Find the subband and channel with the smallest MNR (#min_sb#,
1176 *     and #min_ch#)
1177 * 2. Calculate the increase in bits needed if we increase the bit
1178 *     allocation to the next higher level
1179 * 3. If there are enough bits available for increasing the resolution
1180 *     in #min_sb#, #min_ch#, and the subband has not yet reached its
1181 *     maximum allocation, update the bit allocation, MNR, and bits
1182 *     available accordingly
1183 * 4. Repeat until there are no more bits left, or no more available
1184 *     subbands. (A subband is still available until the maximum
1185 *     number of bits for the subband has been allocated, or there
1186 *     aren't enough bits to go to the next higher resolution in the
1187 *     subband.)
1188 *
1189 ************************************************************************/
1190 
twolame_a_bit_allocation(twolame_options * glopts,FLOAT SMR[2][SBLIMIT],unsigned int scfsi[2][SBLIMIT],unsigned int bit_alloc[2][SBLIMIT],int * adb)1191 int twolame_a_bit_allocation(twolame_options * glopts, FLOAT SMR[2][SBLIMIT],
1192                              unsigned int scfsi[2][SBLIMIT], unsigned int bit_alloc[2][SBLIMIT], int *adb)
1193 {
1194     int sb, min_ch, min_sb, oth_ch, ch, increment, scale, seli, ba;
1195     int bspl, bscf, bsel, ad, bbal = 0;
1196     FLOAT mnr[2][SBLIMIT];
1197     char used[2][SBLIMIT];
1198     frame_header *header = &glopts->header;
1199     int nch = glopts->num_channels_out;
1200     int sblimit = glopts->sblimit;
1201     int jsbound = glopts->jsbound;
1202     int banc, berr;
1203     static const int sfsPerScfsi[] = { 3, 2, 1, 2 };    /* lookup # sfs per scfsi */
1204 
1205     int thisstep_index;
1206 
1207     if (header->error_protection) {
1208         berr = 16;              /* added 92-08-11 shn */
1209         banc = 32;
1210     } else {
1211         berr = 0;
1212         banc = 32;
1213     }
1214 
1215     for (sb = 0; sb < jsbound; sb++)
1216         bbal += nch * nbal[line[glopts->tablenum][sb]]; // (*alloc)[sb][0].bits;
1217     for (sb = jsbound; sb < sblimit; sb++)
1218         bbal += nbal[line[glopts->tablenum][sb]];   // (*alloc)[sb][0].bits;
1219     *adb -= bbal + berr + banc;
1220     ad = *adb;
1221 
1222 
1223     for (sb = 0; sb < sblimit; sb++) {
1224         for (ch = 0; ch < nch; ch++) {
1225             mnr[ch][sb] = SNR[0] - SMR[ch][sb];
1226             bit_alloc[ch][sb] = 0;
1227             used[ch][sb] = 0;
1228         }
1229     }
1230     bspl = bscf = bsel = 0;
1231 
1232     do {
1233         /* locate the subband with minimum SMR */
1234         maxmnr(mnr, used, sblimit, nch, &min_sb, &min_ch);
1235 
1236         if (min_sb > -1) {      /* there was something to find */
1237             int thisline = line[glopts->tablenum][min_sb];
1238             {
1239                 /* find increase in bit allocation in subband [min] */
1240                 int nextstep_index = step_index[thisline][bit_alloc[min_ch][min_sb] + 1];
1241                 increment = SCALE_BLOCK * group[nextstep_index] * bits[nextstep_index];
1242             }
1243             if (used[min_ch][min_sb]) {
1244                 /* If we've already increased the limit on this ch/sb, then subtract the last thing
1245                    that we added */
1246                 thisstep_index = step_index[thisline][bit_alloc[min_ch][min_sb]];
1247                 increment -= SCALE_BLOCK * group[thisstep_index] * bits[thisstep_index];
1248             }
1249 
1250             /* scale factor bits required for subband [min] */
1251             oth_ch = 1 - min_ch;    /* above js bound, need both chans */
1252             if (used[min_ch][min_sb]) {
1253                 scale = seli = 0;
1254             } else {            /* this channel had no bits or scfs before */
1255                 seli = 2;
1256                 scale = 6 * sfsPerScfsi[scfsi[min_ch][min_sb]];
1257                 if (nch == 2 && min_sb >= jsbound) {
1258                     /* each new js sb has L+R scfsis */
1259                     seli += 2;
1260                     scale += 6 * sfsPerScfsi[scfsi[oth_ch][min_sb]];
1261                 }
1262             }
1263 
1264             /* check to see enough bits were available for */
1265             /* increasing resolution in the minimum band */
1266             if (ad >= bspl + bscf + bsel + seli + scale + increment) {
1267                 /* Then there are enough bits to have another go at allocating */
1268                 ba = ++bit_alloc[min_ch][min_sb];   /* next up alloc */
1269                 bspl += increment;  /* bits for subband sample */
1270                 bscf += scale;  /* bits for scale factor */
1271                 bsel += seli;   /* bits for scfsi code */
1272                 used[min_ch][min_sb] = 1;   /* subband has bits */
1273                 thisstep_index = step_index[thisline][ba];
1274                 mnr[min_ch][min_sb] = SNR[thisstep_index] - SMR[min_ch][min_sb];
1275                 /* Check if this min_sb subband has been fully allocated max bits */
1276                 if (ba >= (1 << nbal[line[glopts->tablenum][min_sb]]) - 1)  // (*alloc)[min_sb][0].bits)
1277                     //
1278                     // - 1)
1279                     used[min_ch][min_sb] = 2;   /* don't let this sb get any more bits */
1280             } else {
1281                 used[min_ch][min_sb] = 2;   /* can't increase this alloc */
1282             }
1283             if (min_sb >= jsbound && nch == 2) {
1284                 /* above jsbound, alloc applies L+R */
1285                 ba = bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
1286                 used[oth_ch][min_sb] = used[min_ch][min_sb];
1287                 thisstep_index = step_index[thisline][ba];
1288                 mnr[oth_ch][min_sb] = SNR[thisstep_index] - SMR[oth_ch][min_sb];
1289                 // mnr[oth_ch][min_sb] = SNR[(*alloc)[min_sb][ba].quant + 1] - SMR[oth_ch][min_sb];
1290             }
1291 
1292         }
1293     }
1294     while (min_sb > -1);        /* until could find no channel */
1295 
1296     /* Calculate the number of bits left */
1297     ad -= bspl + bscf + bsel;
1298     *adb = ad;
1299     for (ch = 0; ch < nch; ch++)
1300         for (sb = sblimit; sb < SBLIMIT; sb++)
1301             bit_alloc[ch][sb] = 0;
1302 
1303     return 0;
1304 }
1305 
1306 
1307 // vim:ts=4:sw=4:nowrap:
1308