]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3enc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / ac3enc.c
1 /*
2  * The simplest AC-3 encoder
3  * Copyright (c) 2000 Fabrice Bellard
4  * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5  * Copyright (c) 2006-2010 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 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * The simplest AC-3 encoder.
27  */
28
29 //#define ASSERT_LEVEL 2
30
31 #include <stdint.h>
32
33 #include "libavutil/audioconvert.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/crc.h"
37 #include "libavutil/opt.h"
38 #include "avcodec.h"
39 #include "put_bits.h"
40 #include "dsputil.h"
41 #include "ac3dsp.h"
42 #include "ac3.h"
43 #include "audioconvert.h"
44 #include "fft.h"
45 #include "ac3enc.h"
46 #include "eac3enc.h"
47
48 typedef struct AC3Mant {
49     int16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
50     int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
51 } AC3Mant;
52
53 #define CMIXLEV_NUM_OPTIONS 3
54 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
55     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
56 };
57
58 #define SURMIXLEV_NUM_OPTIONS 3
59 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
60     LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
61 };
62
63 #define EXTMIXLEV_NUM_OPTIONS 8
64 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
65     LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
66     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
67 };
68
69
70 /**
71  * LUT for number of exponent groups.
72  * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
73  */
74 static uint8_t exponent_group_tab[2][3][256];
75
76
77 /**
78  * List of supported channel layouts.
79  */
80 const int64_t ff_ac3_channel_layouts[19] = {
81      AV_CH_LAYOUT_MONO,
82      AV_CH_LAYOUT_STEREO,
83      AV_CH_LAYOUT_2_1,
84      AV_CH_LAYOUT_SURROUND,
85      AV_CH_LAYOUT_2_2,
86      AV_CH_LAYOUT_QUAD,
87      AV_CH_LAYOUT_4POINT0,
88      AV_CH_LAYOUT_5POINT0,
89      AV_CH_LAYOUT_5POINT0_BACK,
90     (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
91     (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
92     (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
93     (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
94     (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
95     (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
96     (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
97      AV_CH_LAYOUT_5POINT1,
98      AV_CH_LAYOUT_5POINT1_BACK,
99      0
100 };
101
102
103 /**
104  * LUT to select the bandwidth code based on the bit rate, sample rate, and
105  * number of full-bandwidth channels.
106  * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
107  */
108 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
109 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
110
111     { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
112       {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
113       {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
114
115     { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
116       {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
117       {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
118
119     { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
120       {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
121       {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
122
123     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
124       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
125       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
126
127     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
128       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
129       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
130 };
131
132
133 /**
134  * LUT to select the coupling start band based on the bit rate, sample rate, and
135  * number of full-bandwidth channels. -1 = coupling off
136  * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
137  *
138  * TODO: more testing for optimal parameters.
139  *       multi-channel tests at 44.1kHz and 32kHz.
140  */
141 static const int8_t ac3_coupling_start_tab[6][3][19] = {
142 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
143
144     // 2/0
145     { {  0,  0,  0,  0,  0,  0,  0,  1,  1,  7,  8, 11, 12, -1, -1, -1, -1, -1, -1 },
146       {  0,  0,  0,  0,  0,  0,  1,  3,  5,  7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
147       {  0,  0,  0,  0,  1,  2,  2,  9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
148
149     // 3/0
150     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
151       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
152       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
153
154     // 2/1 - untested
155     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
156       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
157       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
158
159     // 3/1
160     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
161       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
162       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
163
164     // 2/2 - untested
165     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
166       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
167       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
168
169     // 3/2
170     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
171       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
172       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
173 };
174
175
176 /**
177  * Adjust the frame size to make the average bit rate match the target bit rate.
178  * This is only needed for 11025, 22050, and 44100 sample rates or any E-AC-3.
179  */
180 void ff_ac3_adjust_frame_size(AC3EncodeContext *s)
181 {
182     while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
183         s->bits_written    -= s->bit_rate;
184         s->samples_written -= s->sample_rate;
185     }
186     s->frame_size = s->frame_size_min +
187                     2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
188     s->bits_written    += s->frame_size * 8;
189     s->samples_written += AC3_BLOCK_SIZE * s->num_blocks;
190 }
191
192
193 void ff_ac3_compute_coupling_strategy(AC3EncodeContext *s)
194 {
195     int blk, ch;
196     int got_cpl_snr;
197     int num_cpl_blocks;
198
199     /* set coupling use flags for each block/channel */
200     /* TODO: turn coupling on/off and adjust start band based on bit usage */
201     for (blk = 0; blk < s->num_blocks; blk++) {
202         AC3Block *block = &s->blocks[blk];
203         for (ch = 1; ch <= s->fbw_channels; ch++)
204             block->channel_in_cpl[ch] = s->cpl_on;
205     }
206
207     /* enable coupling for each block if at least 2 channels have coupling
208        enabled for that block */
209     got_cpl_snr = 0;
210     num_cpl_blocks = 0;
211     for (blk = 0; blk < s->num_blocks; blk++) {
212         AC3Block *block = &s->blocks[blk];
213         block->num_cpl_channels = 0;
214         for (ch = 1; ch <= s->fbw_channels; ch++)
215             block->num_cpl_channels += block->channel_in_cpl[ch];
216         block->cpl_in_use = block->num_cpl_channels > 1;
217         num_cpl_blocks += block->cpl_in_use;
218         if (!block->cpl_in_use) {
219             block->num_cpl_channels = 0;
220             for (ch = 1; ch <= s->fbw_channels; ch++)
221                 block->channel_in_cpl[ch] = 0;
222         }
223
224         block->new_cpl_strategy = !blk;
225         if (blk) {
226             for (ch = 1; ch <= s->fbw_channels; ch++) {
227                 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
228                     block->new_cpl_strategy = 1;
229                     break;
230                 }
231             }
232         }
233         block->new_cpl_leak = block->new_cpl_strategy;
234
235         if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
236             block->new_snr_offsets = 1;
237             if (block->cpl_in_use)
238                 got_cpl_snr = 1;
239         } else {
240             block->new_snr_offsets = 0;
241         }
242     }
243     if (!num_cpl_blocks)
244         s->cpl_on = 0;
245
246     /* set bandwidth for each channel */
247     for (blk = 0; blk < s->num_blocks; blk++) {
248         AC3Block *block = &s->blocks[blk];
249         for (ch = 1; ch <= s->fbw_channels; ch++) {
250             if (block->channel_in_cpl[ch])
251                 block->end_freq[ch] = s->start_freq[CPL_CH];
252             else
253                 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
254         }
255     }
256 }
257
258
259 /**
260  * Apply stereo rematrixing to coefficients based on rematrixing flags.
261  */
262 void ff_ac3_apply_rematrixing(AC3EncodeContext *s)
263 {
264     int nb_coefs;
265     int blk, bnd, i;
266     int start, end;
267     uint8_t *flags;
268
269     if (!s->rematrixing_enabled)
270         return;
271
272     for (blk = 0; blk < s->num_blocks; blk++) {
273         AC3Block *block = &s->blocks[blk];
274         if (block->new_rematrixing_strategy)
275             flags = block->rematrixing_flags;
276         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
277         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
278             if (flags[bnd]) {
279                 start = ff_ac3_rematrix_band_tab[bnd];
280                 end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
281                 for (i = start; i < end; i++) {
282                     int32_t lt = block->fixed_coef[1][i];
283                     int32_t rt = block->fixed_coef[2][i];
284                     block->fixed_coef[1][i] = (lt + rt) >> 1;
285                     block->fixed_coef[2][i] = (lt - rt) >> 1;
286                 }
287             }
288         }
289     }
290 }
291
292
293 /**
294  * Initialize exponent tables.
295  */
296 static av_cold void exponent_init(AC3EncodeContext *s)
297 {
298     int expstr, i, grpsize;
299
300     for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
301         grpsize = 3 << expstr;
302         for (i = 12; i < 256; i++) {
303             exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
304             exponent_group_tab[1][expstr][i] = (i              ) / grpsize;
305         }
306     }
307     /* LFE */
308     exponent_group_tab[0][0][7] = 2;
309
310     if (CONFIG_EAC3_ENCODER && s->eac3)
311         ff_eac3_exponent_init();
312 }
313
314
315 /**
316  * Extract exponents from the MDCT coefficients.
317  */
318 static void extract_exponents(AC3EncodeContext *s)
319 {
320     int ch        = !s->cpl_on;
321     int chan_size = AC3_MAX_COEFS * s->num_blocks * (s->channels - ch + 1);
322     AC3Block *block = &s->blocks[0];
323
324     s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
325 }
326
327
328 /**
329  * Exponent Difference Threshold.
330  * New exponents are sent if their SAD exceed this number.
331  */
332 #define EXP_DIFF_THRESHOLD 500
333
334 /**
335  * Table used to select exponent strategy based on exponent reuse block interval.
336  */
337 static const uint8_t exp_strategy_reuse_tab[4][6] = {
338     { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
339     { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
340     { EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
341     { EXP_D45, EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15 }
342 };
343
344 /**
345  * Calculate exponent strategies for all channels.
346  * Array arrangement is reversed to simplify the per-channel calculation.
347  */
348 static void compute_exp_strategy(AC3EncodeContext *s)
349 {
350     int ch, blk, blk1;
351
352     for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
353         uint8_t *exp_strategy = s->exp_strategy[ch];
354         uint8_t *exp          = s->blocks[0].exp[ch];
355         int exp_diff;
356
357         /* estimate if the exponent variation & decide if they should be
358            reused in the next frame */
359         exp_strategy[0] = EXP_NEW;
360         exp += AC3_MAX_COEFS;
361         for (blk = 1; blk < s->num_blocks; blk++, exp += AC3_MAX_COEFS) {
362             if (ch == CPL_CH) {
363                 if (!s->blocks[blk-1].cpl_in_use) {
364                     exp_strategy[blk] = EXP_NEW;
365                     continue;
366                 } else if (!s->blocks[blk].cpl_in_use) {
367                     exp_strategy[blk] = EXP_REUSE;
368                     continue;
369                 }
370             } else if (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
371                 exp_strategy[blk] = EXP_NEW;
372                 continue;
373             }
374             exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
375             exp_strategy[blk] = EXP_REUSE;
376             if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
377                 exp_strategy[blk] = EXP_NEW;
378             else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
379                 exp_strategy[blk] = EXP_NEW;
380         }
381
382         /* now select the encoding strategy type : if exponents are often
383            recoded, we use a coarse encoding */
384         blk = 0;
385         while (blk < s->num_blocks) {
386             blk1 = blk + 1;
387             while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE)
388                 blk1++;
389             exp_strategy[blk] = exp_strategy_reuse_tab[s->num_blks_code][blk1-blk-1];
390             blk = blk1;
391         }
392     }
393     if (s->lfe_on) {
394         ch = s->lfe_channel;
395         s->exp_strategy[ch][0] = EXP_D15;
396         for (blk = 1; blk < s->num_blocks; blk++)
397             s->exp_strategy[ch][blk] = EXP_REUSE;
398     }
399
400     /* for E-AC-3, determine frame exponent strategy */
401     if (CONFIG_EAC3_ENCODER && s->eac3)
402         ff_eac3_get_frame_exp_strategy(s);
403 }
404
405
406 /**
407  * Update the exponents so that they are the ones the decoder will decode.
408  */
409 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
410                                     int cpl)
411 {
412     int nb_groups, i, k;
413
414     nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
415
416     /* for each group, compute the minimum exponent */
417     switch(exp_strategy) {
418     case EXP_D25:
419         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
420             uint8_t exp_min = exp[k];
421             if (exp[k+1] < exp_min)
422                 exp_min = exp[k+1];
423             exp[i-cpl] = exp_min;
424             k += 2;
425         }
426         break;
427     case EXP_D45:
428         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
429             uint8_t exp_min = exp[k];
430             if (exp[k+1] < exp_min)
431                 exp_min = exp[k+1];
432             if (exp[k+2] < exp_min)
433                 exp_min = exp[k+2];
434             if (exp[k+3] < exp_min)
435                 exp_min = exp[k+3];
436             exp[i-cpl] = exp_min;
437             k += 4;
438         }
439         break;
440     }
441
442     /* constraint for DC exponent */
443     if (!cpl && exp[0] > 15)
444         exp[0] = 15;
445
446     /* decrease the delta between each groups to within 2 so that they can be
447        differentially encoded */
448     for (i = 1; i <= nb_groups; i++)
449         exp[i] = FFMIN(exp[i], exp[i-1] + 2);
450     i--;
451     while (--i >= 0)
452         exp[i] = FFMIN(exp[i], exp[i+1] + 2);
453
454     if (cpl)
455         exp[-1] = exp[0] & ~1;
456
457     /* now we have the exponent values the decoder will see */
458     switch (exp_strategy) {
459     case EXP_D25:
460         for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
461             uint8_t exp1 = exp[i-cpl];
462             exp[k--] = exp1;
463             exp[k--] = exp1;
464         }
465         break;
466     case EXP_D45:
467         for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
468             exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
469             k -= 4;
470         }
471         break;
472     }
473 }
474
475
476 /**
477  * Encode exponents from original extracted form to what the decoder will see.
478  * This copies and groups exponents based on exponent strategy and reduces
479  * deltas between adjacent exponent groups so that they can be differentially
480  * encoded.
481  */
482 static void encode_exponents(AC3EncodeContext *s)
483 {
484     int blk, blk1, ch, cpl;
485     uint8_t *exp, *exp_strategy;
486     int nb_coefs, num_reuse_blocks;
487
488     for (ch = !s->cpl_on; ch <= s->channels; ch++) {
489         exp          = s->blocks[0].exp[ch] + s->start_freq[ch];
490         exp_strategy = s->exp_strategy[ch];
491
492         cpl = (ch == CPL_CH);
493         blk = 0;
494         while (blk < s->num_blocks) {
495             AC3Block *block = &s->blocks[blk];
496             if (cpl && !block->cpl_in_use) {
497                 exp += AC3_MAX_COEFS;
498                 blk++;
499                 continue;
500             }
501             nb_coefs = block->end_freq[ch] - s->start_freq[ch];
502             blk1 = blk + 1;
503
504             /* count the number of EXP_REUSE blocks after the current block
505                and set exponent reference block numbers */
506             s->exp_ref_block[ch][blk] = blk;
507             while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE) {
508                 s->exp_ref_block[ch][blk1] = blk;
509                 blk1++;
510             }
511             num_reuse_blocks = blk1 - blk - 1;
512
513             /* for the EXP_REUSE case we select the min of the exponents */
514             s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
515                                        AC3_MAX_COEFS);
516
517             encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
518
519             exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
520             blk = blk1;
521         }
522     }
523
524     /* reference block numbers have been changed, so reset ref_bap_set */
525     s->ref_bap_set = 0;
526 }
527
528
529 /**
530  * Count exponent bits based on bandwidth, coupling, and exponent strategies.
531  */
532 static int count_exponent_bits(AC3EncodeContext *s)
533 {
534     int blk, ch;
535     int nb_groups, bit_count;
536
537     bit_count = 0;
538     for (blk = 0; blk < s->num_blocks; blk++) {
539         AC3Block *block = &s->blocks[blk];
540         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
541             int exp_strategy = s->exp_strategy[ch][blk];
542             int cpl          = (ch == CPL_CH);
543             int nb_coefs     = block->end_freq[ch] - s->start_freq[ch];
544
545             if (exp_strategy == EXP_REUSE)
546                 continue;
547
548             nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_coefs];
549             bit_count += 4 + (nb_groups * 7);
550         }
551     }
552
553     return bit_count;
554 }
555
556
557 /**
558  * Group exponents.
559  * 3 delta-encoded exponents are in each 7-bit group. The number of groups
560  * varies depending on exponent strategy and bandwidth.
561  */
562 void ff_ac3_group_exponents(AC3EncodeContext *s)
563 {
564     int blk, ch, i, cpl;
565     int group_size, nb_groups;
566     uint8_t *p;
567     int delta0, delta1, delta2;
568     int exp0, exp1;
569
570     for (blk = 0; blk < s->num_blocks; blk++) {
571         AC3Block *block = &s->blocks[blk];
572         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
573             int exp_strategy = s->exp_strategy[ch][blk];
574             if (exp_strategy == EXP_REUSE)
575                 continue;
576             cpl = (ch == CPL_CH);
577             group_size = exp_strategy + (exp_strategy == EXP_D45);
578             nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
579             p = block->exp[ch] + s->start_freq[ch] - cpl;
580
581             /* DC exponent */
582             exp1 = *p++;
583             block->grouped_exp[ch][0] = exp1;
584
585             /* remaining exponents are delta encoded */
586             for (i = 1; i <= nb_groups; i++) {
587                 /* merge three delta in one code */
588                 exp0   = exp1;
589                 exp1   = p[0];
590                 p     += group_size;
591                 delta0 = exp1 - exp0 + 2;
592                 av_assert2(delta0 >= 0 && delta0 <= 4);
593
594                 exp0   = exp1;
595                 exp1   = p[0];
596                 p     += group_size;
597                 delta1 = exp1 - exp0 + 2;
598                 av_assert2(delta1 >= 0 && delta1 <= 4);
599
600                 exp0   = exp1;
601                 exp1   = p[0];
602                 p     += group_size;
603                 delta2 = exp1 - exp0 + 2;
604                 av_assert2(delta2 >= 0 && delta2 <= 4);
605
606                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
607             }
608         }
609     }
610 }
611
612
613 /**
614  * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
615  * Extract exponents from MDCT coefficients, calculate exponent strategies,
616  * and encode final exponents.
617  */
618 void ff_ac3_process_exponents(AC3EncodeContext *s)
619 {
620     extract_exponents(s);
621
622     compute_exp_strategy(s);
623
624     encode_exponents(s);
625
626     emms_c();
627 }
628
629
630 /**
631  * Count frame bits that are based solely on fixed parameters.
632  * This only has to be run once when the encoder is initialized.
633  */
634 static void count_frame_bits_fixed(AC3EncodeContext *s)
635 {
636     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
637     int blk;
638     int frame_bits;
639
640     /* assumptions:
641      *   no dynamic range codes
642      *   bit allocation parameters do not change between blocks
643      *   no delta bit allocation
644      *   no skipped data
645      *   no auxilliary data
646      *   no E-AC-3 metadata
647      */
648
649     /* header */
650     frame_bits = 16; /* sync info */
651     if (s->eac3) {
652         /* bitstream info header */
653         frame_bits += 35;
654         frame_bits += 1 + 1;
655         if (s->num_blocks != 0x6)
656             frame_bits++;
657         frame_bits++;
658         /* audio frame header */
659         if (s->num_blocks == 6)
660             frame_bits += 2;
661         frame_bits += 10;
662         /* exponent strategy */
663         if (s->use_frame_exp_strategy)
664             frame_bits += 5 * s->fbw_channels;
665         else
666             frame_bits += s->num_blocks * 2 * s->fbw_channels;
667         if (s->lfe_on)
668             frame_bits += s->num_blocks;
669         /* converter exponent strategy */
670         if (s->num_blks_code != 0x3)
671             frame_bits++;
672         else
673             frame_bits += s->fbw_channels * 5;
674         /* snr offsets */
675         frame_bits += 10;
676         /* block start info */
677         if (s->num_blocks != 1)
678             frame_bits++;
679     } else {
680         frame_bits += 49;
681         frame_bits += frame_bits_inc[s->channel_mode];
682     }
683
684     /* audio blocks */
685     for (blk = 0; blk < s->num_blocks; blk++) {
686         if (!s->eac3) {
687             /* block switch flags */
688             frame_bits += s->fbw_channels;
689
690             /* dither flags */
691             frame_bits += s->fbw_channels;
692         }
693
694         /* dynamic range */
695         frame_bits++;
696
697         /* spectral extension */
698         if (s->eac3)
699             frame_bits++;
700
701         if (!s->eac3) {
702             /* exponent strategy */
703             frame_bits += 2 * s->fbw_channels;
704             if (s->lfe_on)
705                 frame_bits++;
706
707             /* bit allocation params */
708             frame_bits++;
709             if (!blk)
710                 frame_bits += 2 + 2 + 2 + 2 + 3;
711         }
712
713         /* converter snr offset */
714         if (s->eac3)
715             frame_bits++;
716
717         if (!s->eac3) {
718             /* delta bit allocation */
719             frame_bits++;
720
721             /* skipped data */
722             frame_bits++;
723         }
724     }
725
726     /* auxiliary data */
727     frame_bits++;
728
729     /* CRC */
730     frame_bits += 1 + 16;
731
732     s->frame_bits_fixed = frame_bits;
733 }
734
735
736 /**
737  * Initialize bit allocation.
738  * Set default parameter codes and calculate parameter values.
739  */
740 static void bit_alloc_init(AC3EncodeContext *s)
741 {
742     int ch;
743
744     /* init default parameters */
745     s->slow_decay_code = 2;
746     s->fast_decay_code = 1;
747     s->slow_gain_code  = 1;
748     s->db_per_bit_code = s->eac3 ? 2 : 3;
749     s->floor_code      = 7;
750     for (ch = 0; ch <= s->channels; ch++)
751         s->fast_gain_code[ch] = 4;
752
753     /* initial snr offset */
754     s->coarse_snr_offset = 40;
755
756     /* compute real values */
757     /* currently none of these values change during encoding, so we can just
758        set them once at initialization */
759     s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
760     s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
761     s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
762     s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
763     s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
764     s->bit_alloc.cpl_fast_leak = 0;
765     s->bit_alloc.cpl_slow_leak = 0;
766
767     count_frame_bits_fixed(s);
768 }
769
770
771 /**
772  * Count the bits used to encode the frame, minus exponents and mantissas.
773  * Bits based on fixed parameters have already been counted, so now we just
774  * have to add the bits based on parameters that change during encoding.
775  */
776 static void count_frame_bits(AC3EncodeContext *s)
777 {
778     AC3EncOptions *opt = &s->options;
779     int blk, ch;
780     int frame_bits = 0;
781
782     /* header */
783     if (s->eac3) {
784         if (opt->eac3_mixing_metadata) {
785             if (s->channel_mode > AC3_CHMODE_STEREO)
786                 frame_bits += 2;
787             if (s->has_center)
788                 frame_bits += 6;
789             if (s->has_surround)
790                 frame_bits += 6;
791             frame_bits += s->lfe_on;
792             frame_bits += 1 + 1 + 2;
793             if (s->channel_mode < AC3_CHMODE_STEREO)
794                 frame_bits++;
795             frame_bits++;
796         }
797         if (opt->eac3_info_metadata) {
798             frame_bits += 3 + 1 + 1;
799             if (s->channel_mode == AC3_CHMODE_STEREO)
800                 frame_bits += 2 + 2;
801             if (s->channel_mode >= AC3_CHMODE_2F2R)
802                 frame_bits += 2;
803             frame_bits++;
804             if (opt->audio_production_info)
805                 frame_bits += 5 + 2 + 1;
806             frame_bits++;
807         }
808         /* coupling */
809         if (s->channel_mode > AC3_CHMODE_MONO) {
810             frame_bits++;
811             for (blk = 1; blk < s->num_blocks; blk++) {
812                 AC3Block *block = &s->blocks[blk];
813                 frame_bits++;
814                 if (block->new_cpl_strategy)
815                     frame_bits++;
816             }
817         }
818         /* coupling exponent strategy */
819         if (s->cpl_on) {
820             if (s->use_frame_exp_strategy) {
821                 frame_bits += 5 * s->cpl_on;
822             } else {
823                 for (blk = 0; blk < s->num_blocks; blk++)
824                     frame_bits += 2 * s->blocks[blk].cpl_in_use;
825             }
826         }
827     } else {
828         if (opt->audio_production_info)
829             frame_bits += 7;
830         if (s->bitstream_id == 6) {
831             if (opt->extended_bsi_1)
832                 frame_bits += 14;
833             if (opt->extended_bsi_2)
834                 frame_bits += 14;
835         }
836     }
837
838     /* audio blocks */
839     for (blk = 0; blk < s->num_blocks; blk++) {
840         AC3Block *block = &s->blocks[blk];
841
842         /* coupling strategy */
843         if (!s->eac3)
844             frame_bits++;
845         if (block->new_cpl_strategy) {
846             if (!s->eac3)
847                 frame_bits++;
848             if (block->cpl_in_use) {
849                 if (s->eac3)
850                     frame_bits++;
851                 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
852                     frame_bits += s->fbw_channels;
853                 if (s->channel_mode == AC3_CHMODE_STEREO)
854                     frame_bits++;
855                 frame_bits += 4 + 4;
856                 if (s->eac3)
857                     frame_bits++;
858                 else
859                     frame_bits += s->num_cpl_subbands - 1;
860             }
861         }
862
863         /* coupling coordinates */
864         if (block->cpl_in_use) {
865             for (ch = 1; ch <= s->fbw_channels; ch++) {
866                 if (block->channel_in_cpl[ch]) {
867                     if (!s->eac3 || block->new_cpl_coords[ch] != 2)
868                         frame_bits++;
869                     if (block->new_cpl_coords[ch]) {
870                         frame_bits += 2;
871                         frame_bits += (4 + 4) * s->num_cpl_bands;
872                     }
873                 }
874             }
875         }
876
877         /* stereo rematrixing */
878         if (s->channel_mode == AC3_CHMODE_STEREO) {
879             if (!s->eac3 || blk > 0)
880                 frame_bits++;
881             if (s->blocks[blk].new_rematrixing_strategy)
882                 frame_bits += block->num_rematrixing_bands;
883         }
884
885         /* bandwidth codes & gain range */
886         for (ch = 1; ch <= s->fbw_channels; ch++) {
887             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
888                 if (!block->channel_in_cpl[ch])
889                     frame_bits += 6;
890                 frame_bits += 2;
891             }
892         }
893
894         /* coupling exponent strategy */
895         if (!s->eac3 && block->cpl_in_use)
896             frame_bits += 2;
897
898         /* snr offsets and fast gain codes */
899         if (!s->eac3) {
900             frame_bits++;
901             if (block->new_snr_offsets)
902                 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
903         }
904
905         /* coupling leak info */
906         if (block->cpl_in_use) {
907             if (!s->eac3 || block->new_cpl_leak != 2)
908                 frame_bits++;
909             if (block->new_cpl_leak)
910                 frame_bits += 3 + 3;
911         }
912     }
913
914     s->frame_bits = s->frame_bits_fixed + frame_bits;
915 }
916
917
918 /**
919  * Calculate masking curve based on the final exponents.
920  * Also calculate the power spectral densities to use in future calculations.
921  */
922 static void bit_alloc_masking(AC3EncodeContext *s)
923 {
924     int blk, ch;
925
926     for (blk = 0; blk < s->num_blocks; blk++) {
927         AC3Block *block = &s->blocks[blk];
928         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
929             /* We only need psd and mask for calculating bap.
930                Since we currently do not calculate bap when exponent
931                strategy is EXP_REUSE we do not need to calculate psd or mask. */
932             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
933                 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
934                                           block->end_freq[ch], block->psd[ch],
935                                           block->band_psd[ch]);
936                 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
937                                            s->start_freq[ch], block->end_freq[ch],
938                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
939                                            ch == s->lfe_channel,
940                                            DBA_NONE, 0, NULL, NULL, NULL,
941                                            block->mask[ch]);
942             }
943         }
944     }
945 }
946
947
948 /**
949  * Ensure that bap for each block and channel point to the current bap_buffer.
950  * They may have been switched during the bit allocation search.
951  */
952 static void reset_block_bap(AC3EncodeContext *s)
953 {
954     int blk, ch;
955     uint8_t *ref_bap;
956
957     if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
958         return;
959
960     ref_bap = s->bap_buffer;
961     for (ch = 0; ch <= s->channels; ch++) {
962         for (blk = 0; blk < s->num_blocks; blk++)
963             s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
964         ref_bap += AC3_MAX_COEFS * s->num_blocks;
965     }
966     s->ref_bap_set = 1;
967 }
968
969
970 /**
971  * Initialize mantissa counts.
972  * These are set so that they are padded to the next whole group size when bits
973  * are counted in compute_mantissa_size.
974  */
975 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
976 {
977     int blk;
978
979     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
980         memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
981         mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
982         mant_cnt[blk][4] = 1;
983     }
984 }
985
986
987 /**
988  * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
989  * range.
990  */
991 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
992                                           uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
993                                           int start, int end)
994 {
995     int blk;
996
997     for (blk = 0; blk < s->num_blocks; blk++) {
998         AC3Block *block = &s->blocks[blk];
999         if (ch == CPL_CH && !block->cpl_in_use)
1000             continue;
1001         s->ac3dsp.update_bap_counts(mant_cnt[blk],
1002                                     s->ref_bap[ch][blk] + start,
1003                                     FFMIN(end, block->end_freq[ch]) - start);
1004     }
1005 }
1006
1007
1008 /**
1009  * Count the number of mantissa bits in the frame based on the bap values.
1010  */
1011 static int count_mantissa_bits(AC3EncodeContext *s)
1012 {
1013     int ch, max_end_freq;
1014     LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
1015
1016     count_mantissa_bits_init(mant_cnt);
1017
1018     max_end_freq = s->bandwidth_code * 3 + 73;
1019     for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
1020         count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
1021                                       max_end_freq);
1022
1023     return s->ac3dsp.compute_mantissa_size(mant_cnt);
1024 }
1025
1026
1027 /**
1028  * Run the bit allocation with a given SNR offset.
1029  * This calculates the bit allocation pointers that will be used to determine
1030  * the quantization of each mantissa.
1031  * @return the number of bits needed for mantissas if the given SNR offset is
1032  *         is used.
1033  */
1034 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1035 {
1036     int blk, ch;
1037
1038     snr_offset = (snr_offset - 240) << 2;
1039
1040     reset_block_bap(s);
1041     for (blk = 0; blk < s->num_blocks; blk++) {
1042         AC3Block *block = &s->blocks[blk];
1043
1044         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1045             /* Currently the only bit allocation parameters which vary across
1046                blocks within a frame are the exponent values.  We can take
1047                advantage of that by reusing the bit allocation pointers
1048                whenever we reuse exponents. */
1049             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1050                 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
1051                                              s->start_freq[ch], block->end_freq[ch],
1052                                              snr_offset, s->bit_alloc.floor,
1053                                              ff_ac3_bap_tab, s->ref_bap[ch][blk]);
1054             }
1055         }
1056     }
1057     return count_mantissa_bits(s);
1058 }
1059
1060
1061 /**
1062  * Constant bitrate bit allocation search.
1063  * Find the largest SNR offset that will allow data to fit in the frame.
1064  */
1065 static int cbr_bit_allocation(AC3EncodeContext *s)
1066 {
1067     int ch;
1068     int bits_left;
1069     int snr_offset, snr_incr;
1070
1071     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1072     if (bits_left < 0)
1073         return AVERROR(EINVAL);
1074
1075     snr_offset = s->coarse_snr_offset << 4;
1076
1077     /* if previous frame SNR offset was 1023, check if current frame can also
1078        use SNR offset of 1023. if so, skip the search. */
1079     if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1080         if (bit_alloc(s, 1023) <= bits_left)
1081             return 0;
1082     }
1083
1084     while (snr_offset >= 0 &&
1085            bit_alloc(s, snr_offset) > bits_left) {
1086         snr_offset -= 64;
1087     }
1088     if (snr_offset < 0)
1089         return AVERROR(EINVAL);
1090
1091     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1092     for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1093         while (snr_offset + snr_incr <= 1023 &&
1094                bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1095             snr_offset += snr_incr;
1096             FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1097         }
1098     }
1099     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1100     reset_block_bap(s);
1101
1102     s->coarse_snr_offset = snr_offset >> 4;
1103     for (ch = !s->cpl_on; ch <= s->channels; ch++)
1104         s->fine_snr_offset[ch] = snr_offset & 0xF;
1105
1106     return 0;
1107 }
1108
1109
1110 /**
1111  * Perform bit allocation search.
1112  * Finds the SNR offset value that maximizes quality and fits in the specified
1113  * frame size.  Output is the SNR offset and a set of bit allocation pointers
1114  * used to quantize the mantissas.
1115  */
1116 int ff_ac3_compute_bit_allocation(AC3EncodeContext *s)
1117 {
1118     count_frame_bits(s);
1119
1120     s->exponent_bits = count_exponent_bits(s);
1121
1122     bit_alloc_masking(s);
1123
1124     return cbr_bit_allocation(s);
1125 }
1126
1127
1128 /**
1129  * Symmetric quantization on 'levels' levels.
1130  */
1131 static inline int sym_quant(int c, int e, int levels)
1132 {
1133     int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1134     av_assert2(v >= 0 && v < levels);
1135     return v;
1136 }
1137
1138
1139 /**
1140  * Asymmetric quantization on 2^qbits levels.
1141  */
1142 static inline int asym_quant(int c, int e, int qbits)
1143 {
1144     int m;
1145
1146     c = (((c << e) >> (24 - qbits)) + 1) >> 1;
1147     m = (1 << (qbits-1));
1148     if (c >= m)
1149         c = m - 1;
1150     av_assert2(c >= -m);
1151     return c;
1152 }
1153
1154
1155 /**
1156  * Quantize a set of mantissas for a single channel in a single block.
1157  */
1158 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1159                                       uint8_t *exp, uint8_t *bap,
1160                                       int16_t *qmant, int start_freq,
1161                                       int end_freq)
1162 {
1163     int i;
1164
1165     for (i = start_freq; i < end_freq; i++) {
1166         int v;
1167         int c = fixed_coef[i];
1168         int e = exp[i];
1169         int b = bap[i];
1170         switch (b) {
1171         case 0:
1172             v = 0;
1173             break;
1174         case 1:
1175             v = sym_quant(c, e, 3);
1176             switch (s->mant1_cnt) {
1177             case 0:
1178                 s->qmant1_ptr = &qmant[i];
1179                 v = 9 * v;
1180                 s->mant1_cnt = 1;
1181                 break;
1182             case 1:
1183                 *s->qmant1_ptr += 3 * v;
1184                 s->mant1_cnt = 2;
1185                 v = 128;
1186                 break;
1187             default:
1188                 *s->qmant1_ptr += v;
1189                 s->mant1_cnt = 0;
1190                 v = 128;
1191                 break;
1192             }
1193             break;
1194         case 2:
1195             v = sym_quant(c, e, 5);
1196             switch (s->mant2_cnt) {
1197             case 0:
1198                 s->qmant2_ptr = &qmant[i];
1199                 v = 25 * v;
1200                 s->mant2_cnt = 1;
1201                 break;
1202             case 1:
1203                 *s->qmant2_ptr += 5 * v;
1204                 s->mant2_cnt = 2;
1205                 v = 128;
1206                 break;
1207             default:
1208                 *s->qmant2_ptr += v;
1209                 s->mant2_cnt = 0;
1210                 v = 128;
1211                 break;
1212             }
1213             break;
1214         case 3:
1215             v = sym_quant(c, e, 7);
1216             break;
1217         case 4:
1218             v = sym_quant(c, e, 11);
1219             switch (s->mant4_cnt) {
1220             case 0:
1221                 s->qmant4_ptr = &qmant[i];
1222                 v = 11 * v;
1223                 s->mant4_cnt = 1;
1224                 break;
1225             default:
1226                 *s->qmant4_ptr += v;
1227                 s->mant4_cnt = 0;
1228                 v = 128;
1229                 break;
1230             }
1231             break;
1232         case 5:
1233             v = sym_quant(c, e, 15);
1234             break;
1235         case 14:
1236             v = asym_quant(c, e, 14);
1237             break;
1238         case 15:
1239             v = asym_quant(c, e, 16);
1240             break;
1241         default:
1242             v = asym_quant(c, e, b - 1);
1243             break;
1244         }
1245         qmant[i] = v;
1246     }
1247 }
1248
1249
1250 /**
1251  * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1252  */
1253 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1254 {
1255     int blk, ch, ch0=0, got_cpl;
1256
1257     for (blk = 0; blk < s->num_blocks; blk++) {
1258         AC3Block *block = &s->blocks[blk];
1259         AC3Mant m = { 0 };
1260
1261         got_cpl = !block->cpl_in_use;
1262         for (ch = 1; ch <= s->channels; ch++) {
1263             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1264                 ch0     = ch - 1;
1265                 ch      = CPL_CH;
1266                 got_cpl = 1;
1267             }
1268             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1269                                       s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1270                                       s->ref_bap[ch][blk], block->qmant[ch],
1271                                       s->start_freq[ch], block->end_freq[ch]);
1272             if (ch == CPL_CH)
1273                 ch = ch0;
1274         }
1275     }
1276 }
1277
1278
1279 /**
1280  * Write the AC-3 frame header to the output bitstream.
1281  */
1282 static void ac3_output_frame_header(AC3EncodeContext *s)
1283 {
1284     AC3EncOptions *opt = &s->options;
1285
1286     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1287     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1288     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1289     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1290     put_bits(&s->pb, 5,  s->bitstream_id);
1291     put_bits(&s->pb, 3,  s->bitstream_mode);
1292     put_bits(&s->pb, 3,  s->channel_mode);
1293     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1294         put_bits(&s->pb, 2, s->center_mix_level);
1295     if (s->channel_mode & 0x04)
1296         put_bits(&s->pb, 2, s->surround_mix_level);
1297     if (s->channel_mode == AC3_CHMODE_STEREO)
1298         put_bits(&s->pb, 2, opt->dolby_surround_mode);
1299     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1300     put_bits(&s->pb, 5, -opt->dialogue_level);
1301     put_bits(&s->pb, 1, 0);         /* no compression control word */
1302     put_bits(&s->pb, 1, 0);         /* no lang code */
1303     put_bits(&s->pb, 1, opt->audio_production_info);
1304     if (opt->audio_production_info) {
1305         put_bits(&s->pb, 5, opt->mixing_level - 80);
1306         put_bits(&s->pb, 2, opt->room_type);
1307     }
1308     put_bits(&s->pb, 1, opt->copyright);
1309     put_bits(&s->pb, 1, opt->original);
1310     if (s->bitstream_id == 6) {
1311         /* alternate bit stream syntax */
1312         put_bits(&s->pb, 1, opt->extended_bsi_1);
1313         if (opt->extended_bsi_1) {
1314             put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1315             put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1316             put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1317             put_bits(&s->pb, 3, s->loro_center_mix_level);
1318             put_bits(&s->pb, 3, s->loro_surround_mix_level);
1319         }
1320         put_bits(&s->pb, 1, opt->extended_bsi_2);
1321         if (opt->extended_bsi_2) {
1322             put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1323             put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1324             put_bits(&s->pb, 1, opt->ad_converter_type);
1325             put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1326         }
1327     } else {
1328     put_bits(&s->pb, 1, 0);         /* no time code 1 */
1329     put_bits(&s->pb, 1, 0);         /* no time code 2 */
1330     }
1331     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1332 }
1333
1334
1335 /**
1336  * Write one audio block to the output bitstream.
1337  */
1338 static void output_audio_block(AC3EncodeContext *s, int blk)
1339 {
1340     int ch, i, baie, bnd, got_cpl;
1341     int av_uninit(ch0);
1342     AC3Block *block = &s->blocks[blk];
1343
1344     /* block switching */
1345     if (!s->eac3) {
1346         for (ch = 0; ch < s->fbw_channels; ch++)
1347             put_bits(&s->pb, 1, 0);
1348     }
1349
1350     /* dither flags */
1351     if (!s->eac3) {
1352         for (ch = 0; ch < s->fbw_channels; ch++)
1353             put_bits(&s->pb, 1, 1);
1354     }
1355
1356     /* dynamic range codes */
1357     put_bits(&s->pb, 1, 0);
1358
1359     /* spectral extension */
1360     if (s->eac3)
1361         put_bits(&s->pb, 1, 0);
1362
1363     /* channel coupling */
1364     if (!s->eac3)
1365         put_bits(&s->pb, 1, block->new_cpl_strategy);
1366     if (block->new_cpl_strategy) {
1367         if (!s->eac3)
1368             put_bits(&s->pb, 1, block->cpl_in_use);
1369         if (block->cpl_in_use) {
1370             int start_sub, end_sub;
1371             if (s->eac3)
1372                 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1373             if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1374                 for (ch = 1; ch <= s->fbw_channels; ch++)
1375                     put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1376             }
1377             if (s->channel_mode == AC3_CHMODE_STEREO)
1378                 put_bits(&s->pb, 1, 0); /* phase flags in use */
1379             start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1380             end_sub   = (s->cpl_end_freq       - 37) / 12;
1381             put_bits(&s->pb, 4, start_sub);
1382             put_bits(&s->pb, 4, end_sub - 3);
1383             /* coupling band structure */
1384             if (s->eac3) {
1385                 put_bits(&s->pb, 1, 0); /* use default */
1386             } else {
1387                 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1388                     put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1389             }
1390         }
1391     }
1392
1393     /* coupling coordinates */
1394     if (block->cpl_in_use) {
1395         for (ch = 1; ch <= s->fbw_channels; ch++) {
1396             if (block->channel_in_cpl[ch]) {
1397                 if (!s->eac3 || block->new_cpl_coords[ch] != 2)
1398                     put_bits(&s->pb, 1, block->new_cpl_coords[ch]);
1399                 if (block->new_cpl_coords[ch]) {
1400                     put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1401                     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1402                         put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1403                         put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1404                     }
1405                 }
1406             }
1407         }
1408     }
1409
1410     /* stereo rematrixing */
1411     if (s->channel_mode == AC3_CHMODE_STEREO) {
1412         if (!s->eac3 || blk > 0)
1413             put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1414         if (block->new_rematrixing_strategy) {
1415             /* rematrixing flags */
1416             for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1417                 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1418         }
1419     }
1420
1421     /* exponent strategy */
1422     if (!s->eac3) {
1423         for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1424             put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1425         if (s->lfe_on)
1426             put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1427     }
1428
1429     /* bandwidth */
1430     for (ch = 1; ch <= s->fbw_channels; ch++) {
1431         if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1432             put_bits(&s->pb, 6, s->bandwidth_code);
1433     }
1434
1435     /* exponents */
1436     for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1437         int nb_groups;
1438         int cpl = (ch == CPL_CH);
1439
1440         if (s->exp_strategy[ch][blk] == EXP_REUSE)
1441             continue;
1442
1443         /* DC exponent */
1444         put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1445
1446         /* exponent groups */
1447         nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1448         for (i = 1; i <= nb_groups; i++)
1449             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1450
1451         /* gain range info */
1452         if (ch != s->lfe_channel && !cpl)
1453             put_bits(&s->pb, 2, 0);
1454     }
1455
1456     /* bit allocation info */
1457     if (!s->eac3) {
1458         baie = (blk == 0);
1459         put_bits(&s->pb, 1, baie);
1460         if (baie) {
1461             put_bits(&s->pb, 2, s->slow_decay_code);
1462             put_bits(&s->pb, 2, s->fast_decay_code);
1463             put_bits(&s->pb, 2, s->slow_gain_code);
1464             put_bits(&s->pb, 2, s->db_per_bit_code);
1465             put_bits(&s->pb, 3, s->floor_code);
1466         }
1467     }
1468
1469     /* snr offset */
1470     if (!s->eac3) {
1471         put_bits(&s->pb, 1, block->new_snr_offsets);
1472         if (block->new_snr_offsets) {
1473             put_bits(&s->pb, 6, s->coarse_snr_offset);
1474             for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1475                 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1476                 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1477             }
1478         }
1479     } else {
1480         put_bits(&s->pb, 1, 0); /* no converter snr offset */
1481     }
1482
1483     /* coupling leak */
1484     if (block->cpl_in_use) {
1485         if (!s->eac3 || block->new_cpl_leak != 2)
1486             put_bits(&s->pb, 1, block->new_cpl_leak);
1487         if (block->new_cpl_leak) {
1488             put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1489             put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1490         }
1491     }
1492
1493     if (!s->eac3) {
1494         put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1495         put_bits(&s->pb, 1, 0); /* no data to skip */
1496     }
1497
1498     /* mantissas */
1499     got_cpl = !block->cpl_in_use;
1500     for (ch = 1; ch <= s->channels; ch++) {
1501         int b, q;
1502
1503         if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1504             ch0     = ch - 1;
1505             ch      = CPL_CH;
1506             got_cpl = 1;
1507         }
1508         for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1509             q = block->qmant[ch][i];
1510             b = s->ref_bap[ch][blk][i];
1511             switch (b) {
1512             case 0:                                          break;
1513             case 1: if (q != 128) put_bits (&s->pb,   5, q); break;
1514             case 2: if (q != 128) put_bits (&s->pb,   7, q); break;
1515             case 3:               put_sbits(&s->pb,   3, q); break;
1516             case 4: if (q != 128) put_bits (&s->pb,   7, q); break;
1517             case 14:              put_sbits(&s->pb,  14, q); break;
1518             case 15:              put_sbits(&s->pb,  16, q); break;
1519             default:              put_sbits(&s->pb, b-1, q); break;
1520             }
1521         }
1522         if (ch == CPL_CH)
1523             ch = ch0;
1524     }
1525 }
1526
1527
1528 /** CRC-16 Polynomial */
1529 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1530
1531
1532 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1533 {
1534     unsigned int c;
1535
1536     c = 0;
1537     while (a) {
1538         if (a & 1)
1539             c ^= b;
1540         a = a >> 1;
1541         b = b << 1;
1542         if (b & (1 << 16))
1543             b ^= poly;
1544     }
1545     return c;
1546 }
1547
1548
1549 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1550 {
1551     unsigned int r;
1552     r = 1;
1553     while (n) {
1554         if (n & 1)
1555             r = mul_poly(r, a, poly);
1556         a = mul_poly(a, a, poly);
1557         n >>= 1;
1558     }
1559     return r;
1560 }
1561
1562
1563 /**
1564  * Fill the end of the frame with 0's and compute the two CRCs.
1565  */
1566 static void output_frame_end(AC3EncodeContext *s)
1567 {
1568     const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1569     int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1570     uint8_t *frame;
1571
1572     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1573
1574     /* pad the remainder of the frame with zeros */
1575     av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1576     flush_put_bits(&s->pb);
1577     frame = s->pb.buf;
1578     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1579     av_assert2(pad_bytes >= 0);
1580     if (pad_bytes > 0)
1581         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1582
1583     if (s->eac3) {
1584         /* compute crc2 */
1585         crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1586     } else {
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     }
1598     crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1599     /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1600     if (crc2 == 0x770B) {
1601         frame[s->frame_size - 3] ^= 0x1;
1602         crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1603     }
1604     crc2 = av_bswap16(crc2);
1605     AV_WB16(frame + s->frame_size - 2, crc2);
1606 }
1607
1608
1609 /**
1610  * Write the frame to the output bitstream.
1611  */
1612 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1613 {
1614     int blk;
1615
1616     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1617
1618     s->output_frame_header(s);
1619
1620     for (blk = 0; blk < s->num_blocks; blk++)
1621         output_audio_block(s, blk);
1622
1623     output_frame_end(s);
1624 }
1625
1626
1627 static void dprint_options(AC3EncodeContext *s)
1628 {
1629 #ifdef DEBUG
1630     AVCodecContext *avctx = s->avctx;
1631     AC3EncOptions *opt = &s->options;
1632     char strbuf[32];
1633
1634     switch (s->bitstream_id) {
1635     case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)",       32); break;
1636     case  8:  av_strlcpy(strbuf, "AC-3 (standard)",         32); break;
1637     case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)",   32); break;
1638     case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1639     case 16:  av_strlcpy(strbuf, "E-AC-3 (enhanced)",       32); break;
1640     default: snprintf(strbuf, 32, "ERROR");
1641     }
1642     av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1643     av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1644     av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1645     av_dlog(avctx, "channel_layout: %s\n", strbuf);
1646     av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1647     av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1648     av_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
1649     if (s->cutoff)
1650         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1651
1652     av_dlog(avctx, "per_frame_metadata: %s\n",
1653             opt->allow_per_frame_metadata?"on":"off");
1654     if (s->has_center)
1655         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1656                 s->center_mix_level);
1657     else
1658         av_dlog(avctx, "center_mixlev: {not written}\n");
1659     if (s->has_surround)
1660         av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1661                 s->surround_mix_level);
1662     else
1663         av_dlog(avctx, "surround_mixlev: {not written}\n");
1664     if (opt->audio_production_info) {
1665         av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1666         switch (opt->room_type) {
1667         case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1668         case AC3ENC_OPT_LARGE_ROOM:    av_strlcpy(strbuf, "large", 32);        break;
1669         case AC3ENC_OPT_SMALL_ROOM:    av_strlcpy(strbuf, "small", 32);        break;
1670         default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1671         }
1672         av_dlog(avctx, "room_type: %s\n", strbuf);
1673     } else {
1674         av_dlog(avctx, "mixing_level: {not written}\n");
1675         av_dlog(avctx, "room_type: {not written}\n");
1676     }
1677     av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1678     av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1679     if (s->channel_mode == AC3_CHMODE_STEREO) {
1680         switch (opt->dolby_surround_mode) {
1681         case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1682         case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1683         case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1684         default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1685         }
1686         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1687     } else {
1688         av_dlog(avctx, "dsur_mode: {not written}\n");
1689     }
1690     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1691
1692     if (s->bitstream_id == 6) {
1693         if (opt->extended_bsi_1) {
1694             switch (opt->preferred_stereo_downmix) {
1695             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1696             case AC3ENC_OPT_DOWNMIX_LTRT:  av_strlcpy(strbuf, "ltrt", 32);         break;
1697             case AC3ENC_OPT_DOWNMIX_LORO:  av_strlcpy(strbuf, "loro", 32);         break;
1698             default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1699             }
1700             av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1701             av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1702                     opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1703             av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1704                     opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1705             av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1706                     opt->loro_center_mix_level, s->loro_center_mix_level);
1707             av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1708                     opt->loro_surround_mix_level, s->loro_surround_mix_level);
1709         } else {
1710             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1711         }
1712         if (opt->extended_bsi_2) {
1713             switch (opt->dolby_surround_ex_mode) {
1714             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1715             case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1716             case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1717             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1718             }
1719             av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1720             switch (opt->dolby_headphone_mode) {
1721             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1722             case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1723             case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1724             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1725             }
1726             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1727
1728             switch (opt->ad_converter_type) {
1729             case AC3ENC_OPT_ADCONV_STANDARD: av_strlcpy(strbuf, "standard", 32); break;
1730             case AC3ENC_OPT_ADCONV_HDCD:     av_strlcpy(strbuf, "hdcd", 32);     break;
1731             default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1732             }
1733             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1734         } else {
1735             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1736         }
1737     }
1738 #endif
1739 }
1740
1741
1742 #define FLT_OPTION_THRESHOLD 0.01
1743
1744 static int validate_float_option(float v, const float *v_list, int v_list_size)
1745 {
1746     int i;
1747
1748     for (i = 0; i < v_list_size; i++) {
1749         if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1750             v > (v_list[i] - FLT_OPTION_THRESHOLD))
1751             break;
1752     }
1753     if (i == v_list_size)
1754         return -1;
1755
1756     return i;
1757 }
1758
1759
1760 static void validate_mix_level(void *log_ctx, const char *opt_name,
1761                                float *opt_param, const float *list,
1762                                int list_size, int default_value, int min_value,
1763                                int *ctx_param)
1764 {
1765     int mixlev = validate_float_option(*opt_param, list, list_size);
1766     if (mixlev < min_value) {
1767         mixlev = default_value;
1768         if (*opt_param >= 0.0) {
1769             av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1770                    "default value: %0.3f\n", opt_name, list[mixlev]);
1771         }
1772     }
1773     *opt_param = list[mixlev];
1774     *ctx_param = mixlev;
1775 }
1776
1777
1778 /**
1779  * Validate metadata options as set by AVOption system.
1780  * These values can optionally be changed per-frame.
1781  */
1782 int ff_ac3_validate_metadata(AC3EncodeContext *s)
1783 {
1784     AVCodecContext *avctx = s->avctx;
1785     AC3EncOptions *opt = &s->options;
1786
1787     opt->audio_production_info = 0;
1788     opt->extended_bsi_1        = 0;
1789     opt->extended_bsi_2        = 0;
1790     opt->eac3_mixing_metadata  = 0;
1791     opt->eac3_info_metadata    = 0;
1792
1793     /* determine mixing metadata / xbsi1 use */
1794     if (s->channel_mode > AC3_CHMODE_STEREO && opt->preferred_stereo_downmix != AC3ENC_OPT_NONE) {
1795         opt->extended_bsi_1       = 1;
1796         opt->eac3_mixing_metadata = 1;
1797     }
1798     if (s->has_center &&
1799         (opt->ltrt_center_mix_level >= 0 || opt->loro_center_mix_level >= 0)) {
1800         opt->extended_bsi_1       = 1;
1801         opt->eac3_mixing_metadata = 1;
1802     }
1803     if (s->has_surround &&
1804         (opt->ltrt_surround_mix_level >= 0 || opt->loro_surround_mix_level >= 0)) {
1805         opt->extended_bsi_1       = 1;
1806         opt->eac3_mixing_metadata = 1;
1807     }
1808
1809     if (s->eac3) {
1810         /* determine info metadata use */
1811         if (avctx->audio_service_type != AV_AUDIO_SERVICE_TYPE_MAIN)
1812             opt->eac3_info_metadata = 1;
1813         if (opt->copyright != AC3ENC_OPT_NONE || opt->original != AC3ENC_OPT_NONE)
1814             opt->eac3_info_metadata = 1;
1815         if (s->channel_mode == AC3_CHMODE_STEREO &&
1816             (opt->dolby_headphone_mode != AC3ENC_OPT_NONE || opt->dolby_surround_mode != AC3ENC_OPT_NONE))
1817             opt->eac3_info_metadata = 1;
1818         if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1819             opt->eac3_info_metadata = 1;
1820         if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE ||
1821             opt->ad_converter_type != AC3ENC_OPT_NONE) {
1822             opt->audio_production_info = 1;
1823             opt->eac3_info_metadata    = 1;
1824         }
1825     } else {
1826         /* determine audio production info use */
1827         if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE)
1828             opt->audio_production_info = 1;
1829
1830         /* determine xbsi2 use */
1831         if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1832             opt->extended_bsi_2 = 1;
1833         if (s->channel_mode == AC3_CHMODE_STEREO && opt->dolby_headphone_mode != AC3ENC_OPT_NONE)
1834             opt->extended_bsi_2 = 1;
1835         if (opt->ad_converter_type != AC3ENC_OPT_NONE)
1836             opt->extended_bsi_2 = 1;
1837     }
1838
1839     /* validate AC-3 mixing levels */
1840     if (!s->eac3) {
1841         if (s->has_center) {
1842             validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1843                             cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1844                             &s->center_mix_level);
1845         }
1846         if (s->has_surround) {
1847             validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1848                             surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1849                             &s->surround_mix_level);
1850         }
1851     }
1852
1853     /* validate extended bsi 1 / mixing metadata */
1854     if (opt->extended_bsi_1 || opt->eac3_mixing_metadata) {
1855         /* default preferred stereo downmix */
1856         if (opt->preferred_stereo_downmix == AC3ENC_OPT_NONE)
1857             opt->preferred_stereo_downmix = AC3ENC_OPT_NOT_INDICATED;
1858         if (!s->eac3 || s->has_center) {
1859             /* validate Lt/Rt center mix level */
1860             validate_mix_level(avctx, "ltrt_center_mix_level",
1861                                &opt->ltrt_center_mix_level, extmixlev_options,
1862                                EXTMIXLEV_NUM_OPTIONS, 5, 0,
1863                                &s->ltrt_center_mix_level);
1864             /* validate Lo/Ro center mix level */
1865             validate_mix_level(avctx, "loro_center_mix_level",
1866                                &opt->loro_center_mix_level, extmixlev_options,
1867                                EXTMIXLEV_NUM_OPTIONS, 5, 0,
1868                                &s->loro_center_mix_level);
1869         }
1870         if (!s->eac3 || s->has_surround) {
1871             /* validate Lt/Rt surround mix level */
1872             validate_mix_level(avctx, "ltrt_surround_mix_level",
1873                                &opt->ltrt_surround_mix_level, extmixlev_options,
1874                                EXTMIXLEV_NUM_OPTIONS, 6, 3,
1875                                &s->ltrt_surround_mix_level);
1876             /* validate Lo/Ro surround mix level */
1877             validate_mix_level(avctx, "loro_surround_mix_level",
1878                                &opt->loro_surround_mix_level, extmixlev_options,
1879                                EXTMIXLEV_NUM_OPTIONS, 6, 3,
1880                                &s->loro_surround_mix_level);
1881         }
1882     }
1883
1884     /* validate audio service type / channels combination */
1885     if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1886          avctx->channels == 1) ||
1887         ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1888           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
1889           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
1890          && avctx->channels > 1)) {
1891         av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
1892                                     "specified number of channels\n");
1893         return AVERROR(EINVAL);
1894     }
1895
1896     /* validate extended bsi 2 / info metadata */
1897     if (opt->extended_bsi_2 || opt->eac3_info_metadata) {
1898         /* default dolby headphone mode */
1899         if (opt->dolby_headphone_mode == AC3ENC_OPT_NONE)
1900             opt->dolby_headphone_mode = AC3ENC_OPT_NOT_INDICATED;
1901         /* default dolby surround ex mode */
1902         if (opt->dolby_surround_ex_mode == AC3ENC_OPT_NONE)
1903             opt->dolby_surround_ex_mode = AC3ENC_OPT_NOT_INDICATED;
1904         /* default A/D converter type */
1905         if (opt->ad_converter_type == AC3ENC_OPT_NONE)
1906             opt->ad_converter_type = AC3ENC_OPT_ADCONV_STANDARD;
1907     }
1908
1909     /* copyright & original defaults */
1910     if (!s->eac3 || opt->eac3_info_metadata) {
1911         /* default copyright */
1912         if (opt->copyright == AC3ENC_OPT_NONE)
1913             opt->copyright = AC3ENC_OPT_OFF;
1914         /* default original */
1915         if (opt->original == AC3ENC_OPT_NONE)
1916             opt->original = AC3ENC_OPT_ON;
1917     }
1918
1919     /* dolby surround mode default */
1920     if (!s->eac3 || opt->eac3_info_metadata) {
1921         if (opt->dolby_surround_mode == AC3ENC_OPT_NONE)
1922             opt->dolby_surround_mode = AC3ENC_OPT_NOT_INDICATED;
1923     }
1924
1925     /* validate audio production info */
1926     if (opt->audio_production_info) {
1927         if (opt->mixing_level == AC3ENC_OPT_NONE) {
1928             av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1929                    "room_type is set\n");
1930             return AVERROR(EINVAL);
1931         }
1932         if (opt->mixing_level < 80) {
1933             av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1934                    "80dB and 111dB\n");
1935             return AVERROR(EINVAL);
1936         }
1937         /* default room type */
1938         if (opt->room_type == AC3ENC_OPT_NONE)
1939             opt->room_type = AC3ENC_OPT_NOT_INDICATED;
1940     }
1941
1942     /* set bitstream id for alternate bitstream syntax */
1943     if (!s->eac3 && (opt->extended_bsi_1 || opt->extended_bsi_2)) {
1944         if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1945             static int warn_once = 1;
1946             if (warn_once) {
1947                 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1948                        "not compatible with reduced samplerates. writing of "
1949                        "extended bitstream information will be disabled.\n");
1950                 warn_once = 0;
1951             }
1952         } else {
1953             s->bitstream_id = 6;
1954         }
1955     }
1956
1957     return 0;
1958 }
1959
1960
1961 /**
1962  * Finalize encoding and free any memory allocated by the encoder.
1963  */
1964 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1965 {
1966     int blk, ch;
1967     AC3EncodeContext *s = avctx->priv_data;
1968
1969     av_freep(&s->windowed_samples);
1970     for (ch = 0; ch < s->channels; ch++)
1971         av_freep(&s->planar_samples[ch]);
1972     av_freep(&s->planar_samples);
1973     av_freep(&s->bap_buffer);
1974     av_freep(&s->bap1_buffer);
1975     av_freep(&s->mdct_coef_buffer);
1976     av_freep(&s->fixed_coef_buffer);
1977     av_freep(&s->exp_buffer);
1978     av_freep(&s->grouped_exp_buffer);
1979     av_freep(&s->psd_buffer);
1980     av_freep(&s->band_psd_buffer);
1981     av_freep(&s->mask_buffer);
1982     av_freep(&s->qmant_buffer);
1983     av_freep(&s->cpl_coord_exp_buffer);
1984     av_freep(&s->cpl_coord_mant_buffer);
1985     for (blk = 0; blk < s->num_blocks; blk++) {
1986         AC3Block *block = &s->blocks[blk];
1987         av_freep(&block->mdct_coef);
1988         av_freep(&block->fixed_coef);
1989         av_freep(&block->exp);
1990         av_freep(&block->grouped_exp);
1991         av_freep(&block->psd);
1992         av_freep(&block->band_psd);
1993         av_freep(&block->mask);
1994         av_freep(&block->qmant);
1995         av_freep(&block->cpl_coord_exp);
1996         av_freep(&block->cpl_coord_mant);
1997     }
1998
1999     s->mdct_end(s);
2000
2001     av_freep(&avctx->coded_frame);
2002     return 0;
2003 }
2004
2005
2006 /**
2007  * Set channel information during initialization.
2008  */
2009 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2010                                     int64_t *channel_layout)
2011 {
2012     int ch_layout;
2013
2014     if (channels < 1 || channels > AC3_MAX_CHANNELS)
2015         return AVERROR(EINVAL);
2016     if ((uint64_t)*channel_layout > 0x7FF)
2017         return AVERROR(EINVAL);
2018     ch_layout = *channel_layout;
2019     if (!ch_layout)
2020         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2021
2022     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2023     s->channels     = channels;
2024     s->fbw_channels = channels - s->lfe_on;
2025     s->lfe_channel  = s->lfe_on ? s->fbw_channels + 1 : -1;
2026     if (s->lfe_on)
2027         ch_layout -= AV_CH_LOW_FREQUENCY;
2028
2029     switch (ch_layout) {
2030     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
2031     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
2032     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
2033     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
2034     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
2035     case AV_CH_LAYOUT_QUAD:
2036     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
2037     case AV_CH_LAYOUT_5POINT0:
2038     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
2039     default:
2040         return AVERROR(EINVAL);
2041     }
2042     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2043     s->has_surround =  s->channel_mode & 0x04;
2044
2045     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2046     *channel_layout = ch_layout;
2047     if (s->lfe_on)
2048         *channel_layout |= AV_CH_LOW_FREQUENCY;
2049
2050     return 0;
2051 }
2052
2053
2054 static av_cold int validate_options(AC3EncodeContext *s)
2055 {
2056     AVCodecContext *avctx = s->avctx;
2057     int i, ret, max_sr;
2058
2059     /* validate channel layout */
2060     if (!avctx->channel_layout) {
2061         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2062                                       "encoder will guess the layout, but it "
2063                                       "might be incorrect.\n");
2064     }
2065     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2066     if (ret) {
2067         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2068         return ret;
2069     }
2070
2071     /* validate sample rate */
2072     /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2073              decoder that supports half sample rate so we can validate that
2074              the generated files are correct. */
2075     max_sr = s->eac3 ? 2 : 8;
2076     for (i = 0; i <= max_sr; i++) {
2077         if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2078             break;
2079     }
2080     if (i > max_sr) {
2081         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2082         return AVERROR(EINVAL);
2083     }
2084     s->sample_rate        = avctx->sample_rate;
2085     s->bit_alloc.sr_shift = i / 3;
2086     s->bit_alloc.sr_code  = i % 3;
2087     s->bitstream_id       = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2088
2089     /* validate bit rate */
2090     if (s->eac3) {
2091         int max_br, min_br, wpf, min_br_dist, min_br_code;
2092         int num_blks_code, num_blocks, frame_samples;
2093
2094         /* calculate min/max bitrate */
2095         /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
2096                  found use either 6 blocks or 1 block, even though 2 or 3 blocks
2097                  would work as far as the bit rate is concerned. */
2098         for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
2099             num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
2100             frame_samples  = AC3_BLOCK_SIZE * num_blocks;
2101             max_br = 2048 * s->sample_rate / frame_samples * 16;
2102             min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
2103             if (avctx->bit_rate <= max_br)
2104                 break;
2105         }
2106         if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2107             av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2108                    "for this sample rate\n", min_br, max_br);
2109             return AVERROR(EINVAL);
2110         }
2111         s->num_blks_code = num_blks_code;
2112         s->num_blocks    = num_blocks;
2113
2114         /* calculate words-per-frame for the selected bitrate */
2115         wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
2116         av_assert1(wpf > 0 && wpf <= 2048);
2117
2118         /* find the closest AC-3 bitrate code to the selected bitrate.
2119            this is needed for lookup tables for bandwidth and coupling
2120            parameter selection */
2121         min_br_code = -1;
2122         min_br_dist = INT_MAX;
2123         for (i = 0; i < 19; i++) {
2124             int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2125             if (br_dist < min_br_dist) {
2126                 min_br_dist = br_dist;
2127                 min_br_code = i;
2128             }
2129         }
2130
2131         /* make sure the minimum frame size is below the average frame size */
2132         s->frame_size_code = min_br_code << 1;
2133         while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2134             wpf--;
2135         s->frame_size_min = 2 * wpf;
2136     } else {
2137         for (i = 0; i < 19; i++) {
2138             if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2139                 break;
2140         }
2141         if (i == 19) {
2142             av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2143             return AVERROR(EINVAL);
2144         }
2145         s->frame_size_code = i << 1;
2146         s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2147         s->num_blks_code   = 0x3;
2148         s->num_blocks      = 6;
2149     }
2150     s->bit_rate   = avctx->bit_rate;
2151     s->frame_size = s->frame_size_min;
2152
2153     /* validate cutoff */
2154     if (avctx->cutoff < 0) {
2155         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2156         return AVERROR(EINVAL);
2157     }
2158     s->cutoff = avctx->cutoff;
2159     if (s->cutoff > (s->sample_rate >> 1))
2160         s->cutoff = s->sample_rate >> 1;
2161
2162     ret = ff_ac3_validate_metadata(s);
2163     if (ret)
2164         return ret;
2165
2166     s->rematrixing_enabled = s->options.stereo_rematrixing &&
2167                              (s->channel_mode == AC3_CHMODE_STEREO);
2168
2169     s->cpl_enabled = s->options.channel_coupling &&
2170                      s->channel_mode >= AC3_CHMODE_STEREO;
2171
2172     return 0;
2173 }
2174
2175
2176 /**
2177  * Set bandwidth for all channels.
2178  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2179  * default value will be used.
2180  */
2181 static av_cold void set_bandwidth(AC3EncodeContext *s)
2182 {
2183     int blk, ch;
2184     int av_uninit(cpl_start);
2185
2186     if (s->cutoff) {
2187         /* calculate bandwidth based on user-specified cutoff frequency */
2188         int fbw_coeffs;
2189         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2190         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2191     } else {
2192         /* use default bandwidth setting */
2193         s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2194     }
2195
2196     /* set number of coefficients for each channel */
2197     for (ch = 1; ch <= s->fbw_channels; ch++) {
2198         s->start_freq[ch] = 0;
2199         for (blk = 0; blk < s->num_blocks; blk++)
2200             s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2201     }
2202     /* LFE channel always has 7 coefs */
2203     if (s->lfe_on) {
2204         s->start_freq[s->lfe_channel] = 0;
2205         for (blk = 0; blk < s->num_blocks; blk++)
2206             s->blocks[blk].end_freq[ch] = 7;
2207     }
2208
2209     /* initialize coupling strategy */
2210     if (s->cpl_enabled) {
2211         if (s->options.cpl_start != AC3ENC_OPT_AUTO) {
2212             cpl_start = s->options.cpl_start;
2213         } else {
2214             cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2215             if (cpl_start < 0) {
2216                 if (s->options.channel_coupling == AC3ENC_OPT_AUTO)
2217                     s->cpl_enabled = 0;
2218                 else
2219                     cpl_start = 15;
2220             }
2221         }
2222     }
2223     if (s->cpl_enabled) {
2224         int i, cpl_start_band, cpl_end_band;
2225         uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2226
2227         cpl_end_band   = s->bandwidth_code / 4 + 3;
2228         cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2229
2230         s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2231
2232         s->num_cpl_bands = 1;
2233         *cpl_band_sizes  = 12;
2234         for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2235             if (ff_eac3_default_cpl_band_struct[i]) {
2236                 *cpl_band_sizes += 12;
2237             } else {
2238                 s->num_cpl_bands++;
2239                 cpl_band_sizes++;
2240                 *cpl_band_sizes = 12;
2241             }
2242         }
2243
2244         s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2245         s->cpl_end_freq       = cpl_end_band   * 12 + 37;
2246         for (blk = 0; blk < s->num_blocks; blk++)
2247             s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2248     }
2249 }
2250
2251
2252 static av_cold int allocate_buffers(AC3EncodeContext *s)
2253 {
2254     AVCodecContext *avctx = s->avctx;
2255     int blk, ch;
2256     int channels = s->channels + 1; /* includes coupling channel */
2257     int channel_blocks = channels * s->num_blocks;
2258     int total_coefs    = AC3_MAX_COEFS * channel_blocks;
2259
2260     if (s->allocate_sample_buffers(s))
2261         goto alloc_fail;
2262
2263     FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, total_coefs *
2264                      sizeof(*s->bap_buffer), alloc_fail);
2265     FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, total_coefs *
2266                      sizeof(*s->bap1_buffer), alloc_fail);
2267     FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, total_coefs *
2268                       sizeof(*s->mdct_coef_buffer), alloc_fail);
2269     FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, total_coefs *
2270                      sizeof(*s->exp_buffer), alloc_fail);
2271     FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, channel_blocks * 128 *
2272                      sizeof(*s->grouped_exp_buffer), alloc_fail);
2273     FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, total_coefs *
2274                      sizeof(*s->psd_buffer), alloc_fail);
2275     FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, channel_blocks * 64 *
2276                      sizeof(*s->band_psd_buffer), alloc_fail);
2277     FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, channel_blocks * 64 *
2278                      sizeof(*s->mask_buffer), alloc_fail);
2279     FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, total_coefs *
2280                      sizeof(*s->qmant_buffer), alloc_fail);
2281     if (s->cpl_enabled) {
2282         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, channel_blocks * 16 *
2283                          sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2284         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, channel_blocks * 16 *
2285                          sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2286     }
2287     for (blk = 0; blk < s->num_blocks; blk++) {
2288         AC3Block *block = &s->blocks[blk];
2289         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2290                           alloc_fail);
2291         FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2292                           alloc_fail);
2293         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2294                           alloc_fail);
2295         FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2296                           alloc_fail);
2297         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2298                           alloc_fail);
2299         FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2300                           alloc_fail);
2301         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2302                           alloc_fail);
2303         if (s->cpl_enabled) {
2304             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2305                               alloc_fail);
2306             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2307                               alloc_fail);
2308         }
2309
2310         for (ch = 0; ch < channels; ch++) {
2311             /* arrangement: block, channel, coeff */
2312             block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * channels + ch)];
2313             block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
2314             block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * channels + ch)];
2315             block->mask[ch]        = &s->mask_buffer       [64            * (blk * channels + ch)];
2316             block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * channels + ch)];
2317             if (s->cpl_enabled) {
2318                 block->cpl_coord_exp[ch]  = &s->cpl_coord_exp_buffer [16  * (blk * channels + ch)];
2319                 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16  * (blk * channels + ch)];
2320             }
2321
2322             /* arrangement: channel, block, coeff */
2323             block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2324             block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2325         }
2326     }
2327
2328     if (!s->fixed_point) {
2329         FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, total_coefs *
2330                           sizeof(*s->fixed_coef_buffer), alloc_fail);
2331         for (blk = 0; blk < s->num_blocks; blk++) {
2332             AC3Block *block = &s->blocks[blk];
2333             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2334                               sizeof(*block->fixed_coef), alloc_fail);
2335             for (ch = 0; ch < channels; ch++)
2336                 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2337         }
2338     } else {
2339         for (blk = 0; blk < s->num_blocks; blk++) {
2340             AC3Block *block = &s->blocks[blk];
2341             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2342                               sizeof(*block->fixed_coef), alloc_fail);
2343             for (ch = 0; ch < channels; ch++)
2344                 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2345         }
2346     }
2347
2348     return 0;
2349 alloc_fail:
2350     return AVERROR(ENOMEM);
2351 }
2352
2353
2354 /**
2355  * Initialize the encoder.
2356  */
2357 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2358 {
2359     AC3EncodeContext *s = avctx->priv_data;
2360     int ret, frame_size_58;
2361
2362     s->avctx = avctx;
2363
2364     s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2365
2366     ff_ac3_common_init();
2367
2368     ret = validate_options(s);
2369     if (ret)
2370         return ret;
2371
2372     avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
2373
2374     s->bitstream_mode = avctx->audio_service_type;
2375     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2376         s->bitstream_mode = 0x7;
2377
2378     s->bits_written    = 0;
2379     s->samples_written = 0;
2380
2381     /* calculate crc_inv for both possible frame sizes */
2382     frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2383     s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2384     if (s->bit_alloc.sr_code == 1) {
2385         frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2386         s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2387     }
2388
2389     /* set function pointers */
2390     if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2391         s->mdct_end                     = ff_ac3_fixed_mdct_end;
2392         s->mdct_init                    = ff_ac3_fixed_mdct_init;
2393         s->allocate_sample_buffers      = ff_ac3_fixed_allocate_sample_buffers;
2394     } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2395         s->mdct_end                     = ff_ac3_float_mdct_end;
2396         s->mdct_init                    = ff_ac3_float_mdct_init;
2397         s->allocate_sample_buffers      = ff_ac3_float_allocate_sample_buffers;
2398     }
2399     if (CONFIG_EAC3_ENCODER && s->eac3)
2400         s->output_frame_header = ff_eac3_output_frame_header;
2401     else
2402         s->output_frame_header = ac3_output_frame_header;
2403
2404     set_bandwidth(s);
2405
2406     exponent_init(s);
2407
2408     bit_alloc_init(s);
2409
2410     ret = s->mdct_init(s);
2411     if (ret)
2412         goto init_fail;
2413
2414     ret = allocate_buffers(s);
2415     if (ret)
2416         goto init_fail;
2417
2418     avctx->coded_frame= avcodec_alloc_frame();
2419
2420     dsputil_init(&s->dsp, avctx);
2421     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2422
2423     dprint_options(s);
2424
2425     return 0;
2426 init_fail:
2427     ff_ac3_encode_close(avctx);
2428     return ret;
2429 }