ffmpeg / libavcodec / ac3enc.c @ 14166a6d
History  View  Annotate  Download (62.7 KB)
1 
/*


2 
* The simplest AC3 encoder

3 
* Copyright (c) 2000 Fabrice Bellard

4 
* Copyright (c) 20062010 Justin Ruggles <justin.ruggles@gmail.com>

5 
* Copyright (c) 20062010 Prakash Punnoor <prakash@punnoor.de>

6 
*

7 
* This file is part of FFmpeg.

8 
*

9 
* FFmpeg is free software; you can redistribute it and/or

10 
* modify it under the terms of the GNU Lesser General Public

11 
* License as published by the Free Software Foundation; either

12 
* version 2.1 of the License, or (at your option) any later version.

13 
*

14 
* FFmpeg is distributed in the hope that it will be useful,

15 
* but WITHOUT ANY WARRANTY; without even the implied warranty of

16 
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU

17 
* Lesser General Public License for more details.

18 
*

19 
* You should have received a copy of the GNU Lesser General Public

20 
* License along with FFmpeg; if not, write to the Free Software

21 
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 021101301 USA

22 
*/

23  
24 
/**

25 
* @file

26 
* The simplest AC3 encoder.

27 
*/

28  
29 
//#define DEBUG

30  
31 
#include "libavcore/audioconvert.h" 
32 
#include "libavutil/crc.h" 
33 
#include "avcodec.h" 
34 
#include "put_bits.h" 
35 
#include "dsputil.h" 
36 
#include "ac3.h" 
37 
#include "audioconvert.h" 
38  
39  
40 
/** Maximum number of exponent groups. +1 for separate DC exponent. */

41 
#define AC3_MAX_EXP_GROUPS 85 
42  
43 
/** Scale a float value by 2^bits and convert to an integer. */

44 
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits))) 
45  
46 
/** Scale a float value by 2^15, convert to an integer, and clip to range 32767..32767. */

47 
#define FIX15(a) av_clip(SCALE_FLOAT(a, 15), 32767, 32767) 
48  
49  
50 
/**

51 
* Compex number.

52 
* Used in fixedpoint MDCT calculation.

53 
*/

54 
typedef struct IComplex { 
55 
int16_t re,im; 
56 
} IComplex; 
57  
58 
typedef struct AC3MDCTContext { 
59 
int nbits; ///< log2(transform size) 
60 
int16_t *costab; ///< FFT cos table

61 
int16_t *sintab; ///< FFT sin table

62 
int16_t *xcos1; ///< MDCT cos table

63 
int16_t *xsin1; ///< MDCT sin table

64 
int16_t *rot_tmp; ///< temp buffer for prerotated samples

65 
IComplex *cplx_tmp; ///< temp buffer for complex prerotated samples

66 
} AC3MDCTContext; 
67  
68 
/**

69 
* Data for a single audio block.

70 
*/

71 
typedef struct AC3Block { 
72 
uint8_t **bap; ///< bit allocation pointers (bap)

73 
int32_t **mdct_coef; ///< MDCT coefficients

74 
uint8_t **exp; ///< original exponents

75 
uint8_t **grouped_exp; ///< grouped exponents

76 
int16_t **psd; ///< psd per frequency bin

77 
int16_t **band_psd; ///< psd per critical band

78 
int16_t **mask; ///< masking curve

79 
uint16_t **qmant; ///< quantized mantissas

80 
uint8_t exp_strategy[AC3_MAX_CHANNELS]; ///< exponent strategies

81 
int8_t exp_shift[AC3_MAX_CHANNELS]; ///< exponent shift values

82 
} AC3Block; 
83  
84 
/**

85 
* AC3 encoder private context.

86 
*/

87 
typedef struct AC3EncodeContext { 
88 
PutBitContext pb; ///< bitstream writer context

89 
DSPContext dsp; 
90 
AC3MDCTContext mdct; ///< MDCT context

91  
92 
AC3Block blocks[AC3_MAX_BLOCKS]; ///< perblock info

93  
94 
int bitstream_id; ///< bitstream id (bsid) 
95 
int bitstream_mode; ///< bitstream mode (bsmod) 
96  
97 
int bit_rate; ///< target bit rate, in bitspersecond 
98 
int sample_rate; ///< sampling frequency, in Hz 
99  
100 
int frame_size_min; ///< minimum frame size in case rounding is necessary 
101 
int frame_size; ///< current frame size in bytes 
102 
int frame_size_code; ///< frame size code (frmsizecod) 
103 
uint16_t crc_inv[2];

104 
int bits_written; ///< bit count (used to avg. bitrate) 
105 
int samples_written; ///< sample count (used to avg. bitrate) 
106  
107 
int fbw_channels; ///< number of fullbandwidth channels (nfchans) 
108 
int channels; ///< total number of channels (nchans) 
109 
int lfe_on; ///< indicates if there is an LFE channel (lfeon) 
110 
int lfe_channel; ///< channel index of the LFE channel 
111 
int channel_mode; ///< channel mode (acmod) 
112 
const uint8_t *channel_map; ///< channel map used to reorder channels 
113  
114 
int cutoff; ///< userspecified cutoff frequency, in Hz 
115 
int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod) 
116 
int nb_coefs[AC3_MAX_CHANNELS];

117  
118 
/* bitrate allocation control */

119 
int slow_gain_code; ///< slow gain code (sgaincod) 
120 
int slow_decay_code; ///< slow decay code (sdcycod) 
121 
int fast_decay_code; ///< fast decay code (fdcycod) 
122 
int db_per_bit_code; ///< dB/bit code (dbpbcod) 
123 
int floor_code; ///< floor code (floorcod) 
124 
AC3BitAllocParameters bit_alloc; ///< bit allocation parameters

125 
int coarse_snr_offset; ///< coarse SNR offsets (csnroffst) 
126 
int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signaltomask ratio) (fgaincod) 
127 
int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst) 
128 
int frame_bits_fixed; ///< number of noncoefficient bits for fixed parameters 
129 
int frame_bits; ///< all frame bits except exponents and mantissas 
130 
int exponent_bits; ///< number of bits used for exponents 
131  
132 
/* mantissa encoding */

133 
int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4 
134 
uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4

135  
136 
int16_t **planar_samples; 
137 
uint8_t *bap_buffer; 
138 
uint8_t *bap1_buffer; 
139 
int32_t *mdct_coef_buffer; 
140 
uint8_t *exp_buffer; 
141 
uint8_t *grouped_exp_buffer; 
142 
int16_t *psd_buffer; 
143 
int16_t *band_psd_buffer; 
144 
int16_t *mask_buffer; 
145 
uint16_t *qmant_buffer; 
146  
147 
DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];

148 
} AC3EncodeContext; 
149  
150  
151 
/**

152 
* LUT for number of exponent groups.

153 
* exponent_group_tab[exponent strategy1][number of coefficients]

154 
*/

155 
static uint8_t exponent_group_tab[3][256]; 
156  
157  
158 
/**

159 
* Adjust the frame size to make the average bit rate match the target bit rate.

160 
* This is only needed for 11025, 22050, and 44100 sample rates.

161 
*/

162 
static void adjust_frame_size(AC3EncodeContext *s) 
163 
{ 
164 
while (s>bits_written >= s>bit_rate && s>samples_written >= s>sample_rate) {

165 
s>bits_written = s>bit_rate; 
166 
s>samples_written = s>sample_rate; 
167 
} 
168 
s>frame_size = s>frame_size_min + 
169 
2 * (s>bits_written * s>sample_rate < s>samples_written * s>bit_rate);

170 
s>bits_written += s>frame_size * 8;

171 
s>samples_written += AC3_FRAME_SIZE; 
172 
} 
173  
174  
175 
/**

176 
* Deinterleave input samples.

177 
* Channels are reordered from FFmpeg's default order to AC3 order.

178 
*/

179 
static void deinterleave_input_samples(AC3EncodeContext *s, 
180 
const int16_t *samples)

181 
{ 
182 
int ch, i;

183  
184 
/* deinterleave and remap input samples */

185 
for (ch = 0; ch < s>channels; ch++) { 
186 
const int16_t *sptr;

187 
int sinc;

188  
189 
/* copy last 256 samples of previous frame to the start of the current frame */

190 
memcpy(&s>planar_samples[ch][0], &s>planar_samples[ch][AC3_FRAME_SIZE],

191 
AC3_BLOCK_SIZE * sizeof(s>planar_samples[0][0])); 
192  
193 
/* deinterleave */

194 
sinc = s>channels; 
195 
sptr = samples + s>channel_map[ch]; 
196 
for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {

197 
s>planar_samples[ch][i] = *sptr; 
198 
sptr += sinc; 
199 
} 
200 
} 
201 
} 
202  
203  
204 
/**

205 
* Finalize MDCT and free allocated memory.

206 
*/

207 
static av_cold void mdct_end(AC3MDCTContext *mdct) 
208 
{ 
209 
mdct>nbits = 0;

210 
av_freep(&mdct>costab); 
211 
av_freep(&mdct>sintab); 
212 
av_freep(&mdct>xcos1); 
213 
av_freep(&mdct>xsin1); 
214 
av_freep(&mdct>rot_tmp); 
215 
av_freep(&mdct>cplx_tmp); 
216 
} 
217  
218  
219  
220 
/**

221 
* Initialize FFT tables.

222 
* @param ln log2(FFT size)

223 
*/

224 
static av_cold int fft_init(AVCodecContext *avctx, AC3MDCTContext *mdct, int ln) 
225 
{ 
226 
int i, n, n2;

227 
float alpha;

228  
229 
n = 1 << ln;

230 
n2 = n >> 1;

231  
232 
FF_ALLOC_OR_GOTO(avctx, mdct>costab, n2 * sizeof(*mdct>costab),

233 
fft_alloc_fail); 
234 
FF_ALLOC_OR_GOTO(avctx, mdct>sintab, n2 * sizeof(*mdct>sintab),

235 
fft_alloc_fail); 
236  
237 
for (i = 0; i < n2; i++) { 
238 
alpha = 2.0 * M_PI * i / n; 
239 
mdct>costab[i] = FIX15(cos(alpha)); 
240 
mdct>sintab[i] = FIX15(sin(alpha)); 
241 
} 
242  
243 
return 0; 
244 
fft_alloc_fail:

245 
mdct_end(mdct); 
246 
return AVERROR(ENOMEM);

247 
} 
248  
249  
250 
/**

251 
* Initialize MDCT tables.

252 
* @param nbits log2(MDCT size)

253 
*/

254 
static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct, int nbits) 
255 
{ 
256 
int i, n, n4, ret;

257  
258 
n = 1 << nbits;

259 
n4 = n >> 2;

260  
261 
mdct>nbits = nbits; 
262  
263 
ret = fft_init(avctx, mdct, nbits  2);

264 
if (ret)

265 
return ret;

266  
267 
FF_ALLOC_OR_GOTO(avctx, mdct>xcos1, n4 * sizeof(*mdct>xcos1),

268 
mdct_alloc_fail); 
269 
FF_ALLOC_OR_GOTO(avctx, mdct>xsin1, n4 * sizeof(*mdct>xsin1),

270 
mdct_alloc_fail); 
271 
FF_ALLOC_OR_GOTO(avctx, mdct>rot_tmp, n * sizeof(*mdct>rot_tmp),

272 
mdct_alloc_fail); 
273 
FF_ALLOC_OR_GOTO(avctx, mdct>cplx_tmp, n4 * sizeof(*mdct>cplx_tmp),

274 
mdct_alloc_fail); 
275  
276 
for (i = 0; i < n4; i++) { 
277 
float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n; 
278 
mdct>xcos1[i] = FIX15(cos(alpha)); 
279 
mdct>xsin1[i] = FIX15(sin(alpha)); 
280 
} 
281  
282 
return 0; 
283 
mdct_alloc_fail:

284 
mdct_end(mdct); 
285 
return AVERROR(ENOMEM);

286 
} 
287  
288  
289 
/** Butterfly op */

290 
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \

291 
{ \ 
292 
int ax, ay, bx, by; \

293 
bx = pre1; \ 
294 
by = pim1; \ 
295 
ax = qre1; \ 
296 
ay = qim1; \ 
297 
pre = (bx + ax) >> 1; \

298 
pim = (by + ay) >> 1; \

299 
qre = (bx  ax) >> 1; \

300 
qim = (by  ay) >> 1; \

301 
} 
302  
303  
304 
/** Complex multiply */

305 
#define CMUL(pre, pim, are, aim, bre, bim) \

306 
{ \ 
307 
pre = (MUL16(are, bre)  MUL16(aim, bim)) >> 15; \

308 
pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15; \

309 
} 
310  
311  
312 
/**

313 
* Calculate a 2^n point complex FFT on 2^ln points.

314 
* @param z complex input/output samples

315 
* @param ln log2(FFT size)

316 
*/

317 
static void fft(AC3MDCTContext *mdct, IComplex *z, int ln) 
318 
{ 
319 
int j, l, np, np2;

320 
int nblocks, nloops;

321 
register IComplex *p,*q;

322 
int tmp_re, tmp_im;

323  
324 
np = 1 << ln;

325  
326 
/* reverse */

327 
for (j = 0; j < np; j++) { 
328 
int k = av_reverse[j] >> (8  ln); 
329 
if (k < j)

330 
FFSWAP(IComplex, z[k], z[j]); 
331 
} 
332  
333 
/* pass 0 */

334  
335 
p = &z[0];

336 
j = np >> 1;

337 
do {

338 
BF(p[0].re, p[0].im, p[1].re, p[1].im, 
339 
p[0].re, p[0].im, p[1].re, p[1].im); 
340 
p += 2;

341 
} while (j);

342  
343 
/* pass 1 */

344  
345 
p = &z[0];

346 
j = np >> 2;

347 
do {

348 
BF(p[0].re, p[0].im, p[2].re, p[2].im, 
349 
p[0].re, p[0].im, p[2].re, p[2].im); 
350 
BF(p[1].re, p[1].im, p[3].re, p[3].im, 
351 
p[1].re, p[1].im, p[3].im, p[3].re); 
352 
p+=4;

353 
} while (j);

354  
355 
/* pass 2 .. ln1 */

356  
357 
nblocks = np >> 3;

358 
nloops = 1 << 2; 
359 
np2 = np >> 1;

360 
do {

361 
p = z; 
362 
q = z + nloops; 
363 
for (j = 0; j < nblocks; j++) { 
364 
BF(p>re, p>im, q>re, q>im, 
365 
p>re, p>im, q>re, q>im); 
366 
p++; 
367 
q++; 
368 
for(l = nblocks; l < np2; l += nblocks) {

369 
CMUL(tmp_re, tmp_im, mdct>costab[l], mdct>sintab[l], q>re, q>im); 
370 
BF(p>re, p>im, q>re, q>im, 
371 
p>re, p>im, tmp_re, tmp_im); 
372 
p++; 
373 
q++; 
374 
} 
375 
p += nloops; 
376 
q += nloops; 
377 
} 
378 
nblocks = nblocks >> 1;

379 
nloops = nloops << 1;

380 
} while (nblocks);

381 
} 
382  
383  
384 
/**

385 
* Calculate a 512point MDCT

386 
* @param out 256 output frequency coefficients

387 
* @param in 512 windowed input audio samples

388 
*/

389 
static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in) 
390 
{ 
391 
int i, re, im, n, n2, n4;

392 
int16_t *rot = mdct>rot_tmp; 
393 
IComplex *x = mdct>cplx_tmp; 
394  
395 
n = 1 << mdct>nbits;

396 
n2 = n >> 1;

397 
n4 = n >> 2;

398  
399 
/* shift to simplify computations */

400 
for (i = 0; i <n4; i++) 
401 
rot[i] = in[i + 3*n4];

402 
memcpy(&rot[n4], &in[0], 3*n4*sizeof(*in)); 
403  
404 
/* pre rotation */

405 
for (i = 0; i < n4; i++) { 
406 
re = ((int)rot[ 2*i]  (int)rot[ n12*i]) >> 1; 
407 
im = ((int)rot[n2+2*i]  (int)rot[n212*i]) >> 1; 
408 
CMUL(x[i].re, x[i].im, re, im, mdct>xcos1[i], mdct>xsin1[i]); 
409 
} 
410  
411 
fft(mdct, x, mdct>nbits  2);

412  
413 
/* post rotation */

414 
for (i = 0; i < n4; i++) { 
415 
re = x[i].re; 
416 
im = x[i].im; 
417 
CMUL(out[n212*i], out[2*i], re, im, mdct>xsin1[i], mdct>xcos1[i]); 
418 
} 
419 
} 
420  
421  
422 
/**

423 
* Apply KBD window to input samples prior to MDCT.

424 
*/

425 
static void apply_window(int16_t *output, const int16_t *input, 
426 
const int16_t *window, int n) 
427 
{ 
428 
int i;

429 
int n2 = n >> 1; 
430  
431 
for (i = 0; i < n2; i++) { 
432 
output[i] = MUL16(input[i], window[i]) >> 15;

433 
output[ni1] = MUL16(input[ni1], window[i]) >> 15; 
434 
} 
435 
} 
436  
437  
438 
/**

439 
* Calculate the log2() of the maximum absolute value in an array.

440 
* @param tab input array

441 
* @param n number of values in the array

442 
* @return log2(max(abs(tab[])))

443 
*/

444 
static int log2_tab(int16_t *tab, int n) 
445 
{ 
446 
int i, v;

447  
448 
v = 0;

449 
for (i = 0; i < n; i++) 
450 
v = abs(tab[i]); 
451  
452 
return av_log2(v);

453 
} 
454  
455  
456 
/**

457 
* Leftshift each value in an array by a specified amount.

458 
* @param tab input array

459 
* @param n number of values in the array

460 
* @param lshift left shift amount. a negative value means right shift.

461 
*/

462 
static void lshift_tab(int16_t *tab, int n, int lshift) 
463 
{ 
464 
int i;

465  
466 
if (lshift > 0) { 
467 
for (i = 0; i < n; i++) 
468 
tab[i] <<= lshift; 
469 
} else if (lshift < 0) { 
470 
lshift = lshift; 
471 
for (i = 0; i < n; i++) 
472 
tab[i] >>= lshift; 
473 
} 
474 
} 
475  
476  
477 
/**

478 
* Normalize the input samples to use the maximum available precision.

479 
* This assumes signed 16bit input samples. Exponents are reduced by 9 to

480 
* match the 24bit internal precision for MDCT coefficients.

481 
*

482 
* @return exponent shift

483 
*/

484 
static int normalize_samples(AC3EncodeContext *s) 
485 
{ 
486 
int v = 14  log2_tab(s>windowed_samples, AC3_WINDOW_SIZE); 
487 
v = FFMAX(0, v);

488 
lshift_tab(s>windowed_samples, AC3_WINDOW_SIZE, v); 
489 
return v  9; 
490 
} 
491  
492  
493 
/**

494 
* Apply the MDCT to input samples to generate frequency coefficients.

495 
* This applies the KBD window and normalizes the input to reduce precision

496 
* loss due to fixedpoint calculations.

497 
*/

498 
static void apply_mdct(AC3EncodeContext *s) 
499 
{ 
500 
int blk, ch;

501  
502 
for (ch = 0; ch < s>channels; ch++) { 
503 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
504 
AC3Block *block = &s>blocks[blk]; 
505 
const int16_t *input_samples = &s>planar_samples[ch][blk * AC3_BLOCK_SIZE];

506  
507 
apply_window(s>windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE); 
508  
509 
block>exp_shift[ch] = normalize_samples(s); 
510  
511 
mdct512(&s>mdct, block>mdct_coef[ch], s>windowed_samples); 
512 
} 
513 
} 
514 
} 
515  
516  
517 
/**

518 
* Initialize exponent tables.

519 
*/

520 
static av_cold void exponent_init(AC3EncodeContext *s) 
521 
{ 
522 
int i;

523 
for (i = 73; i < 256; i++) { 
524 
exponent_group_tab[0][i] = (i  1) / 3; 
525 
exponent_group_tab[1][i] = (i + 2) / 6; 
526 
exponent_group_tab[2][i] = (i + 8) / 12; 
527 
} 
528 
/* LFE */

529 
exponent_group_tab[0][7] = 2; 
530 
} 
531  
532  
533 
/**

534 
* Extract exponents from the MDCT coefficients.

535 
* This takes into account the normalization that was done to the input samples

536 
* by adjusting the exponents by the exponent shift values.

537 
*/

538 
static void extract_exponents(AC3EncodeContext *s) 
539 
{ 
540 
int blk, ch, i;

541  
542 
for (ch = 0; ch < s>channels; ch++) { 
543 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
544 
AC3Block *block = &s>blocks[blk]; 
545 
for (i = 0; i < AC3_MAX_COEFS; i++) { 
546 
int e;

547 
int v = abs(block>mdct_coef[ch][i]);

548 
if (v == 0) 
549 
e = 24;

550 
else {

551 
e = 23  av_log2(v) + block>exp_shift[ch];

552 
if (e >= 24) { 
553 
e = 24;

554 
block>mdct_coef[ch][i] = 0;

555 
} 
556 
} 
557 
block>exp[ch][i] = e; 
558 
} 
559 
} 
560 
} 
561 
} 
562  
563  
564 
/**

565 
* Exponent Difference Threshold.

566 
* New exponents are sent if their SAD exceed this number.

567 
*/

568 
#define EXP_DIFF_THRESHOLD 1000 
569  
570  
571 
/**

572 
* Calculate exponent strategies for all blocks in a single channel.

573 
*/

574 
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy, uint8_t **exp) 
575 
{ 
576 
int blk, blk1;

577 
int exp_diff;

578  
579 
/* estimate if the exponent variation & decide if they should be

580 
reused in the next frame */

581 
exp_strategy[0] = EXP_NEW;

582 
for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) { 
583 
exp_diff = s>dsp.sad[0](NULL, exp[blk], exp[blk1], 16, 16); 
584 
if (exp_diff > EXP_DIFF_THRESHOLD)

585 
exp_strategy[blk] = EXP_NEW; 
586 
else

587 
exp_strategy[blk] = EXP_REUSE; 
588 
} 
589 
emms_c(); 
590  
591 
/* now select the encoding strategy type : if exponents are often

592 
recoded, we use a coarse encoding */

593 
blk = 0;

594 
while (blk < AC3_MAX_BLOCKS) {

595 
blk1 = blk + 1;

596 
while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)

597 
blk1++; 
598 
switch (blk1  blk) {

599 
case 1: exp_strategy[blk] = EXP_D45; break; 
600 
case 2: 
601 
case 3: exp_strategy[blk] = EXP_D25; break; 
602 
default: exp_strategy[blk] = EXP_D15; break; 
603 
} 
604 
blk = blk1; 
605 
} 
606 
} 
607  
608  
609 
/**

610 
* Calculate exponent strategies for all channels.

611 
* Array arrangement is reversed to simplify the perchannel calculation.

612 
*/

613 
static void compute_exp_strategy(AC3EncodeContext *s) 
614 
{ 
615 
uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; 
616 
uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; 
617 
int ch, blk;

618  
619 
for (ch = 0; ch < s>fbw_channels; ch++) { 
620 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
621 
exp1[ch][blk] = s>blocks[blk].exp[ch]; 
622 
exp_str1[ch][blk] = s>blocks[blk].exp_strategy[ch]; 
623 
} 
624  
625 
compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]); 
626  
627 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) 
628 
s>blocks[blk].exp_strategy[ch] = exp_str1[ch][blk]; 
629 
} 
630 
if (s>lfe_on) {

631 
ch = s>lfe_channel; 
632 
s>blocks[0].exp_strategy[ch] = EXP_D15;

633 
for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) 
634 
s>blocks[blk].exp_strategy[ch] = EXP_REUSE; 
635 
} 
636 
} 
637  
638  
639 
/**

640 
* Set each encoded exponent in a block to the minimum of itself and the

641 
* exponent in the same frequency bin of a following block.

642 
* exp[i] = min(exp[i], exp1[i]

643 
*/

644 
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n) 
645 
{ 
646 
int i;

647 
for (i = 0; i < n; i++) { 
648 
if (exp1[i] < exp[i])

649 
exp[i] = exp1[i]; 
650 
} 
651 
} 
652  
653  
654 
/**

655 
* Update the exponents so that they are the ones the decoder will decode.

656 
*/

657 
static void encode_exponents_blk_ch(uint8_t *exp, 
658 
int nb_exps, int exp_strategy) 
659 
{ 
660 
int nb_groups, i, k;

661  
662 
nb_groups = exponent_group_tab[exp_strategy1][nb_exps] * 3; 
663  
664 
/* for each group, compute the minimum exponent */

665 
switch(exp_strategy) {

666 
case EXP_D25:

667 
for (i = 1, k = 1; i <= nb_groups; i++) { 
668 
uint8_t exp_min = exp[k]; 
669 
if (exp[k+1] < exp_min) 
670 
exp_min = exp[k+1];

671 
exp[i] = exp_min; 
672 
k += 2;

673 
} 
674 
break;

675 
case EXP_D45:

676 
for (i = 1, k = 1; i <= nb_groups; i++) { 
677 
uint8_t exp_min = exp[k]; 
678 
if (exp[k+1] < exp_min) 
679 
exp_min = exp[k+1];

680 
if (exp[k+2] < exp_min) 
681 
exp_min = exp[k+2];

682 
if (exp[k+3] < exp_min) 
683 
exp_min = exp[k+3];

684 
exp[i] = exp_min; 
685 
k += 4;

686 
} 
687 
break;

688 
} 
689  
690 
/* constraint for DC exponent */

691 
if (exp[0] > 15) 
692 
exp[0] = 15; 
693  
694 
/* decrease the delta between each groups to within 2 so that they can be

695 
differentially encoded */

696 
for (i = 1; i <= nb_groups; i++) 
697 
exp[i] = FFMIN(exp[i], exp[i1] + 2); 
698 
i; 
699 
while (i >= 0) 
700 
exp[i] = FFMIN(exp[i], exp[i+1] + 2); 
701  
702 
/* now we have the exponent values the decoder will see */

703 
switch (exp_strategy) {

704 
case EXP_D25:

705 
for (i = nb_groups, k = nb_groups * 2; i > 0; i) { 
706 
uint8_t exp1 = exp[i]; 
707 
exp[k] = exp1; 
708 
exp[k] = exp1; 
709 
} 
710 
break;

711 
case EXP_D45:

712 
for (i = nb_groups, k = nb_groups * 4; i > 0; i) { 
713 
exp[k] = exp[k1] = exp[k2] = exp[k3] = exp[i]; 
714 
k = 4;

715 
} 
716 
break;

717 
} 
718 
} 
719  
720  
721 
/**

722 
* Encode exponents from original extracted form to what the decoder will see.

723 
* This copies and groups exponents based on exponent strategy and reduces

724 
* deltas between adjacent exponent groups so that they can be differentially

725 
* encoded.

726 
*/

727 
static void encode_exponents(AC3EncodeContext *s) 
728 
{ 
729 
int blk, blk1, blk2, ch;

730 
AC3Block *block, *block1, *block2; 
731  
732 
for (ch = 0; ch < s>channels; ch++) { 
733 
blk = 0;

734 
block = &s>blocks[0];

735 
while (blk < AC3_MAX_BLOCKS) {

736 
blk1 = blk + 1;

737 
block1 = block + 1;

738 
/* for the EXP_REUSE case we select the min of the exponents */

739 
while (blk1 < AC3_MAX_BLOCKS && block1>exp_strategy[ch] == EXP_REUSE) {

740 
exponent_min(block>exp[ch], block1>exp[ch], s>nb_coefs[ch]); 
741 
blk1++; 
742 
block1++; 
743 
} 
744 
encode_exponents_blk_ch(block>exp[ch], s>nb_coefs[ch], 
745 
block>exp_strategy[ch]); 
746 
/* copy encoded exponents for reuse case */

747 
block2 = block + 1;

748 
for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) { 
749 
memcpy(block2>exp[ch], block>exp[ch], 
750 
s>nb_coefs[ch] * sizeof(uint8_t));

751 
} 
752 
blk = blk1; 
753 
block = block1; 
754 
} 
755 
} 
756 
} 
757  
758  
759 
/**

760 
* Group exponents.

761 
* 3 deltaencoded exponents are in each 7bit group. The number of groups

762 
* varies depending on exponent strategy and bandwidth.

763 
*/

764 
static void group_exponents(AC3EncodeContext *s) 
765 
{ 
766 
int blk, ch, i;

767 
int group_size, nb_groups, bit_count;

768 
uint8_t *p; 
769 
int delta0, delta1, delta2;

770 
int exp0, exp1;

771  
772 
bit_count = 0;

773 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
774 
AC3Block *block = &s>blocks[blk]; 
775 
for (ch = 0; ch < s>channels; ch++) { 
776 
if (block>exp_strategy[ch] == EXP_REUSE) {

777 
continue;

778 
} 
779 
group_size = block>exp_strategy[ch] + (block>exp_strategy[ch] == EXP_D45); 
780 
nb_groups = exponent_group_tab[block>exp_strategy[ch]1][s>nb_coefs[ch]];

781 
bit_count += 4 + (nb_groups * 7); 
782 
p = block>exp[ch]; 
783  
784 
/* DC exponent */

785 
exp1 = *p++; 
786 
block>grouped_exp[ch][0] = exp1;

787  
788 
/* remaining exponents are delta encoded */

789 
for (i = 1; i <= nb_groups; i++) { 
790 
/* merge three delta in one code */

791 
exp0 = exp1; 
792 
exp1 = p[0];

793 
p += group_size; 
794 
delta0 = exp1  exp0 + 2;

795  
796 
exp0 = exp1; 
797 
exp1 = p[0];

798 
p += group_size; 
799 
delta1 = exp1  exp0 + 2;

800  
801 
exp0 = exp1; 
802 
exp1 = p[0];

803 
p += group_size; 
804 
delta2 = exp1  exp0 + 2;

805  
806 
block>grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2; 
807 
} 
808 
} 
809 
} 
810  
811 
s>exponent_bits = bit_count; 
812 
} 
813  
814  
815 
/**

816 
* Calculate final exponents from the supplied MDCT coefficients and exponent shift.

817 
* Extract exponents from MDCT coefficients, calculate exponent strategies,

818 
* and encode final exponents.

819 
*/

820 
static void process_exponents(AC3EncodeContext *s) 
821 
{ 
822 
extract_exponents(s); 
823  
824 
compute_exp_strategy(s); 
825  
826 
encode_exponents(s); 
827  
828 
group_exponents(s); 
829 
} 
830  
831  
832 
/**

833 
* Count frame bits that are based solely on fixed parameters.

834 
* This only has to be run once when the encoder is initialized.

835 
*/

836 
static void count_frame_bits_fixed(AC3EncodeContext *s) 
837 
{ 
838 
static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 }; 
839 
int blk;

840 
int frame_bits;

841  
842 
/* assumptions:

843 
* no dynamic range codes

844 
* no channel coupling

845 
* no rematrixing

846 
* bit allocation parameters do not change between blocks

847 
* SNR offsets do not change between blocks

848 
* no delta bit allocation

849 
* no skipped data

850 
* no auxilliary data

851 
*/

852  
853 
/* header size */

854 
frame_bits = 65;

855 
frame_bits += frame_bits_inc[s>channel_mode]; 
856  
857 
/* audio blocks */

858 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
859 
frame_bits += s>fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */ 
860 
if (s>channel_mode == AC3_CHMODE_STEREO) {

861 
frame_bits++; /* rematstr */

862 
if (!blk)

863 
frame_bits += 4;

864 
} 
865 
frame_bits += 2 * s>fbw_channels; /* chexpstr[2] * c */ 
866 
if (s>lfe_on)

867 
frame_bits++; /* lfeexpstr */

868 
frame_bits++; /* baie */

869 
frame_bits++; /* snr */

870 
frame_bits += 2; /* delta / skip */ 
871 
} 
872 
frame_bits++; /* cplinu for block 0 */

873 
/* bit alloc info */

874 
/* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */

875 
/* csnroffset[6] */

876 
/* (fsnoffset[4] + fgaincod[4]) * c */

877 
frame_bits += 2*4 + 3 + 6 + s>channels * (4 + 3); 
878  
879 
/* auxdatae, crcrsv */

880 
frame_bits += 2;

881  
882 
/* CRC */

883 
frame_bits += 16;

884  
885 
s>frame_bits_fixed = frame_bits; 
886 
} 
887  
888  
889 
/**

890 
* Initialize bit allocation.

891 
* Set default parameter codes and calculate parameter values.

892 
*/

893 
static void bit_alloc_init(AC3EncodeContext *s) 
894 
{ 
895 
int ch;

896  
897 
/* init default parameters */

898 
s>slow_decay_code = 2;

899 
s>fast_decay_code = 1;

900 
s>slow_gain_code = 1;

901 
s>db_per_bit_code = 3;

902 
s>floor_code = 4;

903 
for (ch = 0; ch < s>channels; ch++) 
904 
s>fast_gain_code[ch] = 4;

905  
906 
/* initial snr offset */

907 
s>coarse_snr_offset = 40;

908  
909 
/* compute real values */

910 
/* currently none of these values change during encoding, so we can just

911 
set them once at initialization */

912 
s>bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s>slow_decay_code] >> s>bit_alloc.sr_shift; 
913 
s>bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s>fast_decay_code] >> s>bit_alloc.sr_shift; 
914 
s>bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s>slow_gain_code]; 
915 
s>bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s>db_per_bit_code]; 
916 
s>bit_alloc.floor = ff_ac3_floor_tab[s>floor_code]; 
917  
918 
count_frame_bits_fixed(s); 
919 
} 
920  
921  
922 
/**

923 
* Count the bits used to encode the frame, minus exponents and mantissas.

924 
* Bits based on fixed parameters have already been counted, so now we just

925 
* have to add the bits based on parameters that change during encoding.

926 
*/

927 
static void count_frame_bits(AC3EncodeContext *s) 
928 
{ 
929 
int blk, ch;

930 
int frame_bits = 0; 
931  
932 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
933 
uint8_t *exp_strategy = s>blocks[blk].exp_strategy; 
934 
for (ch = 0; ch < s>fbw_channels; ch++) { 
935 
if (exp_strategy[ch] != EXP_REUSE)

936 
frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */ 
937 
} 
938 
} 
939 
s>frame_bits = s>frame_bits_fixed + frame_bits; 
940 
} 
941  
942  
943 
/**

944 
* Calculate the number of bits needed to encode a set of mantissas.

945 
*/

946 
static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs) 
947 
{ 
948 
int bits, b, i;

949  
950 
bits = 0;

951 
for (i = 0; i < nb_coefs; i++) { 
952 
b = bap[i]; 
953 
if (b <= 4) { 
954 
// bap=1 to bap=4 will be counted in compute_mantissa_size_final

955 
mant_cnt[b]++; 
956 
} else if (b <= 13) { 
957 
// bap=5 to bap=13 use (bap1) bits

958 
bits += b  1;

959 
} else {

960 
// bap=14 uses 14 bits and bap=15 uses 16 bits

961 
bits += (b == 14) ? 14 : 16; 
962 
} 
963 
} 
964 
return bits;

965 
} 
966  
967  
968 
/**

969 
* Finalize the mantissa bit count by adding in the grouped mantissas.

970 
*/

971 
static int compute_mantissa_size_final(int mant_cnt[5]) 
972 
{ 
973 
// bap=1 : 3 mantissas in 5 bits

974 
int bits = (mant_cnt[1] / 3) * 5; 
975 
// bap=2 : 3 mantissas in 7 bits

976 
// bap=4 : 2 mantissas in 7 bits

977 
bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7; 
978 
// bap=3 : each mantissa is 3 bits

979 
bits += mant_cnt[3] * 3; 
980 
return bits;

981 
} 
982  
983  
984 
/**

985 
* Calculate masking curve based on the final exponents.

986 
* Also calculate the power spectral densities to use in future calculations.

987 
*/

988 
static void bit_alloc_masking(AC3EncodeContext *s) 
989 
{ 
990 
int blk, ch;

991  
992 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
993 
AC3Block *block = &s>blocks[blk]; 
994 
for (ch = 0; ch < s>channels; ch++) { 
995 
/* We only need psd and mask for calculating bap.

996 
Since we currently do not calculate bap when exponent

997 
strategy is EXP_REUSE we do not need to calculate psd or mask. */

998 
if (block>exp_strategy[ch] != EXP_REUSE) {

999 
ff_ac3_bit_alloc_calc_psd(block>exp[ch], 0,

1000 
s>nb_coefs[ch], 
1001 
block>psd[ch], block>band_psd[ch]); 
1002 
ff_ac3_bit_alloc_calc_mask(&s>bit_alloc, block>band_psd[ch], 
1003 
0, s>nb_coefs[ch],

1004 
ff_ac3_fast_gain_tab[s>fast_gain_code[ch]], 
1005 
ch == s>lfe_channel, 
1006 
DBA_NONE, 0, NULL, NULL, NULL, 
1007 
block>mask[ch]); 
1008 
} 
1009 
} 
1010 
} 
1011 
} 
1012  
1013  
1014 
/**

1015 
* Ensure that bap for each block and channel point to the current bap_buffer.

1016 
* They may have been switched during the bit allocation search.

1017 
*/

1018 
static void reset_block_bap(AC3EncodeContext *s) 
1019 
{ 
1020 
int blk, ch;

1021 
if (s>blocks[0].bap[0] == s>bap_buffer) 
1022 
return;

1023 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
1024 
for (ch = 0; ch < s>channels; ch++) { 
1025 
s>blocks[blk].bap[ch] = &s>bap_buffer[AC3_MAX_COEFS * (blk * s>channels + ch)]; 
1026 
} 
1027 
} 
1028 
} 
1029  
1030  
1031 
/**

1032 
* Run the bit allocation with a given SNR offset.

1033 
* This calculates the bit allocation pointers that will be used to determine

1034 
* the quantization of each mantissa.

1035 
* @return the number of bits needed for mantissas if the given SNR offset is

1036 
* is used.

1037 
*/

1038 
static int bit_alloc(AC3EncodeContext *s, 
1039 
int snr_offset)

1040 
{ 
1041 
int blk, ch;

1042 
int mantissa_bits;

1043 
int mant_cnt[5]; 
1044  
1045 
snr_offset = (snr_offset  240) << 2; 
1046  
1047 
reset_block_bap(s); 
1048 
mantissa_bits = 0;

1049 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
1050 
AC3Block *block = &s>blocks[blk]; 
1051 
// initialize grouped mantissa counts. these are set so that they are

1052 
// padded to the next whole group size when bits are counted in

1053 
// compute_mantissa_size_final

1054 
mant_cnt[0] = mant_cnt[3] = 0; 
1055 
mant_cnt[1] = mant_cnt[2] = 2; 
1056 
mant_cnt[4] = 1; 
1057 
for (ch = 0; ch < s>channels; ch++) { 
1058 
/* Currently the only bit allocation parameters which vary across

1059 
blocks within a frame are the exponent values. We can take

1060 
advantage of that by reusing the bit allocation pointers

1061 
whenever we reuse exponents. */

1062 
if (block>exp_strategy[ch] == EXP_REUSE) {

1063 
memcpy(block>bap[ch], s>blocks[blk1].bap[ch], AC3_MAX_COEFS);

1064 
} else {

1065 
ff_ac3_bit_alloc_calc_bap(block>mask[ch], block>psd[ch], 0,

1066 
s>nb_coefs[ch], snr_offset, 
1067 
s>bit_alloc.floor, ff_ac3_bap_tab, 
1068 
block>bap[ch]); 
1069 
} 
1070 
mantissa_bits += compute_mantissa_size(mant_cnt, block>bap[ch], s>nb_coefs[ch]); 
1071 
} 
1072 
mantissa_bits += compute_mantissa_size_final(mant_cnt); 
1073 
} 
1074 
return mantissa_bits;

1075 
} 
1076  
1077  
1078 
/**

1079 
* Constant bitrate bit allocation search.

1080 
* Find the largest SNR offset that will allow data to fit in the frame.

1081 
*/

1082 
static int cbr_bit_allocation(AC3EncodeContext *s) 
1083 
{ 
1084 
int ch;

1085 
int bits_left;

1086 
int snr_offset, snr_incr;

1087  
1088 
bits_left = 8 * s>frame_size  (s>frame_bits + s>exponent_bits);

1089  
1090 
snr_offset = s>coarse_snr_offset << 4;

1091  
1092 
while (snr_offset >= 0 && 
1093 
bit_alloc(s, snr_offset) > bits_left) { 
1094 
snr_offset = 64;

1095 
} 
1096 
if (snr_offset < 0) 
1097 
return AVERROR(EINVAL);

1098  
1099 
FFSWAP(uint8_t *, s>bap_buffer, s>bap1_buffer); 
1100 
for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) { 
1101 
while (snr_offset + 64 <= 1023 && 
1102 
bit_alloc(s, snr_offset + snr_incr) <= bits_left) { 
1103 
snr_offset += snr_incr; 
1104 
FFSWAP(uint8_t *, s>bap_buffer, s>bap1_buffer); 
1105 
} 
1106 
} 
1107 
FFSWAP(uint8_t *, s>bap_buffer, s>bap1_buffer); 
1108 
reset_block_bap(s); 
1109  
1110 
s>coarse_snr_offset = snr_offset >> 4;

1111 
for (ch = 0; ch < s>channels; ch++) 
1112 
s>fine_snr_offset[ch] = snr_offset & 0xF;

1113  
1114 
return 0; 
1115 
} 
1116  
1117  
1118 
/**

1119 
* Downgrade exponent strategies to reduce the bits used by the exponents.

1120 
* This is a fallback for when bit allocation fails with the normal exponent

1121 
* strategies. Each time this function is run it only downgrades the

1122 
* strategy in 1 channel of 1 block.

1123 
* @return nonzero if downgrade was unsuccessful

1124 
*/

1125 
static int downgrade_exponents(AC3EncodeContext *s) 
1126 
{ 
1127 
int ch, blk;

1128  
1129 
for (ch = 0; ch < s>fbw_channels; ch++) { 
1130 
for (blk = AC3_MAX_BLOCKS1; blk >= 0; blk) { 
1131 
if (s>blocks[blk].exp_strategy[ch] == EXP_D15) {

1132 
s>blocks[blk].exp_strategy[ch] = EXP_D25; 
1133 
return 0; 
1134 
} 
1135 
} 
1136 
} 
1137 
for (ch = 0; ch < s>fbw_channels; ch++) { 
1138 
for (blk = AC3_MAX_BLOCKS1; blk >= 0; blk) { 
1139 
if (s>blocks[blk].exp_strategy[ch] == EXP_D25) {

1140 
s>blocks[blk].exp_strategy[ch] = EXP_D45; 
1141 
return 0; 
1142 
} 
1143 
} 
1144 
} 
1145 
for (ch = 0; ch < s>fbw_channels; ch++) { 
1146 
/* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if

1147 
the block number > 0 */

1148 
for (blk = AC3_MAX_BLOCKS1; blk > 0; blk) { 
1149 
if (s>blocks[blk].exp_strategy[ch] > EXP_REUSE) {

1150 
s>blocks[blk].exp_strategy[ch] = EXP_REUSE; 
1151 
return 0; 
1152 
} 
1153 
} 
1154 
} 
1155 
return 1; 
1156 
} 
1157  
1158  
1159 
/**

1160 
* Reduce the bandwidth to reduce the number of bits used for a given SNR offset.

1161 
* This is a second fallback for when bit allocation still fails after exponents

1162 
* have been downgraded.

1163 
* @return nonzero if bandwidth reduction was unsuccessful

1164 
*/

1165 
static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code) 
1166 
{ 
1167 
int ch;

1168  
1169 
if (s>bandwidth_code[0] > min_bw_code) { 
1170 
for (ch = 0; ch < s>fbw_channels; ch++) { 
1171 
s>bandwidth_code[ch]; 
1172 
s>nb_coefs[ch] = s>bandwidth_code[ch] * 3 + 73; 
1173 
} 
1174 
return 0; 
1175 
} 
1176 
return 1; 
1177 
} 
1178  
1179  
1180 
/**

1181 
* Perform bit allocation search.

1182 
* Finds the SNR offset value that maximizes quality and fits in the specified

1183 
* frame size. Output is the SNR offset and a set of bit allocation pointers

1184 
* used to quantize the mantissas.

1185 
*/

1186 
static int compute_bit_allocation(AC3EncodeContext *s) 
1187 
{ 
1188 
int ret;

1189  
1190 
count_frame_bits(s); 
1191  
1192 
bit_alloc_masking(s); 
1193  
1194 
ret = cbr_bit_allocation(s); 
1195 
while (ret) {

1196 
/* fallback 1: downgrade exponents */

1197 
if (!downgrade_exponents(s)) {

1198 
extract_exponents(s); 
1199 
encode_exponents(s); 
1200 
group_exponents(s); 
1201 
ret = compute_bit_allocation(s); 
1202 
continue;

1203 
} 
1204  
1205 
/* fallback 2: reduce bandwidth */

1206 
/* only do this if the user has not specified a specific cutoff

1207 
frequency */

1208 
if (!s>cutoff && !reduce_bandwidth(s, 0)) { 
1209 
process_exponents(s); 
1210 
ret = compute_bit_allocation(s); 
1211 
continue;

1212 
} 
1213  
1214 
/* fallbacks were not enough... */

1215 
break;

1216 
} 
1217  
1218 
return ret;

1219 
} 
1220  
1221  
1222 
/**

1223 
* Symmetric quantization on 'levels' levels.

1224 
*/

1225 
static inline int sym_quant(int c, int e, int levels) 
1226 
{ 
1227 
int v;

1228  
1229 
if (c >= 0) { 
1230 
v = (levels * (c << e)) >> 24;

1231 
v = (v + 1) >> 1; 
1232 
v = (levels >> 1) + v;

1233 
} else {

1234 
v = (levels * ((c) << e)) >> 24;

1235 
v = (v + 1) >> 1; 
1236 
v = (levels >> 1)  v;

1237 
} 
1238 
assert(v >= 0 && v < levels);

1239 
return v;

1240 
} 
1241  
1242  
1243 
/**

1244 
* Asymmetric quantization on 2^qbits levels.

1245 
*/

1246 
static inline int asym_quant(int c, int e, int qbits) 
1247 
{ 
1248 
int lshift, m, v;

1249  
1250 
lshift = e + qbits  24;

1251 
if (lshift >= 0) 
1252 
v = c << lshift; 
1253 
else

1254 
v = c >> (lshift); 
1255 
/* rounding */

1256 
v = (v + 1) >> 1; 
1257 
m = (1 << (qbits1)); 
1258 
if (v >= m)

1259 
v = m  1;

1260 
assert(v >= m); 
1261 
return v & ((1 << qbits)1); 
1262 
} 
1263  
1264  
1265 
/**

1266 
* Quantize a set of mantissas for a single channel in a single block.

1267 
*/

1268 
static void quantize_mantissas_blk_ch(AC3EncodeContext *s, 
1269 
int32_t *mdct_coef, int8_t exp_shift, 
1270 
uint8_t *exp, uint8_t *bap, 
1271 
uint16_t *qmant, int n)

1272 
{ 
1273 
int i;

1274  
1275 
for (i = 0; i < n; i++) { 
1276 
int v;

1277 
int c = mdct_coef[i];

1278 
int e = exp[i]  exp_shift;

1279 
int b = bap[i];

1280 
switch (b) {

1281 
case 0: 
1282 
v = 0;

1283 
break;

1284 
case 1: 
1285 
v = sym_quant(c, e, 3);

1286 
switch (s>mant1_cnt) {

1287 
case 0: 
1288 
s>qmant1_ptr = &qmant[i]; 
1289 
v = 9 * v;

1290 
s>mant1_cnt = 1;

1291 
break;

1292 
case 1: 
1293 
*s>qmant1_ptr += 3 * v;

1294 
s>mant1_cnt = 2;

1295 
v = 128;

1296 
break;

1297 
default:

1298 
*s>qmant1_ptr += v; 
1299 
s>mant1_cnt = 0;

1300 
v = 128;

1301 
break;

1302 
} 
1303 
break;

1304 
case 2: 
1305 
v = sym_quant(c, e, 5);

1306 
switch (s>mant2_cnt) {

1307 
case 0: 
1308 
s>qmant2_ptr = &qmant[i]; 
1309 
v = 25 * v;

1310 
s>mant2_cnt = 1;

1311 
break;

1312 
case 1: 
1313 
*s>qmant2_ptr += 5 * v;

1314 
s>mant2_cnt = 2;

1315 
v = 128;

1316 
break;

1317 
default:

1318 
*s>qmant2_ptr += v; 
1319 
s>mant2_cnt = 0;

1320 
v = 128;

1321 
break;

1322 
} 
1323 
break;

1324 
case 3: 
1325 
v = sym_quant(c, e, 7);

1326 
break;

1327 
case 4: 
1328 
v = sym_quant(c, e, 11);

1329 
switch (s>mant4_cnt) {

1330 
case 0: 
1331 
s>qmant4_ptr = &qmant[i]; 
1332 
v = 11 * v;

1333 
s>mant4_cnt = 1;

1334 
break;

1335 
default:

1336 
*s>qmant4_ptr += v; 
1337 
s>mant4_cnt = 0;

1338 
v = 128;

1339 
break;

1340 
} 
1341 
break;

1342 
case 5: 
1343 
v = sym_quant(c, e, 15);

1344 
break;

1345 
case 14: 
1346 
v = asym_quant(c, e, 14);

1347 
break;

1348 
case 15: 
1349 
v = asym_quant(c, e, 16);

1350 
break;

1351 
default:

1352 
v = asym_quant(c, e, b  1);

1353 
break;

1354 
} 
1355 
qmant[i] = v; 
1356 
} 
1357 
} 
1358  
1359  
1360 
/**

1361 
* Quantize mantissas using coefficients, exponents, and bit allocation pointers.

1362 
*/

1363 
static void quantize_mantissas(AC3EncodeContext *s) 
1364 
{ 
1365 
int blk, ch;

1366  
1367  
1368 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
1369 
AC3Block *block = &s>blocks[blk]; 
1370 
s>mant1_cnt = s>mant2_cnt = s>mant4_cnt = 0;

1371 
s>qmant1_ptr = s>qmant2_ptr = s>qmant4_ptr = NULL;

1372  
1373 
for (ch = 0; ch < s>channels; ch++) { 
1374 
quantize_mantissas_blk_ch(s, block>mdct_coef[ch], block>exp_shift[ch], 
1375 
block>exp[ch], block>bap[ch], 
1376 
block>qmant[ch], s>nb_coefs[ch]); 
1377 
} 
1378 
} 
1379 
} 
1380  
1381  
1382 
/**

1383 
* Write the AC3 frame header to the output bitstream.

1384 
*/

1385 
static void output_frame_header(AC3EncodeContext *s) 
1386 
{ 
1387 
put_bits(&s>pb, 16, 0x0b77); /* frame header */ 
1388 
put_bits(&s>pb, 16, 0); /* crc1: will be filled later */ 
1389 
put_bits(&s>pb, 2, s>bit_alloc.sr_code);

1390 
put_bits(&s>pb, 6, s>frame_size_code + (s>frame_size  s>frame_size_min) / 2); 
1391 
put_bits(&s>pb, 5, s>bitstream_id);

1392 
put_bits(&s>pb, 3, s>bitstream_mode);

1393 
put_bits(&s>pb, 3, s>channel_mode);

1394 
if ((s>channel_mode & 0x01) && s>channel_mode != AC3_CHMODE_MONO) 
1395 
put_bits(&s>pb, 2, 1); /* XXX 4.5 dB */ 
1396 
if (s>channel_mode & 0x04) 
1397 
put_bits(&s>pb, 2, 1); /* XXX 6 dB */ 
1398 
if (s>channel_mode == AC3_CHMODE_STEREO)

1399 
put_bits(&s>pb, 2, 0); /* surround not indicated */ 
1400 
put_bits(&s>pb, 1, s>lfe_on); /* LFE */ 
1401 
put_bits(&s>pb, 5, 31); /* dialog norm: 31 db */ 
1402 
put_bits(&s>pb, 1, 0); /* no compression control word */ 
1403 
put_bits(&s>pb, 1, 0); /* no lang code */ 
1404 
put_bits(&s>pb, 1, 0); /* no audio production info */ 
1405 
put_bits(&s>pb, 1, 0); /* no copyright */ 
1406 
put_bits(&s>pb, 1, 1); /* original bitstream */ 
1407 
put_bits(&s>pb, 1, 0); /* no time code 1 */ 
1408 
put_bits(&s>pb, 1, 0); /* no time code 2 */ 
1409 
put_bits(&s>pb, 1, 0); /* no additional bit stream info */ 
1410 
} 
1411  
1412  
1413 
/**

1414 
* Write one audio block to the output bitstream.

1415 
*/

1416 
static void output_audio_block(AC3EncodeContext *s, 
1417 
int block_num)

1418 
{ 
1419 
int ch, i, baie, rbnd;

1420 
AC3Block *block = &s>blocks[block_num]; 
1421  
1422 
/* block switching */

1423 
for (ch = 0; ch < s>fbw_channels; ch++) 
1424 
put_bits(&s>pb, 1, 0); 
1425  
1426 
/* dither flags */

1427 
for (ch = 0; ch < s>fbw_channels; ch++) 
1428 
put_bits(&s>pb, 1, 1); 
1429  
1430 
/* dynamic range codes */

1431 
put_bits(&s>pb, 1, 0); 
1432  
1433 
/* channel coupling */

1434 
if (!block_num) {

1435 
put_bits(&s>pb, 1, 1); /* coupling strategy present */ 
1436 
put_bits(&s>pb, 1, 0); /* no coupling strategy */ 
1437 
} else {

1438 
put_bits(&s>pb, 1, 0); /* no new coupling strategy */ 
1439 
} 
1440  
1441 
/* stereo rematrixing */

1442 
if (s>channel_mode == AC3_CHMODE_STEREO) {

1443 
if (!block_num) {

1444 
/* first block must define rematrixing (rematstr) */

1445 
put_bits(&s>pb, 1, 1); 
1446  
1447 
/* dummy rematrixing rematflg(1:4)=0 */

1448 
for (rbnd = 0; rbnd < 4; rbnd++) 
1449 
put_bits(&s>pb, 1, 0); 
1450 
} else {

1451 
/* no matrixing (but should be used in the future) */

1452 
put_bits(&s>pb, 1, 0); 
1453 
} 
1454 
} 
1455  
1456 
/* exponent strategy */

1457 
for (ch = 0; ch < s>fbw_channels; ch++) 
1458 
put_bits(&s>pb, 2, block>exp_strategy[ch]);

1459 
if (s>lfe_on)

1460 
put_bits(&s>pb, 1, block>exp_strategy[s>lfe_channel]);

1461  
1462 
/* bandwidth */

1463 
for (ch = 0; ch < s>fbw_channels; ch++) { 
1464 
if (block>exp_strategy[ch] != EXP_REUSE)

1465 
put_bits(&s>pb, 6, s>bandwidth_code[ch]);

1466 
} 
1467  
1468 
/* exponents */

1469 
for (ch = 0; ch < s>channels; ch++) { 
1470 
int nb_groups;

1471  
1472 
if (block>exp_strategy[ch] == EXP_REUSE)

1473 
continue;

1474  
1475 
/* DC exponent */

1476 
put_bits(&s>pb, 4, block>grouped_exp[ch][0]); 
1477  
1478 
/* exponent groups */

1479 
nb_groups = exponent_group_tab[block>exp_strategy[ch]1][s>nb_coefs[ch]];

1480 
for (i = 1; i <= nb_groups; i++) 
1481 
put_bits(&s>pb, 7, block>grouped_exp[ch][i]);

1482  
1483 
/* gain range info */

1484 
if (ch != s>lfe_channel)

1485 
put_bits(&s>pb, 2, 0); 
1486 
} 
1487  
1488 
/* bit allocation info */

1489 
baie = (block_num == 0);

1490 
put_bits(&s>pb, 1, baie);

1491 
if (baie) {

1492 
put_bits(&s>pb, 2, s>slow_decay_code);

1493 
put_bits(&s>pb, 2, s>fast_decay_code);

1494 
put_bits(&s>pb, 2, s>slow_gain_code);

1495 
put_bits(&s>pb, 2, s>db_per_bit_code);

1496 
put_bits(&s>pb, 3, s>floor_code);

1497 
} 
1498  
1499 
/* snr offset */

1500 
put_bits(&s>pb, 1, baie);

1501 
if (baie) {

1502 
put_bits(&s>pb, 6, s>coarse_snr_offset);

1503 
for (ch = 0; ch < s>channels; ch++) { 
1504 
put_bits(&s>pb, 4, s>fine_snr_offset[ch]);

1505 
put_bits(&s>pb, 3, s>fast_gain_code[ch]);

1506 
} 
1507 
} 
1508  
1509 
put_bits(&s>pb, 1, 0); /* no delta bit allocation */ 
1510 
put_bits(&s>pb, 1, 0); /* no data to skip */ 
1511  
1512 
/* mantissas */

1513 
for (ch = 0; ch < s>channels; ch++) { 
1514 
int b, q;

1515 
for (i = 0; i < s>nb_coefs[ch]; i++) { 
1516 
q = block>qmant[ch][i]; 
1517 
b = block>bap[ch][i]; 
1518 
switch (b) {

1519 
case 0: break; 
1520 
case 1: if (q != 128) put_bits(&s>pb, 5, q); break; 
1521 
case 2: if (q != 128) put_bits(&s>pb, 7, q); break; 
1522 
case 3: put_bits(&s>pb, 3, q); break; 
1523 
case 4: if (q != 128) put_bits(&s>pb, 7, q); break; 
1524 
case 14: put_bits(&s>pb, 14, q); break; 
1525 
case 15: put_bits(&s>pb, 16, q); break; 
1526 
default: put_bits(&s>pb, b1, q); break; 
1527 
} 
1528 
} 
1529 
} 
1530 
} 
1531  
1532  
1533 
/** CRC16 Polynomial */

1534 
#define CRC16_POLY ((1 << 0)  (1 << 2)  (1 << 15)  (1 << 16)) 
1535  
1536  
1537 
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly) 
1538 
{ 
1539 
unsigned int c; 
1540  
1541 
c = 0;

1542 
while (a) {

1543 
if (a & 1) 
1544 
c ^= b; 
1545 
a = a >> 1;

1546 
b = b << 1;

1547 
if (b & (1 << 16)) 
1548 
b ^= poly; 
1549 
} 
1550 
return c;

1551 
} 
1552  
1553  
1554 
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly) 
1555 
{ 
1556 
unsigned int r; 
1557 
r = 1;

1558 
while (n) {

1559 
if (n & 1) 
1560 
r = mul_poly(r, a, poly); 
1561 
a = mul_poly(a, a, poly); 
1562 
n >>= 1;

1563 
} 
1564 
return r;

1565 
} 
1566  
1567  
1568 
/**

1569 
* Fill the end of the frame with 0's and compute the two CRCs.

1570 
*/

1571 
static void output_frame_end(AC3EncodeContext *s) 
1572 
{ 
1573 
const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);

1574 
int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;

1575 
uint8_t *frame; 
1576  
1577 
frame_size_58 = ((s>frame_size >> 2) + (s>frame_size >> 4)) << 1; 
1578  
1579 
/* pad the remainder of the frame with zeros */

1580 
flush_put_bits(&s>pb); 
1581 
frame = s>pb.buf; 
1582 
pad_bytes = s>frame_size  (put_bits_ptr(&s>pb)  frame)  2;

1583 
assert(pad_bytes >= 0);

1584 
if (pad_bytes > 0) 
1585 
memset(put_bits_ptr(&s>pb), 0, pad_bytes);

1586  
1587 
/* compute crc1 */

1588 
/* this is not so easy because it is at the beginning of the data... */

1589 
crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58  4)); 
1590 
crc_inv = s>crc_inv[s>frame_size > s>frame_size_min]; 
1591 
crc1 = mul_poly(crc_inv, crc1, CRC16_POLY); 
1592 
AV_WB16(frame + 2, crc1);

1593  
1594 
/* compute crc2 */

1595 
crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,

1596 
s>frame_size  frame_size_58  3);

1597 
crc2 = av_crc(crc_ctx, crc2_partial, frame + s>frame_size  3, 1); 
1598 
/* ensure crc2 does not match sync word by flipping crcrsv bit if needed */

1599 
if (crc2 == 0x770B) { 
1600 
frame[s>frame_size  3] ^= 0x1; 
1601 
crc2 = av_crc(crc_ctx, crc2_partial, frame + s>frame_size  3, 1); 
1602 
} 
1603 
crc2 = av_bswap16(crc2); 
1604 
AV_WB16(frame + s>frame_size  2, crc2);

1605 
} 
1606  
1607  
1608 
/**

1609 
* Write the frame to the output bitstream.

1610 
*/

1611 
static void output_frame(AC3EncodeContext *s, 
1612 
unsigned char *frame) 
1613 
{ 
1614 
int blk;

1615  
1616 
init_put_bits(&s>pb, frame, AC3_MAX_CODED_FRAME_SIZE); 
1617  
1618 
output_frame_header(s); 
1619  
1620 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) 
1621 
output_audio_block(s, blk); 
1622  
1623 
output_frame_end(s); 
1624 
} 
1625  
1626  
1627 
/**

1628 
* Encode a single AC3 frame.

1629 
*/

1630 
static int ac3_encode_frame(AVCodecContext *avctx, 
1631 
unsigned char *frame, int buf_size, void *data) 
1632 
{ 
1633 
AC3EncodeContext *s = avctx>priv_data; 
1634 
const int16_t *samples = data;

1635 
int ret;

1636  
1637 
if (s>bit_alloc.sr_code == 1) 
1638 
adjust_frame_size(s); 
1639  
1640 
deinterleave_input_samples(s, samples); 
1641  
1642 
apply_mdct(s); 
1643  
1644 
process_exponents(s); 
1645  
1646 
ret = compute_bit_allocation(s); 
1647 
if (ret) {

1648 
av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");

1649 
return ret;

1650 
} 
1651  
1652 
quantize_mantissas(s); 
1653  
1654 
output_frame(s, frame); 
1655  
1656 
return s>frame_size;

1657 
} 
1658  
1659  
1660 
/**

1661 
* Finalize encoding and free any memory allocated by the encoder.

1662 
*/

1663 
static av_cold int ac3_encode_close(AVCodecContext *avctx) 
1664 
{ 
1665 
int blk, ch;

1666 
AC3EncodeContext *s = avctx>priv_data; 
1667  
1668 
for (ch = 0; ch < s>channels; ch++) 
1669 
av_freep(&s>planar_samples[ch]); 
1670 
av_freep(&s>planar_samples); 
1671 
av_freep(&s>bap_buffer); 
1672 
av_freep(&s>bap1_buffer); 
1673 
av_freep(&s>mdct_coef_buffer); 
1674 
av_freep(&s>exp_buffer); 
1675 
av_freep(&s>grouped_exp_buffer); 
1676 
av_freep(&s>psd_buffer); 
1677 
av_freep(&s>band_psd_buffer); 
1678 
av_freep(&s>mask_buffer); 
1679 
av_freep(&s>qmant_buffer); 
1680 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
1681 
AC3Block *block = &s>blocks[blk]; 
1682 
av_freep(&block>bap); 
1683 
av_freep(&block>mdct_coef); 
1684 
av_freep(&block>exp); 
1685 
av_freep(&block>grouped_exp); 
1686 
av_freep(&block>psd); 
1687 
av_freep(&block>band_psd); 
1688 
av_freep(&block>mask); 
1689 
av_freep(&block>qmant); 
1690 
} 
1691  
1692 
mdct_end(&s>mdct); 
1693  
1694 
av_freep(&avctx>coded_frame); 
1695 
return 0; 
1696 
} 
1697  
1698  
1699 
/**

1700 
* Set channel information during initialization.

1701 
*/

1702 
static av_cold int set_channel_info(AC3EncodeContext *s, int channels, 
1703 
int64_t *channel_layout) 
1704 
{ 
1705 
int ch_layout;

1706  
1707 
if (channels < 1  channels > AC3_MAX_CHANNELS) 
1708 
return AVERROR(EINVAL);

1709 
if ((uint64_t)*channel_layout > 0x7FF) 
1710 
return AVERROR(EINVAL);

1711 
ch_layout = *channel_layout; 
1712 
if (!ch_layout)

1713 
ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);

1714 
if (av_get_channel_layout_nb_channels(ch_layout) != channels)

1715 
return AVERROR(EINVAL);

1716  
1717 
s>lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY); 
1718 
s>channels = channels; 
1719 
s>fbw_channels = channels  s>lfe_on; 
1720 
s>lfe_channel = s>lfe_on ? s>fbw_channels : 1;

1721 
if (s>lfe_on)

1722 
ch_layout = AV_CH_LOW_FREQUENCY; 
1723  
1724 
switch (ch_layout) {

1725 
case AV_CH_LAYOUT_MONO: s>channel_mode = AC3_CHMODE_MONO; break; 
1726 
case AV_CH_LAYOUT_STEREO: s>channel_mode = AC3_CHMODE_STEREO; break; 
1727 
case AV_CH_LAYOUT_SURROUND: s>channel_mode = AC3_CHMODE_3F; break; 
1728 
case AV_CH_LAYOUT_2_1: s>channel_mode = AC3_CHMODE_2F1R; break; 
1729 
case AV_CH_LAYOUT_4POINT0: s>channel_mode = AC3_CHMODE_3F1R; break; 
1730 
case AV_CH_LAYOUT_QUAD:

1731 
case AV_CH_LAYOUT_2_2: s>channel_mode = AC3_CHMODE_2F2R; break; 
1732 
case AV_CH_LAYOUT_5POINT0:

1733 
case AV_CH_LAYOUT_5POINT0_BACK: s>channel_mode = AC3_CHMODE_3F2R; break; 
1734 
default:

1735 
return AVERROR(EINVAL);

1736 
} 
1737  
1738 
s>channel_map = ff_ac3_enc_channel_map[s>channel_mode][s>lfe_on]; 
1739 
*channel_layout = ch_layout; 
1740 
if (s>lfe_on)

1741 
*channel_layout = AV_CH_LOW_FREQUENCY; 
1742  
1743 
return 0; 
1744 
} 
1745  
1746  
1747 
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s) 
1748 
{ 
1749 
int i, ret;

1750  
1751 
/* validate channel layout */

1752 
if (!avctx>channel_layout) {

1753 
av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "

1754 
"encoder will guess the layout, but it "

1755 
"might be incorrect.\n");

1756 
} 
1757 
ret = set_channel_info(s, avctx>channels, &avctx>channel_layout); 
1758 
if (ret) {

1759 
av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");

1760 
return ret;

1761 
} 
1762  
1763 
/* validate sample rate */

1764 
for (i = 0; i < 9; i++) { 
1765 
if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx>sample_rate) 
1766 
break;

1767 
} 
1768 
if (i == 9) { 
1769 
av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");

1770 
return AVERROR(EINVAL);

1771 
} 
1772 
s>sample_rate = avctx>sample_rate; 
1773 
s>bit_alloc.sr_shift = i % 3;

1774 
s>bit_alloc.sr_code = i / 3;

1775  
1776 
/* validate bit rate */

1777 
for (i = 0; i < 19; i++) { 
1778 
if ((ff_ac3_bitrate_tab[i] >> s>bit_alloc.sr_shift)*1000 == avctx>bit_rate) 
1779 
break;

1780 
} 
1781 
if (i == 19) { 
1782 
av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");

1783 
return AVERROR(EINVAL);

1784 
} 
1785 
s>bit_rate = avctx>bit_rate; 
1786 
s>frame_size_code = i << 1;

1787  
1788 
/* validate cutoff */

1789 
if (avctx>cutoff < 0) { 
1790 
av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");

1791 
return AVERROR(EINVAL);

1792 
} 
1793 
s>cutoff = avctx>cutoff; 
1794 
if (s>cutoff > (s>sample_rate >> 1)) 
1795 
s>cutoff = s>sample_rate >> 1;

1796  
1797 
return 0; 
1798 
} 
1799  
1800  
1801 
/**

1802 
* Set bandwidth for all channels.

1803 
* The user can optionally supply a cutoff frequency. Otherwise an appropriate

1804 
* default value will be used.

1805 
*/

1806 
static av_cold void set_bandwidth(AC3EncodeContext *s) 
1807 
{ 
1808 
int ch, bw_code;

1809  
1810 
if (s>cutoff) {

1811 
/* calculate bandwidth based on userspecified cutoff frequency */

1812 
int fbw_coeffs;

1813 
fbw_coeffs = s>cutoff * 2 * AC3_MAX_COEFS / s>sample_rate;

1814 
bw_code = av_clip((fbw_coeffs  73) / 3, 0, 60); 
1815 
} else {

1816 
/* use default bandwidth setting */

1817 
/* XXX: should compute the bandwidth according to the frame

1818 
size, so that we avoid annoying high frequency artifacts */

1819 
bw_code = 50;

1820 
} 
1821  
1822 
/* set number of coefficients for each channel */

1823 
for (ch = 0; ch < s>fbw_channels; ch++) { 
1824 
s>bandwidth_code[ch] = bw_code; 
1825 
s>nb_coefs[ch] = bw_code * 3 + 73; 
1826 
} 
1827 
if (s>lfe_on)

1828 
s>nb_coefs[s>lfe_channel] = 7; /* LFE channel always has 7 coefs */ 
1829 
} 
1830  
1831  
1832 
static av_cold int allocate_buffers(AVCodecContext *avctx) 
1833 
{ 
1834 
int blk, ch;

1835 
AC3EncodeContext *s = avctx>priv_data; 
1836  
1837 
FF_ALLOC_OR_GOTO(avctx, s>planar_samples, s>channels * sizeof(*s>planar_samples),

1838 
alloc_fail); 
1839 
for (ch = 0; ch < s>channels; ch++) { 
1840 
FF_ALLOCZ_OR_GOTO(avctx, s>planar_samples[ch], 
1841 
(AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s>planar_samples),

1842 
alloc_fail); 
1843 
} 
1844 
FF_ALLOC_OR_GOTO(avctx, s>bap_buffer, AC3_MAX_BLOCKS * s>channels * 
1845 
AC3_MAX_COEFS * sizeof(*s>bap_buffer), alloc_fail);

1846 
FF_ALLOC_OR_GOTO(avctx, s>bap1_buffer, AC3_MAX_BLOCKS * s>channels * 
1847 
AC3_MAX_COEFS * sizeof(*s>bap1_buffer), alloc_fail);

1848 
FF_ALLOC_OR_GOTO(avctx, s>mdct_coef_buffer, AC3_MAX_BLOCKS * s>channels * 
1849 
AC3_MAX_COEFS * sizeof(*s>mdct_coef_buffer), alloc_fail);

1850 
FF_ALLOC_OR_GOTO(avctx, s>exp_buffer, AC3_MAX_BLOCKS * s>channels * 
1851 
AC3_MAX_COEFS * sizeof(*s>exp_buffer), alloc_fail);

1852 
FF_ALLOC_OR_GOTO(avctx, s>grouped_exp_buffer, AC3_MAX_BLOCKS * s>channels * 
1853 
128 * sizeof(*s>grouped_exp_buffer), alloc_fail); 
1854 
FF_ALLOC_OR_GOTO(avctx, s>psd_buffer, AC3_MAX_BLOCKS * s>channels * 
1855 
AC3_MAX_COEFS * sizeof(*s>psd_buffer), alloc_fail);

1856 
FF_ALLOC_OR_GOTO(avctx, s>band_psd_buffer, AC3_MAX_BLOCKS * s>channels * 
1857 
64 * sizeof(*s>band_psd_buffer), alloc_fail); 
1858 
FF_ALLOC_OR_GOTO(avctx, s>mask_buffer, AC3_MAX_BLOCKS * s>channels * 
1859 
64 * sizeof(*s>mask_buffer), alloc_fail); 
1860 
FF_ALLOC_OR_GOTO(avctx, s>qmant_buffer, AC3_MAX_BLOCKS * s>channels * 
1861 
AC3_MAX_COEFS * sizeof(*s>qmant_buffer), alloc_fail);

1862 
for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) { 
1863 
AC3Block *block = &s>blocks[blk]; 
1864 
FF_ALLOC_OR_GOTO(avctx, block>bap, s>channels * sizeof(*block>bap),

1865 
alloc_fail); 
1866 
FF_ALLOCZ_OR_GOTO(avctx, block>mdct_coef, s>channels * sizeof(*block>mdct_coef),

1867 
alloc_fail); 
1868 
FF_ALLOCZ_OR_GOTO(avctx, block>exp, s>channels * sizeof(*block>exp),

1869 
alloc_fail); 
1870 
FF_ALLOCZ_OR_GOTO(avctx, block>grouped_exp, s>channels * sizeof(*block>grouped_exp),

1871 
alloc_fail); 
1872 
FF_ALLOCZ_OR_GOTO(avctx, block>psd, s>channels * sizeof(*block>psd),

1873 
alloc_fail); 
1874 
FF_ALLOCZ_OR_GOTO(avctx, block>band_psd, s>channels * sizeof(*block>band_psd),

1875 
alloc_fail); 
1876 
FF_ALLOCZ_OR_GOTO(avctx, block>mask, s>channels * sizeof(*block>mask),

1877 
alloc_fail); 
1878 
FF_ALLOCZ_OR_GOTO(avctx, block>qmant, s>channels * sizeof(*block>qmant),

1879 
alloc_fail); 
1880  
1881 
for (ch = 0; ch < s>channels; ch++) { 
1882 
block>bap[ch] = &s>bap_buffer [AC3_MAX_COEFS * (blk * s>channels + ch)]; 
1883 
block>mdct_coef[ch] = &s>mdct_coef_buffer [AC3_MAX_COEFS * (blk * s>channels + ch)]; 
1884 
block>exp[ch] = &s>exp_buffer [AC3_MAX_COEFS * (blk * s>channels + ch)]; 
1885 
block>grouped_exp[ch] = &s>grouped_exp_buffer[128 * (blk * s>channels + ch)];

1886 
block>psd[ch] = &s>psd_buffer [AC3_MAX_COEFS * (blk * s>channels + ch)]; 
1887 
block>band_psd[ch] = &s>band_psd_buffer [64 * (blk * s>channels + ch)];

1888 
block>mask[ch] = &s>mask_buffer [64 * (blk * s>channels + ch)];

1889 
block>qmant[ch] = &s>qmant_buffer [AC3_MAX_COEFS * (blk * s>channels + ch)]; 
1890 
} 
1891 
} 
1892  
1893 
return 0; 
1894 
alloc_fail:

1895 
return AVERROR(ENOMEM);

1896 
} 
1897  
1898  
1899 
/**

1900 
* Initialize the encoder.

1901 
*/

1902 
static av_cold int ac3_encode_init(AVCodecContext *avctx) 
1903 
{ 
1904 
AC3EncodeContext *s = avctx>priv_data; 
1905 
int ret, frame_size_58;

1906  
1907 
avctx>frame_size = AC3_FRAME_SIZE; 
1908  
1909 
ac3_common_init(); 
1910  
1911 
ret = validate_options(avctx, s); 
1912 
if (ret)

1913 
return ret;

1914  
1915 
s>bitstream_id = 8 + s>bit_alloc.sr_shift;

1916 
s>bitstream_mode = 0; /* complete main audio service */ 
1917  
1918 
s>frame_size_min = 2 * ff_ac3_frame_size_tab[s>frame_size_code][s>bit_alloc.sr_code];

1919 
s>bits_written = 0;

1920 
s>samples_written = 0;

1921 
s>frame_size = s>frame_size_min; 
1922  
1923 
/* calculate crc_inv for both possible frame sizes */

1924 
frame_size_58 = (( s>frame_size >> 2) + ( s>frame_size >> 4)) << 1; 
1925 
s>crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58)  16, CRC16_POLY); 
1926 
if (s>bit_alloc.sr_code == 1) { 
1927 
frame_size_58 = (((s>frame_size+2) >> 2) + ((s>frame_size+2) >> 4)) << 1; 
1928 
s>crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58)  16, CRC16_POLY); 
1929 
} 
1930  
1931 
set_bandwidth(s); 
1932  
1933 
exponent_init(s); 
1934  
1935 
bit_alloc_init(s); 
1936  
1937 
ret = mdct_init(avctx, &s>mdct, 9);

1938 
if (ret)

1939 
goto init_fail;

1940  
1941 
ret = allocate_buffers(avctx); 
1942 
if (ret)

1943 
goto init_fail;

1944  
1945 
avctx>coded_frame= avcodec_alloc_frame(); 
1946  
1947 
dsputil_init(&s>dsp, avctx); 
1948  
1949 
return 0; 
1950 
init_fail:

1951 
ac3_encode_close(avctx); 
1952 
return ret;

1953 
} 
1954  
1955  
1956 
#ifdef TEST

1957 
/*************************************************************************/

1958 
/* TEST */

1959  
1960 
#include "libavutil/lfg.h" 
1961  
1962 
#define MDCT_NBITS 9 
1963 
#define MDCT_SAMPLES (1 << MDCT_NBITS) 
1964 
#define FN (MDCT_SAMPLES/4) 
1965  
1966  
1967 
static void fft_test(AC3MDCTContext *mdct, AVLFG *lfg) 
1968 
{ 
1969 
IComplex in[FN], in1[FN]; 
1970 
int k, n, i;

1971 
float sum_re, sum_im, a;

1972  
1973 
for (i = 0; i < FN; i++) { 
1974 
in[i].re = av_lfg_get(lfg) % 65535  32767; 
1975 
in[i].im = av_lfg_get(lfg) % 65535  32767; 
1976 
in1[i] = in[i]; 
1977 
} 
1978 
fft(mdct, in, 7);

1979  
1980 
/* do it by hand */

1981 
for (k = 0; k < FN; k++) { 
1982 
sum_re = 0;

1983 
sum_im = 0;

1984 
for (n = 0; n < FN; n++) { 
1985 
a = 2 * M_PI * (n * k) / FN;

1986 
sum_re += in1[n].re * cos(a)  in1[n].im * sin(a); 
1987 
sum_im += in1[n].re * sin(a) + in1[n].im * cos(a); 
1988 
} 
1989 
av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n", 
1990 
k, in[k].re, in[k].im, sum_re / FN, sum_im / FN); 
1991 
} 
1992 
} 
1993  
1994  
1995 
static void mdct_test(AC3MDCTContext *mdct, AVLFG *lfg) 
1996 
{ 
1997 
int16_t input[MDCT_SAMPLES]; 
1998 
int32_t output[AC3_MAX_COEFS]; 
1999 
float input1[MDCT_SAMPLES];

2000 
float output1[AC3_MAX_COEFS];

2001 
float s, a, err, e, emax;

2002 
int i, k, n;

2003  
2004 
for (i = 0; i < MDCT_SAMPLES; i++) { 
2005 
input[i] = (av_lfg_get(lfg) % 65535  32767) * 9 / 10; 
2006 
input1[i] = input[i]; 
2007 
} 
2008  
2009 
mdct512(mdct, output, input); 
2010  
2011 
/* do it by hand */

2012 
for (k = 0; k < AC3_MAX_COEFS; k++) { 
2013 
s = 0;

2014 
for (n = 0; n < MDCT_SAMPLES; n++) { 
2015 
a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES)); 
2016 
s += input1[n] * cos(a); 
2017 
} 
2018 
output1[k] = 2 * s / MDCT_SAMPLES;

2019 
} 
2020  
2021 
err = 0;

2022 
emax = 0;

2023 
for (i = 0; i < AC3_MAX_COEFS; i++) { 
2024 
av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]); 
2025 
e = output[i]  output1[i]; 
2026 
if (e > emax)

2027 
emax = e; 
2028 
err += e * e; 
2029 
} 
2030 
av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax); 
2031 
} 
2032  
2033  
2034 
int main(void) 
2035 
{ 
2036 
AVLFG lfg; 
2037 
AC3MDCTContext mdct; 
2038  
2039 
mdct.avctx = NULL;

2040 
av_log_set_level(AV_LOG_DEBUG); 
2041 
mdct_init(&mdct, 9);

2042  
2043 
fft_test(&mdct, &lfg); 
2044 
mdct_test(&mdct, &lfg); 
2045  
2046 
return 0; 
2047 
} 
2048 
#endif /* TEST */ 
2049  
2050  
2051 
AVCodec ac3_encoder = { 
2052 
"ac3",

2053 
AVMEDIA_TYPE_AUDIO, 
2054 
CODEC_ID_AC3, 
2055 
sizeof(AC3EncodeContext),

2056 
ac3_encode_init, 
2057 
ac3_encode_frame, 
2058 
ac3_encode_close, 
2059 
NULL,

2060 
.sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE}, 
2061 
.long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC3)"),

2062 
.channel_layouts = (const int64_t[]){

2063 
AV_CH_LAYOUT_MONO, 
2064 
AV_CH_LAYOUT_STEREO, 
2065 
AV_CH_LAYOUT_2_1, 
2066 
AV_CH_LAYOUT_SURROUND, 
2067 
AV_CH_LAYOUT_2_2, 
2068 
AV_CH_LAYOUT_QUAD, 
2069 
AV_CH_LAYOUT_4POINT0, 
2070 
AV_CH_LAYOUT_5POINT0, 
2071 
AV_CH_LAYOUT_5POINT0_BACK, 
2072 
(AV_CH_LAYOUT_MONO  AV_CH_LOW_FREQUENCY), 
2073 
(AV_CH_LAYOUT_STEREO  AV_CH_LOW_FREQUENCY), 
2074 
(AV_CH_LAYOUT_2_1  AV_CH_LOW_FREQUENCY), 
2075 
(AV_CH_LAYOUT_SURROUND  AV_CH_LOW_FREQUENCY), 
2076 
(AV_CH_LAYOUT_2_2  AV_CH_LOW_FREQUENCY), 
2077 
(AV_CH_LAYOUT_QUAD  AV_CH_LOW_FREQUENCY), 
2078 
(AV_CH_LAYOUT_4POINT0  AV_CH_LOW_FREQUENCY), 
2079 
AV_CH_LAYOUT_5POINT1, 
2080 
AV_CH_LAYOUT_5POINT1_BACK, 
2081 
0 },

2082 
}; 